text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import assert = require("assert");
import http = require("http");
import sinon = require("sinon");
import AppInsights = require("../../applicationinsights");
import WebSnippet = require("../../AutoCollection/WebSnippet");
import SnippetInjectionHelper = require("../../Library/SnippetInjectionHelper");
describe("AutoCollection/WebSnippet", () => {
var sandbox: sinon.SinonSandbox;
afterEach(() => {
AppInsights.dispose();
sandbox.restore();
});
beforeEach(() =>{
sandbox = sinon.sandbox.create();
})
describe("#init and #dispose()", () => {
it("init should enable and dispose should stop injection", () => {
var appInsights = AppInsights.setup("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333").setWebSnippetInjection(true);
var enableWebSnippetsSpy = sinon.spy(WebSnippet.INSTANCE, "enable");
appInsights.start();
assert.equal(enableWebSnippetsSpy.callCount, 1, "enable should be called once as part of autocollection initialization");
assert.equal(enableWebSnippetsSpy.getCall(0).args[0], true);
AppInsights.dispose();
assert.equal(enableWebSnippetsSpy.callCount, 2, "enable(false) should be called once as part of autocollection shutdown");
assert.equal(enableWebSnippetsSpy.getCall(1).args[0], false);
});
});
describe("#validate response", () => {
it("injection should be triggered only in HTML responses", () => {
var appInsights = AppInsights.setup("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333").setWebSnippetInjection(true);
let webSnippet = WebSnippet.INSTANCE;
let _headers: any = {};
let response: http.ServerResponse = <any>{
setHeader: (header: string, value: string) => {
_headers[header] = value;
},
getHeader: (header: string) => { return _headers[header]; }
};
response.statusCode = 300;
let validHtml = "<html><head></head><body></body></html>";
assert.equal(webSnippet.ValidateInjection(response, validHtml), false); // status code is not 200
response.statusCode = 200;
assert.equal(webSnippet.ValidateInjection(response, validHtml), false); // No html header
response.setHeader("Content-Type", "text/html");
assert.equal(webSnippet.ValidateInjection(response, validHtml), true); // Valid
assert.equal(webSnippet.ValidateInjection(response, "test"), false); // No html text
assert.equal(webSnippet.ValidateInjection(response, "<html><body></body></html>"), false); // No head element
response.setHeader("Content-Type", "text/plain");
assert.equal(webSnippet.ValidateInjection(response, validHtml), false); // No HTML content type
response.setHeader("Content-Type", "text/html");
let validBuffer = Buffer.from(validHtml);
assert.equal(webSnippet.ValidateInjection(response, validBuffer), true); // Valid Buffer
assert.equal(webSnippet.ValidateInjection(response, Buffer.from("test")), false); // not valid Buffer
});
});
describe("#web snippet injection to string", () => {
var appInsights = AppInsights.setup("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333").setWebSnippetInjection(true);
let webSnippet = WebSnippet.INSTANCE;
webSnippet.enable(true);
it("injection add correct snippet code", () => {
let _headers: any = {};
let response: http.ServerResponse = <any>{
setHeader: (header: string, value: string) => {
_headers[header] = value;
},
getHeader: (header: string) => { return _headers[header]; },
removeHeader: (header: string) => { _headers[header] = undefined; }
};
response.setHeader("Content-Type", "text/html");
response.statusCode = 200;
let validHtml = "<html><head></head><body></body></html>";
assert.equal(webSnippet.ValidateInjection(response, validHtml), true);
let newHtml = webSnippet.InjectWebSnippet(response, validHtml).toString();
assert.ok(newHtml.indexOf("https://js.monitor.azure.com/scripts/b/ai.2.min.js") >= 0);
assert.ok(newHtml.indexOf("<html><head>") == 0);
assert.ok(newHtml.indexOf('instrumentationKey: "1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"') >= 0);
});
it("injection web snippet should overwrite content length ", () => {
let _headers: any = {};
let response: http.ServerResponse = <any>{
setHeader: (header: string, value: string) => {
_headers[header] = value;
},
getHeader: (header: string) => { return _headers[header]; },
removeHeader: (header: string) => { _headers[header] = undefined; }
};
response.setHeader("Content-Type", "text/html");
response.setHeader("Content-Length", 39);
let validHtml = "<html><head></head><body></body></html>";
let newHtml = webSnippet.InjectWebSnippet(response, validHtml).toString();
assert.ok(newHtml.length > 4000);
assert.ok(Number(response.getHeader("Content-Length")) > 4000); // Content length updated
});
});
describe("#web snippet injection to buffer", () => {
var appInsights = AppInsights.setup("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333").setWebSnippetInjection(true);
let webSnippet = WebSnippet.INSTANCE
webSnippet.enable(true);
it("injection add correct snippet code", () => {
let _headers: any = {};
let response: http.ServerResponse = <any>{
setHeader: (header: string, value: string) => {
_headers[header] = value;
},
getHeader: (header: string) => { return _headers[header]; },
removeHeader: (header: string) => { _headers[header] = undefined; }
};
response.setHeader("Content-Type", "text/html");
response.statusCode = 200;
let validHtml = "<html><head></head><body></body></html>";
let validBuffer = Buffer.from(validHtml);
assert.equal(webSnippet.ValidateInjection(response, validBuffer), true);
let newHtml = webSnippet.InjectWebSnippet(response, validBuffer).toString();
assert.ok(newHtml.indexOf("https://js.monitor.azure.com/scripts/b/ai.2.min.js") >= 0);
assert.ok(newHtml.indexOf("<html><head>") == 0);
assert.ok(newHtml.indexOf('instrumentationKey: "1aa11111-bbbb-1ccc-8ddd-eeeeffff3333"') >= 0);
});
it("injection web snippet should overwrite content length ", () => {
let _headers: any = {};
let response: http.ServerResponse = <any>{
setHeader: (header: string, value: string) => {
_headers[header] = value;
},
getHeader: (header: string) => { return _headers[header]; },
removeHeader: (header: string) => { _headers[header] = undefined; }
};
let validHtml = "<html><head></head><body>ZKrIVPWptS13MH4my8kbkjWHF5BoNUIfvzfvt6LSE3qg1GoMOZ9bgNJcdcUXDc3l3jyCP9WIK2Z002rqBCn24cfwYjXLmq6kOO6SVFIFhQqNUwrmpA5"+
"vumrQRAHtkqJWWV91I1NS2VjwYpmCytH8rg6qAScR0Qoy0UFXQGd0QO1hkqwH2jzEApklsDqCgMavANBoqKfg715afWySfKba9YG6S5iIIIySsBeg1vlM3" +
"7fvNKTeA7wHHK8IOkbWlTM70yFn1flvJKOlbsabIgnO48atkizsyS0ITZKudpYzcALY3simblbi0I3DIwUjfW46FHyXYTfvfmNo9cbOyVZsJQrJshp2zck</body></html>";
let validBuffer = Buffer.from(validHtml);
let originalBufferSize = validBuffer.length;
response.setHeader("Content-Type", "text/html");
response.setHeader("Content-Length", originalBufferSize);
let newHtml = webSnippet.InjectWebSnippet(response, validBuffer);
let isValidBufferEncode = SnippetInjectionHelper.isBufferType(validBuffer,"utf8");
assert.ok(isValidBufferEncode);
assert.ok(newHtml.length > originalBufferSize);
assert.ok(Number(response.getHeader("Content-Length")) > originalBufferSize); // Content length updated
});
});
describe("#web snippet replace correct connection string from config", () => {
it("injection should use correct connection string from config", () => {
var appInsights = AppInsights.setup("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333").setWebSnippetInjection(true,"InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3330;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/");
let webSnippet = WebSnippet.INSTANCE;
webSnippet.enable(true, "InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeffff3330;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/");
assert.equal(webSnippet["_isIkeyValid"], true,"ikey should be set to valid");
let _headers: any = {};
let response: http.ServerResponse = <any>{
setHeader: (header: string, value: string) => {
_headers[header] = value;
},
getHeader: (header: string) => { return _headers[header]; },
removeHeader: (header: string) => { _headers[header] = undefined; }
};
response.setHeader("Content-Type", "text/html");
response.statusCode = 200;
let validHtml = "<html><head></head><body></body></html>";
assert.equal(webSnippet.ValidateInjection(response, validHtml), true);
let newHtml = webSnippet.InjectWebSnippet(response, validHtml).toString();
assert.ok(newHtml.indexOf("https://js.monitor.azure.com/scripts/b/ai.2.min.js") >= 0);
assert.ok(newHtml.indexOf("<html><head>") == 0);
assert.ok(newHtml.indexOf('instrumentationKey: "1aa11111-bbbb-1ccc-8ddd-eeeeffff3330"') >= 0);
});
});
describe("#web snippet enable should throw errors when ikey from config is not valid", () => {
it("injection should throw errors when ikey from config is not valid", () => {
var infoStub = sandbox.stub(console, "info");
var appInsights = AppInsights.setup("1aa11111-bbbb-1ccc-8ddd-eeeeffff3333").setWebSnippetInjection(true,"InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeff;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/");
let webSnippet = WebSnippet.INSTANCE;
webSnippet.enable(true, "InstrumentationKey=1aa11111-bbbb-1ccc-8ddd-eeeeff;IngestionEndpoint=https://centralus-0.in.applicationinsights.azure.com/");
assert.equal(webSnippet["_isIkeyValid"], false,"ikey should be set to invalid");
assert.ok(infoStub.calledOn, "invalid key warning was raised");
});
});
}); | the_stack |
import { TSDocConfiguration } from '@microsoft/tsdoc';
import * as path from 'path';
import { TSDocConfigFile } from '../TSDocConfigFile';
interface ISnapshot {
s0_filePath: string;
s1_fileNotFound: boolean;
s2_hasErrors: boolean;
s3_errorSummary: string;
s4_log: string[];
s5_extends: ISnapshot[];
}
function replaceAll(text: string, search: string, replace: string): string {
return text.split(search).join(replace);
}
// To make the unit tests deterministic, we need to replace all OS-dependent absolute paths
// with OS-independent paths that are relative to the unit test folder.
function makeStablePath(testPath: string): string {
if (testPath.length === 0) {
return '';
}
console.log('IN: ' + testPath);
console.log('OUT: ' + replaceAll(path.relative(__dirname, testPath), '\\', '/'));
return '.../' + replaceAll(path.relative(__dirname, testPath), '\\', '/');
}
// Build a map from absolute path --> stable path, for each TSDocConfigFile.filePath value
function buildStablePathMap(stablePathMap: Map<string, string>, configFile: TSDocConfigFile): void {
for (const absolutePath of [configFile.filePath, path.dirname(configFile.filePath)]) {
if (!stablePathMap.has(absolutePath)) {
stablePathMap.set(absolutePath, makeStablePath(absolutePath));
}
}
for (const extendsFile of configFile.extendsFiles) {
buildStablePathMap(stablePathMap, extendsFile);
}
}
// Search and replace all absolute paths with the corresponding stable path.
// For example, "Found C:\A\B\C.txt in C:\A\D\E.txt" becomes "Found .../B/C.txt in .../D/E.txt".
function convertToStablePaths(text: string, stablePathMap: Map<string, string>): string {
// Sort the [key,value] pairs by key length from longest to shortest.
// This ensures that a shorter path does not replace a subpath of a longer path.
const pairs: [string, string][] = Array.from(stablePathMap.entries()).sort((x, y) => y[0].length - x[0].length);
for (const pair of pairs) {
text = replaceAll(text, pair[0], pair[1]);
}
// Also convert any loose backslashes to slashes
//text = replaceAll(text, '\\', '/');
return text;
}
function createSnapshot(configFile: TSDocConfigFile, pathFixupMap: Map<string, string>): ISnapshot {
return {
s0_filePath: convertToStablePaths(configFile.filePath, pathFixupMap),
s1_fileNotFound: configFile.fileNotFound,
s2_hasErrors: configFile.hasErrors,
s4_log: configFile.log.messages.map((x) => `[${x.messageId}] ${convertToStablePaths(x.text, pathFixupMap)}`),
s5_extends: configFile.extendsFiles.map((x) => createSnapshot(x, pathFixupMap)),
s3_errorSummary: convertToStablePaths(configFile.getErrorSummary(), pathFixupMap),
};
}
function testLoadingFolder(assetPath: string): ISnapshot {
const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, assetPath));
const pathFixupMap: Map<string, string> = new Map();
buildStablePathMap(pathFixupMap, configFile);
return createSnapshot(configFile, pathFixupMap);
}
test('Load e1', () => {
expect(testLoadingFolder('assets/e1')).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e1/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e1/tsdoc.json:
Error loading config file: data should NOT have additional properties
",
"s4_log": Array [
"[tsdoc-config-schema-error] Error loading config file: data should NOT have additional properties",
],
"s5_extends": Array [],
}
`);
});
test('Load e2', () => {
expect(testLoadingFolder('assets/e2')).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e2/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e2/tsdoc.json:
Error parsing JSON input: Unexpected token '\\\\n' at 3:12
\\"invalid
^
",
"s4_log": Array [
"[tsdoc-config-invalid-json] Error parsing JSON input: Unexpected token '\\\\n' at 3:12
\\"invalid
^",
],
"s5_extends": Array [],
}
`);
});
test('Load e3', () => {
expect(testLoadingFolder('assets/e3')).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e3/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e3/tsdoc.json:
Unsupported JSON \\"$schema\\" value; expecting \\"https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json\\"
",
"s4_log": Array [
"[tsdoc-config-unsupported-schema] Unsupported JSON \\"$schema\\" value; expecting \\"https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json\\"",
],
"s5_extends": Array [],
}
`);
});
test('Load e4', () => {
expect(testLoadingFolder('assets/e4')).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e4/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e4/tsdoc.json:
The \\"tagDefinitions\\" field specifies more than one tag with the name \\"@dupe\\"
",
"s4_log": Array [
"[tsdoc-config-duplicate-tag-name] The \\"tagDefinitions\\" field specifies more than one tag with the name \\"@dupe\\"",
],
"s5_extends": Array [],
}
`);
});
test('Load e5', () => {
expect(testLoadingFolder('assets/e5')).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e5/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e5/tsdoc-a.json:
Circular reference encountered for \\"extends\\" field of \\".../assets/e5/tsdoc-b.json\\"
Error encountered for .../assets/e5/tsdoc-c.json:
Error loading config file: data should NOT have additional properties
",
"s4_log": Array [],
"s5_extends": Array [
Object {
"s0_filePath": ".../assets/e5/tsdoc-a.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e5/tsdoc-a.json:
Circular reference encountered for \\"extends\\" field of \\".../assets/e5/tsdoc-b.json\\"
Error encountered for .../assets/e5/tsdoc-c.json:
Error loading config file: data should NOT have additional properties
",
"s4_log": Array [],
"s5_extends": Array [
Object {
"s0_filePath": ".../assets/e5/tsdoc-b.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e5/tsdoc-a.json:
Circular reference encountered for \\"extends\\" field of \\".../assets/e5/tsdoc-b.json\\"
",
"s4_log": Array [],
"s5_extends": Array [
Object {
"s0_filePath": ".../assets/e5/tsdoc-a.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e5/tsdoc-a.json:
Circular reference encountered for \\"extends\\" field of \\".../assets/e5/tsdoc-b.json\\"
",
"s4_log": Array [
"[tsdoc-config-cyclic-extends] Circular reference encountered for \\"extends\\" field of \\".../assets/e5/tsdoc-b.json\\"",
],
"s5_extends": Array [],
},
],
},
Object {
"s0_filePath": ".../assets/e5/tsdoc-c.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e5/tsdoc-c.json:
Error loading config file: data should NOT have additional properties
",
"s4_log": Array [
"[tsdoc-config-schema-error] Error loading config file: data should NOT have additional properties",
],
"s5_extends": Array [],
},
],
},
],
}
`);
});
test('Load e6', () => {
expect(testLoadingFolder('assets/e6')).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e6/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e6/tsdoc.json:
Unable to resolve \\"extends\\" reference to \\"@rushstack/nonexistent-package/tsdoc.json\\": Cannot find module '@rushstack/nonexistent-package/tsdoc.json' from '.../assets/e6'
",
"s4_log": Array [
"[tsdoc-config-unresolved-extends] Unable to resolve \\"extends\\" reference to \\"@rushstack/nonexistent-package/tsdoc.json\\": Cannot find module '@rushstack/nonexistent-package/tsdoc.json' from '.../assets/e6'",
],
"s5_extends": Array [],
}
`);
});
test('Load e7', () => {
const configFile: TSDocConfigFile = TSDocConfigFile.loadForFolder(path.join(__dirname, 'assets/e7'));
const pathFixupMap: Map<string, string> = new Map();
buildStablePathMap(pathFixupMap, configFile);
expect(createSnapshot(configFile, pathFixupMap)).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e7/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": false,
"s3_errorSummary": "No errors.",
"s4_log": Array [],
"s5_extends": Array [],
}
`);
// The "tsdoc-config-undefined-tag" error is NOT detected by TSDocConfigFile.loadForFolder()
expect(configFile.hasErrors).toBe(false);
const configuration: TSDocConfiguration = new TSDocConfiguration();
configFile.configureParser(configuration);
expect(createSnapshot(configFile, pathFixupMap)).toMatchInlineSnapshot(`
Object {
"s0_filePath": ".../assets/e7/tsdoc.json",
"s1_fileNotFound": false,
"s2_hasErrors": true,
"s3_errorSummary": "Error encountered for .../assets/e7/tsdoc.json:
The \\"supportForTags\\" field refers to an undefined tag \\"@nonExistentTag\\".
",
"s4_log": Array [
"[tsdoc-config-undefined-tag] The \\"supportForTags\\" field refers to an undefined tag \\"@nonExistentTag\\".",
],
"s5_extends": Array [],
}
`);
// The "tsdoc-config-undefined-tag" error IS detected by TSDocConfigFile.configureParser()
expect(configFile.hasErrors).toBe(true);
}); | the_stack |
import { IPC } from "../../../ipc/client";
import { WorkspaceTab } from "./tab";
import { WorkspaceRenderer } from "../renderer";
import { ClassDump, HierarchyEntryDump } from "../../../ipc/objects"
import { isNumber, isObject, isBoolean, isString } from "util";
import { EncryptedVariable } from "../../../puppet/ast";
const ipc = IPC();
const Dialogs = require('dialogs');
const $ = require("jquery");
declare const JSONEditor: any;
const dialogs = Dialogs();
interface RenderedProperty
{
value(): any;
set(value: any): void;
modified(value: boolean): void;
}
type PropertyChangedCallback = (value: any) => void;
interface PropertyRenderer
{
render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty;
}
class StringPropertyRenderer implements PropertyRenderer
{
public render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty
{
const zis = this;
const textField = $('<input type="text" class="form-control form-control-sm" id="' + propertyId + '">')
.appendTo(group)
.val(value)
.change(function()
{
changed($(this).val());
});
if (value)
{
$(textField).attr('placeholder', value);
}
return {
value(): any
{
return textField.val();
},
set(value: any): void
{
textField.val(value);
},
modified(value: boolean): void
{
}
};
}
}
class HashPropertyRenderer implements PropertyRenderer
{
public render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty
{
const zis = this;
group.parent().css('width', '100%');
const buttons = $('<div class="w-100 hash-editor-buttons" style="display: none;"></div>').appendTo(group);
const div = $('<div class="hash-editor" id="' + propertyId + '"></div>')
.appendTo(group);
const revert = $('<button type="button" class="btn btn-sm btn-outline-danger float-right">Revert</button>').appendTo(buttons);
const apply = $('<button type="button" class="btn btn-sm btn-outline-primary btn-space float-right">Apply</button>').appendTo(buttons);
apply.click(() =>
{
changed(editor.get());
});
revert.click(() =>
{
editor.set(value);
buttons.hide();
});
const editor = new JSONEditor(div[0], {
modes: ['code', 'tree'],
mainMenuBar: false,
statusBar: false,
onChange: () =>
{
buttons.show();
}
});
if (value != null)
{
editor.set(value);
}
return {
value(): any
{
return editor.get();
},
set(value: any): void
{
editor.set(value);
},
modified(value: boolean): void
{
}
};
}
}
class EnumPropertyRenderer implements PropertyRenderer
{
private readonly values: Array<string>;
constructor(values: Array<string>)
{
this.values = values;
}
public render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty
{
const zis = this;
const select = $('<select class="selectpicker" id="' + propertyId + '"></select>').appendTo(group);
for (const value_ of this.values)
{
const p_ = (value_ == value) ? " selected" : "";
$('<option' + p_ + '>' + value_ + '</option>').appendTo(select);
}
select.selectpicker({
style: "selectpicker-sm"
}).change(function()
{
changed($(this).val());
});
return {
value(): any
{
return select.val();
},
set(value: any): void
{
select.val(value);
select.selectpicker('refresh');
},
modified(value: boolean): void
{
}
};
}
}
class NumberPropertyRenderer implements PropertyRenderer
{
private isNumberKey(event: any)
{
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
public render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty
{
const zis = this;
const textField = $('<input type="text" class="form-control form-control-sm" id="' + propertyId + '">')
.appendTo(group)
.val(value)
.keypress(this.isNumberKey)
.change(function()
{
changed(parseInt($(this).val()));
});
if (value != null)
{
$(textField).attr('placeholder', value);
}
return {
value(): any
{
return textField.val();
},
set(value: any): void
{
textField.val(value);
},
modified(value: boolean): void
{
}
};
}
}
class BooleanPropertyRenderer implements PropertyRenderer
{
public render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty
{
const zis = this;
const textField = $('<input type="checkbox" id="' + propertyId + '">')
.appendTo(group)
.bootstrapSwitch({
state: value,
size: 'small',
onSwitchChange: (event: any, state: boolean) =>
{
changed(state);
}
});
return {
value(): any
{
return textField.bootstrapSwitch('state');
},
set(value: any): void
{
textField.bootstrapSwitch('state', value, true);
},
modified(value: boolean): void
{
}
};
}
}
class EncryptedPropertyRenderer implements PropertyRenderer
{
public render(group: any, propertyId: string, value: any, changed: PropertyChangedCallback): RenderedProperty
{
const textField = $('<input type="text" class="form-control form-control-sm" id="' + propertyId + '" readonly>')
.appendTo(group)
.val(value);
if (value)
{
$(textField).attr('placeholder', value);
}
return {
value(): any
{
return textField.val();
},
set(value: any): void
{
},
modified(value: boolean): void
{
}
};
}
}
export class NodeClassTab extends WorkspaceTab
{
private info: ClassDump;
protected environment: string;
protected certname: string;
protected className: string;
protected editor: any;
protected renderedProperties: any;
protected hierarchyLevel: number;
protected flex: any;
protected editorHolder: any;
private _keysImported: boolean;
public constructor(path: Array<string>, buttonNode: any, contentNode: any, renderer: WorkspaceRenderer)
{
super(path, buttonNode, contentNode, renderer);
this.hierarchyLevel = -1;
this.renderedProperties = {};
}
public async focusIn(): Promise<void>
{
if (!(await ipc.isNodeClassValid(this.environment, this.certname, this.className)))
{
await this.refresh();
}
}
public async init(): Promise<any>
{
this.environment = this.path[0];
this.certname = this.path[1];
this.className = this.path[2];
await this.acquireInfo();
// highest hierarchy level that modified by default
if (this.hierarchyLevel == -1)
{
this.hierarchyLevel = this.hierarchy.length - 1;
const classFields = this.getProperties();
for (const propertyName of classFields)
{
const modifiedHierarchy = this.isValueModified(propertyName);
if (modifiedHierarchy >= 0 && this.hierarchyLevel > modifiedHierarchy)
{
this.hierarchyLevel = modifiedHierarchy;
}
}
}
this._keysImported = await ipc.isEYamlKeysImported(this.environment, this.certname, this.hierarchyLevel);
}
protected async acquireInfo()
{
this.info = await ipc.acquireNodeClass(this.environment, this.certname, this.className);
}
public get hierarchy(): HierarchyEntryDump[]
{
return this.info.hierarchy;
}
private buildValue(classInfo: any): any
{
const properties: any = {};
for (const property_name in classInfo.defaults)
{
const property = classInfo.defaults[property_name];
if (property.hasOwnProperty("value"))
{
properties[property_name] = property.value;
}
}
return properties
}
private getPropertyRenderer(type: any, value?: any): PropertyRenderer
{
if (type == null)
{
return this.getDefaultPropertyRenderer(value);
}
switch (type.type)
{
case "String":
{
switch(type.data)
{
case "String":
{
return new StringPropertyRenderer();
}
case "Integer":
{
return new NumberPropertyRenderer();
}
case "Boolean":
{
return new BooleanPropertyRenderer();
}
case "Hash":
{
return new HashPropertyRenderer();
}
default:
{
return this.getDefaultPropertyRenderer(value);
}
}
}
case "PuppetASTAccess":
{
switch (type.data.what.type.value)
{
case "Optional":
{
return this.getPropertyRenderer(type.data.values[0]);
}
case "Enum":
{
const values: Array<string> = [];
for (const obj of type.data.values)
{
if (obj.value instanceof Object)
{
values.push(obj.value.value);
}
else
{
values.push(obj.value);
}
}
return new EnumPropertyRenderer(values);
}
default:
{
return this.getDefaultPropertyRenderer(value);
}
}
}
}
return this.getDefaultPropertyRenderer(value);
}
private getDefaultPropertyRenderer(value: any)
{
if (value != null)
{
if (isBoolean(value))
{
return new BooleanPropertyRenderer();
}
if (isObject(value))
{
return new HashPropertyRenderer();
}
if (isNumber(value))
{
return new NumberPropertyRenderer();
}
}
return new StringPropertyRenderer();
}
protected noClassInfoText(): string
{
return "This object does not seem to be recognized, because of compilation issues."
}
protected renderHierarchySelector(parent: any)
{
const zis = this;
const data: any[] = [];
let _id = 0;
for (const hierarchyEntry of this.hierarchy)
{
let title = hierarchyEntry.path;
data.push({
"id": _id,
"text": title,
"eyaml": hierarchyEntry.eyaml
});
_id++;
}
const pad = $('<div class="container-grayed d-flex flex-row" style="flex-shrink: 0"></div>').appendTo(parent);
{
const title = $('<span class="text-muted" style="padding: 6px 10px 6px 10px;"></span>').appendTo(pad);
$('<i class="fas fa-project-diagram" title="This selector affects at what level of hierarchy the edits are made" ' +
'data-toggle="tooltip" data-placement="bottom"></i>').tooltip().appendTo(title);
}
function format(entry: any)
{
if (!entry.id)
{
return entry.text;
}
const _id = parseInt(entry.id);
const icon = entry.eyaml ? "lock" : "stop";
return $('<span class="modified-' + (_id % 12) + '"><i class="fas fa-' + icon + '"></i> ' + entry.text + '</span>');
}
const hierarchySelector = $('<select class="workspace-selector"></select>').appendTo(pad).select2({
"width": "100%",
"data": data,
"templateSelection": format,
"templateResult": format
});
if (this.hierarchy[this.hierarchyLevel].eyaml)
{
let e;
if (this._keysImported)
{
const title = $('<span class="text-success" style="padding: 6px 10px 6px 10px;"></span>').appendTo(pad);
e = $('<i class="fas fa-key" title="click here to configure eyaml keys" ' +
'data-toggle="tooltip" data-placement="bottom"></i>').tooltip().appendTo(title);
}
else
{
const title = $('<span class="text-warning" style="padding: 6px 10px 6px 10px;"></span>').appendTo(pad);
e = $('<i class="fas fa-exclamation-triangle" title="eyaml is not configured, click to configure" ' +
'data-toggle="tooltip" data-placement="bottom"></i>').tooltip().appendTo(title);
}
const eyaml = e;
eyaml.click(async () =>
{
$(eyaml).tooltip('hide');
if (await ipc.manageEYamlKeys(this.environment, this.certname, this.hierarchyLevel))
{
zis.refresh();
}
else
{
dialogs.alert("Failed to update eyaml keys.")
}
});
}
hierarchySelector.val(zis.hierarchyLevel).trigger("change");
hierarchySelector.on("change", () =>
{
zis.hierarchyLevel = parseInt(hierarchySelector.val());
// wtf electron
setTimeout(() => zis.refresh(), 1);
})
}
protected scrollBefore(): any
{
return $(this.editorHolder).scrollTop();
}
protected scrollAfter(before: any): void
{
$(this.editorHolder).scrollTop(before);
}
public render(): any
{
this.flex = $('<div class="w-100 h-100" style="display: flex;flex-direction: column;"></div>').appendTo(this.contentNode);
this.renderHierarchySelector(this.flex);
this.editorHolder = $('<div class="w-100 node-class-properties" style="flex-grow: 1; overflow-y: auto;"></div>').appendTo(this.flex);
if (this.classInfo() == null)
{
const pad = $('<div class="container-w-padding d-flex" style="flex-shrink: 0"></div>').appendTo(this.editorHolder);
$('<div class="alert alert-danger w-100" role="alert" style="margin-bottom: 0;"></div>').appendTo(pad).html(this.noClassInfoText());
}
if (this.hasHints())
{
const pad = $('<div class="container-w-padding d-flex" style="flex-shrink: 0"></div>').appendTo(this.editorHolder);
for (const hint of this.getHints())
{
$('<div class="alert alert-warning w-100" role="alert" style="margin-bottom: 0;"></div>').appendTo(pad).html(hint.message);
}
}
this.renderProperties(this.editorHolder);
const description = this.getDescription();
if (description != null && description != "")
{
const pad = $('<div class="container-w-padding-x2"></div>').appendTo(this.editorHolder);
const i = $('<i class="fas fa-question" title="Click to show documentation">').tooltip().appendTo(pad);
const documentation = $('<pre></pre>').html(description).css("display", "none").appendTo(pad);
i.click(() => {
$(i).tooltip('hide');
$(i).remove();
$(documentation).show();
});
}
}
protected getDescription(): string
{
if (this.info.classInfo == null)
return null;
return this.info.classInfo.description;
}
protected getTag(tag: string, name: string): string
{
if (this.info.classInfo == null)
return null;
const tags = this.info.classInfo.tags;
if (tags[tag] == null)
return null;
return tags[tag][name];
}
private fixedPropertyName(name: string): string
{
return name.replace(/:/g, "_");
}
private renderProperty(propertyName: string, node: any, required: boolean)
{
const zis = this;
const propertyId = 'property-' + this.fixedPropertyName(propertyName);
const humanName = propertyName.replace(/_/g, " ").replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
const modifiedHierarchy = this.isValueModified(propertyName);
const encrypted = this.isPropertyEncrypted(propertyName);
let value = this.getPropertyValue(propertyName);
const label = $('<span class="text-small"></span>').appendTo(node);
// show the modified marker is the class if there is any value to it (including null)
if (modifiedHierarchy >= 0)
{
const modified = $('<a class="class-property-action">' +
'<i class="fas fa-' + (encrypted ? 'lock' : 'trash') + '"></i></a>').appendTo(label);
if (encrypted)
{
modified.attr("title", "Encrypted, click to remove encryption and reset to default value")
}
else
{
modified.attr("title", "Reset to default value");
}
modified.click(async () =>
{
await zis.removeProperty(propertyName, modifiedHierarchy);
await zis.refresh();
}).tooltip();
$(label).addClass("modified").addClass("modified-" + modifiedHierarchy);
$(node).addClass("modified").addClass("modified-" + modifiedHierarchy);
}
const group = $('<div class="input-group"></div>').appendTo(node);
let renderer;
if (this.isPropertyEncrypted(propertyName))
{
renderer = new EncryptedPropertyRenderer();
value = this.getEncryptedPropertyRaw(propertyName);
}
else
{
const typeInfo = this.getPropertyTypeInfo(propertyName);
if (typeInfo != null)
{
renderer = this.getPropertyRenderer(typeInfo, value);
}
else
{
renderer = this.getDefaultPropertyRenderer(value);
}
}
const renderedProperty = this.renderedProperties[propertyName] =
renderer.render(group, propertyId, value, async function(value: any)
{
await zis.setProperty(propertyName, value);
await zis.refresh();
});
if (!encrypted && isString(value) &&
this.hierarchy[this.hierarchyLevel].eyaml && modifiedHierarchy == this.hierarchyLevel)
{
const encrypt = $('<a class="class-property-action" title="Click to encrypt the value">' +
'<i class="fas fa-key"></i></a>').tooltip().appendTo(label);
encrypt.click(async () =>
{
await ipc.encryptNodeClassProperty(zis.environment, zis.certname,
modifiedHierarchy, zis.className, propertyName);
await ipc.invalidateNodeClass(zis.environment, zis.certname, zis.className);
await zis.refresh();
});
}
const l = $('<label for="' + propertyId + '">' + humanName + '</label>').appendTo(label);
const description = this.getTag("param", propertyName);
if (description != null && description != "")
{
$('<i class="fas fa-question text-muted" style="padding-left: 8px;" title="' + description + '">').tooltip().appendTo(l);
}
if (required)
{
$(l).css('font-weight', "bold");
}
const error = this.getPropertyErrorInfo(propertyName);
if (error != null)
{
const p_ = $('<div class="input-group-append"></div>').appendTo(group);
const tooltipTitle = "Cannot resolve defaults:<br/>" + error.message;
$('<button class="btn btn-sm btn-outline-danger" type="button" data-toggle="tooltip" data-placement="left">' +
'<i class="fas fa-times"></i></button>').appendTo(p_).tooltip({
title: tooltipTitle,
html: true
});
}
else
{
const hints = this.getPropertyHints(propertyName);
if (hints != null && hints.length > 0)
{
const p_ = $('<div class="input-group-append"></div>').appendTo(group);
const texts = [];
for (const hint of hints)
{
texts.push(hint.message);
}
const tooltipTitle = texts.join("<br/>");
$('<button class="btn btn-sm btn-outline-warning" type="button" data-toggle="tooltip" data-placement="left">' +
'<i class="fas fa-exclamation-triangle"></i></button>').appendTo(p_).tooltip({
title: tooltipTitle,
html: true
}).click(async () => {
/*
for (const hint of hints)
{
if (hint.kind == "VariableNotFound")
{
if (await new Promise<boolean>((resolve: any) => {
dialogs.confirm("Wold you like to define fake fact ${" + hint.variable + "}?", (result: boolean) =>
{
resolve(result);
})
}))
{
const value = await new Promise<string>((resolve: any) => {
dialogs.prompt("Enter a value for ${" + hint.variable + "}", "", (result: string) =>
{
resolve(result);
})
});
if (value == null)
return;
await ipc.setNodeFact(zis.nodePath, hint.variable, value);
await zis.refresh();
}
return;
}
}
*/
});
}
}
}
protected hasHints(): boolean
{
return this.info.hints != null && this.info.hints.length > 0;
}
protected getHints(): any[]
{
return this.info.hints;
}
protected getPropertyHints(propertyName: string): any[]
{
return this.info.propertyHints[propertyName];
}
protected getPropertyErrorInfo(propertyName: string): any
{
return this.info.errors[propertyName];
}
public getProperties(): Array<string>
{
if (this.info.classInfo == null)
return [];
return this.info.fields;
}
public get values(): any
{
return this.info.values;
}
public classInfo(): any
{
return this.info.classInfo;
}
protected getPropertyTypeInfo(propertyName: string): any
{
return this.info.types[propertyName];
}
protected getPropertyValue(propertyName: string): any
{
return this.values[propertyName];
}
protected isPropertyEncrypted(propertyName: string): boolean
{
return this.info.encrypted.indexOf(propertyName) >= 0;
}
protected getEncryptedPropertyRaw(propertyName: string): string
{
return (<EncryptedVariable>this.getPropertyValue(propertyName)).raw;
}
protected isValueModified(propertyName: string): number
{
return this.info.modified[propertyName];
}
protected isFieldRequired(propertyName: string): boolean
{
return this.info.requiredFields.indexOf(propertyName) >= 0;
}
protected async setProperty(propertyName: string, value: any)
{
await ipc.setNodeClassProperty(this.environment, this.certname,
this.hierarchyLevel, this.className, propertyName, value);
await ipc.invalidateNodeClass(this.environment, this.certname, this.className);
}
protected async hasProperty(propertyName: string)
{
return await ipc.hasNodeClassProperty(this.environment, this.certname, this.className, propertyName);
}
protected async removeProperty(propertyName: string, hierarchyLevel: number)
{
await ipc.removeNodeClassProperty(this.environment, this.certname,
hierarchyLevel, this.className, propertyName);
await ipc.invalidateNodeClass(this.environment, this.certname, this.className);
}
public getIcon(): any
{
const iconData = this.info.icon;
if (iconData != null)
{
return $('<img class="node-entry-icon" src="' + iconData + '" style="width: 16px; height: 16px;">');
}
else
{
return $('<i class="fas fa-puzzle-piece"></i>');
}
}
private renderProperties(node: any)
{
const container = $('<div class="flex-container"></div>').appendTo(node);
const classFields = this.getProperties();
classFields.sort();
// required fields first
let hadRequiredField = false;
for (const fieldName of classFields)
{
if (!this.isFieldRequired(fieldName))
continue;
const inputGroup = $('<div class="node-class-property flex-item"></div>').appendTo(container);
this.renderProperty(fieldName, inputGroup, true);
hadRequiredField = true;
}
if (hadRequiredField)
{
$('<hr>').appendTo(container);
}
// non-required fields last
for (const fieldName of classFields)
{
if (this.isFieldRequired(fieldName))
continue;
const inputGroup = $('<div class="node-class-property flex-item"></div>').appendTo(container);
this.renderProperty(fieldName, inputGroup, false);
}
}
async release(): Promise<any>
{
}
get shortTitle(): string
{
return this.className;
}
get fullTitle(): string
{
return this.path.join("/");
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [amplifybackend](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsamplifyadmin.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Amplifybackend extends PolicyStatement {
public servicePrefix = 'amplifybackend';
/**
* Statement provider for service [amplifybackend](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsamplifyadmin.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to clone an existing Amplify Admin backend environment into a new Amplify Admin backend enviroment
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-environments-backendenvironmentname-clone.html#CloneBackend
*/
public toCloneBackend() {
return this.to('CloneBackend');
}
/**
* Grants permission to create a new Amplify Admin backend environment by Amplify appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend.html#CreateBackend
*/
public toCreateBackend() {
return this.to('CreateBackend');
}
/**
* Grants permission to create an API for an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api.html#CreateBackendAPI
*/
public toCreateBackendAPI() {
return this.to('CreateBackendAPI');
}
/**
* Grants permission to create an auth resource for an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-auth.html#CreateBackendAuth
*/
public toCreateBackendAuth() {
return this.to('CreateBackendAuth');
}
/**
* Grants permission to create a new Amplify Admin backend config by Amplify appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-config.html#CreateBackendConfig
*/
public toCreateBackendConfig() {
return this.to('CreateBackendConfig');
}
/**
* Grants permission to create an Amplify Admin challenge token by appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-challenge.html#CreateToken
*/
public toCreateToken() {
return this.to('CreateToken');
}
/**
* Grants permission to delete an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-environments-backendenvironmentname-remove.html#DeleteBackend
*/
public toDeleteBackend() {
return this.to('DeleteBackend');
}
/**
* Grants permission to delete an API of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api-backendenvironmentname-remove.html#DeleteBackendAPI
*/
public toDeleteBackendAPI() {
return this.to('DeleteBackendAPI');
}
/**
* Grants permission to delete an auth resource of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-auth-backendenvironmentname-remove.html#DeleteBackendAuth
*/
public toDeleteBackendAuth() {
return this.to('DeleteBackendAuth');
}
/**
* Grants permission to delete an Amplify Admin challenge token by appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-challenge-sessionid-remove.html#DeleteToken
*/
public toDeleteToken() {
return this.to('DeleteToken');
}
/**
* Grants permission to generate models for an API of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api-backendenvironmentname-generatemodels.html#GenerateBackendAPIModels
*/
public toGenerateBackendAPIModels() {
return this.to('GenerateBackendAPIModels');
}
/**
* Grants permission to retrieve an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Read
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-details.html#GetBackend
*/
public toGetBackend() {
return this.to('GetBackend');
}
/**
* Grants permission to retrieve an API of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Read
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api-backendenvironmentname-details.html#GetBackendAPI
*/
public toGetBackendAPI() {
return this.to('GetBackendAPI');
}
/**
* Grants permission to retrieve models for an API of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Read
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api-backendenvironmentname-getmodels.html#GetBackendAPIModels
*/
public toGetBackendAPIModels() {
return this.to('GetBackendAPIModels');
}
/**
* Grants permission to retrieve an auth resource of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Read
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-auth-backendenvironmentname-details.html#GetBackendAuth
*/
public toGetBackendAuth() {
return this.to('GetBackendAuth');
}
/**
* Grants permission to retrieve a job of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Read
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-job-backendenvironmentname-jobid.html#GetBackendJob
*/
public toGetBackendJob() {
return this.to('GetBackendJob');
}
/**
* Grants permission to retrieve an Amplify Admin challenge token by appId
*
* Access Level: Read
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-challenge-sessionid.html#GetToken
*/
public toGetToken() {
return this.to('GetToken');
}
/**
* Grants permission to import an existing auth resource of an Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-auth-backendenvironmentname.html#ImportBackendAuth
*/
public toImportBackendAuth() {
return this.to('ImportBackendAuth');
}
/**
* Grants permission to retrieve the jobs of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: List
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-job-backendenvironmentname.html#ListBackendJobs
*/
public toListBackendJobs() {
return this.to('ListBackendJobs');
}
/**
* Grants permission to delete all existing Amplify Admin backend environments by appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-remove.html#RemoveAllBackends
*/
public toRemoveAllBackends() {
return this.to('RemoveAllBackends');
}
/**
* Grants permission to delete an Amplify Admin backend config by Amplify appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-config-remove.html#RemoveBackendConfig
*/
public toRemoveBackendConfig() {
return this.to('RemoveBackendConfig');
}
/**
* Grants permission to update an API of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api-backendenvironmentname.html#UpdateBackendAPI
*/
public toUpdateBackendAPI() {
return this.to('UpdateBackendAPI');
}
/**
* Grants permission to update an auth resource of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-auth-backendenvironmentname.html#UpdateBackendAuth
*/
public toUpdateBackendAuth() {
return this.to('UpdateBackendAuth');
}
/**
* Grants permission to update an Amplify Admin backend config by Amplify appId
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-config-update.html#UpdateBackendConfig
*/
public toUpdateBackendConfig() {
return this.to('UpdateBackendConfig');
}
/**
* Grants permission to update a job of an existing Amplify Admin backend environment by appId and backendEnvironmentName
*
* Access Level: Write
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-job-backendenvironmentname-jobid.html#UpdateBackendJob
*/
public toUpdateBackendJob() {
return this.to('UpdateBackendJob');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CloneBackend",
"CreateBackend",
"CreateBackendAPI",
"CreateBackendAuth",
"CreateBackendConfig",
"CreateToken",
"DeleteBackend",
"DeleteBackendAPI",
"DeleteBackendAuth",
"DeleteToken",
"GenerateBackendAPIModels",
"ImportBackendAuth",
"RemoveAllBackends",
"RemoveBackendConfig",
"UpdateBackendAPI",
"UpdateBackendAuth",
"UpdateBackendConfig",
"UpdateBackendJob"
],
"Read": [
"GetBackend",
"GetBackendAPI",
"GetBackendAPIModels",
"GetBackendAuth",
"GetBackendJob",
"GetToken"
],
"List": [
"ListBackendJobs"
]
};
/**
* Adds a resource of type backend to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onBackend(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type environment to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api-backendenvironmentname-details.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onEnvironment(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}/environments';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type api to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-api.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onApi(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}/api';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type auth to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-auth.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onAuth(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}/auth';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type job to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-job-backendenvironmentname.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onJob(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}/job';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type config to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-config.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onConfig(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}/config';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type token to the statement
*
* https://docs.aws.amazon.com/amplify-admin-ui/latest/APIReference/backend-appid-token.html
*
* @param appId - Identifier for the appId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onToken(appId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:amplifybackend:${Region}:${Account}:backend/${AppId}/token';
arn = arn.replace('${AppId}', appId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import ClientExtensionEventNames from "./ClientExtensionEventNames";
import HostInteropType from "../interop";
// Entry point for web view extensions -- extensions that live inside the web view
interface EventSubscription {
eventName: string;
callback: (data: any) => any;
}
/**
* Implements an event dispatcher for the client services
*/
export class EventDispatcher implements Editor.Extensions.EventDispatcher {
private subscriptions: EventSubscription[] = [];
sendEvent<T extends Atomic.EventCallbackMetaData>(eventCallbackMetaData:T)
sendEvent(eventType: string, data: any)
sendEvent(eventTypeOrWrapped: any, data?: any) {
let eventType: string;
let eventData: any;
if (typeof(eventTypeOrWrapped) == "string") {
eventType = eventTypeOrWrapped;
eventData = data;
} else {
const metaData = eventTypeOrWrapped as Atomic.EventCallbackMetaData;
eventType = metaData._eventType;
eventData = metaData._callbackData;
}
this.subscriptions.forEach(sub => {
if (sub.eventName == eventType) {
sub.callback(eventData);
}
});
}
subscribeToEvent(eventType: string, callback: (...params) => any);
subscribeToEvent(wrapped: Atomic.EventMetaData);
subscribeToEvent(eventTypeOrWrapped: any, callback?: any) {
if (callback) {
this.subscriptions.push({
eventName: eventTypeOrWrapped,
callback: callback
});
} else {
this.subscriptions.push({
eventName: eventTypeOrWrapped._eventType,
callback: eventTypeOrWrapped._callback
});
}
}
}
/**
* Generic registry for storing Editor Extension Services
*/
class ServicesProvider<T extends Editor.Extensions.ServiceEventListener> implements Editor.Extensions.ServicesProvider<T> {
registeredServices: T[] = [];
/**
* Adds a service to the registered services list for this type of service
* @param {T} service the service to register
*/
register(service: T) {
this.registeredServices.push(service);
}
unregister(service: T) {
var index = this.registeredServices.indexOf(service, 0);
if (index > -1) {
this.registeredServices.splice(index, 1);
}
}
}
export class WebViewServicesProvider extends ServicesProvider<Editor.ClientExtensions.WebViewServiceEventListener> {
private projectPreferences = {};
private applicationPreferences = {};
/**
* Sets the preferences for the service locator
* @param {any} projectPreferences
* @param {any} applicationPreferences
* @return {[type]}
*/
setPreferences(projectPreferences?: any, applicationPreferences?: any) {
this.projectPreferences = projectPreferences || this.projectPreferences;
this.applicationPreferences = applicationPreferences || this.applicationPreferences;
}
/**
* Allow this service registry to subscribe to events that it is interested in
* @param {EventDispatcher} eventDispatcher The global event dispatcher
*/
subscribeToEvents(eventDispatcher: Editor.Extensions.EventDispatcher) {
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.CodeLoadedEvent, (ev) => this.codeLoaded(ev));
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.ConfigureEditorEvent, (ev) => this.configureEditor(ev));
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.ResourceRenamedEvent, (ev) => this.renameResource(ev));
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.ResourceDeletedEvent, (ev) => this.deleteResource(ev));
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.CodeSavedEvent, (ev) => this.saveCode(ev));
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.PreferencesChangedEvent, (ev) => this.preferencesChanged(ev));
eventDispatcher.subscribeToEvent(ClientExtensionEventNames.FormatCodeEvent, (ev) => this.formatCode());
}
/**
* Called when code is loaded
* @param {Editor.ClientExtensions.CodeLoadedEvent} ev Event info about the file that is being loaded
*/
codeLoaded(ev: Editor.ClientExtensions.CodeLoadedEvent) {
this.registeredServices.forEach((service) => {
try {
// Notify services that the project has just been loaded
if (service.codeLoaded) {
service.codeLoaded(ev);
}
} catch (e) {
alert(`Extension Error:\n Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Called after code has been saved
* @param {Editor.ClientExtensions.SaveResourceEvent} ev
*/
saveCode(ev: Editor.ClientExtensions.CodeSavedEvent) {
// run through and find any services that can handle this.
this.registeredServices.forEach((service) => {
try {
// Verify that the service contains the appropriate methods and that it can save
if (service.save) {
service.save(ev);
}
} catch (e) {
alert(`Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Called when a resource has been deleted
*/
deleteResource(ev: Editor.ClientExtensions.DeleteResourceEvent) {
this.registeredServices.forEach((service) => {
try {
// Verify that the service contains the appropriate methods and that it can delete
if (service.delete) {
service.delete(ev);
}
} catch (e) {
alert(`Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Called when a resource has been renamed
* @param {Editor.ClientExtensions.RenameResourceEvent} ev
*/
renameResource(ev: Editor.ClientExtensions.RenameResourceEvent) {
this.registeredServices.forEach((service) => {
try {
// Verify that the service contains the appropriate methods and that it can handle the rename
if (service.rename) {
service.rename(ev);
}
} catch (e) {
alert(`Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Called when the editor code should be formatted
*/
formatCode() {
this.registeredServices.forEach((service) => {
try {
// Verify that the service contains the appropriate methods and that it can handle the rename
if (service.formatCode) {
service.formatCode();
}
} catch (e) {
alert(`Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Called when the editor is requesting to be configured for a particular file
* @param {Editor.ClientExtensions.EditorFileEvent} ev
*/
configureEditor(ev: Editor.ClientExtensions.EditorFileEvent) {
this.registeredServices.forEach((service) => {
try {
// Notify services that the project has just been loaded
if (service.configureEditor) {
service.configureEditor(ev);
}
} catch (e) {
alert(`Extension Error:\n Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Called when preferences changes
* @param {Editor.EditorEvents.PreferencesChangedEvent} ev
*/
preferencesChanged(prefs: Editor.ClientExtensions.PreferencesChangedEventData) {
this.registeredServices.forEach((service) => {
// Notify services that the project has been unloaded
try {
if (service.preferencesChanged) {
service.preferencesChanged(prefs);
}
} catch (e) {
alert(`Extension Error:\n Error detected in extension ${service.name}\n \n ${e.stack}`);
}
});
}
/**
* Returns the Host Interop module
* @return {Editor.ClientExtensions.HostInterop}
*/
getHostInterop(): Editor.ClientExtensions.HostInterop {
return HostInteropType.getInstance();
}
/**
* Return a preference value or the provided default from the user settings file
* @param {string} settignsGroup name of the group the preference lives under
* @param {string} preferenceName name of the preference to retrieve
* @param {number | boolean | string} defaultValue value to return if pref doesn't exist
* @return {number|boolean|string}
*/
getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number;
getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string;
getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean;
getUserPreference(settingsGroup: string, preferenceName: string, defaultValue?: any): any {
if (this.projectPreferences) {
let prefs = this.projectPreferences[settingsGroup];
if (prefs) {
return prefs[preferenceName] || defaultValue;
}
}
// if all else fails
return defaultValue;
}
/**
* Return a preference value or the provided default from the user settings file
* @param {string} settignsGroup name of the group the preference lives under
* @param {string} preferenceName name of the preference to retrieve
* @param {number | boolean | string} defaultValue value to return if pref doesn't exist
* @return {number|boolean|string}
*/
getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: number): number;
getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: string): string;
getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: boolean): boolean;
getApplicationPreference(settingsGroup: string, preferenceName: string, defaultValue?: any): any {
if (this.applicationPreferences) {
let prefs = this.applicationPreferences[settingsGroup];
if (prefs) {
return prefs[preferenceName] || defaultValue;
}
}
// if all else fails
return defaultValue;
}
} | the_stack |
import { mocked } from 'ts-jest/utils';
import { bigNumber, warning } from '../../core/src/utils';
import { hexSequenceNormalizer } from '../../core/src/normalizers';
import { hexSequenceValidator } from '../../core/src/validators';
import {
recoverPublicKey as recoverPublicKeyHelper,
userInputValidator,
} from '../../core/src/helpers';
import {
HEX_HASH_TYPE,
REQUIRED_PROPS,
WalletType,
WalletSubType,
} from '../../core/src/constants';
import MetaMaskWallet from '../src/MetaMaskWallet';
import { methodCaller } from '../src/helpers';
import {
signTransaction,
signMessage,
verifyMessage,
} from '../src/staticMethods';
import { PUBLICKEY_RECOVERY_MESSAGE, STD_ERRORS } from '../src/constants';
jest.mock('ethers/providers');
jest.mock('../../core/src/validators');
jest.mock('../../core/src/helpers');
jest.mock('../../core/src/normalizers');
jest.mock('../../core/src/utils');
jest.mock('../src/staticMethods');
jest.mock('../src/helpers');
const mockedHexSequenceNormalizer = mocked(hexSequenceNormalizer);
const mockedHexSequenceValidator = mocked(hexSequenceValidator);
const mockedRecoverPublicKeyHelper = mocked(recoverPublicKeyHelper);
const mockedWarning = mocked(warning);
const mockedBufferFrom = jest.spyOn(Buffer, 'from');
const mockedBufferToString = jest.spyOn(Buffer.prototype, 'toString');
const mockedMessageSignature = 'mocked-message-signature';
/*
* These values are not correct. Do not use the as reference.
* If the validators wouldn't be mocked, they wouldn't pass.
*/
const mockedPublicKey = 'recovered-mocked-public-key';
const address = 'mocked-address';
const mockedTransactionObject = {
to: 'mocked-destination-address',
value: bigNumber(33),
chainId: 1,
gasPrice: bigNumber(44),
gasLimit: bigNumber(45),
nonce: 1,
inputData: '1',
};
const mockedMessage = 'mocked-message';
const mockedMessageObject = {
currentAddress: '0xdeaffeed',
message: mockedMessage,
messageData: 'data',
};
const mockedSignatureObject = {
address: '0xacab',
message: mockedMessage,
signature: 'mocked-signature',
};
describe('Metamask` Wallet Module', () => {
describe('`MetamaskWallet` class', () => {
afterEach(() => {
mockedHexSequenceNormalizer.mockClear();
mockedHexSequenceValidator.mockClear();
mockedRecoverPublicKeyHelper.mockClear();
mockedBufferFrom.mockClear();
});
test('Creates a new wallet instance', () => {
const metamaskWallet = new MetaMaskWallet({
address,
});
/*
* It should be an instance
*/
expect(metamaskWallet).toBeInstanceOf(MetaMaskWallet);
});
test('Detects the injected proxy before adding the observer', async () => {
/* eslint-disable-next-line no-new */
new MetaMaskWallet({ address });
/*
* Call the helper method
*/
expect(methodCaller).toHaveBeenCalled();
});
test('The Wallet Instance has the required (correct) props', () => {
const metamaskWallet = new MetaMaskWallet({ address });
/*
* Address
*/
expect(metamaskWallet).toHaveProperty('address');
/*
* Type and subtyp
*/
expect(metamaskWallet).toHaveProperty('type', WalletType.Software);
expect(metamaskWallet).toHaveProperty('subtype', WalletSubType.MetaMask);
/*
* `sign()` method
*/
expect(metamaskWallet).toHaveProperty('sign');
/*
* `signMessage()` method
*/
expect(metamaskWallet).toHaveProperty('signMessage');
/*
* `verifyMessage()` method
*/
expect(metamaskWallet).toHaveProperty('verifyMessage');
});
test('Calls the correct method to sign a transaction', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.sign(mockedTransactionObject);
expect(signTransaction).toHaveBeenCalled();
});
test('Validates the input before signing a transaction', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.sign(mockedTransactionObject);
expect(userInputValidator).toHaveBeenCalled();
expect(userInputValidator).toHaveBeenCalledWith({
firstArgument: mockedTransactionObject,
});
});
test('Sign a transaction without a destination address', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await expect(
metamaskWallet.sign({ ...mockedTransactionObject, to: undefined }),
).resolves.not.toThrow();
});
test('Calls the correct method to sign a message', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.signMessage(mockedMessageObject);
expect(signMessage).toHaveBeenCalled();
});
test('Validates the input before signing a message', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.signMessage(mockedMessageObject);
expect(userInputValidator).toHaveBeenCalled();
expect(userInputValidator).toHaveBeenCalledWith({
firstArgument: mockedMessageObject,
requiredOr: REQUIRED_PROPS.SIGN_MESSAGE,
});
});
test('Calls the correct method to verify a message', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.verifyMessage(mockedSignatureObject);
expect(verifyMessage).toHaveBeenCalled();
});
test('Validates the input before verifying a signature', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.verifyMessage(mockedSignatureObject);
expect(userInputValidator).toHaveBeenCalled();
expect(userInputValidator).toHaveBeenCalledWith({
firstArgument: mockedSignatureObject,
requiredAll: REQUIRED_PROPS.VERIFY_MESSAGE,
});
});
test('Normalizes the recovery message and makes it a hex String', () => {
const metamaskWallet = new MetaMaskWallet({ address });
metamaskWallet.recoverPublicKey(address);
/*
* Normalizes the hex string
*/
expect(hexSequenceNormalizer).toHaveBeenCalled();
expect(hexSequenceNormalizer).toHaveBeenCalledWith(
Buffer.from(PUBLICKEY_RECOVERY_MESSAGE).toString('hex'),
);
/*
* Uses the Buffer class to transform the message into a hex string
*
* First it makes it a Buffer instance
*/
expect(mockedBufferFrom).toHaveBeenCalled();
expect(mockedBufferFrom).toHaveBeenCalledWith(PUBLICKEY_RECOVERY_MESSAGE);
/*
* Then it converts it into a hex string
*/
expect(mockedBufferToString).toHaveBeenCalled();
expect(mockedBufferToString).toHaveBeenCalledWith(HEX_HASH_TYPE);
});
test('Validates the message signature returned', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
jest
.spyOn(metamaskWallet, 'signMessage')
.mockImplementationOnce(() => Promise.resolve(mockedMessageSignature));
await metamaskWallet.recoverPublicKey(address);
/*
* Validates the signature
*/
expect(hexSequenceValidator).toHaveBeenCalled();
expect(hexSequenceValidator).toHaveBeenCalledWith(mockedMessageSignature);
});
test('Recovers the public key from the signature', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
jest
.spyOn(metamaskWallet, 'signMessage')
.mockImplementationOnce(() => Promise.resolve(mockedMessageSignature));
await metamaskWallet.recoverPublicKey(address);
/*
* Validates the signature
*/
expect(mockedRecoverPublicKeyHelper).toHaveBeenCalled();
expect(mockedRecoverPublicKeyHelper).toHaveBeenCalledWith({
message: PUBLICKEY_RECOVERY_MESSAGE,
signature: mockedMessageSignature,
});
});
test('Normalizes the recovered public key before returning', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await metamaskWallet.recoverPublicKey(address);
/*
* Validates the signature
*/
expect(hexSequenceNormalizer).toHaveBeenCalled();
});
test('Resolves the promise and returns the public key', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
await expect(metamaskWallet.recoverPublicKey(address)).resolves.toEqual(
mockedPublicKey,
);
});
test('Throws if something goes wrong while signing', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
/*
* Mock it locally to simulate an error
*/
mockedRecoverPublicKeyHelper.mockImplementationOnce(() => {
throw new Error('err');
});
await expect(metamaskWallet.recoverPublicKey(address)).rejects.toThrow(
'err',
);
});
test('Warns if the user cancelled signing the message', async () => {
const metamaskWallet = new MetaMaskWallet({ address });
/*
* Mock it locally to simulate the user cancelling the sign message popup
*/
jest.spyOn(metamaskWallet, 'signMessage').mockImplementationOnce(() => {
throw new Error(STD_ERRORS.CANCEL_MSG_SIGN);
});
/*
* Mock it locally so we can test the return
*/
mockedWarning.mockImplementationOnce(() => STD_ERRORS.CANCEL_MSG_SIGN);
const cancelledMessageSign = metamaskWallet.recoverPublicKey(address);
/*
* It doesn't throw
*/
await expect(cancelledMessageSign).resolves.not.toThrow();
/*
* It warns the user
*/
expect(mockedWarning).toHaveBeenCalled();
await expect(cancelledMessageSign).resolves.toEqual(
STD_ERRORS.CANCEL_MSG_SIGN,
);
});
test('Returns the public key getter by signing a message', async () => {
const metamaskWallet = new MetaMaskWallet({
address: 'some weird address',
});
const publicKey = await metamaskWallet.getPublicKey();
expect(publicKey).toEqual(mockedPublicKey);
});
});
}); | the_stack |
import { isNode } from 'browser-or-node';
import Pino from 'pino';
import { IGunChainReference } from 'gun/types/chain';
import { IGunStatic } from 'gun/types/static';
import { BucketMetadata,
FileMetadata,
SharedFileMetadata,
ShareUserMetadata,
UserMetadataStore } from './metadataStore';
let Gun: IGunStatic;
if (isNode) {
Gun = require('gun');
} else {
Gun = require('gun/gun');
require('gun/sea');
require('gun/lib/radix');
require('gun/lib/radisk');
require('gun/lib/store');
require('gun/lib/rindexed');
}
// this is an hack to enable using IGunChainReference in async functions
export type GunChainReference<Data> = Omit<IGunChainReference<Data>, 'then'>;
const BucketMetadataCollection = 'BucketMetadata';
const SharedFileMetadataCollection = 'SharedFileMetadata';
const SharedByMeFileMetadataCollection = 'SharedByMeFileMetadata';
const RecentlySharedWithMetadataCollection = 'RecentlySharedWithMetadata';
const NotificationsLastSeenAtCollection = 'NotificationsLastSeenAtMetadata';
const PublicStoreUsername = '66f47ce32570335085b39bdf';
const PublicStorePassword = '830a20694358651ef14e472fd71c4f9f843ecd50784b241a6c9999dba4c6fced0f90c686bdee28edc';
interface AckError {
err: string;
}
// Remapped bucket metadata type compatible with Gundb
type GunBucketMetadata = Omit<BucketMetadata, 'encryptionKey'> & { encryptionKey: string };
type GunFileMetadata = { data: string };
type EncryptedMetadata = { data: string; };
interface LookupDataState {
[dbIdBucket: string]: EncryptedMetadata;
}
interface LookupFileMetadataState {
[lookupId: string]: GunFileMetadata;
}
interface ListDataState {
[collectionName: string]: EncryptedMetadata[]
}
// Data schema of records stored in gundb
// currently only a single bucket metadata collection
export type GunDataState = LookupDataState | ListDataState | LookupFileMetadataState;
type GunInit = (() => GunChainReference<GunDataState>);
/**
* A Users Storage Metadata store backed by gundsdb.
*
* This is the default MetadataStore used by {@link @spacehq/sdk#UserStorage}.
*
*/
export class GundbMetadataStore implements UserMetadataStore {
private gunInit: GunInit;
// in memory cache list of buckets
private readonly bucketsListCache: BucketMetadata[];
private readonly sharedFilesListCache: SharedFileMetadata[];
private readonly sharedByMeFilesListCache: SharedFileMetadata[];
private readonly recentlySharedWithListCache: ShareUserMetadata[];
private _user?: GunChainReference<GunDataState>;
private _publicUser?: GunChainReference<GunDataState>;
private logger?: Pino.Logger;
/**
* Creates a new instance of this metadata store for users identity.
*
*/
private constructor(
private readonly username: string,
private readonly userpass: string,
gunOrServer?: GunInit | string | string[],
logger?: Pino.Logger | boolean,
) {
if (gunOrServer) {
if (typeof gunOrServer === 'string' || Array.isArray(gunOrServer)) {
this.gunInit = () => Gun(gunOrServer);
} else {
this.gunInit = gunOrServer;
}
} else {
this.gunInit = () => Gun({
localStorage: false,
radisk: true,
peers: 'https://gun.space.storage/gun',
} as any);
}
this.bucketsListCache = [];
this.sharedFilesListCache = [];
this.sharedByMeFilesListCache = [];
this.recentlySharedWithListCache = [];
if (logger) {
if (typeof logger === 'boolean') {
this.logger = Pino({ enabled: logger || false, level: 'trace' });
} else {
this.logger = logger;
}
this.logger = this.logger.child({ storeUser: username });
}
}
/**
* Creates a new instance of this metadata store for users identity.
*
* @param username - Username of user
* @param userpass - Password of user
* @param gunOrServer - initialized gun instance or peer server
* @param logger - Optional pino logger instance for debug mode
*/
static async fromIdentity(
username: string,
userpass: string,
gunOrServer?: GunInit | string | string[],
logger?: Pino.Logger | boolean,
): Promise<GundbMetadataStore> {
const store = new GundbMetadataStore(username, userpass, gunOrServer, logger);
store._user = store.gunInit().user();
await store.authenticateUser(store._user, username, userpass);
store._publicUser = store.gunInit().user();
await store.authenticateUser(store._publicUser, PublicStoreUsername, PublicStorePassword);
await store.startCachingBucketsList();
await store.startCachingList(SharedFileMetadataCollection, store.sharedFilesListCache);
await store.startCachingList(SharedByMeFileMetadataCollection, store.sharedByMeFilesListCache);
await store.startCachingList(RecentlySharedWithMetadataCollection, store.recentlySharedWithListCache);
return store;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.createBucket}
*/
public async createBucket(bucketSlug: string, dbId: string, bucketKey: string): Promise<BucketMetadata> {
// throw if dbId with bucketSlug doesn't already
const existingBucket = await this.findBucket(bucketSlug);
if (existingBucket) {
throw new Error('Bucket with slug and dbId already exists');
}
const schema: BucketMetadata = {
dbId,
slug: bucketSlug,
bucketKey,
};
const encryptedMetadata = await this.encryptBucketSchema(schema);
const lookupKey = this.getBucketsLookupKey(bucketSlug);
const nodeRef = this.lookupUser.get(lookupKey).put(encryptedMetadata);
// store in list too. the unknown cast is required because of typescripts limitation
// but it to ensure that the set has a reference to the actual data
this.listUser.get(BucketMetadataCollection).set(nodeRef as unknown as EncryptedMetadata);
return schema;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.setNotificationsLastSeenAt}
*/
public async setNotificationsLastSeenAt(timestamp: number): Promise<void> {
const encryptedTimestamp = await this.encrypt(timestamp.toString());
const lookupKey = GundbMetadataStore.getNotificationsLastSeenAtLookupKey();
const nodeRef = this.lookupUser.get(lookupKey).put({ data: encryptedTimestamp });
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.getNotificationsLastSeenAt}
*/
public async getNotificationsLastSeenAt(): Promise<number> {
this.logger?.info({ username: this.username }, 'Store.getNotificationsLastSeenAt');
const lookupKey = GundbMetadataStore.getNotificationsLastSeenAtLookupKey();
const res:number|undefined = await this.lookupUserData(lookupKey);
return res || 0;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.findBucket}
*/
public async findBucket(bucketSlug: string): Promise<BucketMetadata | undefined> {
this.logger?.info({ bucketSlug }, 'Store.findBucket');
const lookupKey = this.getBucketsLookupKey(bucketSlug);
const encryptedData = await new Promise<string | undefined>((resolve, reject) => {
this.lookupUser.get(lookupKey).get('data').once((data) => {
if (!data) {
this.logger?.info({ bucketSlug }, 'Bucket Metadata not found');
return resolve(undefined);
}
this.logger?.info({ bucketSlug }, 'Bucket Metadata found');
return resolve(data);
});
});
// unregister lookup
this.lookupUser.get(lookupKey).off();
if (!encryptedData) {
return undefined;
}
return this.decryptBucketSchema({ data: encryptedData });
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.listBuckets}
*/
public async listBuckets(): Promise<BucketMetadata[]> {
return this.bucketsListCache;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.upsertFileMetadata}
*/
public async upsertFileMetadata(
metadata: FileMetadata,
): Promise<FileMetadata> {
const { bucketSlug, dbId, path } = metadata;
const lookupKey = GundbMetadataStore.getFilesLookupKey(bucketSlug, dbId, path);
const existingFileMetadata = await this.findFileMetadata(bucketSlug, dbId, path);
let updatedMetadata = metadata;
if (existingFileMetadata) {
updatedMetadata = {
...existingFileMetadata,
...metadata,
};
}
this.logger?.info({ updatedMetadata }, 'Upserting metadata');
const encryptedMetadata = await this.encrypt(JSON.stringify(updatedMetadata));
this.lookupUser.get(lookupKey).put({ data: encryptedMetadata });
if (updatedMetadata.uuid) {
// store a lookup record of the file by uuid
this.lookupUser.get(GundbMetadataStore.getFilesUuidLookupKey(updatedMetadata.uuid))
.put({ data: encryptedMetadata });
}
return updatedMetadata;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.findFileMetadata}
*/
public async findFileMetadata(
bucketSlug:string,
dbId: string,
path: string,
): Promise<FileMetadata | undefined> {
this.logger?.info({ bucketSlug, dbId, path }, 'Store.findFileMetadata');
const lookupKey = GundbMetadataStore.getFilesLookupKey(bucketSlug, dbId, path);
return this.lookupUserData(lookupKey);
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.findFileMetadataByUuid}
*/
public async findFileMetadataByUuid(uuid: string): Promise<FileMetadata | undefined> {
this.logger?.info({ uuid }, 'Store.findFileMetadataByUuid');
const lookupKey = GundbMetadataStore.getFilesUuidLookupKey(uuid);
// NOTE: This can be speedup by making this fetch promise a race instead of sequential
return this.lookupUserData<FileMetadata>(lookupKey)
.then((data) => {
if (!data) {
return this.lookupPublicFileMetadata(lookupKey);
}
return data;
});
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.setFilePublic}
*/
public async setFilePublic(metadata: FileMetadata): Promise<void> {
if (metadata.uuid === undefined) {
throw new Error('metadata file must have a uuid');
}
const lookupKey = GundbMetadataStore.getFilesUuidLookupKey(metadata.uuid);
this.logger?.info({ metadata, lookupKey }, 'Making file metadata public');
this.publicLookupChain.get(lookupKey).put({ data: JSON.stringify(metadata) });
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.upsertSharedWithMeFile}
*/
public async upsertSharedWithMeFile(fileData: SharedFileMetadata): Promise<SharedFileMetadata> {
const { bucketSlug, dbId, path } = fileData;
const lookupKey = GundbMetadataStore.getFilesLookupKey(bucketSlug, dbId, path);
const existingFileMetadata = await this.lookupUserData<SharedFileMetadata>(lookupKey);
let updatedMetadata = fileData;
if (existingFileMetadata) {
updatedMetadata = {
...existingFileMetadata,
...fileData,
};
}
this.logger?.info({ updatedMetadata }, 'Upserting upsertSharedWithMeFile');
const encryptedMetadata = await this.encrypt(JSON.stringify(updatedMetadata));
const nodeRef = this.lookupUser.get(lookupKey).put({ data: encryptedMetadata });
// track via invitationId
if (updatedMetadata.invitationId) {
this.lookupUser
.get(GundbMetadataStore.getFilesInvitationLookupKey(updatedMetadata.invitationId))
.put({ data: encryptedMetadata });
}
if (updatedMetadata.uuid) {
this.lookupUser.get(GundbMetadataStore.getFilesUuidLookupKey(updatedMetadata.uuid))
.put({ data: encryptedMetadata });
}
this.listUser.get(SharedFileMetadataCollection).set(nodeRef as unknown as EncryptedMetadata);
return updatedMetadata;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.findSharedFilesByInvitation}
*/
async findSharedFilesByInvitation(invitationId: string): Promise<SharedFileMetadata | undefined> {
this.logger?.info({ invitationId }, 'Store.findSharedFilesByInvitation');
const lookupKey = GundbMetadataStore.getFilesInvitationLookupKey(invitationId);
return this.lookupUserData(lookupKey);
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.listSharedWithMeFiles}
*/
public async listSharedWithMeFiles(): Promise<SharedFileMetadata[]> {
return new Promise((resolve) => {
setTimeout(() => { resolve(this.sharedFilesListCache); }, 1000);
});
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.upsertSharedByMeFile}
*/
public async upsertSharedByMeFile(fileData: SharedFileMetadata): Promise<SharedFileMetadata> {
const { bucketSlug, dbId, path } = fileData;
const lookupKey = GundbMetadataStore.getSharedByMeLookupKey(bucketSlug, dbId, path);
const existingFileMetadata = await this.lookupUserData<SharedFileMetadata>(lookupKey);
let updatedMetadata = fileData;
if (existingFileMetadata) {
updatedMetadata = {
...existingFileMetadata,
...fileData,
};
}
this.logger?.info({ updatedMetadata }, 'Upserting upsertSharedByMeFile');
const encryptedMetadata = await this.encrypt(JSON.stringify(updatedMetadata));
const nodeRef = this.lookupUser.get(lookupKey).put({ data: encryptedMetadata });
this.listUser.get(SharedByMeFileMetadataCollection).set(nodeRef as unknown as EncryptedMetadata);
return updatedMetadata;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.listSharedByMeFiles}
*/
public async listSharedByMeFiles(): Promise<SharedFileMetadata[]> {
return new Promise((resolve) => {
setImmediate(() => { resolve(this.sharedByMeFilesListCache); });
});
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.addUserRecentlySharedWith}
*/
public async addUserRecentlySharedWith(user: ShareUserMetadata): Promise<ShareUserMetadata> {
const lookupKey = GundbMetadataStore.getRecentSharedLookupKey(user.publicKey);
const existingUser = await this.lookupUserData<ShareUserMetadata>(lookupKey);
let updatedUser = user;
if (existingUser) {
updatedUser = {
...existingUser,
...user,
};
}
this.logger?.info({ updatedUser }, 'Upserting addUserRecentlySharedWith');
const encryptedMetadata = await this.encrypt(JSON.stringify(updatedUser));
const nodeRef = this.lookupUser.get(lookupKey).put({ data: encryptedMetadata });
this.listUser.get(RecentlySharedWithMetadataCollection).set(nodeRef as unknown as EncryptedMetadata);
return updatedUser;
}
/**
* {@inheritDoc @spacehq/sdk#UserMetadataStore.listUsersRecentlySharedWith}
*/
public async listUsersRecentlySharedWith(): Promise<ShareUserMetadata[]> {
return new Promise((resolve) => {
setTimeout(() => { resolve(this.recentlySharedWithListCache); }, 1000);
});
}
private async lookupUserData<T>(lookupKey: string): Promise<T | undefined> {
return new Promise<T | undefined>((resolve, reject) => {
// using ts-ignore to allow extra non-documented parameters on callback
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
this.lookupUser.get(lookupKey).get('data').once(async (
encryptedData: any,
) => {
if (!encryptedData) {
this.logger?.info({ lookupKey }, 'FileMetadata not found');
resolve(undefined);
return;
}
try {
const decryptedMetadata = await this.decrypt<T>(encryptedData);
this.logger?.debug({ decryptedMetadata, lookupKey }, 'FileMetadata found');
resolve(decryptedMetadata);
} catch (e) {
reject(e);
}
});
});
}
private async lookupPublicFileMetadata(lookupKey: string): Promise<FileMetadata | undefined> {
return new Promise<FileMetadata | undefined>((resolve, reject) => {
this.publicLookupChain.get(lookupKey).get('data').once((data) => {
if (!data) {
this.logger?.info({ lookupKey }, 'Public FileMetadata not found');
resolve(undefined);
return;
}
this.logger?.info({ lookupKey }, 'Public FileMetadata found');
resolve(JSON.parse(data));
});
});
}
private async startCachingBucketsList(): Promise<void> {
this.listUser.get(BucketMetadataCollection).map().once(async (data) => {
if (data) {
try {
const decryptedData = await this.decryptBucketSchema(data);
this.bucketsListCache.push(decryptedData);
} catch (err) {
// an error occurred. most likely not our data
}
}
});
// wait a few seconds so results would start filling cache before returning
await new Promise((resolve) => setTimeout(resolve, 3000));
}
private async startCachingList<T>(collection: string, cache: T[]): Promise<void> {
this.listUser.get(collection).map().once(async (data) => {
if (data) {
try {
const decryptedData = await this.decrypt<T>(data.data);
if (decryptedData) {
cache.push(decryptedData);
}
} catch (err) {
// an error occurred. most likely not our data
}
}
});
}
private static getNotificationsLastSeenAtLookupKey(): string {
return 'notifications/lastSeenAt';
}
private getBucketsLookupKey(bucketSlug: string): string {
return `bucketSchema/${bucketSlug}/${this.username}`;
}
private static getFilesLookupKey(bucketSlug: string, dbId: string, path: string): string {
return `fileMetadata/${bucketSlug}/${dbId}/${path}`;
}
private static getFilesInvitationLookupKey(invitationId: string): string {
return `sharedFileIv/${invitationId}`;
}
private static getSharedByMeLookupKey(bucketSlug: string, dbId: string, path: string): string {
return `sharedByMe/${bucketSlug}/${dbId}/${path}`;
}
private static getRecentSharedLookupKey(publicKey: string): string {
return `recentlySharedWith/${publicKey}`;
}
private static getFilesUuidLookupKey(uuid: string): string {
return `/fuuid/${uuid}`;
}
private get user(): GunChainReference<GunDataState> {
if (!this._user || !(this._user as unknown as { is?: Record<never, never>; }).is) {
throw new Error('gundb user not authenticated');
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._user!;
}
private get publicUser(): GunChainReference<GunDataState> {
if (!this._publicUser || !(this._publicUser as unknown as { is?: Record<never, never>; }).is) {
throw new Error('gundb user not authenticated');
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._publicUser!;
}
// use this alias getter for lookuping up users metadata so typescript works as expected
private get lookupUser(): GunChainReference<LookupDataState> {
return this.user as GunChainReference<LookupDataState>;
}
// use this alias getter for listening to users metadata list so typescript works as expected
private get listUser(): GunChainReference<ListDataState> {
return this.user as GunChainReference<ListDataState>;
}
private get publicLookupChain(): GunChainReference<LookupFileMetadataState> {
return this.publicUser as GunChainReference<LookupFileMetadataState>;
}
// eslint-disable-next-line class-methods-use-this
private async authenticateUser<T>(
user: GunChainReference<T>,
username: string,
userpass: string,
): Promise<void> {
this.logger?.info({ username }, 'Authenticating user');
// user.is checks if user is currently logged in
if ((user as unknown as { is?: Record<never, never>; }).is) {
this.logger?.info({ username }, 'User already authenticated');
return;
}
await new Promise((resolve, reject) => {
user.create(username, userpass, (ack) => {
// if ((ack as AckError).err) {
// // error here means user either exists or is being created, see gundb user docs.
// // so ignoring
// return;
// }
user.auth(username, userpass, (auth) => {
if ((auth as AckError).err) {
reject(new Error(`gundb failed to authenticate user: ${(auth as AckError).err}`));
return;
}
resolve();
});
});
});
}
// encrypts data with users private key
private async encrypt(data: string): Promise<string> {
return Gun.SEA.encrypt(data, this.userpass);
}
private async decrypt<T>(data: string): Promise<T | undefined> {
return ((Gun.SEA.decrypt(data, this.userpass)) as Promise<T | undefined>);
}
private async encryptBucketSchema(schema: BucketMetadata): Promise<EncryptedMetadata> {
return {
data: await this.encrypt(JSON.stringify(schema)),
};
}
private async decryptBucketSchema(encryptedSchema: EncryptedMetadata): Promise<BucketMetadata> {
const gunschema = await this.decrypt<GunBucketMetadata>(encryptedSchema.data);
if (!gunschema) {
throw new Error('Unknown bucket metadata');
}
return gunschema;
}
} | the_stack |
'use strict';
export class NamespaceScope {
parent: any;
namespaces: any;
constructor(parent: any) {
if (!(this instanceof NamespaceScope)) {
return new NamespaceScope(parent);
}
this.parent = parent;
this.namespaces = {};
}
getNamespaceURI = function(prefix, localOnly) {
switch (prefix) {
case 'xml':
return 'http://www.w3.org/XML/1998/namespace';
case 'xmlns':
return 'http://www.w3.org/2000/xmlns/';
default:
var nsUri = this.namespaces[prefix];
/*jshint -W116 */
if (nsUri != null) {
return nsUri.uri;
} else if (!localOnly && this.parent) {
return this.parent.getNamespaceURI(prefix);
} else {
return null;
}
}
}
getNamespaceMapping = function(prefix) {
switch (prefix) {
case 'xml':
return {
uri: 'http://www.w3.org/XML/1998/namespace',
prefix: 'xml',
declared: true
};
case 'xmlns':
return {
uri: 'http://www.w3.org/2000/xmlns/',
prefix: 'xmlns',
declared: true
};
default:
var mapping = this.namespaces[prefix];
/*jshint -W116 */
if (mapping != null) {
return mapping;
} else if (this.parent) {
return this.parent.getNamespaceMapping(prefix);
} else {
return null;
}
}
}
getPrefix = function(nsUri, localOnly) {
switch (nsUri) {
case 'http://www.w3.org/XML/1998/namespace':
return 'xml';
case 'http://www.w3.org/2000/xmlns/':
return 'xmlns';
default:
for (var p in this.namespaces) {
if (this.namespaces[p].uri === nsUri) {
return p;
}
}
if (!localOnly && this.parent) {
return this.parent.getPrefix(nsUri);
} else {
return null;
}
}
}
}
export class NamespaceContext {
scopes: any[];
prefixCount: number;
constructor() {
if (!(this instanceof NamespaceContext)) {
return new NamespaceContext();
}
this.scopes = [];
this.pushContext();
this.prefixCount = 0;
}
addNamespace = function(prefix, nsUri, localOnly) {
if (this.getNamespaceURI(prefix, localOnly) === nsUri) {
return false;
}
if (this.currentScope) {
this.currentScope.namespaces[prefix] = {
uri: nsUri,
prefix: prefix,
declared: false
};
return true;
}
return false;
}
pushContext = function() {
var scope = new NamespaceScope(this.currentScope);
this.scopes.push(scope);
this.currentScope = scope;
return scope;
}
popContext = function() {
var scope = this.scopes.pop();
if (scope) {
this.currentScope = scope.parent;
} else {
this.currentScope = null;
}
return scope;
}
getNamespaceURI = function(prefix, localOnly) {
return this.currentScope && this.currentScope.getNamespaceURI(prefix, localOnly);
}
getPrefix = function(nsUri, localOnly) {
return this.currentScope && this.currentScope.getPrefix(nsUri, localOnly);
}
registerNamespace = function(nsUri) {
var prefix = this.getPrefix(nsUri);
if (prefix) {
// If the namespace has already mapped to a prefix
return prefix;
} else {
// Try to generate a unique namespace
while (true) {
prefix = 'ns' + (++this.prefixCount);
if (!this.getNamespaceURI(prefix)) {
// The prefix is not used
break;
}
}
}
this.addNamespace(prefix, nsUri, true);
return prefix;
}
declareNamespace = function(prefix, nsUri) {
if (this.currentScope) {
var mapping = this.currentScope.getNamespaceMapping(prefix);
if (mapping && mapping.uri === nsUri && mapping.declared) {
return false;
}
this.currentScope.namespaces[prefix] = {
uri: nsUri,
prefix: prefix,
declared: true
};
return true;
}
return false;
}
}
/**
* Scope for XML namespaces
* @param [parent] Parent scope
*
*/
// export function NamespaceScope(parent) {
// if (!(this instanceof NamespaceScope)) {
// return NamespaceScope(parent);
// }
// this.parent = parent;
// this.namespaces = {};
// }
// /**
// * Namespace context that manages hierarchical scopes
// * {NamespaceContext}
// */
// export function NamespaceContext() {
// if (!(this instanceof NamespaceContext)) {
// return NamespaceContext();
// }
// this.scopes = [];
// this.pushContext();
// this.prefixCount = 0;
// }
// /**
// * Look up the namespace URI by prefix
// * @param prefix Namespace prefix
// * @param [localOnly] Search current scope only
// * Namespace URI
// */
// NamespaceScope.prototype.getNamespaceURI = function(prefix, localOnly) {
// switch (prefix) {
// case 'xml':
// return 'http://www.w3.org/XML/1998/namespace';
// case 'xmlns':
// return 'http://www.w3.org/2000/xmlns/';
// default:
// var nsUri = this.namespaces[prefix];
// /*jshint -W116 */
// if (nsUri != null) {
// return nsUri.uri;
// } else if (!localOnly && this.parent) {
// return this.parent.getNamespaceURI(prefix);
// } else {
// return null;
// }
// }
// };
// NamespaceScope.prototype.getNamespaceMapping = function(prefix) {
// switch (prefix) {
// case 'xml':
// return {
// uri: 'http://www.w3.org/XML/1998/namespace',
// prefix: 'xml',
// declared: true
// };
// case 'xmlns':
// return {
// uri: 'http://www.w3.org/2000/xmlns/',
// prefix: 'xmlns',
// declared: true
// };
// default:
// var mapping = this.namespaces[prefix];
// /*jshint -W116 */
// if (mapping != null) {
// return mapping;
// } else if (this.parent) {
// return this.parent.getNamespaceMapping(prefix);
// } else {
// return null;
// }
// }
// };
// /**
// * Look up the namespace prefix by URI
// * @param nsUri Namespace URI
// * @param [localOnly] Search current scope only
// * Namespace prefix
// */
// NamespaceScope.prototype.getPrefix = function(nsUri, localOnly) {
// switch (nsUri) {
// case 'http://www.w3.org/XML/1998/namespace':
// return 'xml';
// case 'http://www.w3.org/2000/xmlns/':
// return 'xmlns';
// default:
// for (var p in this.namespaces) {
// if (this.namespaces[p].uri === nsUri) {
// return p;
// }
// }
// if (!localOnly && this.parent) {
// return this.parent.getPrefix(nsUri);
// } else {
// return null;
// }
// }
// };
// /**
// * Add a prefix/URI namespace mapping
// * @param prefix Namespace prefix
// * @param nsUri Namespace URI
// * @param [localOnly] Search current scope only
// * {boolean} true if the mapping is added or false if the mapping
// * already exists
// */
// NamespaceContext.prototype.addNamespace = function(prefix, nsUri, localOnly) {
// if (this.getNamespaceURI(prefix, localOnly) === nsUri) {
// return false;
// }
// if (this.currentScope) {
// this.currentScope.namespaces[prefix] = {
// uri: nsUri,
// prefix: prefix,
// declared: false
// };
// return true;
// }
// return false;
// };
// /**
// * Push a scope into the context
// * The current scope
// */
// NamespaceContext.prototype.pushContext = function() {
// var scope = NamespaceScope(this.currentScope);
// this.scopes.push(scope);
// this.currentScope = scope;
// return scope;
// };
// /**
// * Pop a scope out of the context
// * The removed scope
// */
// NamespaceContext.prototype.popContext = function() {
// var scope = this.scopes.pop();
// if (scope) {
// this.currentScope = scope.parent;
// } else {
// this.currentScope = null;
// }
// return scope;
// };
// /**
// * Look up the namespace URI by prefix
// * @param prefix Namespace prefix
// * @param [localOnly] Search current scope only
// * Namespace URI
// */
// NamespaceContext.prototype.getNamespaceURI = function(prefix, localOnly) {
// return this.currentScope && this.currentScope.getNamespaceURI(prefix, localOnly);
// };
// /**
// * Look up the namespace prefix by URI
// * @param nsURI Namespace URI
// * @param [localOnly] Search current scope only
// * Namespace prefix
// */
// NamespaceContext.prototype.getPrefix = function(nsUri, localOnly) {
// return this.currentScope && this.currentScope.getPrefix(nsUri, localOnly);
// };
// /**
// * Register a namespace
// * @param nsUri Namespace URI
// * The matching or generated namespace prefix
// */
// NamespaceContext.prototype.registerNamespace = function(nsUri) {
// var prefix = this.getPrefix(nsUri);
// if (prefix) {
// // If the namespace has already mapped to a prefix
// return prefix;
// } else {
// // Try to generate a unique namespace
// while (true) {
// prefix = 'ns' + (++this.prefixCount);
// if (!this.getNamespaceURI(prefix)) {
// // The prefix is not used
// break;
// }
// }
// }
// this.addNamespace(prefix, nsUri, true);
// return prefix;
// };
// /**
// * Declare a namespace prefix/uri mapping
// * @param prefix Namespace prefix
// * @param nsUri Namespace URI
// * true if the declaration is created
// */
// NamespaceContext.prototype.declareNamespace = function(prefix, nsUri) {
// if (this.currentScope) {
// var mapping = this.currentScope.getNamespaceMapping(prefix);
// if (mapping && mapping.uri === nsUri && mapping.declared) {
// return false;
// }
// this.currentScope.namespaces[prefix] = {
// uri: nsUri,
// prefix: prefix,
// declared: true
// };
// return true;
// }
// return false;
// }; | the_stack |
import testMobx from './mobx';
import {
Collection,
PureModel,
Attribute,
updateModelId,
Model,
getRefId,
modelToJSON,
} from '../src';
import { isCollection, isModel } from '../src/helpers/mixin';
import { getModelCollection, getModelId, getModelType } from '../src/helpers/model/utils';
import { mobx } from '@datx/utils';
// @ts-ignore
testMobx.configure({ enforceActions: 'observed' });
describe('Collection', () => {
describe('Basic features', () => {
it('should initialize', () => {
const collection = new Collection();
expect(collection.length).toBe(0);
expect(isCollection(Collection)).toBe(true);
expect(isModel(Collection)).toBe(false);
});
it('should work with models', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Baz extends PureModel {
public static type = 'baz';
}
class FooBar {}
class Store extends Collection {
public static types = [Foo];
public static defaultModel = undefined;
}
const store = new Store();
const store2 = new Store();
const foo1 = store.add({ foo: 1 }, Foo);
const foo2 = store.add<Foo>({ foo: 2 }, 'foo');
const foo3 = store.add(new Foo({ foo: 3 }));
const foo4 = new Foo({ foo: 4 });
expect(store.length).toBe(3);
expect(foo1.foo).toBe(1);
expect(foo2.foo).toBe(2);
expect(foo3.foo).toBe(3);
store.add(foo1);
expect(store.length).toBe(3);
expect(() => store2.add(foo1)).toThrowError('A model can be in a single collection at once');
expect(() => store.add({ foo: 4 })).toThrowError(
'The type needs to be defined if the object is not an instance of the model.',
);
expect(() => store.add({ foo: 4 }, 'bar')).toThrowError(
'No model is defined for the type bar.',
);
expect(() => store.add({ foo: 4 }, Baz)).toThrowError(
'No model is defined for the type baz.',
);
// @ts-expect-error
expect(() => store.add({ foo: 4 }, FooBar)).toThrowError(
'The type needs to be defined if the object is not an instance of the model.',
);
expect(() => store.add([{ foo: 4 }, { foo: 5 }])).toThrowError(
'The type needs to be defined if the object is not an instance of the model.',
);
expect(store.hasItem(foo1)).toBe(true);
expect(store.hasItem(foo4)).toBe(false);
expect(getModelCollection(foo1)).toBe(store);
store.removeOne(foo1);
expect(getModelCollection(foo1)).toBe(undefined);
expect(store.findOne(Foo, 'unexisting')).toBeNull();
expect(store.findOne('unexisting', 1)).toBeNull();
expect(getModelCollection(foo2)).toBe(store);
store.removeOne(Foo, getModelId(foo2));
expect(getModelCollection(foo2)).toBe(undefined);
store.removeOne(Foo, 'unexisting'); // Should not do anything
expect(store.filter((item: Foo) => item.foo > 2).length).toBe(1);
expect(store.length).toBe(store.findAll().length);
expect(store.findAll('unexisting').length).toBe(0);
store.removeOne([foo3, foo4]); // Remove foo3, ignore foo4
expect(store.length).toBe(0);
});
it('should work with property parsers/serializers', () => {
class Foo extends Model {
@Attribute({
parse: (value: string) => parseInt(value, 10),
serialize: (value: number) => `TEST:${value}`,
})
public value!: number;
@Attribute({
parse: (_value: string, data: Record<string, string>) => parseInt(data.value, 10) * 2,
serialize: (value: number, data: Record<string, number>) => `TEST:${value}:${data.value}`,
})
public double!: number;
@Attribute({ isIdentifier: true })
public id!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
const foo = store.add({ value: '123', id: 1 }, Foo);
expect(foo.value).toBe(123);
expect(foo.double).toBe(246);
foo.value = 321;
expect(foo.value).toBe(321);
expect(foo.double).toBe(246);
const snapshot = foo.toJSON();
expect(snapshot.value).toBe('TEST:321');
expect(snapshot.double).toBe('TEST:246:321');
// Make sure it doesn't trigger for other models
store.add({ value: '234', id: 2 }, Foo);
expect(foo.value).toBe(321);
expect(foo.double).toBe(246);
// Make sure it works with upsert
store.add({ value: '345', id: 1 }, Foo);
expect(foo.value).toBe(345);
expect(foo.double).toBe(690);
});
it('should work with preprocess', () => {
class Foo extends PureModel {
public static type = 'foo';
static preprocess(data: object): object {
return {
...data,
baz: 100,
};
}
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
const model = store.add({ foo: 1, bar: 2 }, Foo);
expect(model.baz).toBe(100);
});
it('should work with removing all models of a certain type', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Baz extends PureModel {
public static type = 'baz';
}
class Store extends Collection {
public static types = [Foo, Baz];
}
const store = new Store();
store.add([{}, {}, {}], Foo);
store.add([{}, {}], Baz);
store.add({}, Foo);
store.removeAll(Foo);
expect(store.length).toBe(2);
});
it('should reset the collection', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute()
public foo!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
const foo1 = store.add({ foo: 1 }, Foo);
const foo2 = store.add<Foo>({ foo: 2 }, 'foo');
expect(store.findOne('foo', getModelId(foo2))).toBeTruthy();
expect(getModelCollection(foo1)).toBe(store);
store.reset();
expect(store.findOne('foo', getModelId(foo2))).toBeFalsy();
expect(getModelCollection(foo1)).toBe(undefined);
store.add(foo1);
expect(getModelCollection(foo1)).toBe(store);
});
it('Should support serialization/deserialization', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
const foo1 = store.add({ foo: 1 }, Foo);
store.add<Foo>({ foo: 2 }, 'foo');
store.add(new Foo({ foo: 3 }));
const raw = store.toJSON();
const store2 = new Store(raw);
expect(store2.length).toBe(3);
const foo1b = store2.find((item: Foo) => item.foo === 1);
expect(foo1b).toBeInstanceOf(Foo);
expect(foo1b && getModelId(foo1b)).toBe(getModelId(foo1));
expect(foo1b).not.toBe(foo1);
const fooB = store2.findAll(Foo)[0];
expect(fooB).toBeInstanceOf(Foo);
});
it('should upsert existing models', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
const foo = store.add({ foo: 1 }, Foo);
expect(store.length).toBe(1);
expect(store.findAll(Foo)).toHaveLength(1);
store.add(foo);
expect(store.length).toBe(1);
expect(store.findAll(Foo)).toHaveLength(1);
updateModelId(foo, '123');
store.add(foo);
expect(store.length).toBe(1);
expect(store.findAll(Foo)).toHaveLength(1);
});
it('should make model snapshots immutable', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
const foo1 = store.add({ foo: 1 }, Foo);
store.add<Foo>({ foo: 2 }, 'foo');
store.add(new Foo({ foo: 3 }));
expect(foo1.foo).toBe(1);
const raw = store.toJSON();
raw.models[0].foo = 4;
expect(foo1.foo).toBe(1);
const store2 = new Store(raw);
expect(store2.length).toBe(3);
const foo1b = store2.find((item: Foo) => item.foo === 1);
const foo1c = store2.find((item: Foo) => item.foo === 4);
expect(foo1b).toBeNull();
expect(foo1c).not.toBe(foo1);
expect(foo1.foo).toBe(1);
});
it('should trigger autorun after a model is added', () => {
class Foo extends PureModel {
public static type = 'foo';
@Attribute({ isIdentifier: true })
public id!: number;
@Attribute()
public foo!: number;
@Attribute()
public bar!: number;
@Attribute()
public baz!: number;
}
class Store extends Collection {
public static types = [Foo];
}
const store = new Store();
let autorunLengthCount = 0;
let fooLength;
testMobx.autorun(() => {
autorunLengthCount++;
fooLength = store.findAll(Foo).length;
});
let autorunModelCount = 0;
let foo;
testMobx.autorun(() => {
autorunModelCount++;
foo = store.findOne(Foo, 123);
});
const foo2 = store.add({ id: 123 }, Foo);
if (mobx.useRealMobX) {
expect(autorunModelCount).toBe(2);
expect(foo).toBe(foo2);
expect(autorunLengthCount).toBe(2);
expect(fooLength).toBe(1);
}
// The test doesn't make sense if MobX is not used
});
it('should auto set ref value at be a model is added', () => {
class Pet extends Model {
static type = 'pet';
@Attribute({ isIdentifier: true }) public id!: number;
}
class Toy extends Model {
static type = 'toy';
@Attribute({ isIdentifier: true }) public id!: number;
}
class Person extends Model {
static type = 'person';
@Attribute({ isIdentifier: true }) public id!: number;
@Attribute({ toOne: Person }) public spouse!: Person;
@Attribute({ toMany: Pet }) public pets!: Array<Pet>;
@Attribute({ toOneOrMany: Toy }) public toy!: Toy | Array<Toy>;
}
class Store extends Collection {
static types = [Person, Pet, Toy];
}
const store = new Store();
const steve = store.add<Person>({ spouse: 1111, id: 200, pets: [1, 2, 3] }, Person);
const jane = store.add<Person>({ id: 1111, spouse: 200, toy: 10 }, Person);
store.add([{ id: 1 }, { id: 2 }, { id: 3 }], Pet);
expect(steve.spouse).toBe(jane);
expect(jane.spouse).toBe(steve);
expect(steve.pets).toBeInstanceOf(Array);
expect(steve.pets.map((d) => d.id)).toEqual([1, 2, 3]);
const toy10 = store.add({ id: 10 }, Toy);
expect(jane.toy).toBe(toy10);
jane.toy = store.add([{ id: 11 }, { id: 12 }], Toy);
expect(jane.toy.map((d) => d.id)).toEqual([11, 12]);
const store2 = new Store();
const steve2 = store2.add<Person>({ spouse: { id: 1, type: 'person' }, id: 1 }, Person);
expect(getRefId(steve2, 'spouse')).toEqual({ id: 1, type: 'person' });
});
it('should upgrade ref fields by id or id[]', () => {
class Foo extends Model {
static type = 'foo';
@Attribute({ isIdentifier: true }) public id!: string;
@Attribute({ toOne: Foo }) public parent!: Foo;
@Attribute({ toMany: Foo }) public children!: Array<Foo>;
}
class Store extends Collection {
static types = [Foo];
}
const store = new Store();
store.add(
[
{ id: '1', parent: null, children: ['2', '3', '4'] },
{ id: '1', parent: null, children: ['2', '3', '5'] },
],
Foo,
);
const foo1 = store.findOne<Foo>(Foo, '1');
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const refId = getRefId(foo1!, 'children');
expect(refId).toBeInstanceOf(Array);
expect((refId as Array<any>).map((d) => d.id)).toEqual(['2', '3', '5']);
});
it('should initialize data with id is `0`', () => {
class Foo extends Model {
static type = 'foo';
@Attribute({ isIdentifier: true }) public id!: number;
@Attribute() public name!: string;
}
class Store extends Collection {
static types = [Foo];
}
const store = new Store();
const foo = store.add({ id: 0, name: '99999' }, Foo);
expect(foo.id).toBe(0);
const fooData = modelToJSON(foo);
expect(fooData.id).toBe(0);
// @ts-ignore
expect(fooData.__META__.id).toBe(0);
});
it('should be set nested data as ref', () => {
class Bar extends Model {
static type = 'bar';
@Attribute({ isIdentifier: true }) public id!: number;
@Attribute() public name!: string;
}
class Foo extends Model {
static type = 'foo';
@Attribute({ isIdentifier: true }) public id!: number;
@Attribute() public name!: string;
@Attribute({ toOne: Bar }) public bar!: Bar;
}
class Store extends Collection {
static types = [Foo, Bar];
}
const store = new Store();
store.add(
{
id: 1,
name: 'foo0',
bar: { id: 1, name: 'bar0' },
},
Foo,
);
store.add(
{
id: 1,
name: 'foo0',
bar: { id: 1, name: 'bar1' },
},
Foo,
);
expect(store.findAll(Foo).length).toBe(1);
expect(store.findAll(Bar).length).toBe(1);
});
it('should be set raw (ref) data multi times', () => {
class Foo extends Model {
static type = 'foo';
@Attribute({ isIdentifier: true }) public key!: string;
@Attribute() public name!: string;
@Attribute({ toMany: Foo }) public children!: Array<Foo>;
}
class Store extends Collection {
static types = [Foo];
}
const store = new Store();
store.add(
{
key: '0',
name: 'foo0',
},
Foo,
);
store.add(
{
key: '0',
name: 'foo1',
},
Foo,
);
expect(store.findAll(Foo).length).toBe(1);
const foo = store.findOne<Foo>(Foo, '0');
expect(foo?.name).toBe('foo1');
expect(foo?.children).toEqual([]);
});
it('should throw on invalid model add', () => {
class Foo extends Model {
static type = 'foo';
}
class Bar extends Model {
static type = 'bar';
}
class Store extends Collection {
static types = [Bar];
}
const store = new Store();
expect(() => {
store.add({}, Foo);
}).toThrowError(
`The model type foo was not found. Did you forget to add it to collection types?`,
);
});
it('should not throw on invalid model add', () => {
class Bar extends Model {
static type = 'bar';
}
class Store extends Collection {
static types = [Bar];
}
const store = new Store();
const foo = store.add({}, 'foo');
expect(foo).toBeInstanceOf(Model);
expect(getModelType(foo)).toBe('foo');
});
});
describe('Indirect references', () => {
class Person extends Model {
static type = 'person';
@Attribute({ isIdentifier: true }) id!: number;
@Attribute() public firstName!: string;
@Attribute() public lastName!: string;
// eslint-disable-next-line @typescript-eslint/no-use-before-define
@Attribute({ toMany: () => Pet, referenceProperty: 'owner' }) pets!: Array<Pet>;
// eslint-disable-next-line @typescript-eslint/no-use-before-define
@Attribute({ toMany: () => Toy, referenceProperty: 'owners' }) toys!: Array<Toy>;
}
class Pet extends Model {
static type = 'pet';
@Attribute() public name!: string;
@Attribute({ toOne: () => Person }) public owner!: Person;
}
class Toy extends Model {
static type = 'toy';
@Attribute() public name!: string;
@Attribute({ toMany: () => Person }) public owners!: Array<Person>;
}
it('should be use model for indirect references', () => {
class MyCollection extends Collection {
static types = [Person, Pet];
}
const collection = new MyCollection();
collection.add<Person>({ firstName: 'Jane', id: 1 }, Person);
const steve = collection.add<Person>({ firstName: 'Steve', spouse: 1 }, Person);
const fido = collection.add<Pet>({ name: 'Fido', owner: steve }, Pet);
expect(fido.owner).toBe(steve);
expect(steve.pets.length).toBe(1);
expect(steve.pets[0].name).toBe(fido.name);
});
it('should be use id for indirect references', () => {
class MyCollection extends Collection {
static types = [Person, Pet];
}
const collection = new MyCollection();
collection.add<Person>({ firstName: 'Jane', id: 1 }, Person);
const steve = collection.add<Person>({ firstName: 'Steve', spouse: 1 }, Person);
const fido = collection.add<Pet>({ name: 'Fido', owner: steve.id }, Pet);
const wufi = collection.add<Pet>({ name: 'wufi', owner: steve.id }, Pet);
expect(fido.owner).toBe(steve);
expect(steve.pets.length).toBe(2);
expect(steve.pets[0].name).toBe(fido.name);
expect(steve.pets[1].name).toBe(wufi.name);
collection.removeOne(wufi);
expect(steve.pets.length).toBe(1);
expect(steve.pets[0].name).toBe(fido.name);
});
it('should be use ids for indirect references', () => {
class MyCollection extends Collection {
static types = [Person, Pet, Toy];
}
const collection = new MyCollection();
collection.add<Person>({ firstName: 'Jane', id: 1 }, Person);
const steve = collection.add<Person>({ firstName: 'Steve', spouse: 1 }, Person);
const jane = collection.add<Person>({ firstName: 'Jane', spouse: 1 }, Person);
const fido = collection.add<Toy>({ name: 'Fido', owners: [steve.id, jane.id] }, Toy);
expect(fido.owners.length).toBe(2);
expect(fido.owners[0]).toBe(steve);
expect(fido.owners[1]).toBe(jane);
expect(steve.toys.length).toBe(1);
expect(jane.toys.length).toBe(1);
expect(steve.toys[0].name).toBe(fido.name);
expect(jane.toys[0].name).toBe(fido.name);
});
it('should be use ids for indirect references before references existed', () => {
class MyCollection extends Collection {
static types = [Person, Pet, Toy];
}
const collection = new MyCollection();
collection.add<Person>({ firstName: 'Jane', id: 1 }, Person);
const fido = collection.add<Toy>({ name: 'Fido', owners: [1, 2] }, Toy);
const steve = collection.add<Person>({ firstName: 'Steve', spouse: 2, id: 1 }, Person);
const jane = collection.add<Person>({ firstName: 'Jane', spouse: 1, id: 2 }, Person);
expect(fido.owners.length).toBe(2);
expect(fido.owners[0]).toBe(steve);
expect(fido.owners[1]).toBe(jane);
expect(steve.toys.length).toBe(1);
expect(jane.toys.length).toBe(1);
expect(steve.toys[0].name).toBe(fido.name);
expect(jane.toys[0].name).toBe(fido.name);
});
it('should be use modelRefs for indirect references', () => {
class MyCollection extends Collection {
static types = [Person, Pet, Toy];
}
const collection = new MyCollection();
collection.add<Person>({ firstName: 'Jane', id: 1 }, Person);
const steve = collection.add<Person>({ firstName: 'Steve', spouse: 1 }, Person);
const jane = collection.add<Person>({ firstName: 'Jane', spouse: 1 }, Person);
const fido = collection.add<Toy>(
{
name: 'Fido',
owners: [
{ type: 'person', id: steve.id },
{ type: 'person', id: jane.id },
],
},
Toy,
);
expect(fido.owners.length).toBe(2);
expect(fido.owners[0]).toBe(steve);
expect(fido.owners[1]).toBe(jane);
expect(steve.toys.length).toBe(1);
expect(jane.toys.length).toBe(1);
expect(steve.toys[0].name).toBe(fido.name);
expect(jane.toys[0].name).toBe(fido.name);
});
});
}); | the_stack |
import { config } from "config";
import { State } from "./DatasetAddCommon";
import JsonPath from "jsonpath";
import {
RefObject,
useState,
useEffect,
useRef,
MutableRefObject
} from "react";
import uniq from "lodash/uniq";
/**
* A global module to manage / coordinate validation workflow.
* The overall workflow:
* - every UI component should attempt to register itself to participant the validation
* - ValidationManager will determine whether should get the component involved in the validation process based on config
* - UI components are also responsible for
* - Register the component when componentDidMount and de-register itself when componentWillUnmount
* - Supplie functions for updating component's valid / invalid status (see definition of `ValidationItem`)
* - call `onInputFocusOut` when focus is removed from the component
* - `ValidationManager` supplies `useValidation` hook to facilite this process
* - `ValidationManager` also provides function like `validateAll` to validate all active components on screen
* - To enable `ValidationManager`, `setStateDataGetter` should also be called when the page component is mounted so that `ValidationManager` has access to state data
*/
/**
* A list of field json path (query against [add dataset page state](https://github.com/magda-io/magda/blob/master/magda-web-client/src/Components/Dataset/Add/DatasetAddCommon.ts#L133) that should be validated / Mandatory.
* We currently don't use json path here to query any json data.
* Use json path as a standard way to name the mandatory field only.
* e.g. ["$.dataset.title", "$.distributions[1].license", "$.dataset.defaultLicense"]
*/
export type ValidationFieldList = string[];
export type ElementLikeType = {
getBoundingClientRect: () => ClientRect | DOMRect | null;
scrollIntoView: (arg?: boolean | ScrollIntoViewOptions) => void;
blur: () => void;
focus: (options?: FocusOptions) => void;
};
export type RefType<T = ElementType> =
| MutableRefObject<T | null>
| RefObject<T>;
export type ElementType =
| HTMLInputElement
| HTMLTextAreaElement
| HTMLSelectElement
| HTMLDivElement
| HTMLSpanElement
| ElementLikeType;
/**
* Type for a custom validator. It accepts these parameters:
* - fieldValue: The current value of the input
* - state: the whole add dataset state data
* - validationItem: a ValidationItem, containing information like field label and json path, that might useful for generating a custom error message
*
* The custom validator may return an object the following fields
* - useDefaultValidator: a boolean value to indicate whether the field value is valid (true) or not (false).
* - `undefined`, indicating that the default `isEmpty` validator should be used to re-validate the field
* - a string, indicating that validation has failed - the returned string should be used as an error message.
*
* If the custom validator doesn't return a string and the field value is invalid, a standard error message will be displayed:
* "The [field name] is invalid."
*
* A custom validator should not produce any side effects
*/
/**
* @typedef CustomValidatorType Type for a custom validator function.
*
* The custom validator may return an object the following fields:
* - useDefaultValidator: (Optional, boolean). Default to `false`.
* If `false`, the custom validator's validation result will be used.
* If `true`, the built-in validator `isEmpty` will be used.
* - valid: (Optional, boolean) a boolean value to indicate whether the field value is valid (true) or not (false).
* - validationMessage: (Optional, string) Custom error message. If this field doesn't exist, the standard error message ("The [field name] is invalid.") will be used.
*
* @param {*} fieldValue The current value of the input
* @param {State} state the whole add dataset state data
* @param {ValidationItem} validationItem a ValidationItem, containing information like field label and json path, that might useful for generating a custom error message
* @returns {{
* useDefaultValidator?: boolean;
* valid?: boolean;
* validationMessage?: string;
* }}
*/
export type CustomValidatorType = (
fieldValue: any,
state: State,
validationItem: ValidationItem
) => {
valid?: boolean;
validationMessage?: string;
useDefaultValidator?: boolean;
};
export interface ValidationItem<T = ElementType> {
/**
* the json path will be used:
* - as the id of the ValidationItem
* - to query input value from [add dataset page state](https://github.com/magda-io/magda/blob/5d9adef14f8aeea5bf3039ecad7c362601393307/magda-web-client/src/Components/Dataset/Add/DatasetAddCommon.ts#L133)
*
* @type {string}
* @memberof ValidationItem
*/
jsonPath: string;
/**
* Field label / name
*/
label: string;
/**
* If customValidator exists, it will be used to validate the current input
*/
customValidator?: CustomValidatorType;
/**
* ValidationManager will call this function to turn on the `Invalid` style of the input ctrl
* that is belong to this `ValidationItem` when necessary
*/
setError: (errorMesssage: string) => void;
/**
* ValidationManager will call this function to turn off the `Invalid` style of the input ctrl
* that is belong to this `ValidationItem` when necessary
*/
clearError: () => void;
/**
* A react reference of a DOM element that belongs to this `ValidationItem`.
* ValidationManager will try move this Dom element into viewport when necessary
*/
elRef: RefType<T>;
}
const validationFieldList: ValidationFieldList = config.mandatoryFields.map(
convertConfigFieldItem
);
let validationItems: ValidationItem[] = [];
let stateDataGetter: () => State;
/**
* Convert field name string in the config to json path that we use internally
*
* @param {string} field
* @returns {string[]}
*/
function convertConfigFieldItem(field: string): string {
switch (field) {
case "dataset.title":
return "$.dataset.title";
case "dataset.description":
return "$.dataset.description";
case "dataset.defaultLicense":
return "$.dataset.defaultLicense";
case "files.title":
return "$.distributions[*].title";
case "files.format":
return "$.distributions[*].format";
case "files.license":
return "$.distributions[*].license";
case "distributions.title":
return "$.distributions[*].title";
case "distributions.format":
return "$.distributions[*].format";
case "distributions.license":
return "$.distributions[*].license";
case "dataset.publisher":
return "$.dataset.publisher";
case "licenseLevel":
return "$.licenseLevel";
case "informationSecurity.classification":
return "$.informationSecurity.classification";
case "informationSecurity.disseminationLimits":
return "$.informationSecurity.disseminationLimits";
case "publishToDga":
return "$.datasetPublishing.publishAsOpenData.dga";
default:
throw new Error(`Unknown mandatory field config name: ${field}`);
}
}
export const setStateDataGetter = (getter: () => State) => {
stateDataGetter = getter;
};
function getStateData() {
if (typeof stateDataGetter === "undefined") {
throw new Error("State data getter function is not set yet!");
}
return stateDataGetter();
}
function findItemByExactJsonPathMatch(
jsonPath: string
): ValidationItem | undefined {
if (!jsonPath) {
return undefined;
}
return validationItems.find((item) => item.jsonPath === jsonPath);
}
function findItemsByJsonPath(jsonPath: string): ValidationItem[] {
if (!jsonPath) {
return [];
}
const item = findItemByExactJsonPathMatch(jsonPath);
if (typeof item !== "undefined") {
// --- we will stop if we find an exact matched item
return [item];
}
const items: ValidationItem[] = [];
const stateData = getStateData();
JsonPath.paths(stateData, jsonPath)
.map((item) => JsonPath.stringify(item))
.forEach((resolvedJsonPath) => {
const item = findItemByExactJsonPathMatch(resolvedJsonPath);
if (typeof item !== "undefined") {
items.push(item);
}
});
return items;
}
function findItemsByJsonPaths(jsonPaths: string[]): ValidationItem[] {
if (!jsonPaths || !jsonPaths.length) {
return [];
}
return uniq(jsonPaths.flatMap((jsonPath) => findItemsByJsonPath(jsonPath)));
}
export function shouldValidate(jsonPath: string) {
if (typeof stateDataGetter === "undefined") {
// --- if stateDataGetter is not set, Validation function should be turned off
return false;
}
if (validationFieldList.indexOf(jsonPath) !== -1) {
return true;
}
const stateData = getStateData();
const idx = validationFieldList.findIndex((fieldPath) => {
if (
JsonPath.paths(stateData, fieldPath)
.map((item) => JsonPath.stringify(item))
.indexOf(jsonPath) !== -1
) {
return true;
} else {
return false;
}
});
if (idx !== -1) {
return true;
} else {
return false;
}
}
export const registerValidationItem = (vItem: ValidationItem) => {
if (
shouldValidate(vItem.jsonPath) &&
validationItems.indexOf(vItem) === -1
) {
validationItems.push(vItem);
}
};
export const deregisterValidationItem = (
jsonPathOrItem: string | ValidationItem
) => {
if (typeof jsonPathOrItem === "string") {
const jsonPath = jsonPathOrItem;
// --- should clearError when deregister
validationItems
.filter((item) => item.jsonPath === jsonPath)
.forEach((item) => {
item.clearError();
});
validationItems = validationItems.filter(
(item) => item.jsonPath !== jsonPath
);
} else {
jsonPathOrItem.clearError();
validationItems = validationItems.filter(
(item) => item !== jsonPathOrItem
);
}
};
function isEmptyValue(value: any) {
if (typeof value === "undefined" || value === null) {
return true;
}
if (typeof value === "string" && value.trim() === "") {
return true;
}
return false;
}
function getItemsFromJsonPath(jsonPath: string) {
return validationItems.filter((item) => item.jsonPath === jsonPath);
}
/**
* Execute validation logic on a validation item
* If a customValidator exists for the field, it will be used, otherwise, the default `isEmptyValue` validator will be used.
*
* @param {ValidationItem} item
* @returns {(boolean | string)}
*/
function validateItem(item: ValidationItem): boolean | string {
const jsonPath = item.jsonPath;
const stateData = getStateData();
const value = JsonPath.query(stateData, jsonPath)[0];
const defaultValidationAction = () => {
if (isEmptyValue(value)) {
item.setError(`Error: \`${item.label}\` is a mandatory field.`);
return false;
} else {
item.clearError();
return true;
}
};
if (typeof item.customValidator === "function") {
const result = item.customValidator(value, stateData, item);
if (result.useDefaultValidator === true) {
return defaultValidationAction();
} else if (result.valid === true) {
item.clearError();
return true;
} else if (result.valid === false && !result.validationMessage) {
item.setError(`Error: \`${item.label}\` is invalid.`);
return false;
} else if (result.valid === false && result.validationMessage) {
item.setError(result.validationMessage);
return false;
} else {
throw new Error(
`Invalid return value from customValidator for \`${jsonPath}\``
);
}
} else {
return defaultValidationAction();
}
}
/**
* Input should call this function when focus is removed from it
*
* @param {string} jsonPath
* @returns {boolean} True = the field is valid; False = the field is invalid;
*/
export const onInputFocusOut = (jsonPath: string) => {
const items = getItemsFromJsonPath(jsonPath);
if (!items || !items.length) {
return false;
}
if (items.map((item) => validateItem(item)).filter((r) => !r).length) {
return false;
} else {
return true;
}
};
/**
* Validate a list of validation items
* This function will:
* - Re-validate all inputs
* - Set/unset invalid status of the inputs
* - Move first invalid input (if any) into the viewport
*
* @param {ValidationItem[]} items
* @returns {boolean} True = all fields are valid; False = there is at least one field is invalid;
*/
function validateSelectedItems(items: ValidationItem[]) {
let offsetY: number;
let elRef: RefType<ElementType> | undefined;
let hasInvalidItem = false;
items.forEach((item) => {
if (!validateItem(item)) {
hasInvalidItem = true;
if (!item.elRef.current) {
// --- if element ref is not ready
// --- skip moving viewport
return;
}
const offset = getOffset(item.elRef);
if (typeof offsetY === "undefined") {
elRef = item.elRef;
if (offset) {
offsetY = offset.top;
}
} else if (offset && offset.top < offsetY) {
elRef = item.elRef;
offsetY = offset.top;
}
}
});
if (typeof elRef !== "undefined" && elRef.current) {
// --- there is an invalid input
// --- try to move into viewport
// --- please note: we use [Scroll behavior polyfill](https://github.com/iamdustan/smoothscroll)
elRef.current.scrollIntoView({ behavior: "smooth" });
if (typeof elRef.current.focus === "function") {
elRef.current.focus();
}
}
return !hasInvalidItem;
}
/**
* Validate all registered inputs.
* This function should be called when user requests to move to next page.
* This function will:
* - Re-validate all inputs
* - Set/unset invalid status of the inputs
* - Move first invalid input (if any) into the viewport
*
* @returns {boolean} True = all fields are valid; False = there is at least one field is invalid;
*/
export const validateAll = () => validateSelectedItems(validationItems);
/**
* Validate all inputs matching a list of json Paths.
* This function should be called when user requests to move to next page.
* This function will:
* - Re-validate all inputs
* - Set/unset invalid status of the inputs
* - Move first invalid input (if any) into the viewport
* @param {string[]} fieldPathList a list of json path for selecting inputs
* @returns {boolean} True = all fields are valid; False = there is at least one field is invalid;
*/
export const validateFields = (fieldPathList: string[] = []) => {
if (typeof stateDataGetter === "undefined") {
// --- if stateDataGetter is not set, Validation function should be turned off
return true;
}
const items = findItemsByJsonPaths(fieldPathList);
if (!items.length) {
return true;
}
return validateSelectedItems(items);
};
export const getOffset = (el: RefType<ElementType>) => {
if (!el.current) {
return null;
}
const rect = el.current.getBoundingClientRect();
if (!rect) {
return null;
}
return {
top: rect.top + document.body.scrollTop,
left: rect.left + document.body.scrollLeft
};
};
export const deregisterAllValidationItem = () => {
validationItems = [];
};
interface ValidationHookStateType<T extends ElementType> {
ref: MutableRefObject<T | null>;
isValidationError: boolean;
validationErrorMessage: string;
}
export const useValidation = <T extends ElementType = ElementType>(
fieldJsonPath: string | undefined,
fieldLabel: string | undefined,
customValidator?: CustomValidatorType
): [boolean, string, MutableRefObject<T | null>] => {
const [state, setState] = useState<ValidationHookStateType<T>>({
ref: useRef<T>(null),
isValidationError: false,
validationErrorMessage: ""
});
useEffect(() => {
const validationItem = {
jsonPath: fieldJsonPath ? fieldJsonPath : "",
label: fieldLabel ? fieldLabel : "",
elRef: state.ref,
setError: (errorMessage) => {
setState({
ref: state.ref,
isValidationError: true,
validationErrorMessage: errorMessage
});
},
customValidator,
clearError: () => {
setState({
ref: state.ref,
isValidationError: false,
validationErrorMessage: ""
});
}
};
if (fieldJsonPath) {
registerValidationItem(validationItem);
}
return () => {
if (fieldJsonPath) {
deregisterValidationItem(validationItem);
}
};
}, [fieldJsonPath, fieldLabel, customValidator, state.ref]);
return [state.isValidationError, state.validationErrorMessage, state.ref];
}; | the_stack |
import * as React from 'react';
// Good looks
import styles from './WebSearchTab.module.scss';
// Localization
import * as strings from 'PropertyPaneFilePickerStrings';
// Types
import { IWebSearchTabProps, IWebSearchTabState, ISearchSuggestion, ISearchResult, ImageSize, ImageAspect, ImageLicense } from './WebSearchTab.types';
// Offce Fabric stuff
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/components/Button';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { SearchBox } from 'office-ui-fabric-react/lib/SearchBox';
import { Check } from 'office-ui-fabric-react/lib/Check';
import { Dropdown, IDropdownProps, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown';
import { Image, ImageFit } from 'office-ui-fabric-react/lib/Image';
import { Link } from 'office-ui-fabric-react/lib/Link';
import { FocusZone } from 'office-ui-fabric-react/lib/FocusZone';
import { List } from 'office-ui-fabric-react/lib/List';
import { IRectangle } from 'office-ui-fabric-react/lib/Utilities';
import { Selection, SelectionMode, SelectionZone } from 'office-ui-fabric-react/lib/Selection';
import { MessageBar } from 'office-ui-fabric-react/lib/MessageBar';
// Used for HTTP requests
import { SPHttpClient, IHttpClientOptions, SPHttpClientResponse } from '@microsoft/sp-http';
// CSS utility to combine classes dynamically
import { css } from '@uifabric/utilities/lib/css';
/**
* Rows per page
*/
const ROWS_PER_PAGE = 3;
/**
* Maximum row height
*/
const MAX_ROW_HEIGHT = 250;
/**
* Maximum file size when searching
*/
const MAXFILESIZE = 52428800;
/**
* Maximum number of search results
*/
const MAXRESULTS = 100;
/**
* This is the default search suggestions as of Jan 2019.
* I have no idea where Bing gets them.
* But you can provide your own when calling this component
*/
const DEFAULT_SUGGESTIONS: ISearchSuggestion[] = [
{
topic: 'Backgrounds',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/background_b4f5f0fd0af42d6dc969f795cb65a13c.jpg'
},
{
topic: 'Classrooms',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/classroom_a0b3addf2246028cb7486ddfb0783c6c.jpg'
},
{
topic: 'Conferences',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/conference_b450359b0962cf464f691b68d7c6ecd1.jpg'
},
{
topic: 'Meetings',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/meeting_694397debfa52bc06a952310af01d59d.jpg'
},
{
topic: 'Patterns',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/pattern_6e7c8fd91c9b5fa47519aa3fd4a95a82.jpg'
},
{
topic: 'Teamwork',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/teamwork_5841da2ae9b9424173f601d86e3a252c.jpg'
},
{
topic: 'Technology',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/technology_9a8a4e09c090c65f4c0b3ea06bd48b83.jpg'
},
{
topic: 'Scenery',
backgroundUrl: 'https://spoprod-a.akamaihd.net/files/sp-client-prod_2019-01-11.008/scenery_abe5bfb8f3913bd52be279a793472ead.jpg'
}
];
/**
* The tenant storage key to use when storing the Bing API key.
*/
const BINGAPI_TENANT_STORAGEKEY: string = 'BingApi';
/**
* Renders search suggestions and performs seach queries
*/
export default class WebSearchTab extends React.Component<IWebSearchTabProps, IWebSearchTabState> {
private _columnCount: number;
private _columnWidth: number;
private _rowHeight: number;
private _selection: Selection;
private _listElem: List = undefined;
constructor(props: IWebSearchTabProps) {
super(props);
this._selection = new Selection(
{
selectionMode: SelectionMode.single,
onSelectionChanged: () => {
// Get the selected item
const selectedItems = this._selection.getSelection();
if (selectedItems && selectedItems.length > 0) {
//Get the selected key
const selectedKey: ISearchResult = selectedItems[0] as ISearchResult;
//Brute force approach to making sure all URLs are loading over HTTPS
// even if it breaks the page.
const selectedUrl: string = selectedKey.contentUrl.replace('http://', 'https://');
// Save the selected file
this.setState({
fileUrl: selectedUrl
});
} else {
// Remove any selected file
this.setState({
fileUrl: undefined
});
}
if (this._listElem) {
// Force the list to update to show the selection check
this._listElem.forceUpdate();
}
}
});
this.state = {
isLoading: true,
hasKey: undefined,
results: undefined,
};
}
/**
* Get the API key
*/
public componentDidMount(): void {
// Find out if we should show anything
this._getAPIKey();
}
/**
* Render the tab
*/
public render(): React.ReactElement<IWebSearchTabProps> {
const { hasKey, query, results } = this.state;
return (
<div className={styles.tabContainer}>
<div className={styles.tabHeaderContainer}>
<h2 className={styles.tabHeader}>{strings.WebSearchLinkLabel}</h2>
{hasKey && this._renderSearchBox()}
</div>
<div className={styles.tab}>
{hasKey === false && strings.SorryWebSearch} {/* If we verified we don't have a key, give a little Sorry message */}
{hasKey && !query && this._renderSearchSuggestions()} {/* No search yet, show suggestions */}
{query && results && this._renderSearchResults()} {/* Got results, show them */}
</div>
<div className={styles.actionButtonsContainer}>
{this.state.results && this.state.license === 'Any' && <MessageBar>
{strings.CreativeCommonsMessage}
</MessageBar>}
<Label className={styles.copyrightLabel}>
{strings.CopyrightWarning}
<Link target='_blank' href={strings.CopyrightUrl}>{strings.LearnMoreLink}</Link>
</Label>
<div className={styles.actionButtons}>
<PrimaryButton
disabled={this.state.fileUrl === undefined}
className={styles.actionButton}
onClick={() => this._handleSave()}
>{strings.OpenButtonLabel}</PrimaryButton>
<DefaultButton onClick={() => this._handleClose()} className={styles.actionButton}>{strings.CancelButtonLabel}</DefaultButton>
</div>
</div>
</div>
);
}
/**
* Renders the returned search results
*/
private _renderSearchResults = (): JSX.Element => {
const { results } = this.state;
// If there are no results, tell 'em.
if (results === undefined || results.length < 1) {
return <Label className={styles.noResultLabel}>{strings.NoResultsBadEnglish}</Label>;
}
return (
<FocusZone>
<SelectionZone selection={this._selection}
onItemInvoked={(item: ISearchResult) => this._selection.setKeySelected(item.key, true, true)}
>
<List
ref={this._linkElement}
className={styles.bingGrildList}
items={this.state.results}
getItemCountForPage={this._getItemCountForPage}
getPageHeight={this._getPageHeight}
renderedWindowsAhead={4}
onRenderCell={this._onRenderSearchResultsCell}
/>
</SelectionZone>
</FocusZone>
);
}
/**
* Show an individual search result item
*/
private _onRenderSearchResultsCell = (item: ISearchResult, index: number | undefined): JSX.Element => {
const { query } = this.state;
let isSelected: boolean = false;
if (this._selection && index !== undefined) {
isSelected = this._selection.isIndexSelected(index);
}
// The logic for calculating the thumbnail dimensions is not quite the same as the out-of-the-box file picker,
// but it'll have to do.
// Find the aspect ratio of the picture
const ratio: number = item.width / item.height;
// Fit the height to the desired row height
let thumbnailHeight: number = Math.min(this._rowHeight, item.height);
// Resize the picture with the same aspect ratio
let thumbnailWidth: number = thumbnailHeight * ratio;
const searchResultAltText: string = strings.SearchResultAlt.replace('{0}', query);
return (
<div
className={styles.bingGridListCell}
style={{
width: 100 / this._columnCount + '%'
}}
>
<div
aria-label={searchResultAltText}
className={css(styles.bingTile, isSelected ? styles.isSelected : undefined)}
data-is-focusable={true}
data-selection-index={index}
style={{
width: `${thumbnailWidth}px`,
height: `${thumbnailHeight}px`
}}>
<div className={styles.bingTileContent} data-selection-invoke={true}>
<Image src={item.thumbnailUrl} className={styles.bingTileThumbnail} alt={searchResultAltText} width={thumbnailWidth} height={thumbnailHeight} />
<div className={styles.bingTileFrame}></div>
<div className={styles.bingTileCheckCircle}
role='checkbox'
aria-checked={isSelected}
data-item-index={index} data-selection-toggle={true} data-automationid='CheckCircle'>
<Check checked={isSelected} />
</div>
<div className={styles.bingTileNamePlate}>
<Link
href={item.contentUrl}
target='_blank'
aria-label={strings.SearchResultAriaLabel}
>{item.displayUrl}</Link>
</div>
</div>
</div>
</div>);
}
/**
* Renders suggestions when there aren't any queries
*/
private _renderSearchSuggestions = (): JSX.Element => {
const suggestions: ISearchSuggestion[] = this.props.suggestions !== undefined ? this.props.suggestions : DEFAULT_SUGGESTIONS;
return (
<FocusZone>
<List
className={styles.filePickerFolderCardGrid}
items={suggestions}
getItemCountForPage={this._getItemCountForPage}
getPageHeight={this._getPageHeight}
renderedWindowsAhead={4}
onRenderCell={this._onRenderSuggestionCell}
/>
</FocusZone>
);
}
/**
* Gets search results from Bing
*/
private _getSearchResults = () => {
const aspect: string = this.state.aspect ? this.state.aspect : 'All';
const size: string = this.state.size ? this.state.size : 'All';
const license: string = this.state.license ? this.state.license : 'Any';
const { query } = this.state;
if (query === undefined) {
// No query
return;
}
// Show a loading indicator
this.setState({ isLoading: true });
// Use this client option to prevent CORS issues.
const httpClientOptions: IHttpClientOptions = {
headers: new Headers(),
method: 'GET',
mode: 'cors'
};
// Submit the request
const apiUrl: string = `https://www.bingapis.com/api/v7/images/search?appid=${this.state.apiKey}&traffictype=Internal_monitor&q=${encodeURIComponent(query)}&count=${MAXRESULTS}&aspect=${aspect}&maxFileSize=${MAXFILESIZE}&mkt=en-US&size=${size}&license=${license}`;
this.props.context.httpClient.get(apiUrl,
SPHttpClient.configurations.v1, httpClientOptions)
.then((response: SPHttpClientResponse) => {
response.json().then((responseJSON: any) => {
// Cast to Bing search results (for type safety)
const bingResults: IBingSearchResult[] = responseJSON.value;
//Convert results to search results
const searchResults: ISearchResult[] = bingResults.map((bingResult: IBingSearchResult) => {
// Get dimensions
const width: number = bingResult!.thumbnail!.width ? bingResult!.thumbnail!.width : bingResult!.width;
const height: number = bingResult!.thumbnail!.height ? bingResult!.thumbnail!.height : bingResult!.height;
// Create a search result
const searchResult: ISearchResult = {
thumbnailUrl: bingResult.thumbnailUrl,
contentUrl: bingResult.contentUrl,
displayUrl: this.getDisplayUrl(bingResult.hostPageDisplayUrl),
key: bingResult.imageId,
width: width,
height: height,
};
return searchResult;
});
// Set the items so that the selection zone can keep track of them
this._selection.setItems(searchResults, true);
// Save results and stop loading indicator
this.setState({
isLoading: false,
results: searchResults
});
});
});
}
/**
* Calculates how many items there should be in the page
*/
private _getItemCountForPage = (itemIndex: number, surfaceRect: IRectangle): number => {
if (itemIndex === 0) {
this._columnCount = Math.ceil(surfaceRect.width / MAX_ROW_HEIGHT);
this._columnWidth = Math.floor(surfaceRect.width / this._columnCount);
this._rowHeight = this._columnWidth;
}
return this._columnCount * ROWS_PER_PAGE;
}
/**
* Gets the height of a list "page"
*/
private _getPageHeight = (): number => {
return this._rowHeight * ROWS_PER_PAGE;
}
/**
* Renders a cell for search suggestions
*/
private _onRenderSuggestionCell = (item: ISearchSuggestion, index: number | undefined): JSX.Element => {
return (
<div
className={styles.filePickerFolderCardTile}
data-is-focusable={true}
style={{
width: 100 / this._columnCount + '%'
}}
>
<div className={styles.filePickerFolderCardSizer}>
<div className={styles.filePickerFolderCardPadder}>
<Image src={item.backgroundUrl} className={styles.filePickerFolderCardImage} imageFit={ImageFit.cover} />
<DefaultButton className={styles.filePickerFolderCardLabel} onClick={(_event) => this._handleSearch(item.topic)}>{item.topic}</DefaultButton>
</div>
</div>
</div>
);
}
/**
* Renders the search box
*/
private _renderSearchBox = (): JSX.Element => {
const { query } = this.state;
const hasQuery: boolean = query !== undefined;
const license: string = this.state.license ? this.state.license : 'All';
return <div className={styles.searchBoxContainer}>
<div className={styles.searchBoxMedium}>
<div className={styles.searchBox}>
<SearchBox
placeholder={strings.SearchBoxPlaceholder}
value={query}
onSearch={newQuery => this._handleSearch(newQuery)}
/>
</div>
</div>
<Label>{strings.PoweredByBing}</Label>
{hasQuery && <div className={styles.dropdownContainer}>
<Dropdown
className={styles.filterDropdown}
placeholder={strings.ImageSizePlaceholderText}
onRenderPlaceHolder={(props: IDropdownProps) => this._renderFilterPlaceholder(props)}
selectedKey={this.state.size}
options={[
{ key: 'All', text: strings.SizeOptionAll },
{ key: 'Small', text: strings.SizeOptionSmall },
{ key: 'Medium', text: strings.SizeOptionMedium },
{ key: 'Large', text: strings.SizeOptionLarge },
{ key: 'Wallpaper', text: strings.SizeOptionExtraLarge }
]}
onChange={(event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption, index?: number) => this._handleChangeSize(option)}
/>
<Dropdown
className={styles.filterDropdown}
placeholder={strings.ImageLayoutPlaceholderText}
onRenderPlaceHolder={(props: IDropdownProps) => this._renderFilterPlaceholder(props)}
selectedKey={this.state.aspect}
options={[
{ key: 'All', text: strings.LayoutOptionAll },
{ key: 'Square', text: strings.LayoutOptionSquare },
{ key: 'Wide', text: strings.LayoutOptionWide },
{ key: 'Tall', text: strings.LayoutOptionTall },
]}
onChange={(event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption, index?: number) => this._handleChangeLayout(option)}
/>
<Dropdown
className={styles.filterDropdown}
placeholder={strings.LicensePlaceholderText}
onRenderPlaceHolder={(props: IDropdownProps) => this._renderFilterPlaceholder(props)}
selectedKey={license}
options={[
{ key: 'All', text: strings.LicenseOptionAll },
{ key: 'Any', text: strings.LicenseOptionAny }
]}
onChange={(event: React.FormEvent<HTMLDivElement>, option?: IDropdownOption, index?: number) => this._handleChangeLicense(option)}
/>
</div>}
</div>;
}
/**
* Handles when a user changes the size drop down.
* Resubmits search query
*/
private _handleChangeSize = (option: IDropdownOption) => {
this.setState({
size: option.key as ImageSize
}, () => this._getSearchResults());
}
/**
* Handles when user selects a new layout from the drop down.
* Resubmits search query.
*/
private _handleChangeLayout = (option: IDropdownOption) => {
this.setState({
aspect: option.key as ImageAspect
}, () => this._getSearchResults());
}
/**
* Handles when a user changes the license from the drop down
* Resubits search query
*/
private _handleChangeLicense = (option: IDropdownOption) => {
this.setState({
license: option.key as ImageLicense
}, () => this._getSearchResults());
}
/**
* Renders the drop down placeholders
*/
private _renderFilterPlaceholder = (props: IDropdownProps): JSX.Element => {
return <span>{props.placeholder}</span>;
}
/**
* Handles when user triggers search query
*/
private _handleSearch = (newQuery?: string) => {
this.setState({
query: newQuery
}, () => this._getSearchResults());
}
/**
* Handles when user closes search pane
*/
private _handleClose = () => {
this.props.onClose();
}
/**
* Handes when user saves selection
* Calls property pane file picker's save function
*/
private _handleSave = () => {
this.props.onSave(encodeURI(this.state.fileUrl));
}
/**
* Removes protocol and retrieves only the domain, just like Bing search results does
* in the SharePoint file picker
* @param url The display url as provided by Bing
*/
private getDisplayUrl(url: string): string {
// remove any protocols
if (url.indexOf('://') > -1) {
const urlParts: string[] = url.split('://');
url = urlParts.pop();
}
// Split the URL on the first slash
const splitUrl = url.split('/');
return splitUrl[0];
}
/**
* Retrieves the API key from tenant storage
*/
private _getAPIKey() {
const { absoluteUrl } = this.props.context.pageContext.web;
const apiUrl: string = `${absoluteUrl}/_api/web/GetStorageEntity('${BINGAPI_TENANT_STORAGEKEY}')`;
this.props.context.spHttpClient.get(apiUrl, SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
response.json().then((responseJSON: any) => {
this.setState({
isLoading: false,
apiKey: responseJSON.Value,
hasKey: responseJSON.Value !== undefined
});
});
}, () => {
this.setState({
isLoading: false,
hasKey: false
});
});
}
/**
* Creates a reference to the list
*/
private _linkElement = (e: any) => {
this._listElem = e;
}
} | the_stack |
import { LogEntry, LogItemType } from '@bfemulator/sdk-shared';
import { Activity } from 'botframework-schema';
import {
addTranscript,
appendToLog,
ChatAction,
clearLog,
clearTranscripts,
closeDocument,
newChat,
removeTranscript,
setInspectorObjects,
updateChat,
updateSpeechAdapters,
incomingActivity,
RestartConversationStatus,
postActivity,
setRestartConversationStatus,
setRestartConversationOption,
RestartConversationOptions,
} from '../actions/chatActions';
import { closeNonGlobalTabs } from '../actions/editorActions';
import { chat, ChatState, IncomingActivityRecord } from './chat';
describe('Chat reducer tests', () => {
const testChatId = 'testChat1';
const DEFAULT_STATE: ChatState = {
changeKey: 0,
chats: {
[testChatId]: {
log: {
entries: [],
},
},
},
transcripts: [],
restartStatus: {
[testChatId]: RestartConversationStatus.Started,
},
} as any;
it('should return unaltered state for non-matching action type', () => {
const emptyAction: ChatAction = { type: null, payload: null };
const startingState = { ...DEFAULT_STATE };
const endingState = chat(DEFAULT_STATE, emptyAction);
expect(endingState).toEqual(startingState);
});
it('should add a transcript', () => {
const action = addTranscript('testTranscript');
const state = chat(DEFAULT_STATE, action);
expect(state.transcripts.length).toBe(1);
expect(state.transcripts[0]).toBe('testTranscript');
});
it('should remove a transcript', () => {
let state = chat(DEFAULT_STATE, addTranscript('xs1'));
state = chat(state, addTranscript('xs2'));
expect(state.transcripts.length).toBe(2);
const action = removeTranscript('xs1');
state = chat(state, action);
expect(state.transcripts.length).toBe(1);
expect(state.transcripts).not.toContain('xs1');
});
it('should clear all transcripts', () => {
let state = chat(DEFAULT_STATE, addTranscript('xs1'));
state = chat(state, addTranscript('xs2'));
expect(state.transcripts.length).toBe(2);
const action = clearTranscripts();
state = chat(state, action);
expect(state.transcripts.length).toBe(0);
});
it('should create a new chat', () => {
const newChatName = 'newChat';
const action = newChat(newChatName, 'livechat');
const state = chat(DEFAULT_STATE, action);
expect(state.changeKey).toBe(1);
expect(state.chats[newChatName]).toBeTruthy();
});
it('should close a chat', () => {
let transientState = chat(DEFAULT_STATE, newChat(testChatId, 'livechat'));
transientState = chat(
transientState,
incomingActivity(
{
id: 'act-1',
} as Activity,
testChatId
)
);
transientState = chat(transientState, setRestartConversationStatus(RestartConversationStatus.Started, testChatId));
expect(transientState.restartStatus[testChatId]).not.toBeUndefined();
expect(transientState.chats[testChatId].replayData.incomingActivities.length > 0).toBeTruthy();
const action = closeDocument(testChatId);
transientState = chat(DEFAULT_STATE, action);
expect(transientState.chats[testChatId]).toBeFalsy();
expect(transientState.restartStatus[testChatId]).toBeFalsy();
});
it('should append to the log', () => {
const logEntry: LogEntry = {
timestamp: 123,
items: [
{
type: LogItemType.Text,
payload: {
level: 0,
text: 'testing',
},
},
],
};
const action = appendToLog(testChatId, logEntry);
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
[testChatId]: {
log: {
entries: [],
},
},
},
};
const endingState = chat(startingState, action);
expect(endingState.chats[testChatId].log.entries[0]).toBeTruthy();
expect(endingState.chats[testChatId].log.entries[0]).toEqual(logEntry);
});
it('should clear the log', () => {
const logEntry: LogEntry = {
timestamp: 1234,
items: [
{
type: LogItemType.Text,
payload: {
level: 0,
text: 'testing',
},
},
],
};
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
[testChatId]: {
log: {
entries: [],
},
},
},
};
let state = chat(startingState, appendToLog(testChatId, logEntry));
expect(state.chats[testChatId].log.entries.length).toBeGreaterThan(0);
const action = clearLog(testChatId);
state = chat(state, action);
expect(state.chats[testChatId].log.entries.length).toBe(0);
});
it('should set inspector objects', () => {
const action = setInspectorObjects(testChatId, { testing: true });
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
[testChatId]: {},
},
};
const endingState = chat(startingState, action);
expect(endingState.chats[testChatId].inspectorObjects.length).toBeGreaterThan(0);
expect(endingState.chats[testChatId].inspectorObjects[0]).toEqual({
testing: true,
});
});
it('should reset state on a "close all" editor action', () => {
const tempChat = 'tempChat';
const alteredState: ChatState = {
changeKey: 999,
chats: {
[tempChat]: {
testing: true,
},
},
transcripts: ['xs1', 'xs2', 'xs3'],
} as any;
const action = closeNonGlobalTabs();
const state = chat(alteredState, action);
expect(state.changeKey).toBe(0);
expect(state.transcripts.length).toBe(0);
expect(state.chats[tempChat]).toBeFalsy();
});
it('should update a chat', () => {
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
chat1: {
id: 'chat',
userId: 'userId',
},
},
};
const action = updateChat('chat1', {
id: 'updatedChatId',
userId: 'updatedUserId',
});
const state = chat(startingState, action);
expect(state.chats.chat1.id).toBe('updatedChatId');
expect(state.chats.chat1.userId).toBe('updatedUserId');
});
it('should update the speech adapters for a chat', () => {
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
chat1: {
directLine: undefined,
documentId: 'chat1',
userId: 'user1',
},
},
webSpeechFactories: {
chat1: undefined,
},
};
const directLine: any = {};
const webSpeechPonyfillFactory: any = {};
const action = updateSpeechAdapters('chat1', directLine, webSpeechPonyfillFactory);
const state = chat(startingState, action);
expect(state.chats.chat1.directLine).toEqual(directLine);
expect(state.webSpeechFactories.chat1).toEqual(webSpeechPonyfillFactory);
});
it('should add slots for post activity correctly', () => {
const documentId = 'chatId-1';
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
'chatId-1': {
directLine: undefined,
documentId,
userId: 'user1',
replayData: {},
},
},
webSpeechFactories: {
chat1: undefined,
},
};
const activities: Activity[] = [
{
id: 'activ-1',
name: 'incoming-1',
replyToId: 'reply-to-1',
} as Activity,
{
id: 'activ-2',
name: 'incoming-2',
replyToId: 'reply-to-2',
} as Activity,
{
id: 'activ-3',
name: 'post-activity-1',
} as Activity,
{
id: 'activ-4',
name: 'incoming-3',
replyToId: 'post-activity-1',
} as Activity,
{
id: 'activ-5',
name: 'post-activity-2',
} as Activity,
];
let transientState: ChatState = chat(startingState, incomingActivity(activities[0], documentId));
transientState = chat(transientState, incomingActivity(activities[1], documentId));
transientState = chat(transientState, postActivity(activities[2], documentId));
expect(transientState.chats['chatId-1'].replayData.postActivitiesSlots.length).toBe(1);
expect(transientState.chats['chatId-1'].replayData.postActivitiesSlots[0]).toBe(2);
transientState = chat(transientState, incomingActivity(activities[3], documentId));
const finalState = chat(transientState, postActivity(activities[4], documentId));
expect(finalState.chats['chatId-1'].replayData.postActivitiesSlots[1]).toBe(3);
});
it('should add an incoming activity inside the chatReplay object', () => {
const documentId = 'chatId-1';
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
'chatId-1': {
directLine: undefined,
documentId,
userId: 'user1',
replayData: {},
},
},
webSpeechFactories: {
chat1: undefined,
},
};
const expectedActivity = {
id: 'activ-1',
name: 'test-activity-1',
replyToId: 'reply-to-1',
} as Activity;
let action = incomingActivity(expectedActivity, documentId);
const transientState = chat(startingState, action);
let incomingActivities = transientState.chats['chatId-1'].replayData.incomingActivities;
let lastActivity: IncomingActivityRecord = incomingActivities[incomingActivities.length - 1];
expect(lastActivity.id).toBe(expectedActivity.id);
expect(lastActivity.replyToId).toBe(expectedActivity.replyToId);
const anotherExpectedActivity = {
id: 'activ-2',
name: 'test-activity-2',
replyToId: 'reply-to-2',
} as Activity;
action = incomingActivity(anotherExpectedActivity, documentId);
const finalState = chat(transientState, action);
incomingActivities = finalState.chats['chatId-1'].replayData.incomingActivities;
lastActivity = incomingActivities[incomingActivities.length - 1];
expect(lastActivity.id).toBe(anotherExpectedActivity.id);
expect(lastActivity.replyToId).toBe(anotherExpectedActivity.replyToId);
});
it('should update restart type option correctly', () => {
const documentId = 'chatId-1';
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
'chatId-1': {
directLine: undefined,
documentId,
userId: 'user1',
replayData: {},
},
},
webSpeechFactories: {
chat1: undefined,
},
};
let action = setRestartConversationOption(documentId, RestartConversationOptions.NewUserId);
let transientState = chat(startingState, action);
expect(transientState.chats['chatId-1'].restartConversationOption).toBe(RestartConversationOptions.NewUserId);
action = setRestartConversationOption(documentId, RestartConversationOptions.SameUserId);
transientState = chat(transientState, action);
expect(transientState.chats['chatId-1'].restartConversationOption).toBe(RestartConversationOptions.SameUserId);
});
it('should set restart conversation status', () => {
const documentId = 'chatId-1';
const startingState = {
...DEFAULT_STATE,
chats: {
...DEFAULT_STATE.chats,
'chatId-1': {
directLine: undefined,
documentId,
userId: 'user1',
replayData: {},
},
},
webSpeechFactories: {
chat1: undefined,
},
};
let transientState: ChatState = chat(
startingState,
setRestartConversationStatus(RestartConversationStatus.Started, documentId)
);
expect(transientState.restartStatus[documentId]).toBe(RestartConversationStatus.Started);
transientState = chat(
transientState,
setRestartConversationStatus(RestartConversationStatus.Completed, documentId)
);
expect(transientState.restartStatus[documentId]).toBe(RestartConversationStatus.Completed);
transientState = chat(transientState, setRestartConversationStatus(RestartConversationStatus.Rejected, documentId));
expect(transientState.restartStatus[documentId]).toBe(RestartConversationStatus.Rejected);
transientState = chat(transientState, setRestartConversationStatus(RestartConversationStatus.Stop, documentId));
expect(transientState.restartStatus[documentId]).toBe(RestartConversationStatus.Stop);
expect(transientState.restartStatus['abc']).toBeUndefined();
});
}); | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview A jQuery UI widget that displays all of the configuration settings held in persistent storage and allows the user to manipulate them.
*/
namespace VRS
{
/**
* The state object for the StoredSettingsPlugin.
*/
class StoredSettingsList_State
{
/**
* The container that lists all of the VRS keys.
*/
keysContainer: JQuery = null;
/**
* The container that holds the content of a single key.
*/
keyContentContainer: JQuery = null;
/**
* The currently selected key.
*/
currentKey: string = null;
/**
* The textarea element that shows the import/export settings.
*/
importExportElement: JQuery = null;
/**
* The container that holds all of the import controls.
*/
importControlsContainer: JQuery = null;
}
/**
* A jQuery UI widget that can show the user all of the settings stored at the browser and let them manipulate them.
*/
export class StoredSettingsList extends JQueryUICustomWidget
{
options: {}
private _getState() : StoredSettingsList_State
{
var result = this.element.data('storedSettingsState');
if(result === undefined) {
result = new StoredSettingsList_State();
this.element.data('storedSettingsState', result);
}
return result;
}
_create()
{
var state = this._getState();
this.element.addClass('vrsStoredSettings');
var buttonBlock =
$('<div/>')
.appendTo(this.element);
$('<button />')
.text(VRS.$$.RemoveAll)
.click(() => this._removeAllKeys())
.appendTo(buttonBlock);
$('<button />')
.text(VRS.$$.Refresh)
.click(() => this._refreshDisplay())
.appendTo(buttonBlock);
$('<button />')
.text(VRS.$$.ExportSettings)
.click(() => this._exportSettings())
.appendTo(buttonBlock);
$('<button />')
.text(VRS.$$.ImportSettings)
.click(() => this._showImportControls())
.appendTo(buttonBlock);
var importExport =
$('<div />')
.attr('class', 'importExport')
.appendTo(this.element);
state.importExportElement = $('<textarea />')
.hide()
.appendTo(importExport);
state.importControlsContainer =
$('<div />')
.hide()
.attr('class', 'import')
.appendTo(importExport);
var checkboxesContainer =
$('<ol />')
.appendTo(state.importControlsContainer);
var importOverwrite = this._addCheckBox(checkboxesContainer, VRS.$$.OverwriteExistingSettings, true);
var importReset = this._addCheckBox(checkboxesContainer, VRS.$$.EraseBeforeImport, true);
var importIgnoreRequestFeedId = this._addCheckBox(checkboxesContainer, VRS.$$.DoNotImportRequestFeedId, true);
var importIgnoreLanguage = this._addCheckBox(checkboxesContainer, VRS.$$.DoNotImportLanguageSettings, false);
var importIgnoreSplitters = this._addCheckBox(checkboxesContainer, VRS.$$.DoNotImportSplitters, false);
var importIgnoreCurrentLocation = this._addCheckBox(checkboxesContainer, VRS.$$.DoNotImportCurrentLocation, false);
var importIgnoreAutoSelect = this._addCheckBox(checkboxesContainer, VRS.$$.DoNotImportAutoSelect, false);
var importButton =
$('<button />')
.text(VRS.$$.Import)
.click(() =>
this._importSettings({
overwrite: importOverwrite.prop('checked'),
resetBeforeImport: importReset.prop('checked'),
ignoreLanguage: importIgnoreLanguage.prop('checked'),
ignoreSplitters: importIgnoreSplitters.prop('checked'),
ignoreCurrentLocation: importIgnoreCurrentLocation.prop('checked'),
ignoreAutoSelect: importIgnoreAutoSelect.prop('checked'),
ignoreRequestFeedId: importIgnoreRequestFeedId.prop('checked')
})
)
.appendTo(state.importControlsContainer);
state.keysContainer =
$('<div/>')
.addClass('keys')
.appendTo(this.element);
state.keyContentContainer =
$('<div/>')
.addClass('content')
.appendTo(this.element);
this._buildKeysTable(state);
}
/**
* Appends a checkbox to the control.
*/
private _addCheckBox(parentElement: JQuery, labelText: string, initialCheckedState: boolean) : JQuery
{
var listItem = $('<li />')
.appendTo(parentElement);
var result = $('<input />')
.uniqueId()
.attr('type', 'checkbox')
.prop('checked', initialCheckedState)
.appendTo(listItem);
$('<label />')
.attr('for', result.attr('id'))
.text(labelText)
.appendTo(listItem);
return result;
}
/**
* Builds a table to display the keys that are in use.
*/
private _buildKeysTable(state: StoredSettingsList_State)
{
state.keysContainer.empty();
var statistics =
$('<table/>')
.addClass('statistics')
.appendTo(state.keysContainer)
.append(
$('<tr/>')
.append($('<td/>').text(VRS.$$.StorageEngine + ':'))
.append($('<td/>').text(VRS.configStorage.getStorageEngine()))
)
.append(
$('<tr/>')
.append($('<td/>').text(VRS.$$.StorageSize + ':'))
.append($('<td/>').text(VRS.configStorage.getStorageSize()))
);
var list = $('<ul/>')
.appendTo(state.keysContainer);
var hasContent = false;
var keys = VRS.configStorage.getAllVirtualRadarKeys().sort();
$.each(keys, (idx, key) => {
hasContent = true;
var keyName = String(key);
var listItem =
$('<li/>')
.text(keyName)
.click(() => this._keyClicked(keyName))
.appendTo(list);
if(keyName === state.currentKey) {
listItem.addClass('current');
}
});
if(!hasContent) {
list.append(
$('<li/>')
.text(VRS.$$.NoSettingsFound)
.addClass('empty')
);
}
}
/**
* Displays a single key's content to the user.
*/
private _showKeyContent(keyName: string, content: Object)
{
var state = this._getState();
var container = state.keyContentContainer;
var self = this;
state.currentKey = keyName;
container.empty();
if(keyName) {
$('<p/>')
.addClass('keyTitle')
.text(keyName)
.appendTo(container);
var contentDump = $('<code/>').appendTo(container);
if(content === null || content === undefined) {
contentDump
.addClass('empty')
.text(content === null ? '<null>' : '<undefined>');
} else {
var json = $.toJSON(content);// what are these parameters? -> , null, 4);
json = json
.replace(/&/g, '&')
.replace(/ /g, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\t/g, ' ')
.replace(/\n/g, '<br />');
contentDump.html(json);
}
var buttonBlock = $('<div/>')
.addClass('buttonBlock')
.appendTo(container);
$('<button/>')
.text(VRS.$$.Remove)
.click(() => this._removeKey(keyName))
.appendTo(buttonBlock);
}
this._buildKeysTable(state);
}
/**
* Refreshes the display of keys and content.
*/
private _refreshDisplay()
{
var state = this._getState();
var content = null;
if(state.currentKey) {
var exists = false;
$.each(VRS.configStorage.getAllVirtualRadarKeys(), function() {
exists = String(this) === state.currentKey;
return !exists;
});
if(!exists) {
state.currentKey = null;
} else {
content = VRS.configStorage.getContentWithoutPrefix(state.currentKey);
}
}
this._showKeyContent(state.currentKey, content);
}
/**
* Removes the configuration settings associated with the key passed across.
*/
private _removeKey(keyName: string)
{
var state = this._getState();
VRS.configStorage.removeContentWithoutPrefix(keyName);
state.currentKey = null;
this._buildKeysTable(state);
state.keyContentContainer.empty();
}
/**
* Removes all configuration settings.
*/
private _removeAllKeys()
{
var state = this._getState();
state.currentKey = null;
VRS.configStorage.removeAllContent();
state.keyContentContainer.empty();
this._buildKeysTable(state);
}
/**
* Creates and displays the serialised settings.
*/
private _exportSettings()
{
var state = this._getState();
state.importControlsContainer.hide();
var element = state.importExportElement;
if(element.is(':visible')) {
element.hide();
} else {
element.val('');
element.show();
var settings = VRS.configStorage.exportSettings();
element.val(settings);
}
}
/**
* Displays the import controls.
*/
private _showImportControls()
{
var state = this._getState();
var element = state.importExportElement;
if(!element.is(':visible')) {
element.show();
element.val('');
state.importControlsContainer.show();
} else {
element.hide();
state.importControlsContainer.hide();
}
}
/**
* Takes the text in the import textarea and attempts to import it.
*/
private _importSettings(options: ConfigStorage_ImportOptions)
{
var state = this._getState();
var text = state.importExportElement.val();
if(text) {
state.currentKey = null;
try {
VRS.configStorage.importSettings(text, options);
this._refreshDisplay();
} catch(ex) {
VRS.pageHelper.showMessageBox(VRS.$$.ImportFailedTitle, VRS.stringUtility.format(VRS.$$.ImportFailedBody, ex));
}
}
}
/**
* Called when the user clicks on an entry for the key in the keys table.
* @param {string} keyName The name of the key that was clicked.
* @private
*/
private _keyClicked(keyName: string)
{
var content = VRS.configStorage.getContentWithoutPrefix(keyName);
this._showKeyContent(keyName, content);
}
}
$.widget('vrs.vrsStoredSettingsList', new StoredSettingsList());
}
declare interface JQuery
{
vrsStoredSettingsList();
vrsStoredSettingsList(options: {});
vrsStoredSettingsList(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any);
} | the_stack |
import {
ATNDeserializer, ATNDeserializationOptions, ATN, ATNType, LoopEndState, BlockStartState, ATNStateType,
InvalidState, ATNState, BlockEndState, DecisionState, RuleStartState, RuleStopState, TokensStartState, Transition,
RuleTransition, EpsilonTransition, PlusLoopbackState, PlusBlockStartState, StarLoopbackState, StarLoopEntryState,
LexerAction, LexerActionType, ActionTransition, LexerCustomAction, BasicBlockStartState, BasicState,
AtomTransition, TransitionType, ParserATNSimulator, SetTransition, RangeTransition, NotSetTransition,
} from "antlr4ts/atn";
import { UUID, IntervalSet, Array2DHashSet, Interval, BitSet } from "antlr4ts/misc";
import { NotNull } from "antlr4ts/Decorators";
import { Token } from "antlr4ts";
import { DFA } from "antlr4ts/dfa/DFA";
interface UnicodeDeserializer {
// Work around Java not allowing mutation of captured variables
// by returning amount by which to increment p after each read
readonly size: number;
// Wrapper for readInt() or readInt32()
readUnicode(data: Uint16Array, p: number): number;
}
const enum UnicodeDeserializingMode {
UNICODE_BMP,
UNICODE_SMP,
}
/**
* This derived deserializer makes loading of ATNs generated by standard ANTLR possible. The antlr4ts library uses
* an incompatible version.
* Unfortunately, we have to duplicate all the private stuff to make the class working.
*/
export class CompatibleATNDeserializer extends ATNDeserializer {
private static readonly BASE_SERIALIZED_UUID2: UUID = UUID.fromString("E4178468-DF95-44D0-AD87-F22A5D5FB6D3");
private static readonly ADDED_LEXER_ACTIONS2: UUID = UUID.fromString("AB35191A-1603-487E-B75A-479B831EAF6D");
private static readonly ADDED_UNICODE_SMP2: UUID = UUID.fromString("C23FEA89-0605-4f51-AFB8-058BCAB8C91B");
// antlr4ts uses a different UUID for ADDED_UNICODE_SMP than the original ANTLR4 tool.
private static readonly ADDED_UNICODE_SMP_ORIGINAL: UUID = UUID.fromString("59627784-3BE5-417A-B9EB-8131A7286089");
private static readonly SUPPORTED_UUIDS2: UUID[] = [
CompatibleATNDeserializer.BASE_SERIALIZED_UUID2,
CompatibleATNDeserializer.ADDED_LEXER_ACTIONS2,
CompatibleATNDeserializer.ADDED_UNICODE_SMP_ORIGINAL,
CompatibleATNDeserializer.ADDED_UNICODE_SMP2,
];
/**
* This is the current serialized UUID.
*/
private static readonly SERIALIZED_UUID2: UUID = CompatibleATNDeserializer.ADDED_UNICODE_SMP2;
@NotNull
private readonly deserializationOptions2: ATNDeserializationOptions;
public constructor(deserializationOptions?: ATNDeserializationOptions) {
super(deserializationOptions);
if (deserializationOptions == null) {
deserializationOptions = ATNDeserializationOptions.defaultOptions;
}
this.deserializationOptions2 = deserializationOptions;
}
/**
* Determines if a particular serialized representation of an ATN supports
* a particular feature, identified by the {@link UUID} used for serializing
* the ATN at the time the feature was first introduced.
*
* @param feature The {@link UUID} marking the first time the feature was
* supported in the serialized ATN.
* @param actualUuid The {@link UUID} of the actual serialized ATN which is
* currently being deserialized.
* @returns `true` if the `actualUuid` value represents a
* serialized ATN at or after the feature identified by `feature` was
* introduced; otherwise, `false`.
*/
public static isFeatureSupported(feature: UUID, actualUuid: UUID): boolean {
const featureIndex = CompatibleATNDeserializer.SUPPORTED_UUIDS2.findIndex((e) => e.equals(feature));
if (featureIndex < 0) {
return false;
}
return CompatibleATNDeserializer.SUPPORTED_UUIDS2.findIndex((e) => e.equals(actualUuid)) >= featureIndex;
}
private static getUnicodeDeserializer2(mode: UnicodeDeserializingMode): UnicodeDeserializer {
if (mode === UnicodeDeserializingMode.UNICODE_BMP) {
return {
readUnicode: (data: Uint16Array, p: number): number => ATNDeserializer.toInt(data[p]),
size: 1,
};
} else {
return {
readUnicode: (data: Uint16Array, p: number): number => ATNDeserializer.toInt32(data, p),
size: 2,
};
}
}
private static inlineSetRules2(atn: ATN): number {
let inlinedCalls = 0;
const ruleToInlineTransition = new Array<Transition | undefined>(atn.ruleToStartState.length);
for (let i = 0; i < atn.ruleToStartState.length; i++) {
const startState: RuleStartState = atn.ruleToStartState[i];
let middleState: ATNState = startState;
while (middleState.onlyHasEpsilonTransitions
&& middleState.numberOfOptimizedTransitions === 1
&& middleState.getOptimizedTransition(0).serializationType === TransitionType.EPSILON) {
middleState = middleState.getOptimizedTransition(0).target;
}
if (middleState.numberOfOptimizedTransitions !== 1) {
continue;
}
const matchTransition: Transition = middleState.getOptimizedTransition(0);
const matchTarget: ATNState = matchTransition.target;
if (matchTransition.isEpsilon
|| !matchTarget.onlyHasEpsilonTransitions
|| matchTarget.numberOfOptimizedTransitions !== 1
|| !(matchTarget.getOptimizedTransition(0).target instanceof RuleStopState)) {
continue;
}
switch (matchTransition.serializationType) {
case TransitionType.ATOM:
case TransitionType.RANGE:
case TransitionType.SET:
ruleToInlineTransition[i] = matchTransition;
break;
case TransitionType.NOT_SET:
case TransitionType.WILDCARD:
// not implemented yet
continue;
default:
continue;
}
}
for (const state of atn.states) {
if (state.ruleIndex < 0) {
continue;
}
let optimizedTransitions: Transition[] | undefined;
for (let i = 0; i < state.numberOfOptimizedTransitions; i++) {
const transition: Transition = state.getOptimizedTransition(i);
if (!(transition instanceof RuleTransition)) {
if (optimizedTransitions !== undefined) {
optimizedTransitions.push(transition);
}
continue;
}
const ruleTransition: RuleTransition = transition;
const effective = ruleToInlineTransition[ruleTransition.target.ruleIndex];
if (effective == null) {
if (optimizedTransitions !== undefined) {
optimizedTransitions.push(transition);
}
continue;
}
if (optimizedTransitions == null) {
optimizedTransitions = [];
for (let j = 0; j < i; j++) {
optimizedTransitions.push(state.getOptimizedTransition(i));
}
}
inlinedCalls++;
const target: ATNState = ruleTransition.followState;
const intermediateState: ATNState = new BasicState();
intermediateState.setRuleIndex(target.ruleIndex);
atn.addState(intermediateState);
optimizedTransitions.push(new EpsilonTransition(intermediateState));
switch (effective.serializationType) {
case TransitionType.ATOM:
intermediateState.addTransition(new AtomTransition(target,
(effective as AtomTransition).label.maxElement)); // The label interval only has one member.
break;
case TransitionType.RANGE:
intermediateState.addTransition(new RangeTransition(target, (effective as RangeTransition).from,
(effective as RangeTransition).to));
break;
case TransitionType.SET:
intermediateState.addTransition(new SetTransition(target, (effective as SetTransition).label));
break;
default:
throw new Error("UnsupportedOperationException");
}
}
if (optimizedTransitions !== undefined) {
if (state.isOptimized) {
while (state.numberOfOptimizedTransitions > 0) {
state.removeOptimizedTransition(state.numberOfOptimizedTransitions - 1);
}
}
for (const transition of optimizedTransitions) {
state.addOptimizedTransition(transition);
}
}
}
if (ParserATNSimulator.debug) {
console.log("ATN runtime optimizer removed " + inlinedCalls + " rule invocations by inlining sets.");
}
return inlinedCalls;
}
private static combineChainedEpsilons2(atn: ATN): number {
let removedEdges = 0;
for (const state of atn.states) {
if (!state.onlyHasEpsilonTransitions || state instanceof RuleStopState) {
continue;
}
let optimizedTransitions: Transition[] | undefined;
nextTransition:
for (let i = 0; i < state.numberOfOptimizedTransitions; i++) {
const transition: Transition = state.getOptimizedTransition(i);
const intermediate: ATNState = transition.target;
if (transition.serializationType !== TransitionType.EPSILON
|| (transition as EpsilonTransition).outermostPrecedenceReturn !== -1
|| intermediate.stateType !== ATNStateType.BASIC
|| !intermediate.onlyHasEpsilonTransitions) {
if (optimizedTransitions !== undefined) {
optimizedTransitions.push(transition);
}
continue;
}
for (let j = 0; j < intermediate.numberOfOptimizedTransitions; j++) {
if (intermediate.getOptimizedTransition(j).serializationType !== TransitionType.EPSILON
|| (intermediate.getOptimizedTransition(j) as EpsilonTransition)
.outermostPrecedenceReturn !== -1) {
if (optimizedTransitions !== undefined) {
optimizedTransitions.push(transition);
}
continue nextTransition;
}
}
removedEdges++;
if (optimizedTransitions == null) {
optimizedTransitions = [];
for (let j = 0; j < i; j++) {
optimizedTransitions.push(state.getOptimizedTransition(j));
}
}
for (let j = 0; j < intermediate.numberOfOptimizedTransitions; j++) {
const target: ATNState = intermediate.getOptimizedTransition(j).target;
optimizedTransitions.push(new EpsilonTransition(target));
}
}
if (optimizedTransitions !== undefined) {
if (state.isOptimized) {
while (state.numberOfOptimizedTransitions > 0) {
state.removeOptimizedTransition(state.numberOfOptimizedTransitions - 1);
}
}
for (const transition of optimizedTransitions) {
state.addOptimizedTransition(transition);
}
}
}
if (ParserATNSimulator.debug) {
console.log("ATN runtime optimizer removed " + removedEdges +
" transitions by combining chained epsilon transitions.");
}
return removedEdges;
}
private static optimizeSets2(atn: ATN, preserveOrder: boolean): number {
if (preserveOrder) {
// this optimization currently doesn't preserve edge order.
return 0;
}
let removedPaths = 0;
const decisions: DecisionState[] = atn.decisionToState;
for (const decision of decisions) {
const setTransitions: IntervalSet = new IntervalSet();
for (let i = 0; i < decision.numberOfOptimizedTransitions; i++) {
const epsTransition: Transition = decision.getOptimizedTransition(i);
if (!(epsTransition instanceof EpsilonTransition)) {
continue;
}
if (epsTransition.target.numberOfOptimizedTransitions !== 1) {
continue;
}
const transition: Transition = epsTransition.target.getOptimizedTransition(0);
if (!(transition.target instanceof BlockEndState)) {
continue;
}
if (transition instanceof NotSetTransition) {
// TODO: not yet implemented
continue;
}
if (transition instanceof AtomTransition
|| transition instanceof RangeTransition
|| transition instanceof SetTransition) {
setTransitions.add(i);
}
}
if (setTransitions.size <= 1) {
continue;
}
const optimizedTransitions: Transition[] = [];
for (let i = 0; i < decision.numberOfOptimizedTransitions; i++) {
if (!setTransitions.contains(i)) {
optimizedTransitions.push(decision.getOptimizedTransition(i));
}
}
const blockEndState: ATNState = decision.getOptimizedTransition(setTransitions.minElement).target
.getOptimizedTransition(0).target;
const matchSet: IntervalSet = new IntervalSet();
for (const interval of setTransitions.intervals) {
for (let j = interval.a; j <= interval.b; j++) {
const matchTransition = decision.getOptimizedTransition(j).target.getOptimizedTransition(0);
if (matchTransition instanceof NotSetTransition) {
throw new Error("Not yet implemented.");
} else {
matchSet.addAll(matchTransition.label as IntervalSet);
}
}
}
let newTransition: Transition;
if (matchSet.intervals.length === 1) {
if (matchSet.size === 1) {
newTransition = new AtomTransition(blockEndState, matchSet.minElement);
} else {
const matchInterval: Interval = matchSet.intervals[0];
newTransition = new RangeTransition(blockEndState, matchInterval.a, matchInterval.b);
}
} else {
newTransition = new SetTransition(blockEndState, matchSet);
}
const setOptimizedState: ATNState = new BasicState();
setOptimizedState.setRuleIndex(decision.ruleIndex);
atn.addState(setOptimizedState);
setOptimizedState.addTransition(newTransition);
optimizedTransitions.push(new EpsilonTransition(setOptimizedState));
removedPaths += decision.numberOfOptimizedTransitions - optimizedTransitions.length;
if (decision.isOptimized) {
while (decision.numberOfOptimizedTransitions > 0) {
decision.removeOptimizedTransition(decision.numberOfOptimizedTransitions - 1);
}
}
for (const transition of optimizedTransitions) {
decision.addOptimizedTransition(transition);
}
}
if (ParserATNSimulator.debug) {
console.log("ATN runtime optimizer removed " + removedPaths + " paths by collapsing sets.");
}
return removedPaths;
}
private static identifyTailCalls2(atn: ATN): void {
for (const state of atn.states) {
for (let i = 0; i < state.numberOfTransitions; i++) {
const transition = state.transition(i);
if (!(transition instanceof RuleTransition)) {
continue;
}
transition.tailCall = this.testTailCall2(atn, transition, false);
transition.optimizedTailCall = this.testTailCall2(atn, transition, true);
}
if (!state.isOptimized) {
continue;
}
for (let i = 0; i < state.numberOfOptimizedTransitions; i++) {
const transition = state.getOptimizedTransition(i);
if (!(transition instanceof RuleTransition)) {
continue;
}
transition.tailCall = this.testTailCall2(atn, transition, false);
transition.optimizedTailCall = this.testTailCall2(atn, transition, true);
}
}
}
private static testTailCall2(atn: ATN, transition: RuleTransition, optimizedPath: boolean): boolean {
if (!optimizedPath && transition.tailCall) {
return true;
}
if (optimizedPath && transition.optimizedTailCall) {
return true;
}
const reachable: BitSet = new BitSet(atn.states.length);
const worklist: ATNState[] = [];
worklist.push(transition.followState);
while (true) {
const state = worklist.pop();
if (!state) {
break;
}
if (reachable.get(state.stateNumber)) {
continue;
}
if (state instanceof RuleStopState) {
continue;
}
if (!state.onlyHasEpsilonTransitions) {
return false;
}
const transitionCount = optimizedPath ? state.numberOfOptimizedTransitions : state.numberOfTransitions;
for (let i = 0; i < transitionCount; i++) {
const t = optimizedPath ? state.getOptimizedTransition(i) : state.transition(i);
if (t.serializationType !== TransitionType.EPSILON) {
return false;
}
worklist.push(t.target);
}
}
return true;
}
public deserialize(@NotNull data: Uint16Array): ATN {
data = data.slice(0);
// Each Uint16 value in data is shifted by +2 at the entry to this method. This is an encoding optimization
// targeting the serialized values 0 and -1 (serialized to 0xFFFF), each of which are very common in the
// serialized form of the ATN. In the modified UTF-8 that Java uses for compiled string literals, these two
// character values have multi-byte forms. By shifting each value by +2, they become characters 2 and 1 prior to
// writing the string, each of which have single-byte representations. Since the shift occurs in the tool during
// ATN serialization, each target is responsible for adjusting the values during deserialization.
//
// As a special case, note that the first element of data is not adjusted because it contains the major version
// number of the serialized ATN, which was fixed at 3 at the time the value shifting was implemented.
for (let i = 1; i < data.length; i++) {
data[i] = (data[i] - 2) & 0xFFFF;
}
let p = 0;
const version: number = ATNDeserializer.toInt(data[p++]);
if (version !== ATNDeserializer.SERIALIZED_VERSION) {
const reason =
`Could not deserialize ATN with version ${version} (expected ${ATNDeserializer.SERIALIZED_VERSION}).`;
throw new Error(reason);
}
const uuid: UUID = ATNDeserializer.toUUID(data, p);
p += 8;
if (CompatibleATNDeserializer.SUPPORTED_UUIDS2.findIndex((e) => e.equals(uuid)) < 0) {
const reason = `Could not deserialize ATN with UUID ${uuid.toString()} (expected ` +
`${CompatibleATNDeserializer.SERIALIZED_UUID2.toString()} or a legacy UUID).`;
throw new Error(reason);
}
const generatedByOriginalANTLR4 = uuid.equals(CompatibleATNDeserializer.ADDED_UNICODE_SMP_ORIGINAL);
const supportsLexerActions: boolean = CompatibleATNDeserializer.isFeatureSupported(
CompatibleATNDeserializer.ADDED_LEXER_ACTIONS2, uuid,
);
const grammarType: ATNType = ATNDeserializer.toInt(data[p++]);
const maxTokenType: number = ATNDeserializer.toInt(data[p++]);
const atn: ATN = new ATN(grammarType, maxTokenType);
//
// STATES
//
const loopBackStateNumbers: Array<[LoopEndState, number]> = [];
const endStateNumbers: Array<[BlockStartState, number]> = [];
const nstates: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < nstates; i++) {
const stype: ATNStateType = ATNDeserializer.toInt(data[p++]);
// ignore bad type of states
if (stype === ATNStateType.INVALID_TYPE) {
atn.addState(new InvalidState());
continue;
}
let ruleIndex: number = ATNDeserializer.toInt(data[p++]);
if (ruleIndex === 0xFFFF) {
ruleIndex = -1;
}
const s: ATNState = this.stateFactory(stype, ruleIndex);
if (stype === ATNStateType.LOOP_END) { // special case
const loopBackStateNumber: number = ATNDeserializer.toInt(data[p++]);
loopBackStateNumbers.push([s as LoopEndState, loopBackStateNumber]);
} else if (s instanceof BlockStartState) {
const endStateNumber: number = ATNDeserializer.toInt(data[p++]);
endStateNumbers.push([s, endStateNumber]);
}
atn.addState(s);
}
// delay the assignment of loop back and end states until we know all the state instances have been initialized
for (const pair of loopBackStateNumbers) {
pair[0].loopBackState = atn.states[pair[1]];
}
for (const pair of endStateNumbers) {
pair[0].endState = atn.states[pair[1]] as BlockEndState;
}
const numNonGreedyStates: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < numNonGreedyStates; i++) {
const stateNumber: number = ATNDeserializer.toInt(data[p++]);
(atn.states[stateNumber] as DecisionState).nonGreedy = true;
}
if (!generatedByOriginalANTLR4) {
const numSllDecisions: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < numSllDecisions; i++) {
const stateNumber: number = ATNDeserializer.toInt(data[p++]);
(atn.states[stateNumber] as DecisionState).sll = true;
}
}
const numPrecedenceStates: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < numPrecedenceStates; i++) {
const stateNumber: number = ATNDeserializer.toInt(data[p++]);
(atn.states[stateNumber] as RuleStartState).isPrecedenceRule = true;
}
//
// RULES
//
const nrules: number = ATNDeserializer.toInt(data[p++]);
if (atn.grammarType === ATNType.LEXER) {
atn.ruleToTokenType = new Int32Array(nrules);
}
atn.ruleToStartState = new Array<RuleStartState>(nrules);
for (let i = 0; i < nrules; i++) {
const s: number = ATNDeserializer.toInt(data[p++]);
const startState: RuleStartState = atn.states[s] as RuleStartState;
if (!generatedByOriginalANTLR4) {
startState.leftFactored = ATNDeserializer.toInt(data[p++]) !== 0;
}
atn.ruleToStartState[i] = startState;
if (atn.grammarType === ATNType.LEXER) {
let tokenType: number = ATNDeserializer.toInt(data[p++]);
if (tokenType === 0xFFFF) {
tokenType = Token.EOF;
}
atn.ruleToTokenType[i] = tokenType;
if (!CompatibleATNDeserializer.isFeatureSupported(
CompatibleATNDeserializer.ADDED_LEXER_ACTIONS2, uuid)) {
// this piece of unused metadata was serialized prior to the
// addition of LexerAction
let actionIndexIgnored: number = ATNDeserializer.toInt(data[p++]);
if (actionIndexIgnored === 0xFFFF) {
actionIndexIgnored = -1;
}
}
}
}
atn.ruleToStopState = new Array<RuleStopState>(nrules);
for (const state of atn.states) {
if (!(state instanceof RuleStopState)) {
continue;
}
atn.ruleToStopState[state.ruleIndex] = state;
atn.ruleToStartState[state.ruleIndex].stopState = state;
}
//
// MODES
//
const nmodes: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < nmodes; i++) {
const s: number = ATNDeserializer.toInt(data[p++]);
atn.modeToStartState.push(atn.states[s] as TokensStartState);
}
atn.modeToDFA = new Array<DFA>(nmodes);
for (let i = 0; i < nmodes; i++) {
atn.modeToDFA[i] = new DFA(atn.modeToStartState[i]);
}
//
// SETS
//
const sets: IntervalSet[] = [];
// First, read all sets with 16-bit Unicode code points <= U+FFFF.
p = this.deserializeSets2(data, p, sets,
CompatibleATNDeserializer.getUnicodeDeserializer2(UnicodeDeserializingMode.UNICODE_BMP));
// Next, if the ATN was serialized with the Unicode SMP feature,
// deserialize sets with 32-bit arguments <= U+10FFFF.
if (CompatibleATNDeserializer.isFeatureSupported(CompatibleATNDeserializer.ADDED_UNICODE_SMP2, uuid)
|| CompatibleATNDeserializer.isFeatureSupported(
CompatibleATNDeserializer.ADDED_UNICODE_SMP_ORIGINAL, uuid)) {
p = this.deserializeSets2(data, p, sets,
CompatibleATNDeserializer.getUnicodeDeserializer2(UnicodeDeserializingMode.UNICODE_SMP));
}
//
// EDGES
//
const nedges: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < nedges; i++) {
const src: number = ATNDeserializer.toInt(data[p]);
const trg: number = ATNDeserializer.toInt(data[p + 1]);
const ttype: number = ATNDeserializer.toInt(data[p + 2]);
const arg1: number = ATNDeserializer.toInt(data[p + 3]);
const arg2: number = ATNDeserializer.toInt(data[p + 4]);
const arg3: number = ATNDeserializer.toInt(data[p + 5]);
const trans: Transition = this.edgeFactory(atn, ttype, src, trg, arg1, arg2, arg3, sets);
const srcState: ATNState = atn.states[src];
srcState.addTransition(trans);
p += 6;
}
// edges for rule stop states can be derived, so they aren't serialized
interface T { stopState: number; returnState: number; outermostPrecedenceReturn: number }
const returnTransitionsSet = new Array2DHashSet<T>({
hashCode: (o: T) => o.stopState ^ o.returnState ^ o.outermostPrecedenceReturn,
equals: (a: T, b: T): boolean => a.stopState === b.stopState
&& a.returnState === b.returnState
&& a.outermostPrecedenceReturn === b.outermostPrecedenceReturn,
});
const returnTransitions: T[] = [];
for (const state of atn.states) {
const returningToLeftFactored: boolean = state.ruleIndex >= 0
&& atn.ruleToStartState[state.ruleIndex].leftFactored;
for (let i = 0; i < state.numberOfTransitions; i++) {
const t: Transition = state.transition(i);
if (!(t instanceof RuleTransition)) {
continue;
}
const ruleTransition: RuleTransition = t;
const returningFromLeftFactored = atn.ruleToStartState[ruleTransition.target.ruleIndex].leftFactored;
if (!returningFromLeftFactored && returningToLeftFactored) {
continue;
}
let outermostPrecedenceReturn = -1;
if (atn.ruleToStartState[ruleTransition.target.ruleIndex].isPrecedenceRule) {
if (ruleTransition.precedence === 0) {
outermostPrecedenceReturn = ruleTransition.target.ruleIndex;
}
}
const current = {
stopState: ruleTransition.target.ruleIndex,
returnState: ruleTransition.followState.stateNumber,
outermostPrecedenceReturn,
};
if (returnTransitionsSet.add(current)) {
returnTransitions.push(current);
}
}
}
// Add all elements from returnTransitions to the ATN
for (const returnTransition of returnTransitions) {
const transition = new EpsilonTransition(atn.states[returnTransition.returnState],
returnTransition.outermostPrecedenceReturn);
atn.ruleToStopState[returnTransition.stopState].addTransition(transition);
}
for (const state of atn.states) {
if (state instanceof BlockStartState) {
// we need to know the end state to set its start state
if (state.endState == null) {
throw new Error("IllegalStateException");
}
// block end states can only be associated to a single block start state
if (state.endState.startState !== undefined) {
throw new Error("IllegalStateException");
}
state.endState.startState = state;
}
if (state instanceof PlusLoopbackState) {
const loopbackState: PlusLoopbackState = state;
for (let i = 0; i < loopbackState.numberOfTransitions; i++) {
const target: ATNState = loopbackState.transition(i).target;
if (target instanceof PlusBlockStartState) {
target.loopBackState = loopbackState;
}
}
} else if (state instanceof StarLoopbackState) {
const loopbackState: StarLoopbackState = state;
for (let i = 0; i < loopbackState.numberOfTransitions; i++) {
const target: ATNState = loopbackState.transition(i).target;
if (target instanceof StarLoopEntryState) {
target.loopBackState = loopbackState;
}
}
}
}
//
// DECISIONS
//
const ndecisions: number = ATNDeserializer.toInt(data[p++]);
for (let i = 1; i <= ndecisions; i++) {
const s: number = ATNDeserializer.toInt(data[p++]);
const decState: DecisionState = atn.states[s] as DecisionState;
atn.decisionToState.push(decState);
decState.decision = i - 1;
}
//
// LEXER ACTIONS
//
if (atn.grammarType === ATNType.LEXER) {
if (supportsLexerActions) {
atn.lexerActions = new Array<LexerAction>(ATNDeserializer.toInt(data[p++]));
for (let i = 0; i < atn.lexerActions.length; i++) {
const actionType: LexerActionType = ATNDeserializer.toInt(data[p++]);
let data1: number = ATNDeserializer.toInt(data[p++]);
if (data1 === 0xFFFF) {
data1 = -1;
}
let data2: number = ATNDeserializer.toInt(data[p++]);
if (data2 === 0xFFFF) {
data2 = -1;
}
const lexerAction: LexerAction = this.lexerActionFactory(actionType, data1, data2);
atn.lexerActions[i] = lexerAction;
}
} else {
// for compatibility with older serialized ATNs, convert the old
// serialized action index for action transitions to the new
// form, which is the index of a LexerCustomAction
const legacyLexerActions: LexerAction[] = [];
for (const state of atn.states) {
for (let i = 0; i < state.numberOfTransitions; i++) {
const transition: Transition = state.transition(i);
if (!(transition instanceof ActionTransition)) {
continue;
}
const ruleIndex: number = transition.ruleIndex;
const actionIndex: number = transition.actionIndex;
const lexerAction: LexerCustomAction = new LexerCustomAction(ruleIndex, actionIndex);
state.setTransition(i, new ActionTransition(transition.target, ruleIndex,
legacyLexerActions.length, false));
legacyLexerActions.push(lexerAction);
}
}
atn.lexerActions = legacyLexerActions;
}
}
this.markPrecedenceDecisions(atn);
atn.decisionToDFA = new Array<DFA>(ndecisions);
for (let i = 0; i < ndecisions; i++) {
atn.decisionToDFA[i] = new DFA(atn.decisionToState[i], i);
}
if (this.deserializationOptions2.isVerifyATN) {
this.verifyATN(atn);
}
if (this.deserializationOptions2.isGenerateRuleBypassTransitions && atn.grammarType === ATNType.PARSER) {
atn.ruleToTokenType = new Int32Array(atn.ruleToStartState.length);
for (let i = 0; i < atn.ruleToStartState.length; i++) {
atn.ruleToTokenType[i] = atn.maxTokenType + i + 1;
}
for (let i = 0; i < atn.ruleToStartState.length; i++) {
const bypassStart: BasicBlockStartState = new BasicBlockStartState();
bypassStart.ruleIndex = i;
atn.addState(bypassStart);
const bypassStop: BlockEndState = new BlockEndState();
bypassStop.ruleIndex = i;
atn.addState(bypassStop);
bypassStart.endState = bypassStop;
atn.defineDecisionState(bypassStart);
bypassStop.startState = bypassStart;
let endState: ATNState | undefined;
let excludeTransition: Transition | undefined;
if (atn.ruleToStartState[i].isPrecedenceRule) {
// wrap from the beginning of the rule to the StarLoopEntryState
endState = undefined;
for (const state of atn.states) {
if (state.ruleIndex !== i) {
continue;
}
if (!(state instanceof StarLoopEntryState)) {
continue;
}
const maybeLoopEndState: ATNState = state.transition(state.numberOfTransitions - 1).target;
if (!(maybeLoopEndState instanceof LoopEndState)) {
continue;
}
if (maybeLoopEndState.epsilonOnlyTransitions
&& maybeLoopEndState.transition(0).target instanceof RuleStopState) {
endState = state;
break;
}
}
if (!endState) {
throw new Error("Couldn't identify final state of the precedence rule prefix section.");
}
excludeTransition = (endState as StarLoopEntryState).loopBackState.transition(0);
} else {
endState = atn.ruleToStopState[i];
}
// all non-excluded transitions that currently target end state need to target blockEnd instead
for (const state of atn.states) {
for (let tansitionIndex = 0; tansitionIndex < state.numberOfTransitions; tansitionIndex++) {
const transition = state.transition(tansitionIndex);
if (transition === excludeTransition) {
continue;
}
if (transition.target === endState) {
transition.target = bypassStop;
}
}
}
// all transitions leaving the rule start state need to leave blockStart instead
while (atn.ruleToStartState[i].numberOfTransitions > 0) {
const transition: Transition = atn.ruleToStartState[i].removeTransition(
atn.ruleToStartState[i].numberOfTransitions - 1);
bypassStart.addTransition(transition);
}
// link the new states
atn.ruleToStartState[i].addTransition(new EpsilonTransition(bypassStart));
bypassStop.addTransition(new EpsilonTransition(endState));
const matchState: ATNState = new BasicState();
atn.addState(matchState);
matchState.addTransition(new AtomTransition(bypassStop, atn.ruleToTokenType[i]));
bypassStart.addTransition(new EpsilonTransition(matchState));
}
if (this.deserializationOptions2.isVerifyATN) {
// reverify after modification
this.verifyATN(atn);
}
}
if (this.deserializationOptions2.isOptimize) {
while (true) {
let optimizationCount = 0;
optimizationCount += CompatibleATNDeserializer.inlineSetRules2(atn);
optimizationCount += CompatibleATNDeserializer.combineChainedEpsilons2(atn);
const preserveOrder: boolean = atn.grammarType === ATNType.LEXER;
optimizationCount += CompatibleATNDeserializer.optimizeSets2(atn, preserveOrder);
if (optimizationCount === 0) {
break;
}
}
if (this.deserializationOptions2.isVerifyATN) {
// reverify after modification
this.verifyATN(atn);
}
}
CompatibleATNDeserializer.identifyTailCalls2(atn);
return atn;
}
private deserializeSets2(data: Uint16Array, p: number, sets: IntervalSet[],
unicodeDeserializer: UnicodeDeserializer): number {
const nsets: number = ATNDeserializer.toInt(data[p++]);
for (let i = 0; i < nsets; i++) {
const nintervals: number = ATNDeserializer.toInt(data[p]);
p++;
const set: IntervalSet = new IntervalSet();
sets.push(set);
const containsEof: boolean = ATNDeserializer.toInt(data[p++]) !== 0;
if (containsEof) {
set.add(-1);
}
for (let j = 0; j < nintervals; j++) {
const a: number = unicodeDeserializer.readUnicode(data, p);
p += unicodeDeserializer.size;
const b: number = unicodeDeserializer.readUnicode(data, p);
p += unicodeDeserializer.size;
set.add(a, b);
}
}
return p;
}
} | the_stack |
import bytes from "bytes";
import convict from "convict";
import Joi from "joi";
import { compact } from "lodash";
import { parseConnectionString } from "mongodb-core";
import ms from "ms";
import { LOCALES } from "coral-common/helpers/i18n/locales";
import { ensureEndSlash } from "coral-common/utils";
import { WrappedInternalError } from "./errors";
// Add custom format for the mongo uri scheme.
convict.addFormat({
name: "mongo-uri",
validate: (url: string) => {
parseConnectionString(url, (err) => {
if (err) {
throw new WrappedInternalError(err, "invalid mongo-uri");
}
});
},
});
// Add custom format for the redis uri scheme.
convict.addFormat({
name: "redis-uri",
validate: (url: string) => {
Joi.assert(
url,
Joi.string().uri({
scheme: ["redis"],
})
);
},
});
// Add a custom format for the optional-trailing-url that includes a trailing
// slash.
convict.addFormat({
name: "optional-trailing-url",
validate: (url: string) => {
if (url) {
Joi.assert(url, Joi.string().uri());
}
},
// Ensure that there is an ending slash.
coerce: (url: string) => (url ? ensureEndSlash(url) : url),
});
// Add a custom format for the optional-url.
convict.addFormat({
name: "optional-url",
validate: (url: string) => {
if (url) {
Joi.assert(url, Joi.string().uri());
}
},
});
// Add a custom format for domain.
convict.addFormat({
name: "domain",
validate: (domain: string) => {
if (domain) {
Joi.assert(domain, Joi.string().domain());
}
},
});
// Add a custom format for a list of comma seperated strings.
convict.addFormat({
name: "list",
validate: (list: string[]) => {
if (!list || list.length === 0) {
throw new Error("list should not contain empty entries");
}
},
coerce: (list: string) => compact(list.split(",").map((item) => item.trim())),
});
// Add a custom format that is a duration parsed with `ms` to used instead of
// the default format which will use `moment`.
convict.addFormat({
name: "ms",
validate: (val: number) => {
Joi.assert(val, Joi.number().positive().integer().required());
},
coerce: (val: string): number => ms(val),
});
// Add a custom format that is a number of bytes parsed with `bytes`. This
// allows more compact representations of values (10mb instead of 10e6).
convict.addFormat({
name: "bytes",
validate: (val: number) => {
Joi.assert(val, Joi.number().positive().integer().required());
},
coerce: (val: string): number => bytes(val),
});
const algorithms = [
"HS256",
"HS384",
"HS512",
"RS256",
"RS384",
"RS512",
"ES256",
"ES384",
"ES512",
];
const config = convict({
env: {
doc: "The application environment.",
format: ["production", "development", "test"],
default: "development",
env: "NODE_ENV",
},
default_locale: {
doc:
"Specify the default locale to use for all requests without a locale specified",
format: LOCALES,
default: "en-US",
env: "LOCALE",
},
trust_proxy: {
doc:
'When provided, it configures the "trust proxy" settings for Express (See https://expressjs.com/en/guide/behind-proxies.html)',
format: String,
default: "",
env: "TRUST_PROXY",
},
enable_graphiql: {
doc: "When true, this will enable the GraphiQL interface at /graphiql",
format: Boolean,
default: false,
env: "ENABLE_GRAPHIQL",
},
port: {
doc: "The port to bind.",
format: "port",
default: 3000,
env: "PORT",
},
metrics_username: {
doc: "The username to use to authenticate to the metrics endpoint.",
format: "String",
default: "",
env: "METRICS_USERNAME",
},
metrics_password: {
doc: "The password to use to authenticate to the metrics endpoint.",
format: "String",
default: "",
env: "METRICS_PASSWORD",
sensitive: true,
},
metrics_port: {
doc: "The port that the metrics handler should be mounted.",
format: "port",
default: 9000,
env: "METRICS_PORT",
},
dev_port: {
doc: "The port to bind for the Webpack Dev Server.",
format: "port",
default: 8080,
env: "DEV_PORT",
},
mongodb: {
doc: "The MongoDB database to connect to.",
format: "mongo-uri",
default: "mongodb://127.0.0.1:27017/coral",
env: "MONGODB_URI",
sensitive: true,
},
mongodb_archive: {
doc: "The MongoDB database to connect for archiving stories.",
format: "mongo-uri",
default: "mongodb://127.0.0.1:27017/coral",
env: "MONGODB_ARCHIVE_URI",
sensitive: true,
},
redis: {
doc: "The Redis database to connect to.",
format: "redis-uri",
default: "redis://127.0.0.1:6379",
env: "REDIS_URI",
sensitive: true,
},
redis_options: {
doc: "The Redis options to connect to Redis Server.",
format: Object,
default: {},
env: "REDIS_OPTIONS",
},
signing_secret: {
doc:
"The shared secret to use to sign JSON Web Tokens (JWT) with the selected signing algorithm.",
format: "*",
default: "keyboard cat", // TODO: (wyattjoh) evaluate best solution
env: "SIGNING_SECRET",
sensitive: true,
},
signing_algorithm: {
doc: "The signing algorithm used to sign JSON Web Tokens (JWT).",
format: algorithms,
default: "HS256",
env: "SIGNING_ALGORITHM",
},
management_signing_secret: {
doc: "The secret used to verify management API requests.",
format: "*",
default: null,
env: "MANAGEMENT_SIGNING_SECRET",
sensitive: true,
},
management_signing_algorithm: {
doc: "The algorithm used to sign management API requests",
format: algorithms,
default: "HS256",
env: "MANAGEMENT_SIGNING_ALGORITHM",
},
logging_level: {
doc: "The logging level to print to the console",
format: ["fatal", "error", "warn", "info", "debug", "trace"],
default: "info",
env: "LOGGING_LEVEL",
},
static_uri: {
doc: "The URL that static assets will be hosted from",
format: "optional-trailing-url",
default: "",
env: "STATIC_URI",
},
graphql_subscription_uri: {
doc:
"The URL that should be used for GraphQL subscription traffic over websockets. Example: wss://yourdomain.com/api/graphql/live",
format: "optional-url",
default: "",
env: "GRAPHQL_SUBSCRIPTION_URI",
},
websocket_keep_alive_timeout: {
doc:
"The keepalive timeout (in ms) that should be used to send keep alive messages through the websocket to keep the socket alive",
format: "ms",
default: ms("30 seconds"),
env: "WEBSOCKET_KEEP_ALIVE_TIMEOUT",
},
disable_tenant_caching: {
doc:
"Disables the tenant caching, all tenants will be loaded from MongoDB each time it's needed",
format: Boolean,
default: false,
env: "DISABLE_TENANT_CACHING",
},
disable_live_updates: {
doc:
"Disables subscriptions for the comment stream for all stories across all tenants",
format: Boolean,
default: false,
env: "DISABLE_LIVE_UPDATES",
},
disable_live_updates_timeout: {
doc:
"Disables subscriptions for the comment stream for all stories across all tenants where a comment has not been left within the timeout",
format: "ms",
default: ms("2 weeks"),
env: "DISABLE_LIVE_UPDATES_TIMEOUT",
},
disable_client_routes: {
doc:
"Disables mounting of client routes for developing with Webpack Dev Server",
format: Boolean,
default: false,
env: "DISABLE_CLIENT_ROUTES",
},
disable_rate_limiters: {
doc:
"Disables the rate limiters in development. This will only work when also set to a development environment",
format: Boolean,
default: false,
env: "DISABLE_RATE_LIMITERS",
},
scrape_max_response_size: {
doc: "The maximum size (in bytes) to allow for scraping responses.",
format: "bytes",
default: bytes("10mb"),
env: "SCRAPE_MAX_RESPONSE_SIZE",
},
max_request_size: {
doc: "The maximum size (in bytes) to allow for post bodies to accept.",
format: "bytes",
default: bytes("500kb"),
env: "MAX_REQUEST_SIZE",
},
scrape_timeout: {
doc: "The request timeout (in ms) for scraping operations.",
format: "ms",
default: ms("10 seconds"),
env: "SCRAPE_TIMEOUT",
},
perspective_timeout: {
doc:
"The request timeout (in ms) for perspective comment checking operations.",
format: "ms",
default: ms("800 milliseconds"),
env: "PERSPECTIVE_TIMEOUT",
},
story_viewer_timeout: {
doc:
"The length of time (in ms) that a user should be considered active on a story without interaction.",
format: "ms",
default: ms("15 minutes"),
env: "STORY_VIEWER_TIMEOUT",
},
force_ssl: {
doc:
"Forces SSL in production by redirecting all HTTP requests to HTTPS, and sending HSTS headers.",
format: Boolean,
default: false,
env: "FORCE_SSL",
},
disable_job_processors: {
doc: "Disables job processors when running.",
format: Boolean,
default: false,
env: "DISABLE_JOB_PROCESSORS",
},
word_list_timeout: {
doc:
"The word list timeout (in ms) that should be used to limit the amount of time the process is frozen processing a word list comparison",
format: "ms",
default: ms("100ms"),
env: "WORD_LIST_TIMEOUT",
},
sentry_frontend_key: {
format: String,
default: "",
env: "SENTRY_FRONTEND_KEY",
},
sentry_backend_key: {
format: String,
default: "",
env: "SENTRY_BACKEND_KEY",
},
analytics_frontend_key: {
doc: "Analytics write key from RudderStack for the Javascript client.",
format: String,
default: "",
env: "ANALYTICS_FRONTEND_KEY",
},
analytics_backend_key: {
doc: "Analytics write key from RudderStack for the Node server.",
format: String,
default: "",
env: "ANALYTICS_BACKEND_KEY",
},
analytics_frontend_sdk_url: {
doc: "Analytics URL to the RudderStack Frontend JS SDK. Defaults to the ",
format: "url",
default: "https://cdn.rudderlabs.com/v1/rudder-analytics.min.js",
env: "ANALYTICS_FRONTEND_SDK_URL",
},
analytics_data_plane_url: {
doc: "Analytics URL to the RudderStack data plane instance.",
format: "optional-trailing-url",
default: "",
env: "ANALYTICS_DATA_PLANE_URL",
},
jsonp_cache_max_age: {
doc:
"The max age for jsonp endpoints designed to be used as embeddable scripts.",
format: "ms",
default: ms("2m"),
env: "JSONP_CACHE_MAX_AGE",
},
jsonp_cache_immutable: {
doc:
"When enabled, jsonp endpoints designed to be used as embeddable scripts will have an immutable directive added to the cache control headers.",
format: Boolean,
default: false,
env: "JSONP_CACHE_IMMUTABLE",
},
jsonp_response_cache: {
doc: "When enabled, will enable caching JSONP responses in Redis.",
format: Boolean,
default: false,
env: "JSONP_RESPONSE_CACHE",
},
default_graphql_cache_max_age: {
doc:
"Specifies the max age for the GraphQL requests. Must be larger than 1 second.",
format: "ms",
default: ms("30 seconds"),
env: "DEFAULT_GRAPHQL_CACHE_MAX_AGE",
},
graphql_response_cache: {
doc: "When enabled, will enable caching GraphQL responses in Redis.",
format: Boolean,
default: false,
env: "GRAPHQL_RESPONSE_CACHE",
},
graphql_cache_headers: {
doc:
"When enabled, Coral will send Cache-Control headers along with GraphQL requests. If this is not enabled, the response cache is also not enabled.",
format: Boolean,
default: false,
env: "GRAPHQL_CACHE_HEADERS",
},
nodejs_keep_alive_timeout: {
doc:
"Specifies the keep alive timeout to set for the HTTP server used by Coral.",
format: "ms",
default: ms("5s"),
env: "NODEJS_KEEP_ALIVE_TIMEOUT",
},
nodejs_headers_timeout: {
doc:
"Specifies the headers timeout to set for the HTTP server used by Coral.",
format: "ms",
default: ms("1m"),
env: "NODEJS_HEADERS_TIMEOUT",
},
google_cloud_profiler: {
doc:
"When enabled, will start the Google Cloud Profiler using the default application credentials.",
format: Boolean,
default: false,
env: "GOOGLE_CLOUD_PROFILER",
},
google_cloud_profiler_service_context: {
doc:
"Passed down to the Google Cloud Profiler if enabled as `{ serviceContext }`.",
format: Object,
default: {},
env: "GOOGLE_CLOUD_PROFILER_SERVICE_CONTEXT",
},
amp_cache_domains: {
doc: "Specifies the amp cache domains as a comma seperated list",
format: "list",
default: ["cdn.ampproject.org"],
env: "AMP_CACHE_DOMAINS",
},
smtp_transport_send_max: {
doc:
"Maximum number of emails that a given transport can send before it's reset.",
env: "SMTP_TRANSPORT_SEND_MAX",
format: Number,
default: 50,
},
smtp_transport_timeout: {
doc:
"Maximum time that the transport can take sending a Email before it aborts.",
format: "ms",
default: ms("20s"),
env: "SMTP_TRANSPORT_TIMEOUT",
},
mailer_job_timeout: {
doc:
"Maximum time that the mailer can take to process any mailer jobs before it aborts.",
format: "ms",
default: ms("30s"),
env: "MAILER_JOB_TIMEOUT",
},
download_gdpr_comments_link_domain: {
doc:
"Specifies an alternative domain to be used for the download GDPR comments link sent out in emails. If set to default empty string, will use the tenant domain. Example: yourdomain.com",
format: "domain",
default: "",
env: "DOWNLOAD_GDPR_COMMENTS_LINK_DOMAIN",
},
non_fingerprinted_cache_max_age: {
doc: "Max age for the ",
format: "ms",
default: ms("30 minutes"),
env: "NON_FINGERPRINTED_CACHE_MAX_AGE",
},
enable_auto_archiving: {
doc:
"Enables auto archiving for stories older than the specified interval.",
format: Boolean,
default: false,
env: "ENABLE_AUTO_ARCHIVING",
},
auto_archive_older_than: {
doc:
"If stories are older than this age, they will be auto archived if auto archiving is enabled.",
format: "ms",
default: ms("120 days"),
env: "AUTO_ARCHIVE_OLDER_THAN",
},
auto_archiving_interval: {
doc:
"The cron scheduling interval for how often auto archiving should run.",
format: String,
default: "0,15,30,45 * * * *",
env: "AUTO_ARCHIVING_INTERVAL",
},
auto_archiving_batch_size: {
doc:
"Determines how many stories to try and archive per interval of archiving.",
format: Number,
default: 500,
env: "AUTO_ARCHIVING_BATCH_SIZE",
},
force_admin_local_auth: {
doc:
"Will force local auth in the admin to on so that it cannot be turned off.",
format: Boolean,
default: false,
env: "FORCE_ADMIN_LOCAL_AUTH",
},
});
export type Config = typeof config;
// Setup the base configuration.
export default config; | the_stack |
import 'vs/css!./inspectEditorTokens';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { CharCode } from 'vs/base/common/charCode';
import { Color } from 'vs/base/common/color';
import { KeyCode } from 'vs/base/common/keyCodes';
import { Disposable } from 'vs/base/common/lifecycle';
import { ContentWidgetPositionPreference, IActiveCodeEditor, ICodeEditor, IContentWidget, IContentWidgetPosition } from 'vs/editor/browser/editorBrowser';
import { EditorAction, ServicesAccessor, registerEditorAction, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { ITextModel } from 'vs/editor/common/model';
import { SemanticTokensLegend, SemanticTokens } from 'vs/editor/common/languages';
import { FontStyle, ColorId, StandardTokenType, TokenMetadata } from 'vs/editor/common/encodedTokenAttributes';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { editorHoverBackground, editorHoverBorder } from 'vs/platform/theme/common/colorRegistry';
import { registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { findMatchingThemeRule } from 'vs/workbench/services/textMate/common/TMHelper';
import { ITextMateService } from 'vs/workbench/services/textMate/browser/textMate';
import type { IGrammar, IToken, StackElement } from 'vscode-textmate';
import { IWorkbenchThemeService } from 'vs/workbench/services/themes/common/workbenchThemeService';
import { CancellationTokenSource } from 'vs/base/common/cancellation';
import { ColorThemeData, TokenStyleDefinitions, TokenStyleDefinition, TextMateThemingRuleDefinitions } from 'vs/workbench/services/themes/common/colorThemeData';
import { SemanticTokenRule, TokenStyleData, TokenStyle } from 'vs/platform/theme/common/tokenClassificationRegistry';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { SEMANTIC_HIGHLIGHTING_SETTING_ID, IEditorSemanticHighlightingOptions } from 'vs/editor/common/services/modelService';
import { isHighContrast } from 'vs/platform/theme/common/theme';
import { Schemas } from 'vs/base/common/network';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
const $ = dom.$;
class InspectEditorTokensController extends Disposable implements IEditorContribution {
public static readonly ID = 'editor.contrib.inspectEditorTokens';
public static get(editor: ICodeEditor): InspectEditorTokensController | null {
return editor.getContribution<InspectEditorTokensController>(InspectEditorTokensController.ID);
}
private _editor: ICodeEditor;
private _textMateService: ITextMateService;
private _themeService: IWorkbenchThemeService;
private _languageService: ILanguageService;
private _notificationService: INotificationService;
private _configurationService: IConfigurationService;
private _languageFeaturesService: ILanguageFeaturesService;
private _widget: InspectEditorTokensWidget | null;
constructor(
editor: ICodeEditor,
@ITextMateService textMateService: ITextMateService,
@ILanguageService languageService: ILanguageService,
@IWorkbenchThemeService themeService: IWorkbenchThemeService,
@INotificationService notificationService: INotificationService,
@IConfigurationService configurationService: IConfigurationService,
@ILanguageFeaturesService languageFeaturesService: ILanguageFeaturesService
) {
super();
this._editor = editor;
this._textMateService = textMateService;
this._themeService = themeService;
this._languageService = languageService;
this._notificationService = notificationService;
this._configurationService = configurationService;
this._languageFeaturesService = languageFeaturesService;
this._widget = null;
this._register(this._editor.onDidChangeModel((e) => this.stop()));
this._register(this._editor.onDidChangeModelLanguage((e) => this.stop()));
this._register(this._editor.onKeyUp((e) => e.keyCode === KeyCode.Escape && this.stop()));
}
public override dispose(): void {
this.stop();
super.dispose();
}
public launch(): void {
if (this._widget) {
return;
}
if (!this._editor.hasModel()) {
return;
}
if (this._editor.getModel().uri.scheme === Schemas.vscodeNotebookCell) {
// disable in notebooks
return;
}
this._widget = new InspectEditorTokensWidget(this._editor, this._textMateService, this._languageService, this._themeService, this._notificationService, this._configurationService, this._languageFeaturesService);
}
public stop(): void {
if (this._widget) {
this._widget.dispose();
this._widget = null;
}
}
public toggle(): void {
if (!this._widget) {
this.launch();
} else {
this.stop();
}
}
}
class InspectEditorTokens extends EditorAction {
constructor() {
super({
id: 'editor.action.inspectTMScopes',
label: nls.localize('inspectEditorTokens', "Developer: Inspect Editor Tokens and Scopes"),
alias: 'Developer: Inspect Editor Tokens and Scopes',
precondition: undefined
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const controller = InspectEditorTokensController.get(editor);
if (controller) {
controller.toggle();
}
}
}
interface ITextMateTokenInfo {
token: IToken;
metadata: IDecodedMetadata;
}
interface ISemanticTokenInfo {
type: string;
modifiers: string[];
range: Range;
metadata?: IDecodedMetadata;
definitions: TokenStyleDefinitions;
}
interface IDecodedMetadata {
languageId: string | undefined;
tokenType: StandardTokenType;
bold: boolean | undefined;
italic: boolean | undefined;
underline: boolean | undefined;
strikethrough: boolean | undefined;
foreground: string | undefined;
background: string | undefined;
}
function renderTokenText(tokenText: string): string {
if (tokenText.length > 40) {
tokenText = tokenText.substr(0, 20) + '…' + tokenText.substr(tokenText.length - 20);
}
let result: string = '';
for (let charIndex = 0, len = tokenText.length; charIndex < len; charIndex++) {
const charCode = tokenText.charCodeAt(charIndex);
switch (charCode) {
case CharCode.Tab:
result += '\u2192'; // →
break;
case CharCode.Space:
result += '\u00B7'; // ·
break;
default:
result += String.fromCharCode(charCode);
}
}
return result;
}
type SemanticTokensResult = { tokens: SemanticTokens; legend: SemanticTokensLegend };
class InspectEditorTokensWidget extends Disposable implements IContentWidget {
private static readonly _ID = 'editor.contrib.inspectEditorTokensWidget';
// Editor.IContentWidget.allowEditorOverflow
public readonly allowEditorOverflow = true;
private _isDisposed: boolean;
private readonly _editor: IActiveCodeEditor;
private readonly _languageService: ILanguageService;
private readonly _themeService: IWorkbenchThemeService;
private readonly _textMateService: ITextMateService;
private readonly _notificationService: INotificationService;
private readonly _configurationService: IConfigurationService;
private readonly _languageFeaturesService: ILanguageFeaturesService;
private readonly _model: ITextModel;
private readonly _domNode: HTMLElement;
private readonly _currentRequestCancellationTokenSource: CancellationTokenSource;
constructor(
editor: IActiveCodeEditor,
textMateService: ITextMateService,
languageService: ILanguageService,
themeService: IWorkbenchThemeService,
notificationService: INotificationService,
configurationService: IConfigurationService,
languageFeaturesService: ILanguageFeaturesService
) {
super();
this._isDisposed = false;
this._editor = editor;
this._languageService = languageService;
this._themeService = themeService;
this._textMateService = textMateService;
this._notificationService = notificationService;
this._configurationService = configurationService;
this._languageFeaturesService = languageFeaturesService;
this._model = this._editor.getModel();
this._domNode = document.createElement('div');
this._domNode.className = 'token-inspect-widget';
this._currentRequestCancellationTokenSource = new CancellationTokenSource();
this._beginCompute(this._editor.getPosition());
this._register(this._editor.onDidChangeCursorPosition((e) => this._beginCompute(this._editor.getPosition())));
this._register(themeService.onDidColorThemeChange(_ => this._beginCompute(this._editor.getPosition())));
this._register(configurationService.onDidChangeConfiguration(e => e.affectsConfiguration('editor.semanticHighlighting.enabled') && this._beginCompute(this._editor.getPosition())));
this._editor.addContentWidget(this);
}
public override dispose(): void {
this._isDisposed = true;
this._editor.removeContentWidget(this);
this._currentRequestCancellationTokenSource.cancel();
super.dispose();
}
public getId(): string {
return InspectEditorTokensWidget._ID;
}
private _beginCompute(position: Position): void {
const grammar = this._textMateService.createGrammar(this._model.getLanguageId());
const semanticTokens = this._computeSemanticTokens(position);
dom.clearNode(this._domNode);
this._domNode.appendChild(document.createTextNode(nls.localize('inspectTMScopesWidget.loading', "Loading...")));
Promise.all([grammar, semanticTokens]).then(([grammar, semanticTokens]) => {
if (this._isDisposed) {
return;
}
this._compute(grammar, semanticTokens, position);
this._domNode.style.maxWidth = `${Math.max(this._editor.getLayoutInfo().width * 0.66, 500)}px`;
this._editor.layoutContentWidget(this);
}, (err) => {
this._notificationService.warn(err);
setTimeout(() => {
InspectEditorTokensController.get(this._editor)?.stop();
});
});
}
private _isSemanticColoringEnabled() {
const setting = this._configurationService.getValue<IEditorSemanticHighlightingOptions>(SEMANTIC_HIGHLIGHTING_SETTING_ID, { overrideIdentifier: this._model.getLanguageId(), resource: this._model.uri })?.enabled;
if (typeof setting === 'boolean') {
return setting;
}
return this._themeService.getColorTheme().semanticHighlighting;
}
private _compute(grammar: IGrammar | null, semanticTokens: SemanticTokensResult | null, position: Position) {
const textMateTokenInfo = grammar && this._getTokensAtPosition(grammar, position);
const semanticTokenInfo = semanticTokens && this._getSemanticTokenAtPosition(semanticTokens, position);
if (!textMateTokenInfo && !semanticTokenInfo) {
dom.reset(this._domNode, 'No grammar or semantic tokens available.');
return;
}
const tmMetadata = textMateTokenInfo?.metadata;
const semMetadata = semanticTokenInfo?.metadata;
const semTokenText = semanticTokenInfo && renderTokenText(this._model.getValueInRange(semanticTokenInfo.range));
const tmTokenText = textMateTokenInfo && renderTokenText(this._model.getLineContent(position.lineNumber).substring(textMateTokenInfo.token.startIndex, textMateTokenInfo.token.endIndex));
const tokenText = semTokenText || tmTokenText || '';
dom.reset(this._domNode,
$('h2.tiw-token', undefined,
tokenText,
$('span.tiw-token-length', undefined, `${tokenText.length} ${tokenText.length === 1 ? 'char' : 'chars'}`)));
dom.append(this._domNode, $('hr.tiw-metadata-separator', { 'style': 'clear:both' }));
dom.append(this._domNode, $('table.tiw-metadata-table', undefined,
$('tbody', undefined,
$('tr', undefined,
$('td.tiw-metadata-key', undefined, 'language'),
$('td.tiw-metadata-value', undefined, tmMetadata?.languageId || '')
),
$('tr', undefined,
$('td.tiw-metadata-key', undefined, 'standard token type' as string),
$('td.tiw-metadata-value', undefined, this._tokenTypeToString(tmMetadata?.tokenType || StandardTokenType.Other))
),
...this._formatMetadata(semMetadata, tmMetadata)
)
));
if (semanticTokenInfo) {
dom.append(this._domNode, $('hr.tiw-metadata-separator'));
const table = dom.append(this._domNode, $('table.tiw-metadata-table', undefined));
const tbody = dom.append(table, $('tbody', undefined,
$('tr', undefined,
$('td.tiw-metadata-key', undefined, 'semantic token type' as string),
$('td.tiw-metadata-value', undefined, semanticTokenInfo.type)
)
));
if (semanticTokenInfo.modifiers.length) {
dom.append(tbody, $('tr', undefined,
$('td.tiw-metadata-key', undefined, 'modifiers'),
$('td.tiw-metadata-value', undefined, semanticTokenInfo.modifiers.join(' ')),
));
}
if (semanticTokenInfo.metadata) {
const properties: (keyof TokenStyleData)[] = ['foreground', 'bold', 'italic', 'underline', 'strikethrough'];
const propertiesByDefValue: { [rule: string]: string[] } = {};
const allDefValues = new Array<[Array<HTMLElement | string>, string]>(); // remember the order
// first collect to detect when the same rule is used for multiple properties
for (const property of properties) {
if (semanticTokenInfo.metadata[property] !== undefined) {
const definition = semanticTokenInfo.definitions[property];
const defValue = this._renderTokenStyleDefinition(definition, property);
const defValueStr = defValue.map(el => el instanceof HTMLElement ? el.outerHTML : el).join();
let properties = propertiesByDefValue[defValueStr];
if (!properties) {
propertiesByDefValue[defValueStr] = properties = [];
allDefValues.push([defValue, defValueStr]);
}
properties.push(property);
}
}
for (const [defValue, defValueStr] of allDefValues) {
dom.append(tbody, $('tr', undefined,
$('td.tiw-metadata-key', undefined, propertiesByDefValue[defValueStr].join(', ')),
$('td.tiw-metadata-value', undefined, ...defValue)
));
}
}
}
if (textMateTokenInfo) {
const theme = this._themeService.getColorTheme();
dom.append(this._domNode, $('hr.tiw-metadata-separator'));
const table = dom.append(this._domNode, $('table.tiw-metadata-table'));
const tbody = dom.append(table, $('tbody'));
if (tmTokenText && tmTokenText !== tokenText) {
dom.append(tbody, $('tr', undefined,
$('td.tiw-metadata-key', undefined, 'textmate token' as string),
$('td.tiw-metadata-value', undefined, `${tmTokenText} (${tmTokenText.length})`)
));
}
const scopes = new Array<HTMLElement | string>();
for (let i = textMateTokenInfo.token.scopes.length - 1; i >= 0; i--) {
scopes.push(textMateTokenInfo.token.scopes[i]);
if (i > 0) {
scopes.push($('br'));
}
}
dom.append(tbody, $('tr', undefined,
$('td.tiw-metadata-key', undefined, 'textmate scopes' as string),
$('td.tiw-metadata-value.tiw-metadata-scopes', undefined, ...scopes),
));
const matchingRule = findMatchingThemeRule(theme, textMateTokenInfo.token.scopes, false);
const semForeground = semanticTokenInfo?.metadata?.foreground;
if (matchingRule) {
if (semForeground !== textMateTokenInfo.metadata.foreground) {
let defValue = $('code.tiw-theme-selector', undefined,
matchingRule.rawSelector, $('br'), JSON.stringify(matchingRule.settings, null, '\t'));
if (semForeground) {
defValue = $('s', undefined, defValue);
}
dom.append(tbody, $('tr', undefined,
$('td.tiw-metadata-key', undefined, 'foreground'),
$('td.tiw-metadata-value', undefined, defValue),
));
}
} else if (!semForeground) {
dom.append(tbody, $('tr', undefined,
$('td.tiw-metadata-key', undefined, 'foreground'),
$('td.tiw-metadata-value', undefined, 'No theme selector' as string),
));
}
}
}
private _formatMetadata(semantic?: IDecodedMetadata, tm?: IDecodedMetadata): Array<HTMLElement | string> {
const elements = new Array<HTMLElement | string>();
function render(property: 'foreground' | 'background') {
const value = semantic?.[property] || tm?.[property];
if (value !== undefined) {
const semanticStyle = semantic?.[property] ? 'tiw-metadata-semantic' : '';
elements.push($('tr', undefined,
$('td.tiw-metadata-key', undefined, property),
$(`td.tiw-metadata-value.${semanticStyle}`, undefined, value)
));
}
return value;
}
const foreground = render('foreground');
const background = render('background');
if (foreground && background) {
const backgroundColor = Color.fromHex(background), foregroundColor = Color.fromHex(foreground);
if (backgroundColor.isOpaque()) {
elements.push($('tr', undefined,
$('td.tiw-metadata-key', undefined, 'contrast ratio' as string),
$('td.tiw-metadata-value', undefined, backgroundColor.getContrastRatio(foregroundColor.makeOpaque(backgroundColor)).toFixed(2))
));
} else {
elements.push($('tr', undefined,
$('td.tiw-metadata-key', undefined, 'Contrast ratio cannot be precise for background colors that use transparency' as string),
$('td.tiw-metadata-value')
));
}
}
const fontStyleLabels = new Array<HTMLElement | string>();
function addStyle(key: 'bold' | 'italic' | 'underline' | 'strikethrough') {
let label: HTMLElement | string | undefined;
if (semantic && semantic[key]) {
label = $('span.tiw-metadata-semantic', undefined, key);
} else if (tm && tm[key]) {
label = key;
}
if (label) {
if (fontStyleLabels.length) {
fontStyleLabels.push(' ');
}
fontStyleLabels.push(label);
}
}
addStyle('bold');
addStyle('italic');
addStyle('underline');
addStyle('strikethrough');
if (fontStyleLabels.length) {
elements.push($('tr', undefined,
$('td.tiw-metadata-key', undefined, 'font style' as string),
$('td.tiw-metadata-value', undefined, ...fontStyleLabels)
));
}
return elements;
}
private _decodeMetadata(metadata: number): IDecodedMetadata {
const colorMap = this._themeService.getColorTheme().tokenColorMap;
const languageId = TokenMetadata.getLanguageId(metadata);
const tokenType = TokenMetadata.getTokenType(metadata);
const fontStyle = TokenMetadata.getFontStyle(metadata);
const foreground = TokenMetadata.getForeground(metadata);
const background = TokenMetadata.getBackground(metadata);
return {
languageId: this._languageService.languageIdCodec.decodeLanguageId(languageId),
tokenType: tokenType,
bold: (fontStyle & FontStyle.Bold) ? true : undefined,
italic: (fontStyle & FontStyle.Italic) ? true : undefined,
underline: (fontStyle & FontStyle.Underline) ? true : undefined,
strikethrough: (fontStyle & FontStyle.Strikethrough) ? true : undefined,
foreground: colorMap[foreground],
background: colorMap[background]
};
}
private _tokenTypeToString(tokenType: StandardTokenType): string {
switch (tokenType) {
case StandardTokenType.Other: return 'Other';
case StandardTokenType.Comment: return 'Comment';
case StandardTokenType.String: return 'String';
case StandardTokenType.RegEx: return 'RegEx';
default: return '??';
}
}
private _getTokensAtPosition(grammar: IGrammar, position: Position): ITextMateTokenInfo {
const lineNumber = position.lineNumber;
const stateBeforeLine = this._getStateBeforeLine(grammar, lineNumber);
const tokenizationResult1 = grammar.tokenizeLine(this._model.getLineContent(lineNumber), stateBeforeLine);
const tokenizationResult2 = grammar.tokenizeLine2(this._model.getLineContent(lineNumber), stateBeforeLine);
let token1Index = 0;
for (let i = tokenizationResult1.tokens.length - 1; i >= 0; i--) {
const t = tokenizationResult1.tokens[i];
if (position.column - 1 >= t.startIndex) {
token1Index = i;
break;
}
}
let token2Index = 0;
for (let i = (tokenizationResult2.tokens.length >>> 1); i >= 0; i--) {
if (position.column - 1 >= tokenizationResult2.tokens[(i << 1)]) {
token2Index = i;
break;
}
}
return {
token: tokenizationResult1.tokens[token1Index],
metadata: this._decodeMetadata(tokenizationResult2.tokens[(token2Index << 1) + 1])
};
}
private _getStateBeforeLine(grammar: IGrammar, lineNumber: number): StackElement | null {
let state: StackElement | null = null;
for (let i = 1; i < lineNumber; i++) {
const tokenizationResult = grammar.tokenizeLine(this._model.getLineContent(i), state);
state = tokenizationResult.ruleStack;
}
return state;
}
private isSemanticTokens(token: any): token is SemanticTokens {
return token && token.data;
}
private async _computeSemanticTokens(position: Position): Promise<SemanticTokensResult | null> {
if (!this._isSemanticColoringEnabled()) {
return null;
}
const tokenProviders = this._languageFeaturesService.documentSemanticTokensProvider.ordered(this._model);
if (tokenProviders.length) {
const provider = tokenProviders[0];
const tokens = await Promise.resolve(provider.provideDocumentSemanticTokens(this._model, null, this._currentRequestCancellationTokenSource.token));
if (this.isSemanticTokens(tokens)) {
return { tokens, legend: provider.getLegend() };
}
}
const rangeTokenProviders = this._languageFeaturesService.documentRangeSemanticTokensProvider.ordered(this._model);
if (rangeTokenProviders.length) {
const provider = rangeTokenProviders[0];
const lineNumber = position.lineNumber;
const range = new Range(lineNumber, 1, lineNumber, this._model.getLineMaxColumn(lineNumber));
const tokens = await Promise.resolve(provider.provideDocumentRangeSemanticTokens(this._model, range, this._currentRequestCancellationTokenSource.token));
if (this.isSemanticTokens(tokens)) {
return { tokens, legend: provider.getLegend() };
}
}
return null;
}
private _getSemanticTokenAtPosition(semanticTokens: SemanticTokensResult, pos: Position): ISemanticTokenInfo | null {
const tokenData = semanticTokens.tokens.data;
const defaultLanguage = this._model.getLanguageId();
let lastLine = 0;
let lastCharacter = 0;
const posLine = pos.lineNumber - 1, posCharacter = pos.column - 1; // to 0-based position
for (let i = 0; i < tokenData.length; i += 5) {
const lineDelta = tokenData[i], charDelta = tokenData[i + 1], len = tokenData[i + 2], typeIdx = tokenData[i + 3], modSet = tokenData[i + 4];
const line = lastLine + lineDelta; // 0-based
const character = lineDelta === 0 ? lastCharacter + charDelta : charDelta; // 0-based
if (posLine === line && character <= posCharacter && posCharacter < character + len) {
const type = semanticTokens.legend.tokenTypes[typeIdx] || 'not in legend (ignored)';
const modifiers = [];
let modifierSet = modSet;
for (let modifierIndex = 0; modifierSet > 0 && modifierIndex < semanticTokens.legend.tokenModifiers.length; modifierIndex++) {
if (modifierSet & 1) {
modifiers.push(semanticTokens.legend.tokenModifiers[modifierIndex]);
}
modifierSet = modifierSet >> 1;
}
if (modifierSet > 0) {
modifiers.push('not in legend (ignored)');
}
const range = new Range(line + 1, character + 1, line + 1, character + 1 + len);
const definitions = {};
const colorMap = this._themeService.getColorTheme().tokenColorMap;
const theme = this._themeService.getColorTheme() as ColorThemeData;
const tokenStyle = theme.getTokenStyleMetadata(type, modifiers, defaultLanguage, true, definitions);
let metadata: IDecodedMetadata | undefined = undefined;
if (tokenStyle) {
metadata = {
languageId: undefined,
tokenType: StandardTokenType.Other,
bold: tokenStyle?.bold,
italic: tokenStyle?.italic,
underline: tokenStyle?.underline,
strikethrough: tokenStyle?.strikethrough,
foreground: colorMap[tokenStyle?.foreground || ColorId.None],
background: undefined
};
}
return { type, modifiers, range, metadata, definitions };
}
lastLine = line;
lastCharacter = character;
}
return null;
}
private _renderTokenStyleDefinition(definition: TokenStyleDefinition | undefined, property: keyof TokenStyleData): Array<HTMLElement | string> {
const elements = new Array<HTMLElement | string>();
if (definition === undefined) {
return elements;
}
const theme = this._themeService.getColorTheme() as ColorThemeData;
if (Array.isArray(definition)) {
const scopesDefinition: TextMateThemingRuleDefinitions = {};
theme.resolveScopes(definition, scopesDefinition);
const matchingRule = scopesDefinition[property];
if (matchingRule && scopesDefinition.scope) {
const scopes = $('ul.tiw-metadata-values');
const strScopes = Array.isArray(matchingRule.scope) ? matchingRule.scope : [String(matchingRule.scope)];
for (const strScope of strScopes) {
scopes.appendChild($('li.tiw-metadata-value.tiw-metadata-scopes', undefined, strScope));
}
elements.push(
scopesDefinition.scope.join(' '),
scopes,
$('code.tiw-theme-selector', undefined, JSON.stringify(matchingRule.settings, null, '\t')));
return elements;
}
return elements;
} else if (SemanticTokenRule.is(definition)) {
const scope = theme.getTokenStylingRuleScope(definition);
if (scope === 'setting') {
elements.push(`User settings: ${definition.selector.id} - ${this._renderStyleProperty(definition.style, property)}`);
return elements;
} else if (scope === 'theme') {
elements.push(`Color theme: ${definition.selector.id} - ${this._renderStyleProperty(definition.style, property)}`);
return elements;
}
return elements;
} else {
const style = theme.resolveTokenStyleValue(definition);
elements.push(`Default: ${style ? this._renderStyleProperty(style, property) : ''}`);
return elements;
}
}
private _renderStyleProperty(style: TokenStyle, property: keyof TokenStyleData) {
switch (property) {
case 'foreground': return style.foreground ? Color.Format.CSS.formatHexA(style.foreground, true) : '';
default: return style[property] !== undefined ? String(style[property]) : '';
}
}
public getDomNode(): HTMLElement {
return this._domNode;
}
public getPosition(): IContentWidgetPosition {
return {
position: this._editor.getPosition(),
preference: [ContentWidgetPositionPreference.BELOW, ContentWidgetPositionPreference.ABOVE]
};
}
}
registerEditorContribution(InspectEditorTokensController.ID, InspectEditorTokensController);
registerEditorAction(InspectEditorTokens);
registerThemingParticipant((theme, collector) => {
const border = theme.getColor(editorHoverBorder);
if (border) {
const borderWidth = isHighContrast(theme.type) ? 2 : 1;
collector.addRule(`.monaco-editor .token-inspect-widget { border: ${borderWidth}px solid ${border}; }`);
collector.addRule(`.monaco-editor .token-inspect-widget .tiw-metadata-separator { background-color: ${border}; }`);
}
const background = theme.getColor(editorHoverBackground);
if (background) {
collector.addRule(`.monaco-editor .token-inspect-widget { background-color: ${background}; }`);
}
}); | the_stack |
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import * as chai from 'chai';
import sinonChai from 'sinon-chai';
import * as sinon from 'sinon';
import dayjs from 'dayjs';
import { ArtemisTestModule } from '../../../test.module';
import { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';
import { TranslateService } from '@ngx-translate/core';
import { ActivatedRoute, convertToParamMap, UrlSegment } from '@angular/router';
import { Course } from 'app/entities/course.model';
import { ExamManagementComponent } from 'app/exam/manage/exam-management.component';
import { Exam } from 'app/entities/exam.model';
import { ExamManagementService } from 'app/exam/manage/exam-management.service';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { SortService } from 'app/shared/service/sort.service';
import { AccountService } from 'app/core/auth/account.service';
import { ExamInformationDTO } from 'app/entities/exam-information.model';
import { EventManager } from 'app/core/util/event-manager.service';
import { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';
import { MockComponent, MockDirective, MockPipe } from 'ng-mocks';
import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';
import { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';
import { MockRouterLinkDirective } from '../../lecture-unit/lecture-unit-management.component.spec';
import { AlertComponent } from 'app/shared/alert/alert.component';
import { DurationPipe } from 'app/shared/pipes/artemis-duration.pipe';
import { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';
import { SortDirective } from 'app/shared/sort/sort.directive';
chai.use(sinonChai);
const expect = chai.expect;
describe('Exam Management Component', () => {
const course = { id: 456 } as Course;
const exam = new Exam();
exam.course = course;
exam.id = 123;
let comp: ExamManagementComponent;
let fixture: ComponentFixture<ExamManagementComponent>;
let service: ExamManagementService;
let courseManagementService: CourseManagementService;
let sortService: SortService;
let accountService: AccountService;
let eventManager: EventManager;
const route = { snapshot: { paramMap: convertToParamMap({ courseId: course.id }) }, url: new Observable<UrlSegment[]>() } as any as ActivatedRoute;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ArtemisTestModule],
declarations: [
ExamManagementComponent,
MockDirective(HasAnyAuthorityDirective),
MockPipe(ArtemisTranslatePipe),
MockPipe(ArtemisDatePipe),
MockRouterLinkDirective,
MockDirective(SortDirective),
MockComponent(AlertComponent),
MockPipe(DurationPipe),
MockDirective(DeleteButtonDirective),
],
providers: [
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: TranslateService, useClass: MockTranslateService },
{ provide: ActivatedRoute, useValue: route },
EventManager,
],
}).compileComponents();
fixture = TestBed.createComponent(ExamManagementComponent);
comp = fixture.componentInstance;
service = TestBed.inject(ExamManagementService);
courseManagementService = TestBed.inject(CourseManagementService);
sortService = TestBed.inject(SortService);
accountService = TestBed.inject(AccountService);
eventManager = TestBed.inject(EventManager);
});
afterEach(function () {
// completely restore all fakes created through the sandbox
sinon.restore();
});
it('Should call courseService on init', () => {
// GIVEN
const responseFakeCourse = { body: course as Course } as HttpResponse<Course>;
sinon.replace(courseManagementService, 'find', sinon.fake.returns(of(responseFakeCourse)));
// WHEN
comp.ngOnInit();
// THEN
expect(courseManagementService.find).to.have.been.calledOnce;
expect(comp.course).to.eq(course);
});
it('Should call loadAllExamsForCourse on init', () => {
// GIVEN
const responseFakeCourse = { body: course as Course } as HttpResponse<Course>;
sinon.replace(courseManagementService, 'find', sinon.fake.returns(of(responseFakeCourse)));
const responseFakeExams = { body: [exam] } as HttpResponse<Exam[]>;
sinon.replace(service, 'findAllExamsForCourse', sinon.fake.returns(of(responseFakeExams)));
// WHEN
comp.ngOnInit();
// THEN
expect(service.findAllExamsForCourse).to.have.been.calledOnce;
expect(comp.exams).to.deep.eq([exam]);
});
it('Should call isAtLeastInstructorInCourse on init', () => {
// GIVEN
const responseFakeCourse = { body: course as Course } as HttpResponse<Course>;
sinon.replace(courseManagementService, 'find', sinon.fake.returns(of(responseFakeCourse)));
const expectedAtLeastInstructor = true;
sinon.replace(accountService, 'isAtLeastInstructorInCourse', sinon.fake.returns(expectedAtLeastInstructor));
// WHEN
comp.ngOnInit();
// THEN
expect(accountService.isAtLeastInstructorInCourse).to.have.been.calledOnce;
expect(comp.isAtLeastInstructor).to.eq(expectedAtLeastInstructor);
});
it('Should call isAtLeastTutorInCourse on init', () => {
// GIVEN
const responseFakeCourse = { body: course as Course } as HttpResponse<Course>;
sinon.replace(courseManagementService, 'find', sinon.fake.returns(of(responseFakeCourse)));
const expectedAtLeastTutor = true;
sinon.replace(accountService, 'isAtLeastTutorInCourse', sinon.fake.returns(expectedAtLeastTutor));
// WHEN
comp.ngOnInit();
// THEN
expect(accountService.isAtLeastTutorInCourse).to.have.been.calledOnce;
expect(comp.isAtLeastTutor).to.eq(expectedAtLeastTutor);
});
it('Should call getLatestIndividualDate on init', () => {
// GIVEN
const responseFakeCourse = { body: course as Course } as HttpResponse<Course>;
sinon.replace(courseManagementService, 'find', sinon.fake.returns(of(responseFakeCourse)));
const responseFakeExams = { body: [exam] } as HttpResponse<Exam[]>;
sinon.replace(service, 'findAllExamsForCourse', sinon.fake.returns(of(responseFakeExams)));
const examInformationDTO = new ExamInformationDTO();
examInformationDTO.latestIndividualEndDate = dayjs();
const responseFakeLatestIndividualEndDateOfExam = { body: examInformationDTO } as HttpResponse<ExamInformationDTO>;
sinon.replace(service, 'getLatestIndividualEndDateOfExam', sinon.fake.returns(of(responseFakeLatestIndividualEndDateOfExam)));
// WHEN
comp.ngOnInit();
// THEN
expect(service.getLatestIndividualEndDateOfExam).to.have.been.calledOnce;
expect(comp.exams[0].latestIndividualEndDate).to.eq(examInformationDTO.latestIndividualEndDate);
});
it('Should call findAllExamsForCourse on examListModification event being fired after registering for exam changes ', () => {
// GIVEN
comp.course = course;
const responseFakeExams = { body: [exam] } as HttpResponse<Exam[]>;
sinon.replace(service, 'findAllExamsForCourse', sinon.fake.returns(of(responseFakeExams)));
// WHEN
comp.registerChangeInExams();
eventManager.broadcast({ name: 'examListModification', content: 'dummy' });
// THEN
expect(service.findAllExamsForCourse).to.have.been.calledOnce;
expect(comp.exams).to.deep.eq([exam]);
});
it('Should delete an exam when delete exam is called', () => {
// GIVEN
comp.exams = [exam];
comp.course = course;
const responseFakeDelete = {} as HttpResponse<any[]>;
const responseFakeEmptyExamArray = { body: [exam] } as HttpResponse<Exam[]>;
sinon.replace(service, 'delete', sinon.fake.returns(of(responseFakeDelete)));
sinon.replace(service, 'findAllExamsForCourse', sinon.fake.returns(of(responseFakeEmptyExamArray)));
// WHEN
comp.deleteExam(exam.id!);
// THEN
expect(service.delete).to.have.been.calledOnce;
expect(comp.exams.length).to.eq(0);
});
it('Should return false for examHasFinished when component has no exam information ', () => {
// GIVEN
exam.latestIndividualEndDate = undefined;
// WHEN
const examHasFinished = comp.examHasFinished(exam);
// THEN
expect(examHasFinished).to.be.false;
});
it('Should return true for examHasFinished when exam is in the past ', () => {
// GIVEN
exam.latestIndividualEndDate = dayjs().subtract(1, 'days');
// WHEN
const examHasFinished = comp.examHasFinished(exam);
// THEN
expect(examHasFinished).to.be.true;
});
it('Should return false for examHasFinished when exam is in the future ', () => {
// GIVEN
exam.latestIndividualEndDate = dayjs().add(1, 'minute');
// WHEN
const examHasFinished = comp.examHasFinished(exam);
// THEN
expect(examHasFinished).to.be.false;
});
it('Should return exam.id, when item in the exam table is being tracked ', () => {
// WHEN
const itemId = comp.trackId(0, exam);
// THEN
expect(itemId).to.eq(exam.id);
});
it('Should call sortService when sortRows is called ', () => {
// GIVEN
sinon.replace(sortService, 'sortByProperty', sinon.fake.returns([]));
// WHEN
comp.sortRows();
// THEN
expect(sortService.sortByProperty).to.have.been.calledOnce;
});
}); | the_stack |
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzru {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzru>;
public static CONTENT_URI: globalAndroid.net.Uri;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzrv {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzrv>;
public onChange(param0: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzrw {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzrw>;
public static isUserUnlocked(param0: globalAndroid.content.Context): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzrx extends com.google.android.gms.internal.measurement.zzsb {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzrx>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzry extends com.google.android.gms.internal.measurement.zzsd<any> {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzry>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzrz {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzrz>;
public onChange(param0: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsa {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsa>;
/**
* Constructs a new instance of the com.google.android.gms.internal.measurement.zzsa interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zztp(): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsb {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsb>;
/**
* Constructs a new instance of the com.google.android.gms.internal.measurement.zzsb interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzfn(param0: string): any;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsc {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsc>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsd<V> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsd<any>>;
/**
* Constructs a new instance of the com.google.android.gms.internal.measurement.zzsd<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzto(): V;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzse extends com.google.android.gms.internal.measurement.zzsb {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzse>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsf extends com.google.android.gms.internal.measurement.zzsd<any> {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsf>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsg {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsg>;
public onChange(param0: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsh {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export abstract class zzsi<T> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsi<any>>;
public getDefaultValue(): T;
public get(): T;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsj extends com.google.android.gms.internal.measurement.zzsi<java.lang.Long> {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsk extends com.google.android.gms.internal.measurement.zzsi<java.lang.Integer> {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsk>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsl extends com.google.android.gms.internal.measurement.zzsi<java.lang.Boolean> {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsl>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsm extends com.google.android.gms.internal.measurement.zzsi<java.lang.Double> {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsm>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsn extends java.lang.Object /* com.google.android.gms.internal.measurement.zzsi<string>*/ {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsn>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzso {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzso>;
public constructor(param0: globalAndroid.net.Uri);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsp extends com.google.android.gms.internal.measurement.zzsb {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsp>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzsq {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzsq>;
public onSharedPreferenceChanged(param0: globalAndroid.content.SharedPreferences, param1: string): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzu {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzu>;
/**
* Constructs a new instance of the com.google.android.gms.internal.measurement.zzu interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: globalAndroid.os.Bundle): globalAndroid.os.Bundle;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export abstract class zzv implements com.google.android.gms.internal.measurement.zzu {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzv>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module internal {
export module measurement {
export class zzw implements com.google.android.gms.internal.measurement.zzu {
public static class: java.lang.Class<com.google.android.gms.internal.measurement.zzw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export class AppMeasurement {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement>;
public static CRASH_ORIGIN: string;
public static FCM_ORIGIN: string;
public static FIAM_ORIGIN: string;
public unregisterOnMeasurementEventListener(param0: com.google.android.gms.measurement.AppMeasurement.OnEventListener): void;
public getCurrentScreenName(): string;
public getBoolean(): java.lang.Boolean;
public getString(): string;
public setSessionTimeoutDuration(param0: number): void;
public setUserProperty(param0: string, param1: string): void;
public getConditionalUserPropertiesAs(param0: string, param1: string, param2: string): java.util.List<com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty>;
public registerOnMeasurementEventListener(param0: com.google.android.gms.measurement.AppMeasurement.OnEventListener): void;
public setConditionalUserPropertyAs(param0: com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty): void;
public getMaxUserProperties(param0: string): number;
public setConditionalUserProperty(param0: com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty): void;
public endAdUnitExposure(param0: string): void;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbw*/);
public getUserProperties(param0: string, param1: string, param2: boolean): java.util.Map<string,any>;
public getGmpAppId(): string;
public logEventInternal(param0: string, param1: string, param2: globalAndroid.os.Bundle): void;
public getUserProperties(param0: boolean): java.util.Map<string,any>;
public beginAdUnitExposure(param0: string): void;
public getInteger(): java.lang.Integer;
public static getInstance(param0: globalAndroid.content.Context): com.google.android.gms.measurement.AppMeasurement;
public setUserPropertyInternal(param0: string, param1: string, param2: any): void;
public setEventInterceptor(param0: com.google.android.gms.measurement.AppMeasurement.EventInterceptor): void;
public getUserPropertiesAs(param0: string, param1: string, param2: string, param3: boolean): java.util.Map<string,any>;
public logEvent(param0: string, param1: globalAndroid.os.Bundle): void;
public logEventInternalNoInterceptor(param0: string, param1: string, param2: globalAndroid.os.Bundle, param3: number): void;
public getLong(): java.lang.Long;
public getDouble(): java.lang.Double;
public setMeasurementEnabled(param0: boolean): void;
public setMinimumSessionDuration(param0: number): void;
public generateEventId(): number;
public clearConditionalUserProperty(param0: string, param1: string, param2: globalAndroid.os.Bundle): void;
public getCurrentScreenClass(): string;
public getAppInstanceId(): string;
public clearConditionalUserPropertyAs(param0: string, param1: string, param2: string, param3: globalAndroid.os.Bundle): void;
public getConditionalUserProperties(param0: string, param1: string): java.util.List<com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty>;
}
export module AppMeasurement {
export class ConditionalUserProperty {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty>;
public mAppId: string;
public mOrigin: string;
public mName: string;
public mValue: any;
public mTriggerEventName: string;
public mTriggerTimeout: number;
public mTimedOutEventName: string;
public mTimedOutEventParams: globalAndroid.os.Bundle;
public mTriggeredEventName: string;
public mTriggeredEventParams: globalAndroid.os.Bundle;
public mTimeToLive: number;
public mExpiredEventName: string;
public mExpiredEventParams: globalAndroid.os.Bundle;
public mCreationTimestamp: number;
public mActive: boolean;
public mTriggeredTimestamp: number;
public constructor();
public constructor(param0: com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty);
}
export class Event {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement.Event>;
public static APP_EXCEPTION: string;
public static AD_REWARD: string;
}
export class EventInterceptor {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement.EventInterceptor>;
/**
* Constructs a new instance of the com.google.android.gms.measurement.AppMeasurement$EventInterceptor interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
interceptEvent(param0: string, param1: string, param2: globalAndroid.os.Bundle, param3: number): void;
});
public constructor();
public interceptEvent(param0: string, param1: string, param2: globalAndroid.os.Bundle, param3: number): void;
}
export class OnEventListener {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement.OnEventListener>;
/**
* Constructs a new instance of the com.google.android.gms.measurement.AppMeasurement$OnEventListener interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
onEvent(param0: string, param1: string, param2: globalAndroid.os.Bundle, param3: number): void;
});
public constructor();
public onEvent(param0: string, param1: string, param2: globalAndroid.os.Bundle, param3: number): void;
}
export class Param {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement.Param>;
public static FATAL: string;
public static TIMESTAMP: string;
public static TYPE: string;
}
export class UserProperty {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurement.UserProperty>;
public static FIREBASE_LAST_NOTIFICATION: string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export class AppMeasurementContentProvider {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurementContentProvider>;
public constructor();
public delete(param0: globalAndroid.net.Uri, param1: string, param2: native.Array<string>): number;
public attachInfo(param0: globalAndroid.content.Context, param1: globalAndroid.content.pm.ProviderInfo): void;
public query(param0: globalAndroid.net.Uri, param1: native.Array<string>, param2: string, param3: native.Array<string>, param4: string): globalAndroid.database.Cursor;
public onCreate(): boolean;
public getType(param0: globalAndroid.net.Uri): string;
public update(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues, param2: string, param3: native.Array<string>): number;
public insert(param0: globalAndroid.net.Uri, param1: globalAndroid.content.ContentValues): globalAndroid.net.Uri;
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export class AppMeasurementInstallReferrerReceiver implements com.google.android.gms.measurement.internal.zzbp {
public static class: java.lang.Class<com.google.android.gms.measurement.AppMeasurementInstallReferrerReceiver>;
public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
public constructor();
public doGoAsync(): globalAndroid.content.BroadcastReceiver.PendingResult;
public doStartService(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zza extends com.google.android.gms.measurement.internal.zze {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zza>;
public endAdUnitExposure(param0: string, param1: number): void;
public getContext(): globalAndroid.content.Context;
public beginAdUnitExposure(param0: string, param1: number): void;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbw*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzaa extends com.google.android.gms.measurement.internal.zzcs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzaa>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzab {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzab>;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzac {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzac>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzad extends com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable implements java.lang.Iterable<string> {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzad>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzad>*/;
public iterator(): java.util.Iterator<string>;
public size(): number;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public toString(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzae extends java.util.Iterator<string> {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzae>;
public hasNext(): boolean;
public remove(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzaf extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzad>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzaf>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzag {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzag>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzag>*/;
public name: string;
public origin: string;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
public toString(): string;
public constructor(param0: string, param1: any /* com.google.android.gms.measurement.internal.zzad*/, param2: string, param3: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzah extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzag>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzah>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzai {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzai>;
}
export module zzai {
export class zza<V> extends java.lang.Object {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzai.zza<any>>;
public get(): V;
public get(param0: V): V;
public getKey(): string;
}
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzaj {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzaj>;
/**
* Constructs a new instance of the com.google.android.gms.measurement.internal.zzaj interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zza(param0: any /* com.google.android.gms.measurement.internal.zzag*/, param1: any /* com.google.android.gms.measurement.internal.zzk*/): void;
zza(param0: any /* com.google.android.gms.measurement.internal.zzfu*/, param1: any /* com.google.android.gms.measurement.internal.zzk*/): void;
zza(param0: any /* com.google.android.gms.measurement.internal.zzk*/): void;
zza(param0: any /* com.google.android.gms.measurement.internal.zzag*/, param1: string, param2: string): void;
zzb(param0: any /* com.google.android.gms.measurement.internal.zzk*/): void;
zza(param0: any /* com.google.android.gms.measurement.internal.zzk*/, param1: boolean): any /* java.util.List<com.google.android.gms.measurement.internal.zzfu>*/;
zza(param0: any /* com.google.android.gms.measurement.internal.zzag*/, param1: string): native.Array<number>;
zza(param0: number, param1: string, param2: string, param3: string): void;
zzc(param0: any /* com.google.android.gms.measurement.internal.zzk*/): string;
zza(param0: any /* com.google.android.gms.measurement.internal.zzo*/, param1: any /* com.google.android.gms.measurement.internal.zzk*/): void;
zzb(param0: any /* com.google.android.gms.measurement.internal.zzo*/): void;
zza(param0: string, param1: string, param2: boolean, param3: any /* com.google.android.gms.measurement.internal.zzk*/): any /* java.util.List<com.google.android.gms.measurement.internal.zzfu>*/;
zza(param0: string, param1: string, param2: string, param3: boolean): any /* java.util.List<com.google.android.gms.measurement.internal.zzfu>*/;
zza(param0: string, param1: string, param2: any /* com.google.android.gms.measurement.internal.zzk*/): any /* java.util.List<com.google.android.gms.measurement.internal.zzo>*/;
zze(param0: string, param1: string, param2: string): any /* java.util.List<com.google.android.gms.measurement.internal.zzo>*/;
zzd(param0: any /* com.google.android.gms.measurement.internal.zzk*/): void;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export abstract class zzak implements com.google.android.gms.measurement.internal.zzaj {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzak>;
public constructor();
public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzal implements com.google.android.gms.measurement.internal.zzaj {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzal>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzam extends com.google.android.gms.measurement.internal.zzf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzam>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzan {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzan>;
public origin: string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzao extends com.google.android.gms.measurement.internal.zzf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzao>;
public getContext(): globalAndroid.content.Context;
public resetAnalyticsData(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzap {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzap>;
public onUpgrade(param0: globalAndroid.database.sqlite.SQLiteDatabase, param1: number, param2: number): void;
public onOpen(param0: globalAndroid.database.sqlite.SQLiteDatabase): void;
public onCreate(param0: globalAndroid.database.sqlite.SQLiteDatabase): void;
public onDowngrade(param0: globalAndroid.database.sqlite.SQLiteDatabase, param1: number, param2: number): void;
public getWritableDatabase(): globalAndroid.database.sqlite.SQLiteDatabase;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzaq extends com.google.android.gms.measurement.internal.zzcs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzaq>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzar extends java.lang.Object /* com.google.android.gms.common.internal.BaseGmsClient<com.google.android.gms.measurement.internal.zzaj>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzar>;
public getStartServiceAction(): string;
public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.BaseGmsClient.BaseConnectionCallbacks, param3: com.google.android.gms.common.internal.BaseGmsClient.BaseOnConnectionFailedListener);
public getMinApkVersion(): number;
public getServiceDescriptor(): string;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzas extends com.google.android.gms.measurement.internal.zzcs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzas>;
public getContext(): globalAndroid.content.Context;
public isLoggable(param0: number): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzat {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzat>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzau {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzau>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzav {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzav>;
public constructor(param0: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzb {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzb>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbd extends com.google.android.gms.measurement.internal.zzcs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbd>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbe {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbe>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbf>;
public get(): boolean;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbd*/, param1: string, param2: boolean);
public set(param0: boolean): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbg {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbg>;
public set(param0: number): void;
public get(): number;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbd*/, param1: string, param2: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbh {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbh>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbi {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbi>;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbd*/, param1: string, param2: string);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbj {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbj>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbk {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbk>;
public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void;
public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbl {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbl>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbm {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbm>;
public onReceive(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbp*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbn {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbn>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbo {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbo>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbp {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbp>;
/**
* Constructs a new instance of the com.google.android.gms.measurement.internal.zzbp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
doStartService(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
doGoAsync(): globalAndroid.content.BroadcastReceiver.PendingResult;
});
public constructor();
public doGoAsync(): globalAndroid.content.BroadcastReceiver.PendingResult;
public doStartService(param0: globalAndroid.content.Context, param1: globalAndroid.content.Intent): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbr extends com.google.android.gms.measurement.internal.zzcs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbr>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbs>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbt {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbt>;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbr*/, param1: string);
public uncaughtException(param0: java.lang.Thread, param1: java.lang.Throwable): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbu<V> extends java.util.concurrent.FutureTask<any> implements any /* java.lang.Comparable<com.google.android.gms.measurement.internal.zzbu<any>>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbu<any>>;
public setException(param0: java.lang.Throwable): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbv {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbv>;
public constructor(param0: string, param1: any /* java.util.concurrent.BlockingQueue<com.google.android.gms.measurement.internal.zzbu<any>>*/);
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbw extends com.google.android.gms.measurement.internal.zzct {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbw>;
public getContext(): globalAndroid.content.Context;
public start(): void;
public isEnabled(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzbx {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzbx>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzc {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzc>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzcr extends com.google.android.gms.measurement.internal.zzct {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzcr>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export abstract class zzcs extends com.google.android.gms.measurement.internal.zzcr {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzcs>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzct {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzct>;
/**
* Constructs a new instance of the com.google.android.gms.measurement.internal.zzct interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzgw(): any /* com.google.android.gms.measurement.internal.zzn*/;
zzgt(): any /* com.google.android.gms.measurement.internal.zzas*/;
zzgs(): any /* com.google.android.gms.measurement.internal.zzbr*/;
getContext(): globalAndroid.content.Context;
zzbx(): com.google.android.gms.common.util.Clock;
});
public constructor();
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzcz {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzcz>;
public constructor(param0: globalAndroid.content.Context, param1: any /* com.google.android.gms.measurement.internal.zzan*/);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzd {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzd>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzda extends com.google.android.gms.measurement.internal.zzf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzda>;
public getGmpAppId(): string;
public getContext(): globalAndroid.content.Context;
public getCurrentScreenName(): string;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbw*/);
public logEvent(param0: string, param1: string, param2: globalAndroid.os.Bundle, param3: boolean, param4: boolean, param5: number): void;
public setSessionTimeoutDuration(param0: number): void;
public getUserProperties(param0: string, param1: string, param2: boolean): java.util.Map<string,any>;
public clearConditionalUserPropertyAs(param0: string, param1: string, param2: string, param3: globalAndroid.os.Bundle): void;
public getConditionalUserProperties(param0: string, param1: string): java.util.List<com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty>;
public logEvent(param0: string, param1: string, param2: globalAndroid.os.Bundle): void;
public clearConditionalUserProperty(param0: string, param1: string, param2: globalAndroid.os.Bundle): void;
public setMinimumSessionDuration(param0: number): void;
public getCurrentScreenClass(): string;
public setConditionalUserProperty(param0: com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty): void;
public setMeasurementEnabled(param0: boolean): void;
public getConditionalUserPropertiesAs(param0: string, param1: string, param2: string): java.util.List<com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty>;
public resetAnalyticsData(param0: number): void;
public getUserPropertiesAs(param0: string, param1: string, param2: string, param3: boolean): java.util.Map<string,any>;
public setConditionalUserPropertyAs(param0: com.google.android.gms.measurement.AppMeasurement.ConditionalUserProperty): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdb {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdb>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdc {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdc>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdd {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdd>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzde {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzde>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdf>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdg {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdg>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdh {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdh>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdi {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdi>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdj {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdj>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdk {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdk>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdl {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdl>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdm {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdm>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdn {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdn>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdo {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdo>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdp {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdp>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdq {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdq>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdr {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdr>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzds {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzds>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdt {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdt>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdu {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdu>;
public onActivityPaused(param0: globalAndroid.app.Activity): void;
public onActivityStarted(param0: globalAndroid.app.Activity): void;
public onActivityCreated(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void;
public onActivitySaveInstanceState(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void;
public onActivityResumed(param0: globalAndroid.app.Activity): void;
public onActivityDestroyed(param0: globalAndroid.app.Activity): void;
public onActivityStopped(param0: globalAndroid.app.Activity): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdx {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdx>;
public constructor(param0: string, param1: string, param2: number);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdy extends com.google.android.gms.measurement.internal.zzf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdy>;
public onActivityPaused(param0: globalAndroid.app.Activity): void;
public getContext(): globalAndroid.content.Context;
public onActivityCreated(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void;
public onActivitySaveInstanceState(param0: globalAndroid.app.Activity, param1: globalAndroid.os.Bundle): void;
public setCurrentScreen(param0: globalAndroid.app.Activity, param1: string, param2: string): void;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbw*/);
public onActivityResumed(param0: globalAndroid.app.Activity): void;
public onActivityDestroyed(param0: globalAndroid.app.Activity): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzdz {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzdz>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zze extends com.google.android.gms.measurement.internal.zzcr implements com.google.android.gms.measurement.internal.zzct {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zze>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzea {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzea>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzeb extends com.google.android.gms.measurement.internal.zzf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzeb>;
public getContext(): globalAndroid.content.Context;
public disconnect(): void;
public isConnected(): boolean;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzbw*/);
public resetAnalyticsData(): void;
public getAppInstanceId(param0: any /* com.google.android.gms.internal.measurement.zzdq*/): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzec extends com.google.android.gms.measurement.internal.zzy {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzec>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzed {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzed>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzee {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzee>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzef {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzef>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzeg {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzeg>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzeh {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzeh>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzei {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzei>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzej {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzej>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzek extends com.google.android.gms.measurement.internal.zzy {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzek>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzel {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzel>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzem {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzem>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzen {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzen>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzeo {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzeo>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzep {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzep>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzeq {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzeq>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzer {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzer>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzes {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzes>;
public onServiceDisconnected(param0: globalAndroid.content.ComponentName): void;
public onConnectionFailed(param0: com.google.android.gms.common.ConnectionResult): void;
public constructor(param0: any /* com.google.android.gms.measurement.internal.zzeb*/);
public onConnected(param0: globalAndroid.os.Bundle): void;
public onServiceConnected(param0: globalAndroid.content.ComponentName, param1: globalAndroid.os.IBinder): void;
public onConnectionSuspended(param0: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzet {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzet>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzeu {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzeu>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzev {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzev>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzew {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzew>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzex {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzex>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export abstract class zzf extends com.google.android.gms.measurement.internal.zze {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzf>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfd extends com.google.android.gms.measurement.internal.zzf {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfd>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfe extends com.google.android.gms.measurement.internal.zzy {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfe>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzff extends com.google.android.gms.measurement.internal.zzy {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzff>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfg {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfg>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfh {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfh>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfi {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfi>;
public start(): void;
public clear(): void;
public constructor(param0: com.google.android.gms.common.util.Clock);
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfu {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfu>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzfu>*/;
public name: string;
public origin: string;
public getValue(): any;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfv extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzfu>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfv>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfw {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfw>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfx extends com.google.android.gms.measurement.internal.zzcs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfx>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfy {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfy>;
public createSocket(param0: java.net.InetAddress, param1: number): java.net.Socket;
public createSocket(param0: java.net.InetAddress, param1: number, param2: java.net.InetAddress, param3: number): java.net.Socket;
public createSocket(param0: java.net.Socket, param1: string, param2: number, param3: boolean): java.net.Socket;
public createSocket(): java.net.Socket;
public getSupportedCipherSuites(): native.Array<string>;
public createSocket(param0: string, param1: number, param2: java.net.InetAddress, param3: number): java.net.Socket;
public getDefaultCipherSuites(): native.Array<string>;
public createSocket(param0: string, param1: number): java.net.Socket;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzfz {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzfz>;
public close(): void;
public addHandshakeCompletedListener(param0: javax.net.ssl.HandshakeCompletedListener): void;
public setWantClientAuth(param0: boolean): void;
public getSupportedProtocols(): native.Array<string>;
public setEnabledCipherSuites(param0: native.Array<string>): void;
public getOOBInline(): boolean;
public setSoTimeout(param0: number): void;
public getTcpNoDelay(): boolean;
public setNeedClientAuth(param0: boolean): void;
public setTcpNoDelay(param0: boolean): void;
public setSendBufferSize(param0: number): void;
public getLocalSocketAddress(): java.net.SocketAddress;
public sendUrgentData(param0: number): void;
public bind(param0: java.net.SocketAddress): void;
public setReceiveBufferSize(param0: number): void;
public getReuseAddress(): boolean;
public getChannel(): java.nio.channels.SocketChannel;
public getLocalAddress(): java.net.InetAddress;
public connect(param0: java.net.SocketAddress): void;
public setReuseAddress(param0: boolean): void;
public setTrafficClass(param0: number): void;
public getEnabledCipherSuites(): native.Array<string>;
public getNeedClientAuth(): boolean;
public setSoLinger(param0: boolean, param1: number): void;
public shutdownOutput(): void;
public shutdownInput(): void;
public getSession(): javax.net.ssl.SSLSession;
public getWantClientAuth(): boolean;
public getUseClientMode(): boolean;
public isInputShutdown(): boolean;
public getKeepAlive(): boolean;
public isOutputShutdown(): boolean;
public setEnabledProtocols(param0: native.Array<string>): void;
public getLocalPort(): number;
public equals(param0: any): boolean;
public setKeepAlive(param0: boolean): void;
public getPort(): number;
public toString(): string;
public getSoTimeout(): number;
public getInetAddress(): java.net.InetAddress;
public startHandshake(): void;
public getOutputStream(): java.io.OutputStream;
public setPerformancePreferences(param0: number, param1: number, param2: number): void;
public getSendBufferSize(): number;
public removeHandshakeCompletedListener(param0: javax.net.ssl.HandshakeCompletedListener): void;
public getSoLinger(): number;
public setOOBInline(param0: boolean): void;
public isConnected(): boolean;
public getInputStream(): java.io.InputStream;
public getSupportedCipherSuites(): native.Array<string>;
public isClosed(): boolean;
public getEnableSessionCreation(): boolean;
public setUseClientMode(param0: boolean): void;
public isBound(): boolean;
public getEnabledProtocols(): native.Array<string>;
public getRemoteSocketAddress(): java.net.SocketAddress;
public setEnableSessionCreation(param0: boolean): void;
public getReceiveBufferSize(): number;
public getTrafficClass(): number;
public connect(param0: java.net.SocketAddress, param1: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzg {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzg>;
public getGmpAppId(): string;
public getAppInstanceId(): string;
public setAppVersion(param0: string): void;
public setMeasurementEnabled(param0: boolean): void;
public getFirebaseInstanceId(): string;
public isMeasurementEnabled(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzk {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzk>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzk>*/;
public packageName: string;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzl extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzk>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzl>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzn {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzn>;
public static isMainThread(): boolean;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzo {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzo>;
public static CREATOR: any /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzo>*/;
public packageName: string;
public origin: string;
public creationTimestamp: number;
public active: boolean;
public triggerEventName: string;
public triggerTimeout: number;
public timeToLive: number;
public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzp extends java.lang.Object /* globalAndroid.os.Parcelable.Creator<com.google.android.gms.measurement.internal.zzo>*/ {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzp>;
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzq extends com.google.android.gms.measurement.internal.zzcr {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzq>;
public getContext(): globalAndroid.content.Context;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzr extends com.google.android.gms.measurement.internal.zzs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzr>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzs {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzs>;
/**
* Constructs a new instance of the com.google.android.gms.measurement.internal.zzs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class.
*/
public constructor(implementation: {
zzf(param0: string, param1: string): string;
});
public constructor();
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzx {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzx>;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export abstract class zzy {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzy>;
public run(): void;
}
}
}
}
}
}
}
declare module com {
export module google {
export module android {
export module gms {
export module measurement {
export module internal {
export class zzz {
public static class: java.lang.Class<com.google.android.gms.measurement.internal.zzz>;
public run(): void;
}
}
}
}
}
}
}
//Generics information:
//com.google.android.gms.internal.measurement.zzsd:1
//com.google.android.gms.internal.measurement.zzsi:1
//com.google.android.gms.measurement.internal.zzai.zza:1
//com.google.android.gms.measurement.internal.zzbu:1 | the_stack |
jest.mock('../../../lib/tx');
import {
OktaAuth,
AuthApiError,
} from '@okta/okta-auth-js';
import tokens from '@okta/test.support/tokens';
import {postToTransaction} from '../../../lib/tx';
import { APIError, isAccessToken, isIDToken } from '../../../lib/types';
describe('OktaAuth (api)', function() {
let auth;
let issuer;
beforeEach(function() {
issuer = 'http://my-okta-domain';
auth = new OktaAuth({ issuer, pkce: false });
});
it('is a valid constructor', function() {
expect(auth instanceof OktaAuth).toBe(true);
});
describe('service methods', () => {
beforeEach(() => {
jest.spyOn(auth.token, 'isLoginRedirect').mockReturnValue(false);
});
afterEach(() => {
auth.stop();
});
describe('start', () => {
it('starts the token service', () => {
jest.spyOn(auth.tokenManager, 'start');
auth.start();
expect(auth.tokenManager.start).toHaveBeenCalled();
});
it('updates auth state', () => {
jest.spyOn(auth.authStateManager, 'updateAuthState');
auth.start();
expect(auth.authStateManager.updateAuthState).toHaveBeenCalled();
});
it('should not update auth state during login redirect', () => {
jest.spyOn(auth.authStateManager, 'updateAuthState');
jest.spyOn(auth.token, 'isLoginRedirect').mockReturnValue(true);
auth.start();
expect(auth.authStateManager.updateAuthState).not.toHaveBeenCalled();
});
});
describe('stop', () => {
it('stops the token service', () => {
jest.spyOn(auth.tokenManager, 'stop');
auth.start();
auth.stop();
expect(auth.tokenManager.stop).toHaveBeenCalled();
});
});
});
describe('signInWithCredentials', () => {
let options;
beforeEach(() => {
options = { username: 'fake', password: 'fake' };
auth.fingerprint = jest.fn().mockResolvedValue('fake fingerprint');
});
it('should call "/api/v1/authn" endpoint with default options', async () => {
await auth.signInWithCredentials(options);
expect(postToTransaction).toHaveBeenCalledWith(auth, '/api/v1/authn', options, { withCredentials: true });
});
it('should call fingerprint if has sendFingerprint in options', async () => {
options.sendFingerprint = true;
await auth.signInWithCredentials(options);
delete options.sendFingerprint;
expect(auth.fingerprint).toHaveBeenCalled();
expect(postToTransaction).toHaveBeenCalledWith(auth, '/api/v1/authn', options, {
headers: { 'X-Device-Fingerprint': 'fake fingerprint' },
withCredentials: true
});
});
});
describe('signIn', () => {
let options;
beforeEach(() => {
options = { username: 'fake', password: 'fake' };
auth.signInWithCredentials = jest.fn();
});
it('should call signIn() with provided options', async () => {
await auth.signIn(options);
expect(auth.signInWithCredentials).toHaveBeenCalledWith(options);
});
});
describe('revokeAccessToken', function() {
it('will read from TokenManager and call token.revoke', function() {
var accessToken = { accessToken: 'fake' };
spyOn(auth.tokenManager, 'getTokens').and.returnValue(Promise.resolve({ accessToken }));
spyOn(auth.tokenManager, 'remove').and.returnValue(Promise.resolve(accessToken));
spyOn(auth.token, 'revoke').and.returnValue(Promise.resolve());
return auth.revokeAccessToken()
.then(function() {
expect(auth.tokenManager.getTokens).toHaveBeenCalled();
expect(auth.tokenManager.remove).toHaveBeenCalled();
expect(auth.token.revoke).toHaveBeenCalledWith(accessToken);
});
});
it('will throw if token.revoke rejects with unknown error', function() {
var accessToken = { accessToken: 'fake' };
spyOn(auth.tokenManager, 'getTokens').and.returnValue(Promise.resolve({ accessToken }));
var testError = new Error('test error');
spyOn(auth.token, 'revoke').and.callFake(function() {
return Promise.reject(testError);
});
return auth.revokeAccessToken()
.catch(function(e) {
expect(e).toBe(testError);
});
});
it('can pass an access token object to bypass TokenManager', function() {
var accessToken = { accessToken: 'fake' };
spyOn(auth.token, 'revoke').and.returnValue(Promise.resolve());
spyOn(auth.tokenManager, 'get');
return auth.revokeAccessToken(accessToken)
.then(function() {
expect(auth.tokenManager.get).not.toHaveBeenCalled();
expect(auth.token.revoke).toHaveBeenCalledWith(accessToken);
});
});
it('if accessToken cannot be located, will resolve without error', function() {
spyOn(auth.token, 'revoke').and.returnValue(Promise.resolve());
spyOn(auth.tokenManager, 'getTokens').and.returnValue(Promise.resolve({}));
return auth.revokeAccessToken()
.then(() => {
expect(auth.tokenManager.getTokens).toHaveBeenCalled();
expect(auth.token.revoke).not.toHaveBeenCalled();
});
});
});
describe('closeSession', function() {
it('Default options: clears TokenManager, closes session', function() {
spyOn(auth.session, 'close').and.returnValue(Promise.resolve());
spyOn(auth.tokenManager, 'clear');
return auth.closeSession()
.then(function() {
expect(auth.tokenManager.clear).toHaveBeenCalled();
expect(auth.session.close).toHaveBeenCalled();
});
});
it('catches and absorbs "AuthApiError" errors with errorCode E0000007 (RESOURCE_NOT_FOUND_EXCEPTION)', function() {
var testError = new AuthApiError({ errorCode: 'E0000007' } as unknown as APIError);
spyOn(auth.session, 'close').and.callFake(function() {
return Promise.reject(testError);
});
return auth.closeSession()
.then(function() {
expect(auth.session.close).toHaveBeenCalled();
});
});
it('will throw unknown errors', function() {
var testError = new Error('test error');
spyOn(auth.session, 'close').and.callFake(function() {
return Promise.reject(testError);
});
return auth.closeSession()
.catch(function(e) {
expect(e).toBe(testError);
});
});
});
describe('isAuthenticated', () => {
beforeEach(function() {
auth = new OktaAuth({ issuer, pkce: false, tokenManager: {
autoRenew: false,
autoRemove: false,
} });
});
it('returns true if accessToken and idToken exist and are not expired', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { fake: true },
idToken: { fake: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockReturnValue(false);
const res = await auth.isAuthenticated();
expect(res).toBe(true);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
});
it('returns false if accessToken does not exist', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: null,
idToken: { fake: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockReturnValue(false);
const res = await auth.isAuthenticated();
expect(res).toBe(false);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(1);
});
it('returns false if idToken does not exist', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { fake: true },
idToken: null
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockReturnValue(false);
const res = await auth.isAuthenticated();
expect(res).toBe(false);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(1);
});
it('returns false if accessToken is expired', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { accessToken: true },
idToken: { idToken: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockImplementation(token => {
return isAccessToken(token) ? true : false;
});
const res = await auth.isAuthenticated();
expect(res).toBe(false);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
});
it('returns false if idToken is expired', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { accessToken: true },
idToken: { idToken: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockImplementation(token => {
return isIDToken(token) ? true : false;
});
const res = await auth.isAuthenticated();
expect(res).toBe(false);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
});
describe('if autoRenew=true', () => {
beforeEach(function() {
auth = new OktaAuth({ issuer, pkce: false, tokenManager: {
autoRenew: true,
autoRemove: false,
} });
});
it('renew expired accessToken and return true', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { accessToken: true },
idToken: { idToken: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockImplementation(token => {
return isAccessToken(token) ? true : false;
});
jest.spyOn(auth.tokenManager, 'renew').mockReturnValue(true);
const res = await auth.isAuthenticated();
expect(res).toBe(true);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
expect(auth.tokenManager.renew).toHaveBeenCalledTimes(1);
expect(auth.tokenManager.renew).toHaveBeenCalledWith('accessToken');
});
it('renew expired idToken and return true', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { accessToken: true },
idToken: { idToken: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockImplementation(token => {
return isIDToken(token) ? true : false;
});
jest.spyOn(auth.tokenManager, 'renew').mockReturnValue(true);
const res = await auth.isAuthenticated();
expect(res).toBe(true);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
expect(auth.tokenManager.renew).toHaveBeenCalledTimes(1);
expect(auth.tokenManager.renew).toHaveBeenCalledWith('idToken');
});
});
describe('if autoRemove=true', () => {
beforeEach(function() {
auth = new OktaAuth({ issuer, pkce: false, tokenManager: {
autoRenew: false,
autoRemove: true,
} });
});
it('remove expired accessToken and return false', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { accessToken: true },
idToken: { idToken: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockImplementation(token => {
return isAccessToken(token) ? true : false;
});
jest.spyOn(auth.tokenManager, 'remove').mockReturnValue(undefined);
const res = await auth.isAuthenticated();
expect(res).toBe(false);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
expect(auth.tokenManager.remove).toHaveBeenCalledTimes(1);
expect(auth.tokenManager.remove).toHaveBeenCalledWith('accessToken');
});
it('remove expired idToken and return false', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: { accessToken: true },
idToken: { idToken: true }
});
jest.spyOn(auth.tokenManager, 'hasExpired').mockImplementation(token => {
return isIDToken(token) ? true : false;
});
jest.spyOn(auth.tokenManager, 'remove').mockReturnValue(undefined);
const res = await auth.isAuthenticated();
expect(res).toBe(false);
expect(auth.tokenManager.getTokensSync).toHaveBeenCalled();
expect(auth.tokenManager.hasExpired).toHaveBeenCalledTimes(2);
expect(auth.tokenManager.remove).toHaveBeenCalledTimes(1);
expect(auth.tokenManager.remove).toHaveBeenCalledWith('idToken');
});
});
});
describe('getUser', () => {
it('should call token.getUserInfo with tokens from tokenManager', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
idToken: tokens.standardIdTokenParsed,
accessToken: tokens.standardAccessTokenParsed
});
jest.spyOn(auth.token, 'getUserInfo').mockReturnValue(undefined);
await auth.getUser();
expect(auth.token.getUserInfo).toHaveBeenCalledWith(tokens.standardAccessTokenParsed, tokens.standardIdTokenParsed);
});
});
describe('getIdToken', () => {
it('retrieves token from tokenManager', () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
idToken: tokens.standardIdTokenParsed
});
const retVal = auth.getIdToken();
expect(retVal).toBe(tokens.standardIdToken);
});
it('should return undefined if no idToken in tokenManager', () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({});
const retVal = auth.getIdToken();
expect(retVal).toBe(undefined);
});
});
describe('getAccessToken', () => {
it('retrieves token from tokenManager', () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({
accessToken: tokens.standardAccessTokenParsed
});
const retVal = auth.getAccessToken();
expect(retVal).toBe(tokens.standardAccessToken);
});
it('should return undefined if no accessToken in tokenManager', async () => {
jest.spyOn(auth.tokenManager, 'getTokensSync').mockReturnValue({});
const retVal = auth.getAccessToken();
expect(retVal).toBe(undefined);
});
});
describe('isPKCE', () => {
it('is true by default', () => {
auth = new OktaAuth({ issuer });
expect(auth.isPKCE()).toBe(true);
});
it('is false if pkce option is false', () => {
auth = new OktaAuth({ issuer, pkce: false });
expect(auth.isPKCE()).toBe(false);
});
});
describe('hasResponseType', () => {
it('returns true if responseType is a string', () => {
auth = new OktaAuth({ issuer, responseType: 'fake' });
expect(auth.hasResponseType('fake')).toBe(true);
});
it('returns true if responseType is an array', () => {
auth = new OktaAuth({ issuer, responseType: ['fake', 'alsofake'] });
expect(auth.hasResponseType('fake')).toBe(true);
});
it('returns false if responseType does not match string', () => {
auth = new OktaAuth({ issuer, responseType: 'abc' });
expect(auth.hasResponseType('fake')).toBe(false);
});
it('returns false if responseType does not match entry in array', () => {
auth = new OktaAuth({ issuer, responseType: ['abc', 'def'] });
expect(auth.hasResponseType('fake')).toBe(false);
});
});
describe('isAuthorizationCodeFlow', () => {
it('is false by default', () => {
auth = new OktaAuth({ issuer });
expect(auth.isAuthorizationCodeFlow()).toBe(false);
});
it('will be true if is "code"', () => {
auth = new OktaAuth({ issuer, responseType: 'code' });
expect(auth.isAuthorizationCodeFlow()).toBe(true);
});
it('will be true if responseType is ["code"]', () => {
auth = new OktaAuth({ issuer, pkce: false, responseType: ['code'] });
expect(auth.isAuthorizationCodeFlow()).toBe(true);
});
it('will be true if responseType is [..., "code"]', () => {
auth = new OktaAuth({ issuer, pkce: false, responseType: ['abc', 'code'] });
expect(auth.isAuthorizationCodeFlow()).toBe(true);
});
});
}); | the_stack |
import localforage from 'localforage';
import queryString from 'query-string';
import message from '../common/message';
import {
ACLRecord,
AppInfo,
Batch,
BatchHistoryItem,
ChartFields,
Connection,
ConnectionClient,
} from '../types';
import { api } from '../utilities/api';
import { getHistory } from '../utilities/history';
import {
removeLocalQueryText,
setLocalQueryText,
} from '../utilities/localQueryText';
import updateCompletions from '../utilities/updateCompletions';
import {
EditorSession,
INITIAL_SESSION,
INITIAL_STATE,
SchemaState,
useEditorStore,
} from './editor-store';
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const { getState, setState } = useEditorStore;
function setSession(sessionId: string, update: Partial<EditorSession>) {
const { editorSessions } = getState();
const session = getState().getSession(sessionId);
if (!session) {
return setState({
editorSessions: {
...editorSessions,
[sessionId]: { ...INITIAL_SESSION, ...update },
},
});
}
setState({
editorSessions: {
...editorSessions,
[sessionId]: { ...session, ...update },
},
});
}
// Schedule connectionClient Heartbeat
// This only does work if data exists to do the work on
// Assumption here is that the API call will finish in the 10 seconds this is scheduled for
setInterval(async () => {
const { editorSessions } = getState();
for (const sessionId of Object.keys(editorSessions)) {
const { connectionClient } = getState().getSession(sessionId) || {};
if (connectionClient) {
const updateJson = await api.put(
`/api/connection-clients/${connectionClient.id}`,
{}
);
const currentConnectionClient =
getState().getSession(sessionId)?.connectionClient;
// If the connectionClient changed since hearbeat, do nothing
if (
!currentConnectionClient ||
currentConnectionClient.id !== connectionClient?.id
) {
return;
}
// If the PUT didn't return a connectionClient object or has an error,
// the connectionClient has been disconnected
if (updateJson.error || !updateJson.data) {
setSession(sessionId, {
connectionClient: undefined,
});
} else {
setSession(sessionId, {
connectionClient: updateJson.data,
});
}
}
}
}, 10000);
function setBatch(sessionId: string, batchId: string, batch: Batch) {
const { batches, statements } = getState();
const { selectedStatementId } = getState().getSession(sessionId) || {};
const updatedStatements = {
...statements,
};
if (batch?.statements) {
for (const statement of batch.statements) {
updatedStatements[statement.id] = statement;
}
if (batch.statements.length === 1) {
const onlyStatementId = batch.statements[0].id;
if (selectedStatementId !== onlyStatementId) {
setSession(sessionId, { selectedStatementId: onlyStatementId });
}
}
}
setState({
statements: updatedStatements,
batches: {
...batches,
[batchId]: batch,
},
});
}
export const initEditor = async (
config: AppInfo['config'],
connections: Connection[]
) => {
try {
let [selectedConnectionId] = await Promise.all([
localforage.getItem('selectedConnectionId'),
]);
let initialConnectionId = '';
if (connections.length === 1) {
initialConnectionId = connections[0].id;
} else {
const { defaultConnectionId } = config || {};
if (defaultConnectionId) {
const foundDefault = connections.find(
(c) => c.id === defaultConnectionId
);
if (Boolean(foundDefault)) {
initialConnectionId = defaultConnectionId;
}
}
if (typeof selectedConnectionId === 'string') {
const selectedConnection = connections.find(
(c) => c.id === selectedConnectionId
);
if (Boolean(selectedConnection)) {
initialConnectionId = selectedConnectionId;
}
}
const qs = queryString.parse(window.location.search);
const qsConnectionName = qs.connectionName;
if (qsConnectionName) {
const selectedConnection = connections.find(
(c) => c.name === qsConnectionName
);
if (selectedConnection?.id) {
initialConnectionId = selectedConnection?.id;
}
}
const qsConnectionId = qs.connectionId;
if (qsConnectionId) {
const selectedConnection = connections.find(
(c) => c.id === qsConnectionId
);
if (selectedConnection?.id) {
initialConnectionId = selectedConnection?.id;
}
}
}
const { focusedSessionId } = getState();
setSession(focusedSessionId, { connectionId: initialConnectionId });
if (initialConnectionId) {
loadSchema(initialConnectionId);
}
setState({ initialized: true });
} catch (error) {
console.error(error);
message.error('Error initializing application');
}
};
export function toggleShowQueryModal() {
const { showQueryModal } = getState();
setState({ showQueryModal: !showQueryModal });
}
export function setMouseOverResultPane(mouseOverResultPane: boolean) {
setState({ mouseOverResultPane });
}
/**
* Reset state (on signout for example)
*/
export async function resetState() {
setState({ ...INITIAL_STATE });
}
/**
* Open a connection client for the currently selected connection if supported
*/
export async function connectConnectionClient() {
const { focusedSessionId } = getState();
const { connectionClient, connectionId } = getState().getFocusedSession();
// If a connectionClient is already open or selected connection id doesn't exist, do nothing
if (connectionClient || !connectionId) {
return;
}
// Regular users are not allowed to get connections by id, but they can get list of connections
// May want to store selected connection instead of just id
const { data: connections } = await api.getConnections();
const connection = (connections || []).find(
(connection) => connection.id === connectionId
);
if (connection) {
setAsynchronousDriver(connection.isAsynchronous);
}
const supportedAndEnabled =
connection &&
connection.supportsConnectionClient &&
connection.multiStatementTransactionEnabled;
if (!supportedAndEnabled) {
return;
}
const json = await api.post('/api/connection-clients', {
connectionId,
});
if (json.error) {
return message.error('Problem connecting to database');
}
setSession(focusedSessionId, {
connectionClient: json.data,
isDriverAsynchronous: connection ? connection.isAsynchronous : false,
});
}
/**
* Disconnect the current connection client if one exists
*/
export async function disconnectConnectionClient() {
const { focusedSessionId } = getState();
const { connectionClient } = getState().getFocusedSession();
if (connectionClient) {
api
.delete(`/api/connection-clients/${connectionClient.id}`)
.then((json) => {
if (json.error) {
message.error(json.error);
}
});
}
setSession(focusedSessionId, {
connectionClient: undefined,
});
}
function cleanupConnectionClient(connectionClient?: ConnectionClient) {
// Close connection client but do not wait for this to complete
if (connectionClient) {
api
.delete(`/api/connection-clients/${connectionClient.id}`)
.then((json) => {
if (json.error) {
message.error(json.error);
}
});
}
}
/**
* Select connection and disconnect connectionClient if it exists
* @param connectionId
*/
export function selectConnectionId(connectionId: string) {
const { focusedSessionId } = getState();
const { connectionClient } = getState().getFocusedSession();
localforage
.setItem('selectedConnectionId', connectionId)
.catch((error) => message.error(error));
cleanupConnectionClient(connectionClient);
setSession(focusedSessionId, {
connectionId,
connectionClient: undefined,
});
}
export const formatQuery = async () => {
const { focusedSessionId } = getState();
const { queryText, queryId } = getState().getFocusedSession();
const json = await api.post('/api/format-sql', {
query: queryText,
});
if (json.error) {
message.error(json.error);
return;
}
if (!json.data || !json.data.query) {
console.warn('unexpected API result');
return;
}
setLocalQueryText(queryId, json.data.query);
setSession(focusedSessionId, {
queryText: json.data.query,
unsavedChanges: true,
});
};
/**
* Loads query and stores in editor session state.
* Returns a promise of API result to allow context-dependent behavior,
* like showing not found modal in query editor.
* @param queryId
*/
export const loadQuery = async (queryId: string) => {
const response = await api.getQuery(queryId);
const { error, data } = response;
if (error || !data) {
return response;
}
const { focusedSessionId } = getState();
const { connectionClient, ...restOfCurrentSession } =
getState().getFocusedSession();
// Cleanup existing connection
// Even if the connection isn't changing, the client should be refreshed
// This is to prevent accidental state from carrying over
// For example, if there is an open transaction,
// we don't want that impacting the new query if same connectionId is used)
cleanupConnectionClient(connectionClient);
setSession(focusedSessionId, {
...restOfCurrentSession,
// Map query object to flattened editor session data
queryId,
connectionId: data.connectionId,
connectionClient: undefined,
queryText: data.queryText,
queryName: data.name,
tags: data.tags,
acl: data.acl,
chartType: data?.chart?.chartType,
chartFields: data?.chart?.fields,
canDelete: data.canDelete,
canRead: data.canRead,
canWrite: data.canWrite,
// Reset result/error/unsaved/running states
batchId: '',
selectedStatementId: '',
isRunning: false,
queryError: undefined,
unsavedChanges: false,
});
return response;
};
export const runQuery = async () => {
const { focusedSessionId } = getState();
const {
queryId,
queryName,
queryText,
chartType,
chartFields,
connectionId,
connectionClient,
selectedText,
isDriverAsynchronous,
} = getState().getFocusedSession();
if (!connectionId) {
return setSession(focusedSessionId, {
queryError: 'Connection required',
selectedStatementId: '',
});
}
if (!queryText) {
return setSession(focusedSessionId, {
queryError: 'SQL text required',
selectedStatementId: '',
});
}
setSession(focusedSessionId, {
batchId: undefined,
isRunning: true,
isExecutionStarting: false,
runQueryStartTime: new Date(),
selectedStatementId: '',
});
const postData = {
connectionId,
connectionClientId: connectionClient && connectionClient.id,
queryId,
name: queryName,
batchText: queryText,
selectedText,
chart: {
chartType,
fields: chartFields,
},
};
let res = await api.createBatch(postData);
setSession(focusedSessionId, {
isExecutionStarting: isDriverAsynchronous ? true : false,
});
let error = res.error;
let batch = res.data;
if (error) {
return setSession(focusedSessionId, {
queryError: error,
});
}
if (!batch) {
return setSession(focusedSessionId, {
queryError: 'error creating batch',
});
}
setBatch(focusedSessionId, batch.id, batch);
while (
batch?.id &&
!(
(batch?.status === 'finished' ||
batch?.status === 'error' ||
batch?.status === 'cancelled') &&
!error
)
) {
await sleep(500);
res = await api.getBatch(batch.id);
error = res.error;
batch = res.data;
setSession(focusedSessionId, {
batchId: batch?.id,
queryError: error,
});
if (batch) {
setBatch(focusedSessionId, batch.id, batch);
}
}
setSession(focusedSessionId, {
isRunning: false,
isExecutionStarting: false,
});
};
export const cancelQuery = async () => {
const { focusedSessionId } = getState();
const { connectionId, isDriverAsynchronous, batchId } =
getState().getFocusedSession();
if (!isDriverAsynchronous) {
return setSession(focusedSessionId, {
queryError: 'Driver does not support cancellation',
selectedStatementId: '',
});
}
if (!batchId) {
return setSession(focusedSessionId, {
queryError: 'Batch ID required',
selectedStatementId: '',
});
}
if (!connectionId) {
return setSession(focusedSessionId, {
queryError: 'Connection required',
selectedStatementId: '',
});
}
setSession(focusedSessionId, {
isRunning: true,
isExecutionStarting: true,
runQueryStartTime: new Date(),
selectedStatementId: '',
});
const putData = {
connectionId: connectionId,
};
await api.cancelBatch(batchId, putData);
message.error('Query cancelled by user');
return setSession(focusedSessionId, {
batchId: undefined,
isRunning: false,
isExecutionStarting: false,
});
};
export const setEditorBatchHistoryItem = async (
batchHistoryItem: BatchHistoryItem
) => {
const { focusedSessionId } = getState();
// Statements might not exist if query result data is purged
// In that case, just restore the SQL and chart config and similar
// clear out batchId/selectedStatementId
const hasStatements = batchHistoryItem.statements;
setSession(focusedSessionId, {
queryName: batchHistoryItem.name,
queryText: batchHistoryItem.batchText,
chartType: batchHistoryItem.chart?.chartType,
chartFields: batchHistoryItem.chart?.fields,
connectionId: batchHistoryItem.connectionId,
connectionClient: undefined,
selectedText: '',
batchId: hasStatements ? batchHistoryItem.id : undefined,
selectedStatementId: undefined,
isRunning: false,
runQueryStartTime: batchHistoryItem.startTime,
});
if (hasStatements) {
setBatch(focusedSessionId, batchHistoryItem.id, batchHistoryItem);
}
};
export const saveQuery = async (additionalUpdates?: Partial<EditorSession>) => {
const { focusedSessionId } = getState();
const session = getState().getFocusedSession();
// If can't write, bail early
if (!session.canWrite) {
setSession(focusedSessionId, { showValidation: false });
setState({ showQueryModal: false });
return;
}
const mergedSession = { ...session, ...additionalUpdates };
const {
queryId,
connectionId,
queryName,
queryText,
chartFields,
chartType,
tags,
acl,
} = mergedSession;
if (!queryName) {
setSession(focusedSessionId, { showValidation: true });
setState({ showQueryModal: true });
return;
}
setSession(focusedSessionId, { isSaving: true, saveError: undefined });
const queryData = {
connectionId,
name: queryName,
queryText,
acl,
chart: {
chartType,
fields: chartFields,
},
tags,
};
if (queryId) {
api.updateQuery(queryId, queryData).then((json) => {
const { error, data } = json;
if (error) {
// If there was an error, show the save dialog.
// It might be closed and it is where the error is placed.
// This should be rare, and not sure what might trigger it at this point, but just in case
setSession(focusedSessionId, { isSaving: false, saveError: error });
setState({ showQueryModal: true });
return;
}
// TypeScript doesn't know that if error did not exist we are dealing with data
if (data) {
removeLocalQueryText(data.id);
setSession(focusedSessionId, {
isSaving: false,
unsavedChanges: false,
connectionId: data.connectionId,
queryId: data.id,
queryText: data.queryText,
queryName: data.name,
tags: data.tags,
acl: data.acl,
chartType: data?.chart?.chartType,
chartFields: data?.chart?.fields,
canDelete: data.canDelete,
canRead: data.canRead,
canWrite: data.canWrite,
});
setState({ showQueryModal: false });
}
});
} else {
api.createQuery(queryData).then((json) => {
const { error, data } = json;
if (error) {
// If there was an error, show the save dialog.
// It might be closed and it is where the error is placed.
// This should be rare, and not sure what might trigger it at this point, but just in case
setSession(focusedSessionId, { isSaving: false, saveError: error });
setState({ showQueryModal: true });
return;
}
// TypeScript doesn't know that if error did not exist we are dealing with data
if (data) {
const history = getHistory();
history?.push(`/queries/${data.id}`);
removeLocalQueryText(data.id);
setSession(focusedSessionId, {
isSaving: false,
unsavedChanges: false,
connectionId: data.connectionId,
queryId: data.id,
queryText: data.queryText,
queryName: data.name,
tags: data.tags,
acl: data.acl,
chartType: data?.chart?.chartType,
chartFields: data?.chart?.fields,
canDelete: data.canDelete,
canRead: data.canRead,
canWrite: data.canWrite,
});
setState({ showQueryModal: false });
}
});
}
};
// Clone works by updating existing session, then navigating to URL with `/queries/new`
// The session doesn't change, so the new should not get applied
export const handleCloneClick = () => {
const { focusedSessionId } = getState();
const { queryName } = getState().getFocusedSession();
const history = getHistory();
setSession(focusedSessionId, {
queryId: '',
queryName: `Copy of ${queryName}`,
unsavedChanges: true,
canDelete: true,
canWrite: true,
canRead: true,
});
history?.push(`/queries/new`);
};
export const resetNewQuery = () => {
const { focusedSessionId } = getState();
// Get some editor state from current session and carry that on to new session
const {
showSchema,
showVisProperties,
schemaExpansions,
connectionId,
connectionClient,
} = getState().getFocusedSession();
const session = {
...INITIAL_SESSION,
showSchema,
showVisProperties,
schemaExpansions,
connectionId,
connectionClient,
};
setSession(focusedSessionId, session);
};
export const selectStatementId = (selectedStatementId: string) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { selectedStatementId });
};
export const setQueryText = (queryText: string) => {
const { focusedSessionId } = getState();
const { queryId } = getState().getFocusedSession();
setLocalQueryText(queryId, queryText);
setSession(focusedSessionId, { queryText, unsavedChanges: true });
};
export const setQueryName = (queryName: string) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { queryName, unsavedChanges: true });
};
export const setTags = (tags: string[]) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { tags, unsavedChanges: true });
};
export const setAcl = (acl: Partial<ACLRecord>[]) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { acl, unsavedChanges: true });
};
export const setChartType = (chartType: string) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { chartType, unsavedChanges: true });
};
export const setChartFields = (chartFields: ChartFields) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { chartFields, unsavedChanges: true });
};
export const handleChartConfigurationFieldsChange = (
chartFieldId: string,
queryResultField: string | boolean | number
) => {
const { focusedSessionId } = getState();
const { chartFields } = getState().getFocusedSession();
setSession(focusedSessionId, {
chartFields: { ...chartFields, [chartFieldId]: queryResultField },
unsavedChanges: true,
});
};
export const handleChartTypeChange = (chartType: string) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { chartType, unsavedChanges: true });
};
export const handleQuerySelectionChange = (selectedText: string) => {
const { focusedSessionId } = getState();
setSession(focusedSessionId, { selectedText });
};
export function toggleSchema() {
const { focusedSessionId } = getState();
const { showSchema } = getState().getFocusedSession();
setSession(focusedSessionId, { showSchema: !showSchema });
}
export function toggleVisProperties() {
const { focusedSessionId } = getState();
const { showVisProperties } = getState().getFocusedSession();
setSession(focusedSessionId, { showVisProperties: !showVisProperties });
}
export function setSchemaState(connectionId: string, schemaState: SchemaState) {
const { schemaStates } = getState();
const update = {
...schemaStates,
[connectionId]: schemaState,
};
setState({ schemaStates: update });
}
/**
* Get schema via API and store into editor store
* @param connectionId - connection id to get schema for
* @param reload - force cache refresh for schema
*/
export async function loadSchema(connectionId: string, reload?: boolean) {
const { schemaStates, focusedSessionId } = getState();
const { showSchema, schemaExpansions } = getState().getFocusedSession();
if (!schemaStates[connectionId] || reload) {
setSchemaState(connectionId, {
loading: true,
});
const json = await api.getConnectionSchema(connectionId, reload);
const { error, data } = json;
if (error) {
setSchemaState(connectionId, {
loading: false,
error,
});
// If sidebar is not shown, send error notification
// It is otherwise shown in sidebar where schema would be
if (!showSchema) {
message.error(error);
}
return;
}
// Pre-expand schemas
const expanded: { [key: string]: boolean } = {};
// Added schemas length restriction before auto-expand.
// This limit is there because there is no collapse-all function in the UI
// and render time can explode quickly.
// In datawarehousing there can be 100's of schema's each containing 50-100
// tables and those containing each 5+ columns and manually collapsing
// them is very annoying.
// NOTE: the 5 here is completely arbitrary it may be preferable to not auto expand unless there is only 1.
if (data?.schemas && data?.schemas.length <= 5) {
data.schemas.forEach((schema) => {
expanded[schema.name] = true;
});
}
const stringCompare = new Intl.Collator('en', { sensitivity: 'base' });
const nameCompare: { (a: { name: string }, b: { name: string }): number } =
(a, b) => stringCompare.compare(a.name, b.name);
if (data?.schemas) {
data.schemas.sort(nameCompare);
data.schemas.forEach((schema) => {
schema.tables.sort(nameCompare);
// NOTE: we do not sort columns that can be annoying with regards to creation order.
});
}
if (data?.tables) {
data.tables.sort(nameCompare);
}
setSchemaState(connectionId, {
loading: false,
connectionSchema: data,
error: undefined,
});
setSession(focusedSessionId, {
schemaExpansions: { ...schemaExpansions, [connectionId]: expanded },
});
}
// Refresh completions
const connectionSchema =
getState().schemaStates[connectionId]?.connectionSchema;
if (connectionSchema?.schemas || connectionSchema?.tables) {
updateCompletions(connectionSchema);
} else {
updateCompletions({ schemas: [] });
}
}
export function toggleSchemaItem(connectionId: string, item: { id: string }) {
const { focusedSessionId } = getState();
const { schemaExpansions } = getState().getFocusedSession();
const expanded = { ...schemaExpansions[connectionId] };
expanded[item.id] = !expanded[item.id];
setSession(focusedSessionId, {
schemaExpansions: { ...schemaExpansions, [connectionId]: expanded },
});
}
/**
* Sets the state for an asynchronous driver that will enable cancel queries
* @param {boolean} setAsynchronousDriver
*/
export function setAsynchronousDriver(asynchronous?: boolean) {
const { focusedSessionId } = getState();
const isAsync = asynchronous ? true : false;
setSession(focusedSessionId, {
isDriverAsynchronous: isAsync,
});
} | the_stack |
import { Path } from './path'
import { Point } from './point'
import { Ellipse } from './ellipse'
import { Geometry } from './geometry'
import { Polyline } from './polyline'
import { Rectangle } from './rectangle'
export class Line extends Geometry {
public start: Point
public end: Point
protected get [Symbol.toStringTag]() {
return Line.toStringTag
}
get center() {
return new Point(
(this.start.x + this.end.x) / 2,
(this.start.y + this.end.y) / 2,
)
}
constructor(x1: number, y1: number, x2: number, y2: number)
constructor(
p1: Point.PointLike | Point.PointData,
p2: Point.PointLike | Point.PointData,
)
constructor(
x1: number | Point.PointLike | Point.PointData,
y1: number | Point.PointLike | Point.PointData,
x2?: number,
y2?: number,
) {
super()
if (typeof x1 === 'number' && typeof y1 === 'number') {
this.start = new Point(x1, y1)
this.end = new Point(x2, y2)
} else {
this.start = Point.create(x1)
this.end = Point.create(y1)
}
}
getCenter() {
return this.center
}
/**
* Rounds the line to the given `precision`.
*/
round(precision = 0) {
this.start.round(precision)
this.end.round(precision)
return this
}
translate(tx: number, ty: number): this
translate(p: Point.PointLike | Point.PointData): this
translate(tx: number | Point.PointLike | Point.PointData, ty?: number) {
if (typeof tx === 'number') {
this.start.translate(tx, ty as number)
this.end.translate(tx, ty as number)
} else {
this.start.translate(tx)
this.end.translate(tx)
}
return this
}
/**
* Rotate the line by `angle` around `origin`.
*/
rotate(angle: number, origin?: Point.PointLike | Point.PointData) {
this.start.rotate(angle, origin)
this.end.rotate(angle, origin)
return this
}
/**
* Scale the line by `sx` and `sy` about the given `origin`. If origin is not
* specified, the line is scaled around `0,0`.
*/
scale(sx: number, sy: number, origin?: Point.PointLike | Point.PointData) {
this.start.scale(sx, sy, origin)
this.end.scale(sx, sy, origin)
return this
}
/**
* Returns the length of the line.
*/
length() {
return Math.sqrt(this.squaredLength())
}
/**
* Useful for distance comparisons in which real length is not necessary
* (saves one `Math.sqrt()` operation).
*/
squaredLength() {
const dx = this.start.x - this.end.x
const dy = this.start.y - this.end.y
return dx * dx + dy * dy
}
/**
* Scale the line so that it has the requested length. The start point of
* the line is preserved.
*/
setLength(length: number) {
const total = this.length()
if (!total) {
return this
}
const scale = length / total
return this.scale(scale, scale, this.start)
}
parallel(distance: number) {
const line = this.clone()
if (!line.isDifferentiable()) {
return line
}
const { start, end } = line
const eRef = start.clone().rotate(270, end)
const sRef = end.clone().rotate(90, start)
start.move(sRef, distance)
end.move(eRef, distance)
return line
}
/**
* Returns the vector of the line with length equal to length of the line.
*/
vector() {
return new Point(this.end.x - this.start.x, this.end.y - this.start.y)
}
/**
* Returns the angle of incline of the line.
*
* The function returns `NaN` if the start and end endpoints of the line
* both lie at the same coordinates(it is impossible to determine the angle
* of incline of a line that appears to be a point). The
* `line.isDifferentiable()` function may be used in advance to determine
* whether the angle of incline can be computed for a given line.
*/
angle() {
const horizontal = new Point(this.start.x + 1, this.start.y)
return this.start.angleBetween(this.end, horizontal)
}
/**
* Returns a rectangle that is the bounding box of the line.
*/
bbox() {
const left = Math.min(this.start.x, this.end.x)
const top = Math.min(this.start.y, this.end.y)
const right = Math.max(this.start.x, this.end.x)
const bottom = Math.max(this.start.y, this.end.y)
return new Rectangle(left, top, right - left, bottom - top)
}
/**
* Returns the bearing (cardinal direction) of the line.
*
* The return value is one of the following strings:
* 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW' and 'N'.
*
* The function returns 'N' if the two endpoints of the line are coincident.
*/
bearing() {
return this.start.bearing(this.end)
}
/**
* Returns the point on the line that lies closest to point `p`.
*/
closestPoint(p: Point.PointLike | Point.PointData) {
return this.pointAt(this.closestPointNormalizedLength(p))
}
/**
* Returns the length of the line up to the point that lies closest to point `p`.
*/
closestPointLength(p: Point.PointLike | Point.PointData) {
return this.closestPointNormalizedLength(p) * this.length()
}
/**
* Returns a line that is tangent to the line at the point that lies closest
* to point `p`.
*/
closestPointTangent(p: Point.PointLike | Point.PointData) {
return this.tangentAt(this.closestPointNormalizedLength(p))
}
/**
* Returns the normalized length (distance from the start of the line / total
* line length) of the line up to the point that lies closest to point.
*/
closestPointNormalizedLength(p: Point.PointLike | Point.PointData) {
const product = this.vector().dot(new Line(this.start, p).vector())
const normalized = Math.min(1, Math.max(0, product / this.squaredLength()))
// normalized returns `NaN` if this line has zero length
if (Number.isNaN(normalized)) {
return 0
}
return normalized
}
/**
* Returns a point on the line that lies `rate` (normalized length) away from
* the beginning of the line.
*/
pointAt(ratio: number) {
const start = this.start
const end = this.end
if (ratio <= 0) {
return start.clone()
}
if (ratio >= 1) {
return end.clone()
}
return start.lerp(end, ratio)
}
/**
* Returns a point on the line that lies length away from the beginning of
* the line.
*/
pointAtLength(length: number) {
const start = this.start
const end = this.end
let fromStart = true
if (length < 0) {
fromStart = false // start calculation from end point
length = -length // eslint-disable-line
}
const total = this.length()
if (length >= total) {
return fromStart ? end.clone() : start.clone()
}
const rate = (fromStart ? length : total - length) / total
return this.pointAt(rate)
}
/**
* Divides the line into two lines at the point that lies `rate` (normalized
* length) away from the beginning of the line.
*/
divideAt(ratio: number) {
const dividerPoint = this.pointAt(ratio)
return [
new Line(this.start, dividerPoint),
new Line(dividerPoint, this.end),
]
}
/**
* Divides the line into two lines at the point that lies length away from
* the beginning of the line.
*/
divideAtLength(length: number) {
const dividerPoint = this.pointAtLength(length)
return [
new Line(this.start, dividerPoint),
new Line(dividerPoint, this.end),
]
}
/**
* Returns `true` if the point `p` lies on the line. Return `false` otherwise.
*/
containsPoint(p: Point.PointLike | Point.PointData) {
const start = this.start
const end = this.end
// cross product of 0 indicates that this line and
// the vector to `p` are collinear.
if (start.cross(p, end) !== 0) {
return false
}
const length = this.length()
if (new Line(start, p).length() > length) {
return false
}
if (new Line(p, end).length() > length) {
return false
}
return true
}
/**
* Returns an array of the intersection points of the line with another
* geometry shape.
*/
intersect(shape: Line | Rectangle | Polyline | Ellipse): Point[] | null
intersect(shape: Path, options?: Path.Options): Point[] | null
intersect(
shape: Line | Rectangle | Polyline | Ellipse | Path,
options?: Path.Options,
): Point[] | null {
const ret = shape.intersectsWithLine(this, options)
if (ret) {
return Array.isArray(ret) ? ret : [ret]
}
return null
}
/**
* Returns the intersection point of the line with another line. Returns
* `null` if no intersection exists.
*/
intersectsWithLine(line: Line) {
const pt1Dir = new Point(
this.end.x - this.start.x,
this.end.y - this.start.y,
)
const pt2Dir = new Point(
line.end.x - line.start.x,
line.end.y - line.start.y,
)
const det = pt1Dir.x * pt2Dir.y - pt1Dir.y * pt2Dir.x
const deltaPt = new Point(
line.start.x - this.start.x,
line.start.y - this.start.y,
)
const alpha = deltaPt.x * pt2Dir.y - deltaPt.y * pt2Dir.x
const beta = deltaPt.x * pt1Dir.y - deltaPt.y * pt1Dir.x
if (det === 0 || alpha * det < 0 || beta * det < 0) {
return null
}
if (det > 0) {
if (alpha > det || beta > det) {
return null
}
} else if (alpha < det || beta < det) {
return null
}
return new Point(
this.start.x + (alpha * pt1Dir.x) / det,
this.start.y + (alpha * pt1Dir.y) / det,
)
}
/**
* Returns `true` if a tangent line can be found for the line.
*
* Tangents cannot be found if both of the line endpoints are coincident
* (the line appears to be a point).
*/
isDifferentiable() {
return !this.start.equals(this.end)
}
/**
* Returns the perpendicular distance between the line and point. The
* distance is positive if the point lies to the right of the line, negative
* if the point lies to the left of the line, and `0` if the point lies on
* the line.
*/
pointOffset(p: Point.PointLike | Point.PointData) {
const ref = Point.clone(p)
const start = this.start
const end = this.end
const determinant =
(end.x - start.x) * (ref.y - start.y) -
(end.y - start.y) * (ref.x - start.x)
return determinant / this.length()
}
/**
* Returns the squared distance between the line and the point.
*/
pointSquaredDistance(x: number, y: number): number
pointSquaredDistance(p: Point.PointLike | Point.PointData): number
pointSquaredDistance(
x: number | Point.PointLike | Point.PointData,
y?: number,
) {
const p = Point.create(x, y)
return this.closestPoint(p).squaredDistance(p)
}
/**
* Returns the distance between the line and the point.
*/
pointDistance(x: number, y: number): number
pointDistance(p: Point.PointLike | Point.PointData): number
pointDistance(x: number | Point.PointLike | Point.PointData, y?: number) {
const p = Point.create(x, y)
return this.closestPoint(p).distance(p)
}
/**
* Returns a line tangent to the line at point that lies `rate` (normalized
* length) away from the beginning of the line.
*/
tangentAt(ratio: number) {
if (!this.isDifferentiable()) {
return null
}
const start = this.start
const end = this.end
const tangentStart = this.pointAt(ratio)
const tangentLine = new Line(start, end)
tangentLine.translate(tangentStart.x - start.x, tangentStart.y - start.y)
return tangentLine
}
/**
* Returns a line tangent to the line at point that lies `length` away from
* the beginning of the line.
*/
tangentAtLength(length: number) {
if (!this.isDifferentiable()) {
return null
}
const start = this.start
const end = this.end
const tangentStart = this.pointAtLength(length)
const tangentLine = new Line(start, end)
tangentLine.translate(tangentStart.x - start.x, tangentStart.y - start.y)
return tangentLine
}
/**
* Returns which direction the line would have to rotate in order to direct
* itself at a point.
*
* Returns 1 if the given point on the right side of the segment, 0 if its
* on the segment, and -1 if the point is on the left side of the segment.
*
* @see https://softwareengineering.stackexchange.com/questions/165776/what-do-ptlinedist-and-relativeccw-do
*/
relativeCcw(x: number, y: number): -1 | 0 | 1
relativeCcw(p: Point.PointLike | Point.PointData): -1 | 0 | 1
relativeCcw(x: number | Point.PointLike | Point.PointData, y?: number) {
const ref = Point.create(x, y)
let dx1 = ref.x - this.start.x
let dy1 = ref.y - this.start.y
const dx2 = this.end.x - this.start.x
const dy2 = this.end.y - this.start.y
let ccw = dx1 * dy2 - dy1 * dx2
if (ccw === 0) {
ccw = dx1 * dx2 + dy1 * dy2
if (ccw > 0.0) {
dx1 -= dx2
dy1 -= dy2
ccw = dx1 * dx2 + dy1 * dy2
if (ccw < 0.0) {
ccw = 0.0
}
}
}
return ccw < 0.0 ? -1 : ccw > 0.0 ? 1 : 0
}
/**
* Return `true` if the line equals the other line.
*/
equals(l: Line) {
return (
l != null &&
this.start.x === l.start.x &&
this.start.y === l.start.y &&
this.end.x === l.end.x &&
this.end.y === l.end.y
)
}
/**
* Returns another line which is a clone of the line.
*/
clone() {
return new Line(this.start, this.end)
}
toJSON() {
return { start: this.start.toJSON(), end: this.end.toJSON() }
}
serialize() {
return [this.start.serialize(), this.end.serialize()].join(' ')
}
}
export namespace Line {
export const toStringTag = `X6.Geometry.${Line.name}`
export function isLine(instance: any): instance is Line {
if (instance == null) {
return false
}
if (instance instanceof Line) {
return true
}
const tag = instance[Symbol.toStringTag]
const line = instance as Line
try {
if (
(tag == null || tag === toStringTag) &&
Point.isPoint(line.start) &&
Point.isPoint(line.end) &&
typeof line.vector === 'function' &&
typeof line.bearing === 'function' &&
typeof line.parallel === 'function' &&
typeof line.intersect === 'function'
) {
return true
}
} catch (e) {
return false
}
return false
}
} | the_stack |
import { assign, cloneDeep } from 'lodash';
import gql from 'graphql-tag';
import { itAsync, mockSingleLink, subscribeAndCount } from '../testing';
import { InMemoryCache, InMemoryCacheConfig, FieldMergeFunction } from '../cache';
import { ApolloClient, NetworkStatus, ObservableQuery } from '../core';
import { offsetLimitPagination, concatPagination } from '../utilities';
describe('updateQuery on a simple query', () => {
const query = gql`
query thing {
entry {
value
__typename
}
__typename
}
`;
const result = {
data: {
__typename: 'Query',
entry: {
__typename: 'Entry',
value: 1,
},
},
};
itAsync('triggers new result from updateQuery', (resolve, reject) => {
let latestResult: any = null;
const link = mockSingleLink({
request: { query },
result,
}).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const obsHandle = client.watchQuery({
query,
});
const sub = obsHandle.subscribe({
next(queryResult: any) {
// do nothing
latestResult = queryResult;
},
});
return new Promise(resolve => setTimeout(resolve, 5))
.then(() => obsHandle)
.then((watchedQuery: ObservableQuery<any>) => {
expect(latestResult.data.entry.value).toBe(1);
watchedQuery.updateQuery((prevResult: any) => {
const res = cloneDeep(prevResult);
res.entry.value = 2;
return res;
});
})
.then(() => expect(latestResult.data.entry.value).toBe(2))
.then(() => sub.unsubscribe())
.then(resolve, reject);
});
});
describe('updateQuery on a query with required and optional variables', () => {
const query = gql`
query thing($requiredVar: String!, $optionalVar: String) {
entry(requiredVar: $requiredVar, optionalVar: $optionalVar) {
value
__typename
}
__typename
}
`;
// the test will pass if optionalVar is uncommented
const variables = {
requiredVar: 'x',
// optionalVar: 'y',
};
const result = {
data: {
__typename: 'Query',
entry: {
__typename: 'Entry',
value: 1,
},
},
};
itAsync('triggers new result from updateQuery', (resolve, reject) => {
let latestResult: any = null;
const link = mockSingleLink({
request: {
query,
variables,
},
result,
}).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const obsHandle = client.watchQuery({
query,
variables,
});
const sub = obsHandle.subscribe({
next(queryResult: any) {
// do nothing
latestResult = queryResult;
},
});
return new Promise(resolve => setTimeout(resolve, 5))
.then(() => obsHandle)
.then((watchedQuery: ObservableQuery<any>) => {
expect(latestResult.data.entry.value).toBe(1);
watchedQuery.updateQuery((prevResult: any) => {
const res = cloneDeep(prevResult);
res.entry.value = 2;
return res;
});
})
.then(() => expect(latestResult.data.entry.value).toBe(2))
.then(() => sub.unsubscribe())
.then(resolve, reject);
});
});
// TODO: Delete this test after removal of updateQuery from fetchMore.
// This test squashes deprecation notice errors when the suite is run, but not
// when individual tests are run.
describe('updateQuery with fetchMore deprecation notice', () => {
const query = gql`
query thing {
entry
}
`;
const result = {
data: {
__typename: 'Query',
entry: 1,
},
};
const result1 = cloneDeep(result);
itAsync('fetchMore warns exactly once', (resolve, reject) => {
const spy = jest.spyOn(console, "warn").mockImplementation();
const link = mockSingleLink({
request: { query },
result,
}, {
request: { query },
result: result1,
}).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const observable = client.watchQuery({query});
return observable.fetchMore({updateQuery: (prev) => prev}).then(() => {
expect(spy).toHaveBeenCalledTimes(1);
}).then(() => {
return observable.fetchMore({updateQuery: (prev) => prev});
}).then(() => {
expect(spy).toHaveBeenCalledTimes(1);
}).finally(() => {
spy.mockRestore();
}).then(resolve, reject);
});
});
describe('fetchMore on an observable query', () => {
const query = gql`
query Comment($repoName: String!, $start: Int!, $limit: Int!) {
entry(repoFullName: $repoName) {
comments(start: $start, limit: $limit) {
text
__typename
}
__typename
}
}
`;
const query2 = gql`
query NewComments($start: Int!, $limit: Int!) {
comments(start: $start, limit: $limit) {
text
__typename
}
__typename
}
`;
const variables = {
repoName: 'org/repo',
start: 0,
limit: 10,
};
const variablesMore = assign({}, variables, { start: 10, limit: 10 });
const variables2 = {
start: 10,
limit: 20,
};
const result: any = {
data: {
__typename: 'Query',
entry: {
__typename: 'Entry',
comments: [],
},
},
};
const resultMore = cloneDeep(result);
const result2: any = {
data: {
__typename: 'Query',
comments: [],
},
};
for (let i = 1; i <= 10; i++) {
result.data.entry.comments.push({
text: `comment ${i}`,
__typename: 'Comment',
});
}
for (let i = 11; i <= 20; i++) {
resultMore.data.entry.comments.push({
text: `comment ${i}`,
__typename: 'Comment',
});
result2.data.comments.push({
text: `new comment ${i}`,
__typename: 'Comment',
});
}
function setup(
reject: (reason: any) => any,
...mockedResponses: any[]
) {
const link = mockSingleLink({
request: {
query,
variables,
},
result,
}, ...mockedResponses).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
entry: {
merge: false,
},
},
},
},
}),
});
return client.watchQuery<any>({
query,
variables,
});
}
function setupWithCacheConfig(
reject: (reason: any) => any,
cacheConfig: InMemoryCacheConfig,
...mockedResponses: any[]
) {
const client = new ApolloClient({
link: mockSingleLink({
request: {
query,
variables,
},
result,
}, ...mockedResponses).setOnError(reject),
cache: new InMemoryCache(cacheConfig),
});
return client.watchQuery<any>({
query,
variables,
});
}
describe('triggers new result with async new variables', () => {
itAsync('updateQuery', (resolve, reject) => {
const observable = setup(reject, {
request: {
query,
variables: variablesMore,
},
result: resultMore,
});
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
// Rely on the fact that the original variables had limit: 10
variables: { start: 10 },
updateQuery: (prev, options) => {
expect(options.variables).toEqual(variablesMore);
const state = cloneDeep(prev) as any;
state.entry.comments = [
...state.entry.comments,
...(options.fetchMoreResult as any).entry.comments,
];
return state;
},
}).then(data => {
// This is the server result
expect(data.data.entry.comments).toHaveLength(10);
expect(data.loading).toBe(false);
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 20; i++) {
expect(comments[i - 1].text).toEqual(`comment ${i}`);
}
}).then(resolve, reject);
});
itAsync('field policy', (resolve, reject) => {
const observable = setupWithCacheConfig(reject, {
typePolicies: {
Entry: {
fields: {
comments: concatPagination(),
},
},
},
}, {
request: { query, variables: variablesMore },
result: resultMore,
});
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
// Rely on the fact that the original variables had limit: 10
variables: { start: 10 },
}).then(data => {
// This is the server result
expect(data.data.entry.comments).toHaveLength(10);
expect(data.loading).toBe(false);
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 20; i++) {
expect(comments[i - 1].text).toEqual(`comment ${i}`);
}
}).then(resolve, reject);
});
});
describe('basic fetchMore results merging', () => {
itAsync('updateQuery', (resolve, reject) => {
const observable = setup(reject, {
request: {
query,
variables: variablesMore,
},
result: resultMore,
});
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
variables: { start: 10 }, // rely on the fact that the original variables had limit: 10
updateQuery: (prev, options) => {
const state = cloneDeep(prev) as any;
state.entry.comments = [
...state.entry.comments,
...(options.fetchMoreResult as any).entry.comments,
];
return state;
},
}).then(data => {
expect(data.data.entry.comments).toHaveLength(10); // this is the server result
expect(data.loading).toBe(false);
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 20; i++) {
expect(comments[i - 1].text).toEqual(`comment ${i}`);
}
}).then(resolve, reject);
});
itAsync('field policy', (resolve, reject) => {
const observable = setupWithCacheConfig(reject, {
typePolicies: {
Entry: {
fields: {
comments: concatPagination(),
},
},
},
}, {
request: {
query,
variables: variablesMore,
},
result: resultMore,
});
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
variables: { start: 10 }, // rely on the fact that the original variables had limit: 10
}).then(data => {
expect(data.data.entry.comments).toHaveLength(10); // this is the server result
expect(data.loading).toBe(false);
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 20; i++) {
expect(comments[i - 1].text).toEqual(`comment ${i}`);
}
}).then(resolve, reject);
});
});
itAsync('fetchMore passes new args to field merge function', (resolve, reject) => {
const mergeArgsHistory: (Record<string, any> | null)[] = [];
const groceriesFieldPolicy = offsetLimitPagination();
const { merge } = groceriesFieldPolicy;
groceriesFieldPolicy.merge = function (existing, incoming, options) {
mergeArgsHistory.push(options.args);
return (merge as FieldMergeFunction<any>).call(
this, existing, incoming, options);
};
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
groceries: groceriesFieldPolicy,
},
},
},
});
const query = gql`
query GroceryList($offset: Int!, $limit: Int!) {
groceries(offset: $offset, limit: $limit) {
id
item
found
}
}
`;
const initialVars = {
offset: 0,
limit: 2,
};
const initialGroceries = [
{
__typename: "GroceryItem",
id: 1,
item: "organic whole milk",
found: false,
},
{
__typename: "GroceryItem",
id: 2,
item: "beer that we both like",
found: false,
},
];
const additionalVars = {
offset: 2,
limit: 3,
};
const additionalGroceries = [
{
__typename: "GroceryItem",
id: 3,
item: "gluten-free pasta",
found: false,
},
{
__typename: "GroceryItem",
id: 4,
item: "goat cheese",
found: false,
},
{
__typename: "GroceryItem",
id: 5,
item: "paper towels",
found: false,
},
];
const finalGroceries = [
...initialGroceries,
...additionalGroceries,
];
const client = new ApolloClient({
cache,
link: mockSingleLink({
request: {
query,
variables: initialVars,
},
result: {
data: {
groceries: initialGroceries,
},
},
}, {
request: {
query,
variables: additionalVars,
},
result: {
data: {
groceries: additionalGroceries,
},
},
}).setOnError(reject),
});
const observable = client.watchQuery({
query,
variables: initialVars,
});
subscribeAndCount(reject, observable, (count, result) => {
if (count === 1) {
expect(result).toEqual({
loading: false,
networkStatus: NetworkStatus.ready,
data: {
groceries: initialGroceries,
},
});
expect(mergeArgsHistory).toEqual([
{ offset: 0, limit: 2 },
]);
observable.fetchMore({
variables: {
offset: 2,
limit: 3,
},
}).then(result => {
expect(result).toEqual({
loading: false,
networkStatus: NetworkStatus.ready,
data: {
groceries: additionalGroceries,
},
});
expect(observable.options.fetchPolicy).toBeUndefined();
});
} else if (count === 2) {
// This result comes entirely from the cache, without updating the
// original variables for the ObservableQuery, because the
// offsetLimitPagination field policy has keyArgs:false.
expect(result).toEqual({
loading: false,
networkStatus: NetworkStatus.ready,
data: {
groceries: finalGroceries,
},
});
expect(mergeArgsHistory).toEqual([
{ offset: 0, limit: 2 },
{ offset: 2, limit: 3 },
]);
resolve();
}
});
});
itAsync('fetching more with a different query', (resolve, reject) => {
const observable = setup(reject, {
request: {
query: query2,
variables: variables2,
},
result: result2,
});
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
query: query2,
variables: variables2,
updateQuery: (prev, options) => {
const state = cloneDeep(prev) as any;
state.entry.comments = [
...state.entry.comments,
...(options.fetchMoreResult as any).comments,
];
return state;
},
}).then(() => {
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 10; i++) {
expect(comments[i - 1].text).toEqual(`comment ${i}`);
}
for (let i = 11; i <= 20; i++) {
expect(comments[i - 1].text).toEqual(`new comment ${i}`);
}
}).then(resolve, reject);
});
describe('will not get an error from `fetchMore` if thrown', () => {
itAsync('updateQuery', (resolve, reject) => {
const fetchMoreError = new Error('Uh, oh!');
const link = mockSingleLink({
request: { query, variables },
result,
delay: 5,
}, {
request: { query, variables: variablesMore },
error: fetchMoreError,
delay: 5,
});
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const observable = client.watchQuery({
query,
variables,
notifyOnNetworkStatusChange: true,
});
let count = 0;
observable.subscribe({
next: ({ data, networkStatus }) => {
switch (++count) {
case 1:
expect(networkStatus).toBe(NetworkStatus.ready);
expect((data as any).entry.comments.length).toBe(10);
observable.fetchMore({
variables: { start: 10 },
updateQuery: prev => {
reject(new Error("should not have called updateQuery"));
return prev;
},
}).catch(e => {
expect(e.networkError).toBe(fetchMoreError);
resolve();
});
break;
}
},
error: () => {
reject(new Error('`error` called when it wasn’t supposed to be.'));
},
complete: () => {
reject(
new Error('`complete` called when it wasn’t supposed to be.'),
);
},
});
});
itAsync('field policy', (resolve, reject) => {
const fetchMoreError = new Error('Uh, oh!');
const link = mockSingleLink({
request: { query, variables },
result,
delay: 5,
}, {
request: { query, variables: variablesMore },
error: fetchMoreError,
delay: 5,
});
let calledFetchMore = false;
const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Entry: {
fields: {
comments: {
keyArgs: false,
merge(_, incoming) {
if (calledFetchMore) {
reject(new Error("should not have called merge"));
}
return incoming;
},
},
},
},
},
}),
});
const observable = client.watchQuery({
query,
variables,
notifyOnNetworkStatusChange: true,
});
let count = 0;
observable.subscribe({
next: ({ data, networkStatus }) => {
switch (++count) {
case 1:
expect(networkStatus).toBe(NetworkStatus.ready);
expect((data as any).entry.comments.length).toBe(10);
calledFetchMore = true;
observable.fetchMore({
variables: { start: 10 },
}).catch(e => {
expect(e.networkError).toBe(fetchMoreError);
resolve();
});
break;
}
},
error: () => {
reject(new Error('`error` called when it wasn’t supposed to be.'));
},
complete: () => {
reject(
new Error('`complete` called when it wasn’t supposed to be.'),
);
},
});
});
});
itAsync('will not leak fetchMore query', (resolve, reject) => {
const observable = setup(reject, {
request: {
query,
variables: variablesMore,
},
result: resultMore,
})
function count(): number {
return (observable as any).queryManager.queries.size;
}
const beforeQueryCount = count();
observable.fetchMore({
variables: { start: 10 }, // rely on the fact that the original variables had limit: 10
}).then(() => {
expect(count()).toBe(beforeQueryCount);
}).then(resolve, reject);
});
});
describe('fetchMore on an observable query with connection', () => {
const query = gql`
query Comment($repoName: String!, $start: Int!, $limit: Int!) {
entry(repoFullName: $repoName, start: $start, limit: $limit)
@connection(key: "repoName") {
comments {
text
}
}
}
`;
const transformedQuery = gql`
query Comment($repoName: String!, $start: Int!, $limit: Int!) {
entry(repoFullName: $repoName, start: $start, limit: $limit) {
comments {
text
__typename
}
__typename
}
}
`;
const variables = {
repoName: 'org/repo',
start: 0,
limit: 10,
};
const variablesMore = assign({}, variables, { start: 10, limit: 10 });
const result: any = {
data: {
__typename: 'Query',
entry: {
__typename: 'Entry',
comments: [],
},
},
};
const resultMore = cloneDeep(result);
for (let i = 1; i <= 10; i++) {
result.data.entry.comments.push({
text: `comment ${i}`,
__typename: 'Comment',
});
}
for (let i = 11; i <= 20; i++) {
resultMore.data.entry.comments.push({
text: `comment ${i}`,
__typename: 'Comment',
});
}
function setup(
reject: (reason: any) => any,
...mockedResponses: any[]
) {
const link = mockSingleLink({
request: {
query: transformedQuery,
variables,
},
result,
}, ...mockedResponses).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
entry: {
merge: false,
},
},
},
},
}),
});
return client.watchQuery<any>({
query,
variables,
});
}
function setupWithCacheConfig(
reject: (reason: any) => any,
cacheConfig: InMemoryCacheConfig,
...mockedResponses: any[]
) {
const client = new ApolloClient({
link: mockSingleLink({
request: {
query: transformedQuery,
variables,
},
result,
}, ...mockedResponses).setOnError(reject),
cache: new InMemoryCache(cacheConfig),
});
return client.watchQuery<any>({
query,
variables,
});
}
describe('fetchMore with connection results merging', () => {
itAsync('updateQuery', (resolve, reject) => {
const observable = setup(reject, {
request: {
query: transformedQuery,
variables: variablesMore,
},
result: resultMore,
})
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
variables: { start: 10 }, // rely on the fact that the original variables had limit: 10
updateQuery: (prev, options) => {
const state = cloneDeep(prev) as any;
state.entry.comments = [
...state.entry.comments,
...(options.fetchMoreResult as any).entry.comments,
];
return state;
},
}).then(data => {
expect(data.data.entry.comments).toHaveLength(10); // this is the server result
expect(data.loading).toBe(false);
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 20; i++) {
expect(comments[i - 1].text).toBe(`comment ${i}`);
}
}).then(resolve, reject);
});
itAsync('field policy', (resolve, reject) => {
const observable = setupWithCacheConfig(reject, {
typePolicies: {
Entry: {
fields: {
comments: concatPagination(),
},
},
},
}, {
request: {
query: transformedQuery,
variables: variablesMore,
},
result: resultMore,
})
let latestResult: any;
observable.subscribe({
next(result: any) {
latestResult = result;
},
});
return observable.fetchMore({
variables: { start: 10 }, // rely on the fact that the original variables had limit: 10
}).then(data => {
expect(data.data.entry.comments).toHaveLength(10); // this is the server result
expect(data.loading).toBe(false);
const comments = latestResult.data.entry.comments;
expect(comments).toHaveLength(20);
for (let i = 1; i <= 20; i++) {
expect(comments[i - 1].text).toBe(`comment ${i}`);
}
}).then(resolve, reject);
});
});
describe('will set the network status to `fetchMore`', () => {
itAsync('updateQuery', (resolve, reject) => {
const link = mockSingleLink({
request: { query: transformedQuery, variables },
result,
delay: 5,
}, {
request: { query: transformedQuery, variables: variablesMore },
result: resultMore,
delay: 5,
}).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
const observable = client.watchQuery({
query,
variables,
notifyOnNetworkStatusChange: true,
});
let count = 0;
observable.subscribe({
next: ({ data, networkStatus }) => {
switch (count++) {
case 0:
expect(networkStatus).toBe(NetworkStatus.ready);
expect((data as any).entry.comments.length).toBe(10);
observable.fetchMore({
variables: { start: 10 },
updateQuery: (prev: any, options: any) => {
const state = cloneDeep(prev) as any;
state.entry.comments = [
...state.entry.comments,
...(options.fetchMoreResult as any).entry.comments,
];
return state;
},
});
break;
case 1:
expect(networkStatus).toBe(NetworkStatus.fetchMore);
expect((data as any).entry.comments.length).toBe(10);
break;
case 2:
expect(networkStatus).toBe(NetworkStatus.ready);
expect((data as any).entry.comments.length).toBe(20);
setTimeout(resolve, 10);
break;
default:
reject(new Error('`next` called too many times'));
}
},
error: (error: any) => reject(error),
complete: () => reject(new Error('Should not have completed')),
});
});
itAsync('field policy', (resolve, reject) => {
const link = mockSingleLink({
request: { query: transformedQuery, variables },
result,
delay: 5,
}, {
request: { query: transformedQuery, variables: variablesMore },
result: resultMore,
delay: 5,
}).setOnError(reject);
const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Entry: {
fields: {
comments: concatPagination(),
},
},
},
}),
});
const observable = client.watchQuery({
query,
variables,
notifyOnNetworkStatusChange: true,
});
let count = 0;
observable.subscribe({
next: ({ data, networkStatus }) => {
switch (count++) {
case 0:
expect(networkStatus).toBe(NetworkStatus.ready);
expect((data as any).entry.comments.length).toBe(10);
observable.fetchMore({
variables: { start: 10 },
});
break;
case 1:
expect(networkStatus).toBe(NetworkStatus.fetchMore);
expect((data as any).entry.comments.length).toBe(10);
break;
case 2:
expect(networkStatus).toBe(NetworkStatus.ready);
expect((data as any).entry.comments.length).toBe(20);
setTimeout(resolve, 10);
break;
default:
reject(new Error('`next` called too many times'));
}
},
error: (error: any) => reject(error),
complete: () => reject(new Error('Should not have completed')),
});
});
});
}); | the_stack |
import { CSSObject, ThemedStyledInterface } from 'styled-components'
import warning from 'warning'
import {
factory,
modifiedFactory,
constFactory,
modifiedArgumentedFactory,
} from './lib'
import {
EffectType,
CharcoalAbstractTheme as Theme,
Key,
} from '@charcoal-ui/theme'
import {
objectAssign,
unreachable,
ReadonlyArrayConstructor,
objectKeys,
isPresent,
} from './util'
import { columnSystem } from '@charcoal-ui/foundation'
import {
halfLeading,
applyEffect,
applyEffectToGradient,
dur,
gradient,
GradientDirection,
notDisabledSelector,
disabledSelector,
px,
} from '@charcoal-ui/utils'
export { type Modified, type ModifiedArgumented } from './lib'
const colorProperties = ['bg', 'font'] as const
type ColorProperty = typeof colorProperties[number]
const spacingProperties = ['margin', 'padding'] as const
const spacingDirections = [
'top',
'right',
'bottom',
'left',
'vertical',
'horizontal',
'all',
] as const
type SpacingProperty = typeof spacingProperties[number]
type SpacingDirection = typeof spacingDirections[number]
const fixedProperties = ['width', 'height'] as const
type FixedProperty = typeof fixedProperties[number]
const borderDirections = ['top', 'right', 'bottom', 'left'] as const
type BorderDirection = typeof borderDirections[number]
const outlineType = ['focus'] as const
type OutlineType = typeof outlineType[number]
/**
* `theme(o => [...])` の `o` の部分を構築する
*
* @param theme テーマオブジェクト
* @param isPhantom 型推論のためだけに使う場合にランタイムコストをゼロにするフラグ
*/
function builder<T extends Theme>(
theme: {
// factoryの第二引数に入れ込むものだけ明示的に型変数を展開しておくことで型の具象化を遅延する
color: T['color']
gradientColor: T['gradientColor']
border: T['border']
outline: T['outline']
} & Omit<T, 'color' | 'gradientColor' | 'border' | 'outline'>,
isPhantom = false
) {
if (isPhantom) {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {} as never
}
const colors = objectKeys(theme.color)
const effects = objectKeys(theme.effect)
// 色
const gradientColors = objectKeys(theme.gradientColor)
const colorCss = createColorCss(theme)
const gradientColorCss = createGradientColorCss(theme)
const colorObject = constFactory(
{},
{
bg: objectAssign(
factory({}, colors, (color) =>
modifiedFactory(effects, (modifiers) =>
colorCss('bg', color, modifiers)
)
),
factory(
{},
gradientColors,
(color) => (direction: GradientDirection) =>
modifiedFactory(effects, (modifiers) =>
gradientColorCss(color, modifiers, direction)
)
)
),
font: factory({}, colors, (color) =>
modifiedFactory(effects, (modifiers) =>
colorCss('font', color, modifiers)
)
),
}
)
// タイポグラフィ
const typographyModifiers = [
// TODO
'monospace',
'bold',
'preserveHalfLeading',
] as const
const typographyCss = createTypographyCss(theme)
const typographyObject = factory(
{},
['typography'] as const,
(_) => (size: keyof T['typography']['size']) =>
modifiedFactory(typographyModifiers, (modifiers) =>
typographyCss(size, {
preserveHalfLeading: modifiers.includes('preserveHalfLeading'),
monospace: modifiers.includes('monospace'),
bold: modifiers.includes('bold'),
})
)
)
// スペーシング
const spacingCss = createSpacingCss(theme)
const spacingObject = factory({}, spacingProperties, (spacingProperty) =>
modifiedArgumentedFactory(
spacingDirections,
(modifiers) => spacingCss(spacingProperty, modifiers),
{} as keyof T['spacing'] | 'auto' // 推論のためのメタタイプ
)
)
// 大きさ
const fixedPxCss = createFixedPxCss(theme)
const fixedColumnCss = createFixedColumnCss(theme)
const fixedRelativeCss = createFixedRelativeCss(theme)
const fixedObject = factory({}, fixedProperties, (property) =>
constFactory(
{},
{
px: (size: keyof T['spacing'] | 'auto') => fixedPxCss(property, size),
column: (span: number) => fixedColumnCss(property, span),
auto: fixedRelativeCss(property, 'auto'),
full: fixedRelativeCss(property, '100%'),
}
)
)
// 要素へのエフェクト (etc: 透過)
const elementEffectCss = createElementEffectCss(theme)
const elementEffectObject = modifiedFactory(
objectKeys(theme.elementEffect),
(modifiers) => elementEffectCss(modifiers)
)
// ボーダー
const borderCss = createBorderCss(theme)
const borderObject = constFactory(
{},
{
border: factory({}, objectKeys(theme.border), (variant) =>
modifiedFactory(borderDirections, (modifiers) =>
borderCss(variant, modifiers)
)
),
}
)
// 角丸
const borderRadiusCss = createBorderRadiusCss(theme)
const borderRadiusObject = constFactory(
{},
{
borderRadius: (radius: keyof T['borderRadius']) =>
borderRadiusCss(radius),
}
)
// アウトライン
const outlineCss = createOutlineColorCss(theme)
const outlineObject = constFactory(
{},
{
outline: factory({}, objectKeys(theme.outline), (variant) =>
modifiedFactory(outlineType, (modifiers) =>
outlineCss(variant, modifiers)
)
),
}
)
return objectAssign(
colorObject,
typographyObject,
spacingObject,
fixedObject,
elementEffectObject,
borderObject,
borderRadiusObject,
outlineObject
)
}
function targetProperty(target: ColorProperty) {
return target === 'bg' ? 'background-color' : 'color'
}
function isSupportedEffect(effect: Key): effect is EffectType {
return ['hover', 'press', 'disabled'].includes(effect as string)
}
function onEffectPseudo(effect: EffectType, css: CSSObject) {
return effect === 'hover'
? { '&:hover': { [notDisabledSelector]: css } }
: effect === 'press'
? { '&:active': { [notDisabledSelector]: css } }
: // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
effect === 'disabled'
? { [disabledSelector]: css }
: unreachable(effect)
}
const createColorCss =
<T extends Theme>(theme: T) =>
(
target: ColorProperty,
color: keyof T['color'],
effects: readonly (keyof T['effect'])[] = []
): Internal =>
internal(
() => ({
[targetProperty(target)]: theme.color[color],
...effects.filter(isSupportedEffect).reduce<CSSObject>(
(acc, effect) => ({
...acc,
...onEffectPseudo(effect, {
[targetProperty(target)]: applyEffect(
theme.color[color],
theme.effect[effect] ?? []
),
}),
}),
{}
),
}),
effects.length > 0
? target === 'font'
? {
colorTransition: true,
}
: {
backgroundColorTransition: true,
}
: {}
)
// TODO: deprecate
const TRANSITION_DURATION = 0.2
const createGradientColorCss =
<T extends Theme>(theme: T) =>
(
color: keyof T['gradientColor'],
effects: readonly (keyof T['effect'])[] = [],
direction: GradientDirection
): Internal => {
const toLinearGradient = gradient(direction)
return internal((context) => {
const optimized = !useHalfLeadingCanceller(context)
const duration = dur(TRANSITION_DURATION)
if (optimized && effects.length > 0) {
return {
position: 'relative',
zIndex: 0,
overflow: 'hidden',
...effects.filter(isSupportedEffect).reduce<CSSObject>(
(acc, effect) => ({
...acc,
'&::before': {
zIndex: -1,
...overlayElement,
transition: `${duration} background-color`,
},
'&::after': {
zIndex: -2,
...overlayElement,
...toLinearGradient(theme.gradientColor[color]),
},
...onEffectPseudo(effect, {
'&::before': {
backgroundColor: applyEffect(
null,
theme.effect[effect] ?? []
),
},
}),
}),
{}
),
}
} else {
warning(
effects.length === 0,
// eslint-disable-next-line max-len
`'Transition' will not be applied. You can get around this by specifying 'preserveHalfLeading' or both 'padding' and 'typograpy'.`
)
return {
...toLinearGradient(theme.gradientColor[color]),
...effects.filter(isSupportedEffect).reduce<CSSObject>(
(acc, effect) => ({
...acc,
...onEffectPseudo(effect, {
...toLinearGradient(
applyEffectToGradient(theme.effect[effect] ?? [])(
theme.gradientColor[color]
)
),
}),
}),
{}
),
}
}
})
}
/**
* @see https://developer.mozilla.org/ja/docs/Web/CSS/:focus-visible#selectively_showing_the_focus_indicator
*/
const onFocus = (css: CSSObject) => ({
[notDisabledSelector]: {
'&:focus, &:active': {
outline: 'none',
...css,
},
'&:focus:not(:focus-visible), &:active:not(:focus-visible)': {
outline: 'none',
},
'&:focus-visible': {
outline: 'none',
...css,
},
},
})
const outlineCss = (weight: number, color: string) => ({
boxShadow: `0 0 0 ${px(weight)} ${color}`,
})
const createOutlineColorCss =
<T extends Theme>(theme: T) =>
(
variant: keyof T['outline'],
modifiers: readonly OutlineType[]
): Internal => {
const weight = theme.outline[variant].weight
const color = theme.outline[variant].color
return internal(
() =>
modifiers.includes('focus')
? onFocus(outlineCss(weight, color))
: { '&&': { [notDisabledSelector]: outlineCss(weight, color) } },
{
boxShadowTransition: true,
}
)
}
const overlayElement: CSSObject = {
content: "''",
display: 'block',
position: 'absolute',
width: '100%',
height: '100%',
top: 0,
left: 0,
}
// half-leadingをキャンセルするとき && 垂直方向のpaddingが無い時
// -> before/afterを入れる
const useHalfLeadingCanceller = ({
cancelHalfLeadingPx,
hasVerticalPadding = false,
}: Context) => cancelHalfLeadingPx !== undefined && !hasVerticalPadding
const createTypographyCss =
<T extends Theme>(theme: T) =>
(
size: keyof T['typography']['size'],
options: {
preserveHalfLeading?: boolean
monospace?: boolean
bold?: boolean
} = {}
): Internal => {
const {
preserveHalfLeading = false,
monospace = false,
bold = false,
} = options
const descriptor = theme.typography.size[size]
const margin = -halfLeading(descriptor)
return internal(
(context) => ({
fontSize: px(descriptor.fontSize),
lineHeight: px(descriptor.lineHeight),
...(monospace && {
fontFamily: 'monospace',
}),
...(bold && {
fontWeight: 'bold',
}),
...(useHalfLeadingCanceller(context) && {
// prevent margin collapsing
display: 'flow-root',
// cancel half-leading with negative margin
'&::before': {
...leadingCancel,
marginTop: px(margin),
},
'&::after': {
...leadingCancel,
marginBottom: px(margin),
},
}),
}),
!preserveHalfLeading
? {
cancelHalfLeadingPx: margin,
}
: {}
)
}
const leadingCancel: CSSObject = {
display: 'block',
width: 0,
height: 0,
content: `''`,
}
function spacingProperty(
property: SpacingProperty,
direction: 'top' | 'right' | 'bottom' | 'left'
) {
return `${property}-${direction}`
}
const createSpacingCss =
<T extends Theme>(theme: { spacing: T['spacing'] }) =>
(
property: SpacingProperty,
modifiers: readonly [SpacingDirection, keyof T['spacing'] | 'auto'][]
): Internal => {
const { top, right, bottom, left } = modifiers.reduce(
(acc, [direction, size]) => {
if (direction === 'all') {
acc.top = size
acc.right = size
acc.bottom = size
acc.left = size
} else if (direction === 'vertical') {
acc.top = size
acc.bottom = size
} else if (direction === 'horizontal') {
acc.right = size
acc.left = size
} else {
acc[direction] = size
}
return acc
},
{} as Partial<
Record<'top' | 'right' | 'bottom' | 'left', keyof T['spacing'] | 'auto'>
>
)
const hasVerticalPadding =
property === 'padding' &&
top !== undefined &&
bottom !== undefined &&
top !== 'auto' &&
bottom !== 'auto'
return internal(
({ cancelHalfLeadingPx = 0 }) => ({
...(top !== undefined && {
[spacingProperty(property, 'top')]:
top === 'auto'
? 'auto'
: px(
theme.spacing[top] +
(hasVerticalPadding ? cancelHalfLeadingPx : 0)
),
}),
...(bottom !== undefined && {
[spacingProperty(property, 'bottom')]:
bottom === 'auto'
? 'auto'
: px(
theme.spacing[bottom] +
(hasVerticalPadding ? cancelHalfLeadingPx : 0)
),
}),
...(right !== undefined && {
[spacingProperty(property, 'right')]:
right === 'auto' ? 'auto' : px(theme.spacing[right]),
}),
...(left !== undefined && {
[spacingProperty(property, 'left')]:
left === 'auto' ? 'auto' : px(theme.spacing[left]),
}),
}),
hasVerticalPadding ? { hasVerticalPadding: true } : {}
)
}
const createFixedPxCss =
<T extends Theme>(theme: T) =>
(property: FixedProperty, size: keyof T['spacing'] | 'auto'): Internal =>
internal(() => ({
[property]: size === 'auto' ? 'auto' : px(theme.spacing[size]),
}))
const createFixedRelativeCss =
<T extends Theme>(_theme: T) =>
(property: FixedProperty, amount: '100%' | 'auto'): Internal =>
internal(() => ({
[property]: amount,
}))
const createFixedColumnCss =
<T extends Theme>(theme: T) =>
(property: FixedProperty, span: number): Internal =>
internal(() => ({
[property]: px(
columnSystem(span, theme.grid.unit.column, theme.grid.unit.gutter)
),
}))
const createElementEffectCss =
<T extends Theme, TElementEffect extends T['elementEffect']>(theme: {
elementEffect: TElementEffect
}) =>
(effects: readonly (keyof TElementEffect)[] = []): Internal =>
internal(() =>
effects.filter(isSupportedEffect).reduce<CSSObject>(
(acc, effect) => ({
...acc,
...onEffectPseudo(effect, {
opacity:
!(Array as ReadonlyArrayConstructor).isArray(
theme.elementEffect[effect]
) && theme.elementEffect[effect]?.type === 'opacity'
? theme.elementEffect[effect]?.opacity
: unreachable(),
}),
}),
{}
)
)
function borderProperty(direction: BorderDirection) {
return `border-${direction}`
}
function borderShorthand(color: string) {
return `solid 1px ${color}`
}
const createBorderCss =
<T extends Theme>(theme: T) =>
(
variant: keyof T['border'],
directions: readonly BorderDirection[]
): Internal => {
const all = directions.length === 0
const value = borderShorthand(theme.border[variant].color)
return internal(() => ({
...(all
? { border: value }
: directions.reduce<CSSObject>(
(acc, direction) => ({
...acc,
[borderProperty(direction)]: value,
}),
{}
)),
}))
}
const createBorderRadiusCss =
<T extends Theme>(theme: T) =>
(size: keyof T['borderRadius']): Internal =>
internal(() => ({
borderRadius: px(theme.borderRadius[size]),
}))
interface Context {
cancelHalfLeadingPx?: number
hasVerticalPadding?: boolean
boxShadowTransition?: boolean
colorTransition?: boolean
backgroundColorTransition?: boolean
}
const commonSpec = (_theme: unknown): Internal => {
const duration = dur(TRANSITION_DURATION)
const transition = (property: string[]) => ({
transition: property.map((v) => `${duration} ${v}`).join(', '),
})
return internal(
({
colorTransition = false,
backgroundColorTransition = false,
boxShadowTransition = false,
}) =>
transition(
[
colorTransition ? 'color' : null,
backgroundColorTransition ? 'background-color' : null,
boxShadowTransition ? 'box-shadow' : null,
].filter(isPresent)
)
)
}
const internalSym: unique symbol = Symbol('internal')
function internal(
operation: (context: Context) => CSSObject,
context: Context = {}
): Internal {
return {
[internalSym]: {
operation,
context,
},
}
}
export interface Internal {
[internalSym]: {
operation: (context: Context) => CSSObject
context: Context
}
}
type Blank = null | undefined | false
const nonBlank = <T>(value: T): value is T extends Blank ? never : T =>
isPresent(value) && (value as unknown) !== false
/**
* `theme(o => [...])` の `theme` ユーティリティを構築する
*
* @param _styled styled-componnets の `styled` そのもの (型推論のために用いられる)
*
* @example
*
* import styled from 'styled-components'
* const theme = createTheme(styled)
*
* @example
*
* const theme = createTheme<DefaultTheme>()
*/
function createTheme<T extends Theme>(_styled?: ThemedStyledInterface<T>) {
// `theme(o => [...])` の `o` の部分の型推論のためだけに使う意味のない変数
// Tを型変数のまま渡してcreateThemeが呼ばれるまで型の具象化が行われないようにする
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
const _phantomBuilder = builder<T>({} as any, true)
// ランタイムの `theme(o => [...])` のインターフェースを構築する
return (
// ユーザー定義
spec: (
o: typeof _phantomBuilder
) => Blank | Internal | (Blank | Internal)[]
): ThemeProp<T> =>
({ theme }) => {
// styled-componentsのランタイムから受け取ったthemeオブジェクトをbuilderに食わせて`o`をつくる
// さらに、ユーザー定義にbuilderが構築した`o`を食わせる
// (`o`を一時変数に入れてしまうと型Tの具象化が行われるので関数合成を優先する)
const rawSpecDescriptor = spec(builder(theme))
// ユーザー定義の配列を整形
const specDescriptor = [
...(Array.isArray(rawSpecDescriptor)
? rawSpecDescriptor
: [rawSpecDescriptor]),
commonSpec(theme),
].filter(nonBlank)
// 1パス目
// 全ユーザー定義を舐めて相互に影響し合う定義をチェックし、その結果(コンテキスト)を取得
const context = specDescriptor.reduce<Context>(
(acc, v) => ({ ...acc, ...v[internalSym].context }),
{}
)
// 2パス目
// コンテキストを見ながら最適化されたCSSを構築
return specDescriptor.map((v) => v[internalSym].operation(context))
}
}
export default createTheme
export type ThemeProp<T> = ({ theme }: { theme: T }) => CSSObject | CSSObject[] | the_stack |
export * from '././account';
export * from '././accountType';
export * from '././accounts';
export * from '././accountsPayable';
export * from '././accountsReceivable';
export * from '././action';
export * from '././actions';
export * from '././address';
export * from '././addressForOrganisation';
export * from '././allocation';
export * from '././allocations';
export * from '././attachment';
export * from '././attachments';
export * from '././balanceDetails';
export * from '././balances';
export * from '././bankTransaction';
export * from '././bankTransactions';
export * from '././bankTransfer';
export * from '././bankTransfers';
export * from '././batchPayment';
export * from '././batchPaymentDetails';
export * from '././batchPayments';
export * from '././bill';
export * from '././brandingTheme';
export * from '././brandingThemes';
export * from '././budget';
export * from '././budgetBalance';
export * from '././budgetLine';
export * from '././budgets';
export * from '././cISOrgSetting';
export * from '././cISOrgSettings';
export * from '././cISSetting';
export * from '././cISSettings';
export * from '././contact';
export * from '././contactGroup';
export * from '././contactGroups';
export * from '././contactPerson';
export * from '././contacts';
export * from '././conversionBalances';
export * from '././conversionDate';
export * from '././countryCode';
export * from '././creditNote';
export * from '././creditNotes';
export * from '././currencies';
export * from '././currency';
export * from '././currencyCode';
export * from '././element';
export * from '././employee';
export * from '././employees';
export * from '././expenseClaim';
export * from '././expenseClaims';
export * from '././externalLink';
export * from '././historyRecord';
export * from '././historyRecords';
export * from '././importSummary';
export * from '././importSummaryAccounts';
export * from '././importSummaryObject';
export * from '././importSummaryOrganisation';
export * from '././invoice';
export * from '././invoiceReminder';
export * from '././invoiceReminders';
export * from '././invoices';
export * from '././item';
export * from '././items';
export * from '././journal';
export * from '././journalLine';
export * from '././journals';
export * from '././lineAmountTypes';
export * from '././lineItem';
export * from '././lineItemTracking';
export * from '././linkedTransaction';
export * from '././linkedTransactions';
export * from '././manualJournal';
export * from '././manualJournalLine';
export * from '././manualJournals';
export * from '././modelError';
export * from '././onlineInvoice';
export * from '././onlineInvoices';
export * from '././organisation';
export * from '././organisations';
export * from '././overpayment';
export * from '././overpayments';
export * from '././payment';
export * from '././paymentDelete';
export * from '././paymentService';
export * from '././paymentServices';
export * from '././paymentTerm';
export * from '././paymentTermType';
export * from '././payments';
export * from '././phone';
export * from '././prepayment';
export * from '././prepayments';
export * from '././purchase';
export * from '././purchaseOrder';
export * from '././purchaseOrders';
export * from '././quote';
export * from '././quoteLineAmountTypes';
export * from '././quoteStatusCodes';
export * from '././quotes';
export * from '././receipt';
export * from '././receipts';
export * from '././repeatingInvoice';
export * from '././repeatingInvoices';
export * from '././report';
export * from '././reportAttribute';
export * from '././reportCell';
export * from '././reportFields';
export * from '././reportRow';
export * from '././reportRows';
export * from '././reportWithRow';
export * from '././reportWithRows';
export * from '././reports';
export * from '././requestEmpty';
export * from '././rowType';
export * from '././salesTrackingCategory';
export * from '././schedule';
export * from '././setup';
export * from '././taxComponent';
export * from '././taxRate';
export * from '././taxRates';
export * from '././taxType';
export * from '././tenNinetyNineContact';
export * from '././timeZone';
export * from '././trackingCategories';
export * from '././trackingCategory';
export * from '././trackingOption';
export * from '././trackingOptions';
export * from '././user';
export * from '././users';
export * from '././validationError';
import localVarRequest = require('request');
import { Account } from '././account';
import { AccountType } from '././accountType';
import { Accounts } from '././accounts';
import { AccountsPayable } from '././accountsPayable';
import { AccountsReceivable } from '././accountsReceivable';
import { Action } from '././action';
import { Actions } from '././actions';
import { Address } from '././address';
import { AddressForOrganisation } from '././addressForOrganisation';
import { Allocation } from '././allocation';
import { Allocations } from '././allocations';
import { Attachment } from '././attachment';
import { Attachments } from '././attachments';
import { BalanceDetails } from '././balanceDetails';
import { Balances } from '././balances';
import { BankTransaction } from '././bankTransaction';
import { BankTransactions } from '././bankTransactions';
import { BankTransfer } from '././bankTransfer';
import { BankTransfers } from '././bankTransfers';
import { BatchPayment } from '././batchPayment';
import { BatchPaymentDetails } from '././batchPaymentDetails';
import { BatchPayments } from '././batchPayments';
import { Bill } from '././bill';
import { BrandingTheme } from '././brandingTheme';
import { BrandingThemes } from '././brandingThemes';
import { Budget } from '././budget';
import { BudgetBalance } from '././budgetBalance';
import { BudgetLine } from '././budgetLine';
import { Budgets } from '././budgets';
import { CISOrgSetting } from '././cISOrgSetting';
import { CISOrgSettings } from '././cISOrgSettings';
import { CISSetting } from '././cISSetting';
import { CISSettings } from '././cISSettings';
import { Contact } from '././contact';
import { ContactGroup } from '././contactGroup';
import { ContactGroups } from '././contactGroups';
import { ContactPerson } from '././contactPerson';
import { Contacts } from '././contacts';
import { ConversionBalances } from '././conversionBalances';
import { ConversionDate } from '././conversionDate';
import { CountryCode } from '././countryCode';
import { CreditNote } from '././creditNote';
import { CreditNotes } from '././creditNotes';
import { Currencies } from '././currencies';
import { Currency } from '././currency';
import { CurrencyCode } from '././currencyCode';
import { Element } from '././element';
import { Employee } from '././employee';
import { Employees } from '././employees';
import { ExpenseClaim } from '././expenseClaim';
import { ExpenseClaims } from '././expenseClaims';
import { ExternalLink } from '././externalLink';
import { HistoryRecord } from '././historyRecord';
import { HistoryRecords } from '././historyRecords';
import { ImportSummary } from '././importSummary';
import { ImportSummaryAccounts } from '././importSummaryAccounts';
import { ImportSummaryObject } from '././importSummaryObject';
import { ImportSummaryOrganisation } from '././importSummaryOrganisation';
import { Invoice } from '././invoice';
import { InvoiceReminder } from '././invoiceReminder';
import { InvoiceReminders } from '././invoiceReminders';
import { Invoices } from '././invoices';
import { Item } from '././item';
import { Items } from '././items';
import { Journal } from '././journal';
import { JournalLine } from '././journalLine';
import { Journals } from '././journals';
import { LineAmountTypes } from '././lineAmountTypes';
import { LineItem } from '././lineItem';
import { LineItemTracking } from '././lineItemTracking';
import { LinkedTransaction } from '././linkedTransaction';
import { LinkedTransactions } from '././linkedTransactions';
import { ManualJournal } from '././manualJournal';
import { ManualJournalLine } from '././manualJournalLine';
import { ManualJournals } from '././manualJournals';
import { ModelError } from '././modelError';
import { OnlineInvoice } from '././onlineInvoice';
import { OnlineInvoices } from '././onlineInvoices';
import { Organisation } from '././organisation';
import { Organisations } from '././organisations';
import { Overpayment } from '././overpayment';
import { Overpayments } from '././overpayments';
import { Payment } from '././payment';
import { PaymentDelete } from '././paymentDelete';
import { PaymentService } from '././paymentService';
import { PaymentServices } from '././paymentServices';
import { PaymentTerm } from '././paymentTerm';
import { PaymentTermType } from '././paymentTermType';
import { Payments } from '././payments';
import { Phone } from '././phone';
import { Prepayment } from '././prepayment';
import { Prepayments } from '././prepayments';
import { Purchase } from '././purchase';
import { PurchaseOrder } from '././purchaseOrder';
import { PurchaseOrders } from '././purchaseOrders';
import { Quote } from '././quote';
import { QuoteLineAmountTypes } from '././quoteLineAmountTypes';
import { QuoteStatusCodes } from '././quoteStatusCodes';
import { Quotes } from '././quotes';
import { Receipt } from '././receipt';
import { Receipts } from '././receipts';
import { RepeatingInvoice } from '././repeatingInvoice';
import { RepeatingInvoices } from '././repeatingInvoices';
import { Report } from '././report';
import { ReportAttribute } from '././reportAttribute';
import { ReportCell } from '././reportCell';
import { ReportFields } from '././reportFields';
import { ReportRow } from '././reportRow';
import { ReportRows } from '././reportRows';
import { ReportWithRow } from '././reportWithRow';
import { ReportWithRows } from '././reportWithRows';
import { Reports } from '././reports';
import { RequestEmpty } from '././requestEmpty';
import { RowType } from '././rowType';
import { SalesTrackingCategory } from '././salesTrackingCategory';
import { Schedule } from '././schedule';
import { Setup } from '././setup';
import { TaxComponent } from '././taxComponent';
import { TaxRate } from '././taxRate';
import { TaxRates } from '././taxRates';
import { TaxType } from '././taxType';
import { TenNinetyNineContact } from '././tenNinetyNineContact';
import { TimeZone } from '././timeZone';
import { TrackingCategories } from '././trackingCategories';
import { TrackingCategory } from '././trackingCategory';
import { TrackingOption } from '././trackingOption';
import { TrackingOptions } from '././trackingOptions';
import { User } from '././user';
import { Users } from '././users';
import { ValidationError } from '././validationError';
/* tslint:disable:no-unused-variable */
let primitives = [
"string",
"boolean",
"double",
"integer",
"long",
"float",
"number",
"any"
];
let enumsMap: {[index: string]: any} = {
"Account.StatusEnum": Account.StatusEnum,
"Account.BankAccountTypeEnum": Account.BankAccountTypeEnum,
"Account.ClassEnum": Account.ClassEnum,
"Account.SystemAccountEnum": Account.SystemAccountEnum,
"AccountType": AccountType,
"Action.StatusEnum": Action.StatusEnum,
"Address.AddressTypeEnum": Address.AddressTypeEnum,
"AddressForOrganisation.AddressTypeEnum": AddressForOrganisation.AddressTypeEnum,
"BankTransaction.TypeEnum": BankTransaction.TypeEnum,
"BankTransaction.StatusEnum": BankTransaction.StatusEnum,
"BatchPayment.TypeEnum": BatchPayment.TypeEnum,
"BatchPayment.StatusEnum": BatchPayment.StatusEnum,
"BrandingTheme.TypeEnum": BrandingTheme.TypeEnum,
"Budget.TypeEnum": Budget.TypeEnum,
"Contact.ContactStatusEnum": Contact.ContactStatusEnum,
"ContactGroup.StatusEnum": ContactGroup.StatusEnum,
"CountryCode": CountryCode,
"CreditNote.TypeEnum": CreditNote.TypeEnum,
"CreditNote.StatusEnum": CreditNote.StatusEnum,
"CurrencyCode": CurrencyCode,
"Employee.StatusEnum": Employee.StatusEnum,
"ExpenseClaim.StatusEnum": ExpenseClaim.StatusEnum,
"ExternalLink.LinkTypeEnum": ExternalLink.LinkTypeEnum,
"Invoice.TypeEnum": Invoice.TypeEnum,
"Invoice.StatusEnum": Invoice.StatusEnum,
"Journal.SourceTypeEnum": Journal.SourceTypeEnum,
"LineAmountTypes": LineAmountTypes,
"LinkedTransaction.StatusEnum": LinkedTransaction.StatusEnum,
"LinkedTransaction.TypeEnum": LinkedTransaction.TypeEnum,
"LinkedTransaction.SourceTransactionTypeCodeEnum": LinkedTransaction.SourceTransactionTypeCodeEnum,
"ManualJournal.StatusEnum": ManualJournal.StatusEnum,
"Organisation.VersionEnum": Organisation.VersionEnum,
"Organisation.OrganisationTypeEnum": Organisation.OrganisationTypeEnum,
"Organisation.SalesTaxBasisEnum": Organisation.SalesTaxBasisEnum,
"Organisation.SalesTaxPeriodEnum": Organisation.SalesTaxPeriodEnum,
"Organisation.OrganisationEntityTypeEnum": Organisation.OrganisationEntityTypeEnum,
"Organisation.ClassEnum": Organisation.ClassEnum,
"Organisation.EditionEnum": Organisation.EditionEnum,
"Overpayment.TypeEnum": Overpayment.TypeEnum,
"Overpayment.StatusEnum": Overpayment.StatusEnum,
"Payment.StatusEnum": Payment.StatusEnum,
"Payment.PaymentTypeEnum": Payment.PaymentTypeEnum,
"PaymentTermType": PaymentTermType,
"Phone.PhoneTypeEnum": Phone.PhoneTypeEnum,
"Prepayment.TypeEnum": Prepayment.TypeEnum,
"Prepayment.StatusEnum": Prepayment.StatusEnum,
"PurchaseOrder.StatusEnum": PurchaseOrder.StatusEnum,
"QuoteLineAmountTypes": QuoteLineAmountTypes,
"QuoteStatusCodes": QuoteStatusCodes,
"Receipt.StatusEnum": Receipt.StatusEnum,
"RepeatingInvoice.TypeEnum": RepeatingInvoice.TypeEnum,
"RepeatingInvoice.StatusEnum": RepeatingInvoice.StatusEnum,
"Report.ReportTypeEnum": Report.ReportTypeEnum,
"RowType": RowType,
"Schedule.UnitEnum": Schedule.UnitEnum,
"Schedule.DueDateTypeEnum": Schedule.DueDateTypeEnum,
"TaxRate.StatusEnum": TaxRate.StatusEnum,
"TaxRate.ReportTaxTypeEnum": TaxRate.ReportTaxTypeEnum,
"TaxType": TaxType,
"TimeZone": TimeZone,
"TrackingCategory.StatusEnum": TrackingCategory.StatusEnum,
"TrackingOption.StatusEnum": TrackingOption.StatusEnum,
"User.OrganisationRoleEnum": User.OrganisationRoleEnum,
}
let typeMap: {[index: string]: any} = {
"Account": Account,
"Accounts": Accounts,
"AccountsPayable": AccountsPayable,
"AccountsReceivable": AccountsReceivable,
"Action": Action,
"Actions": Actions,
"Address": Address,
"AddressForOrganisation": AddressForOrganisation,
"Allocation": Allocation,
"Allocations": Allocations,
"Attachment": Attachment,
"Attachments": Attachments,
"BalanceDetails": BalanceDetails,
"Balances": Balances,
"BankTransaction": BankTransaction,
"BankTransactions": BankTransactions,
"BankTransfer": BankTransfer,
"BankTransfers": BankTransfers,
"BatchPayment": BatchPayment,
"BatchPaymentDetails": BatchPaymentDetails,
"BatchPayments": BatchPayments,
"Bill": Bill,
"BrandingTheme": BrandingTheme,
"BrandingThemes": BrandingThemes,
"Budget": Budget,
"BudgetBalance": BudgetBalance,
"BudgetLine": BudgetLine,
"Budgets": Budgets,
"CISOrgSetting": CISOrgSetting,
"CISOrgSettings": CISOrgSettings,
"CISSetting": CISSetting,
"CISSettings": CISSettings,
"Contact": Contact,
"ContactGroup": ContactGroup,
"ContactGroups": ContactGroups,
"ContactPerson": ContactPerson,
"Contacts": Contacts,
"ConversionBalances": ConversionBalances,
"ConversionDate": ConversionDate,
"CreditNote": CreditNote,
"CreditNotes": CreditNotes,
"Currencies": Currencies,
"Currency": Currency,
"Element": Element,
"Employee": Employee,
"Employees": Employees,
"ExpenseClaim": ExpenseClaim,
"ExpenseClaims": ExpenseClaims,
"ExternalLink": ExternalLink,
"HistoryRecord": HistoryRecord,
"HistoryRecords": HistoryRecords,
"ImportSummary": ImportSummary,
"ImportSummaryAccounts": ImportSummaryAccounts,
"ImportSummaryObject": ImportSummaryObject,
"ImportSummaryOrganisation": ImportSummaryOrganisation,
"Invoice": Invoice,
"InvoiceReminder": InvoiceReminder,
"InvoiceReminders": InvoiceReminders,
"Invoices": Invoices,
"Item": Item,
"Items": Items,
"Journal": Journal,
"JournalLine": JournalLine,
"Journals": Journals,
"LineItem": LineItem,
"LineItemTracking": LineItemTracking,
"LinkedTransaction": LinkedTransaction,
"LinkedTransactions": LinkedTransactions,
"ManualJournal": ManualJournal,
"ManualJournalLine": ManualJournalLine,
"ManualJournals": ManualJournals,
"ModelError": ModelError,
"OnlineInvoice": OnlineInvoice,
"OnlineInvoices": OnlineInvoices,
"Organisation": Organisation,
"Organisations": Organisations,
"Overpayment": Overpayment,
"Overpayments": Overpayments,
"Payment": Payment,
"PaymentDelete": PaymentDelete,
"PaymentService": PaymentService,
"PaymentServices": PaymentServices,
"PaymentTerm": PaymentTerm,
"Payments": Payments,
"Phone": Phone,
"Prepayment": Prepayment,
"Prepayments": Prepayments,
"Purchase": Purchase,
"PurchaseOrder": PurchaseOrder,
"PurchaseOrders": PurchaseOrders,
"Quote": Quote,
"Quotes": Quotes,
"Receipt": Receipt,
"Receipts": Receipts,
"RepeatingInvoice": RepeatingInvoice,
"RepeatingInvoices": RepeatingInvoices,
"Report": Report,
"ReportAttribute": ReportAttribute,
"ReportCell": ReportCell,
"ReportFields": ReportFields,
"ReportRow": ReportRow,
"ReportRows": ReportRows,
"ReportWithRow": ReportWithRow,
"ReportWithRows": ReportWithRows,
"Reports": Reports,
"RequestEmpty": RequestEmpty,
"SalesTrackingCategory": SalesTrackingCategory,
"Schedule": Schedule,
"Setup": Setup,
"TaxComponent": TaxComponent,
"TaxRate": TaxRate,
"TaxRates": TaxRates,
"TenNinetyNineContact": TenNinetyNineContact,
"TrackingCategories": TrackingCategories,
"TrackingCategory": TrackingCategory,
"TrackingOption": TrackingOption,
"TrackingOptions": TrackingOptions,
"User": User,
"Users": Users,
"ValidationError": ValidationError,
}
export class ObjectSerializer {
public static findCorrectType(data: any, expectedType: string) {
if (data == undefined) {
return expectedType;
} else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) {
return expectedType;
} else if (expectedType === "Date") {
return expectedType;
} else {
if (enumsMap[expectedType]) {
return expectedType;
}
if (!typeMap[expectedType]) {
return expectedType; // w/e we don't know the type
}
// Check the discriminator
let discriminatorProperty = typeMap[expectedType].discriminator;
if (discriminatorProperty == null) {
return expectedType; // the type does not have a discriminator. use it.
} else {
if (data[discriminatorProperty]) {
var discriminatorType = data[discriminatorProperty];
if(typeMap[discriminatorType]){
return discriminatorType; // use the type given in the discriminator
} else {
return expectedType; // discriminator did not map to a type
}
} else {
return expectedType; // discriminator was not present (or an empty string)
}
}
}
}
public static serialize(data: any, type: string) {
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
return data;
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
for (let index in data) {
let date = data[index];
transformedData.push(ObjectSerializer.serialize(date, subType));
}
if(subType === 'string') {
return transformedData.join(',')
} else {
return transformedData
}
} else if (type === "Date") {
return data.toISOString();
} else {
if (enumsMap[type]) {
return data;
}
if (!typeMap[type]) { // in case we dont know the type
return data;
}
// Get the actual type of this object
type = this.findCorrectType(data, type);
// get the map for the correct type.
let attributeTypes = typeMap[type].getAttributeTypeMap();
let instance: {[index: string]: any} = {};
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type);
}
return instance;
}
}
public static deserializeDateFormats(type: string, data: any) {
const isDate = new Date(data)
if (isNaN(isDate.getTime())) {
const re = /-?\d+/;
const m = re.exec(data);
return new Date(parseInt(m[0], 10));
} else {
return isDate
}
}
public static deserialize(data: any, type: string) {
// polymorphism may change the actual type.
type = ObjectSerializer.findCorrectType(data, type);
if (data == undefined) {
return data;
} else if (primitives.indexOf(type.toLowerCase()) !== -1) {
if (type === "string" && data.toString().substring(0, 6) === "/Date(") {
return this.deserializeDateFormats(type, data) // For MS dates that are of type 'string'
}
else {
return data;
}
} else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6
let subType: string = type.replace("Array<", ""); // Array<Type> => Type>
subType = subType.substring(0, subType.length - 1); // Type> => Type
let transformedData: any[] = [];
// Asset API returns string even for Array<Model>
const dataFormatted = typeof data == 'string' ? JSON.parse(data) : data
for (let index in dataFormatted) {
let currentData = dataFormatted[index];
transformedData.push(ObjectSerializer.deserialize(currentData, subType));
}
return transformedData;
} else if (type === "Date") {
return this.deserializeDateFormats(type, data)
} else {
if (enumsMap[type]) {// is Enum
return data;
}
if (!typeMap[type]) { // dont know the type
return data;
}
let instance = new typeMap[type]();
let attributeTypes = typeMap[type].getAttributeTypeMap();
for (let index in attributeTypes) {
let attributeType = attributeTypes[index];
instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type);
}
return instance;
}
}
}
export interface Authentication {
/**
* Apply authentication settings to header and query params.
*/
applyToRequest(requestOptions: localVarRequest.Options): Promise<void> | void;
}
export class HttpBasicAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
requestOptions.auth = {
username: this.username, password: this.password
}
}
}
export class ApiKeyAuth implements Authentication {
public apiKey: string = '';
constructor(private location: string, private paramName: string) {
}
applyToRequest(requestOptions: localVarRequest.Options): void {
if (this.location == "query") {
(<any>requestOptions.qs)[this.paramName] = this.apiKey;
} else if (this.location == "header" && requestOptions && requestOptions.headers) {
requestOptions.headers[this.paramName] = this.apiKey;
}
}
}
export class OAuth implements Authentication {
public accessToken: string = '';
applyToRequest(requestOptions: localVarRequest.Options): void {
if (requestOptions && requestOptions.headers) {
requestOptions.headers["Authorization"] = "Bearer " + this.accessToken;
}
}
}
export class VoidAuth implements Authentication {
public username: string = '';
public password: string = '';
applyToRequest(_: localVarRequest.Options): void {
// Do nothing
}
} | the_stack |
import { BuilderElement } from "@builder.io/sdk";
import {
Button,
CircularProgress,
createMuiTheme,
CssBaseline,
Divider,
FormControlLabel,
IconButton,
MuiThemeProvider,
Switch,
TextField,
Tooltip,
Typography,
Select,
MenuItem,
withStyles,
} from "@material-ui/core";
import green from "@material-ui/core/colors/green";
import { HelpOutline } from "@material-ui/icons";
import Favorite from "@material-ui/icons/Favorite";
import LaptopMac from "@material-ui/icons/LaptopMac";
import PhoneIphone from "@material-ui/icons/PhoneIphone";
import TabletMac from "@material-ui/icons/TabletMac";
import * as fileType from "file-type";
import { action, computed, observable, when } from "mobx";
import { observer } from "mobx-react";
import * as pako from "pako";
import * as React from "react";
import * as ReactDOM from "react-dom";
import * as md5 from "spark-md5";
import * as traverse from "traverse";
import { arrayBufferToBase64 } from "../lib/functions/buffer-to-base64";
import { SafeComponent } from "./classes/safe-component";
import { settings } from "./constants/settings";
import { theme as themeVars } from "./constants/theme";
import { fastClone } from "./functions/fast-clone";
import { traverseLayers } from "./functions/traverse-layers";
import "./ui.css";
import { IntlProvider, FormattedMessage } from "react-intl";
import { en, ru } from "./localize/i18n";
// Simple debug flag - flip when needed locally
const useDev = false;
const apiHost = useDev ? "http://localhost:5000" : "https://builder.io";
const selectionToBuilder = async (
selection: SceneNode[]
): Promise<BuilderElement[]> => {
const useGzip = true;
selection = fastClone(selection);
traverse(selection).forEach(function (item) {
if (this.key === "intArr") {
this.delete();
}
});
const res = await fetch(`${apiHost}/api/v1/figma-to-builder`, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(
useGzip
? {
compressedNodes: pako.deflate(JSON.stringify(selection), {
to: "string",
}),
}
: {
nodes: selection,
}
),
}).then((res) => {
if (!res.ok) {
console.error("Figma-to-builder request failed", res);
throw new Error("Figma-to-builder request failed");
}
return res.json();
});
return res.blocks;
};
interface ClientStorage {
imageUrlsByHash: { [hash: string]: string | null } | undefined;
}
const apiKey = process.env.API_KEY || null;
const apiRoot =
process.env.API_ROOT && process.env.NODE_ENV !== "production"
? process.env.API_ROOT
: "https://builder.io";
const WIDTH_LS_KEY = "builder.widthSetting";
const FRAMES_LS_KEY = "builder.useFramesSetting";
// TODO: make async and use figma.clientStorage
function lsGet(key: string) {
try {
return JSON.parse(localStorage.getItem(key)!);
} catch (err) {
return undefined;
}
}
function lsSet(key: string, value: any) {
try {
return localStorage.setItem(key, JSON.stringify(value));
} catch (err) {
return undefined;
}
}
const clamp = (num: number, min: number, max: number) =>
Math.max(min, Math.min(max, num));
type Node = TextNode | RectangleNode;
const theme = createMuiTheme({
typography: themeVars.typography,
palette: {
primary: { main: themeVars.colors.primary },
secondary: green,
},
});
const StyledButton = withStyles({
root: {
fontSize: "12px",
padding: "8px",
height: "30px",
minHeight: "unset",
display: "flex",
justifyContent: "center",
},
})(MenuItem);
const BASE64_MARKER = ";base64,";
function convertDataURIToBinary(dataURI: string) {
const base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
const base64 = dataURI.substring(base64Index);
const raw = window.atob(base64);
const rawLength = raw.length;
const array = new Uint8Array(new ArrayBuffer(rawLength));
for (let i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
function getImageFills(layer: Node) {
const images =
Array.isArray(layer.fills) &&
layer.fills.filter((item) => item.type === "IMAGE");
return images;
}
// TODO: CACHE!
// const imageCache: { [key: string]: Uint8Array | undefined } = {};
async function processImages(layer: Node) {
const images = getImageFills(layer);
const convertToSvg = (value: string) => {
(layer as any).type = "SVG";
(layer as any).svg = value;
if (typeof layer.fills !== "symbol") {
layer.fills = layer.fills.filter((item) => item.type !== "IMAGE");
}
};
return images
? Promise.all(
images.map(async (image: any) => {
try {
if (image) {
const url = image.url;
if (url.startsWith("data:")) {
const type = url.split(/[:,;]/)[1];
if (type.includes("svg")) {
const svgValue = decodeURIComponent(url.split(",")[1]);
convertToSvg(svgValue);
return Promise.resolve();
} else {
if (url.includes(BASE64_MARKER)) {
image.intArr = convertDataURIToBinary(url);
delete image.url;
} else {
console.info(
"Found data url that could not be converted",
url
);
}
return;
}
}
const isSvg = url.endsWith(".svg");
// Proxy returned content through Builder so we can access cross origin for
// pulling in photos, etc
const res = await fetch(
"https://builder.io/api/v1/proxy-api?url=" +
encodeURIComponent(url)
);
const contentType = res.headers.get("content-type");
if (isSvg || (contentType && contentType.includes("svg"))) {
const text = await res.text();
convertToSvg(text);
} else {
const arrayBuffer = await res.arrayBuffer();
const type = fileType(arrayBuffer);
if (
type &&
(type.ext.includes("svg") || type.mime.includes("svg"))
) {
convertToSvg(await res.text());
return;
} else {
const intArr = new Uint8Array(arrayBuffer);
delete image.url;
image.intArr = intArr;
}
}
}
} catch (err) {
console.warn("Could not fetch image", layer, err);
}
})
)
: Promise.resolve([]);
}
export type Component = "row" | "stack" | "absolute";
export type SizeType = "shrink" | "expand" | "fixed";
export const sizeTypes: SizeType[] = ["expand", "shrink", "fixed"];
const invalidOptionString = "...";
type InvalidComponentOption = typeof invalidOptionString;
@observer
class App extends SafeComponent {
editorRef: HTMLIFrameElement | null = null;
@observable loading = false;
// TODO: lsget/set?
@observable lipsum = false; // process.env.NODE_ENV !== "production";
@observable loadingGenerate = false;
@observable apiRoot = apiRoot;
@observable clientStorage: ClientStorage | null = null;
@observable errorMessage = "";
@observable generatingCode = false;
@observable urlValue = "https://www.builder.io";
@observable width = lsGet(WIDTH_LS_KEY) || "1200";
@observable online = navigator.onLine;
@observable useFrames = lsGet(FRAMES_LS_KEY) || false;
@observable showMoreOptions = true; // lsGet(MORE_OPTIONS_LS_KEY) || false;
@observable selection: (BaseNode & { data?: { [key: string]: any } })[] = [];
@observable.ref selectionWithImages:
| (BaseNode & {
data?: { [key: string]: any };
})[]
| null = null;
@observable commandKeyDown = false;
@observable shiftKeyDown = false;
@observable altKeyDown = false;
@observable ctrlKeyDown = false;
@observable showRequestFailedError = false;
@observable showImportInvalidError = false;
@observable isValidImport: null | boolean = null;
@observable.ref previewData: any;
@observable displayFiddleUrl = "";
@observable currentLanguage = "en";
editorScriptAdded = false;
dataToPost: any;
async getImageUrl(
intArr: Uint8Array,
imageHash?: string
): Promise<string | null> {
let hash = imageHash;
if (!hash) {
hash = md5.ArrayBuffer.hash(intArr);
}
const fromCache =
hash &&
this.clientStorage &&
this.clientStorage.imageUrlsByHash &&
this.clientStorage.imageUrlsByHash[hash];
if (fromCache) {
console.debug("Used URL from cache", fromCache);
return fromCache;
}
if (!apiKey) {
console.warn("Tried to upload image without API key");
return null;
}
return fetch(`${apiRoot}/api/v1/upload?apiKey=${apiKey}`, {
method: "POST",
body: JSON.stringify({
image: arrayBufferToBase64(intArr),
}),
headers: {
"content-type": "application/json",
},
})
.then((res) => res.json())
.then((data) => {
const { url } = data;
if (typeof url !== "string") {
return null;
}
if (this.clientStorage && hash) {
if (!this.clientStorage.imageUrlsByHash) {
this.clientStorage.imageUrlsByHash = {};
}
this.clientStorage.imageUrlsByHash[hash] = url;
}
return url;
});
}
getDataForSelection(name: string, multipleValuesResponse = null) {
if (!this.selection.length) {
return multipleValuesResponse;
}
const firstNode = this.selection[0];
let value = firstNode.data && firstNode.data[name];
for (const item of this.selection.slice(1)) {
const itemValue = item.data && item.data[name];
if (itemValue !== value) {
return multipleValuesResponse;
}
}
return value;
}
async updateStorage() {
await when(() => !!this.clientStorage);
parent.postMessage(
{
pluginMessage: {
type: "setStorage",
data: fastClone(this.clientStorage),
},
},
"*"
);
}
setDataForSelection(name: string, value: any) {
for (const node of this.selection) {
if (!node.data) {
node.data = {
[name]: value,
};
} else {
node.data[name] = value;
}
}
// TODO: throttleNextTick
this.saveUpdates();
}
form: HTMLFormElement | null = null;
urlInputRef: HTMLInputElement | null = null;
iframeRef: HTMLIFrameElement | null = null;
@computed get urlValid() {
function validURL(str: string) {
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // fragment locator
return !!pattern.test(str);
}
return validURL(this.urlValue);
}
@action
updateKeyPositions(event: KeyboardEvent) {
this.commandKeyDown = event.metaKey;
this.altKeyDown = event.altKey;
this.shiftKeyDown = event.shiftKey;
this.ctrlKeyDown = event.ctrlKey;
}
@action
async getCode(useFiddle = false) {
this.displayFiddleUrl = "";
this.showImportInvalidError = false;
this.showRequestFailedError = false;
if (!this.lipsum) {
this.selectionWithImages = null;
parent.postMessage(
{
pluginMessage: {
type: "getSelectionWithImages",
},
},
"*"
);
this.generatingCode = true;
await when(() => !!this.selectionWithImages);
} else {
this.selectionWithImages = this.selection;
}
if (!(this.selectionWithImages && this.selectionWithImages[0])) {
console.warn("No selection with images");
return;
}
// TODO: analyze if page is properly nested and annotated, if not
// suggest in the UI what needs grouping
const selectionToBuilderPromise = selectionToBuilder(
this.selectionWithImages as any
).catch((err) => {
this.loadingGenerate = false;
this.generatingCode = false;
this.showRequestFailedError = true;
throw err;
});
const imagesPromises: Promise<any>[] = [];
const imageMap: { [key: string]: string } = {};
for (const layer of this.selectionWithImages as SceneNode[]) {
traverseLayers(layer, (node) => {
const imageFills = getImageFills(node as Node);
const image = imageFills && imageFills[0];
if ((image as any)?.intArr) {
imagesPromises.push(
(async () => {
const { id } = await fetch(`${apiHost}/api/v1/stage-image`, {
method: "POST",
body: JSON.stringify({
image: arrayBufferToBase64((image as any).intArr),
}),
headers: {
"content-type": "application/json",
},
}).then((res) => {
if (!res.ok) {
console.error("Image upload failed", res);
throw new Error("Image upload failed");
}
return res.json();
});
delete (node as any).intArr;
imageMap[node.id] = id;
})()
);
}
});
}
const blocks = await selectionToBuilderPromise;
await Promise.all(imagesPromises).catch((err) => {
this.loadingGenerate = false;
this.generatingCode = false;
this.showRequestFailedError = true;
throw err;
});
traverse(blocks).forEach((item) => {
if (item?.["@type"] === "@builder.io/sdk:Element") {
const image = imageMap[item.meta?.figmaLayerId];
if (image) {
const url = `https://cdn.builder.io/api/v1/image/assets%2FTEMP%2F${image}`;
if (item.component?.options) {
item.component.options.image = url;
} else if (item.responsiveStyles?.large?.backgroundImage) {
item.responsiveStyles.large.backgroundImage = `url("${url}")`;
}
}
}
});
const data = {
data: {
blocks: blocks,
},
};
this.isValidImport = null;
parent.postMessage(
{
pluginMessage: {
type: "checkIfCanGetCode",
},
},
"*"
);
this.generatingCode = true;
await when(() => typeof this.isValidImport === "boolean");
if (!this.isValidImport) {
this.generatingCode = false;
this.isValidImport = null;
this.showImportInvalidError = true;
return;
}
this.isValidImport = null;
const json = JSON.stringify(data);
if (useFiddle) {
const res = await fetch(apiHost + "/api/v1/fiddle", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: json,
})
.then((res) => {
if (!res.ok) {
console.error("Failed to create fiddle", res);
throw new Error("Failed to create fiddle");
}
return res.json();
})
.catch((err) => {
this.generatingCode = false;
this.selectionWithImages = null;
this.showRequestFailedError = true;
throw err;
});
if (res.url) {
open(res.url, "_blank");
this.displayFiddleUrl = res.url;
}
this.generatingCode = false;
this.selectionWithImages = null;
} else {
const blob = new Blob([json], {
type: "application/json",
});
const link = document.createElement("a");
link.setAttribute("href", URL.createObjectURL(blob));
link.setAttribute("download", "page.builder.json");
document.body.appendChild(link); // Required for FF
link.click();
document.body.removeChild(link);
this.generatingCode = false;
this.selectionWithImages = null;
}
}
@observable initialized = false;
componentDidMount() {
window.addEventListener("message", (e) => {
const { data: rawData, source } = e as MessageEvent;
this.initialized = true;
const data = rawData.pluginMessage;
if (!data) {
return;
}
if (data.type === "selectionChange") {
this.selection = data.elements;
}
if (data.type === "selectionWithImages") {
this.selectionWithImages = data.elements;
}
if (data.type === "canGetCode") {
this.isValidImport = data.value;
}
if (data.type === "doneLoading") {
this.loading = false;
}
if (data.type === "storage") {
this.clientStorage = data.data || {};
}
});
parent.postMessage(
{
pluginMessage: {
type: "getStorage",
},
},
"*"
);
parent.postMessage(
{
pluginMessage: {
type: "init",
},
},
"*"
);
// TODO: destroy on component unmount
this.safeReaction(
() => this.urlValue,
() => (this.errorMessage = "")
);
this.selectAllUrlInputText();
this.safeListenToEvent(window, "offline", () => (this.online = false));
this.safeListenToEvent(window, "keydown", (e) => {
this.updateKeyPositions(e as KeyboardEvent);
});
this.safeListenToEvent(window, "keyup", (e) => {
this.updateKeyPositions(e as KeyboardEvent);
});
this.safeListenToEvent(window, "online", () => (this.online = true));
this.safeReaction(
() => this.clientStorage && fastClone(this.clientStorage),
() => {
if (this.clientStorage) {
this.updateStorage();
}
}
);
}
saveUpdates = () => {
if (this.selection.length) {
parent.postMessage(
{
pluginMessage: {
type: "updateElements",
elements: fastClone(this.selection),
},
},
"*"
);
}
};
onCreate = () => {
if (this.loading) {
return;
}
if (!this.validate()) {
if (!this.urlValid) {
this.errorMessage = "Please enter a valid URL";
return;
}
}
this.loading = true;
if (this.urlValue) {
const width = clamp(parseInt(this.width) || 1200, 200, 3000);
const widthString = String(width);
this.width = widthString;
lsSet(WIDTH_LS_KEY, widthString);
const apiRoot = this.apiRoot || "https://builder.io";
const encocedUrl = encodeURIComponent(this.urlValue);
lsSet(FRAMES_LS_KEY, this.useFrames);
// We need to run the code to process DOM through a backend to run it in a headless browser.
// Builder.io provides this for the Figma plugin for free.
fetch(
`${apiRoot}/api/v1/url-to-figma?url=${encocedUrl}&width=${width}&useFrames=${this.useFrames}`
)
.then((res) => {
if (!res.ok) {
console.error("Url-to-figma failed", res);
throw new Error("Url-to-figma failed");
}
return res.json();
})
.then((data) => {
const layers = data.layers;
return Promise.all(
[data].concat(
layers.map(async (rootLayer: Node) => {
await traverseLayers(rootLayer, (layer: any) => {
if (getImageFills(layer)) {
return processImages(layer).catch((err) => {
console.warn("Could not process image", err);
});
}
});
})
)
);
})
.then((data) => {
parent.postMessage(
{ pluginMessage: { type: "import", data: data[0] } },
"*"
);
})
.catch((err) => {
this.loading = false;
console.error(err);
alert(err);
});
}
};
onCancel = () => {
parent.postMessage({ pluginMessage: { type: "cancel" } }, "*");
};
validate() {
if (!this.form) {
return false;
}
return this.form!.reportValidity();
}
selectAllUrlInputText() {
const input = this.urlInputRef;
if (input) {
input.setSelectionRange(0, input.value.length);
}
}
getLang() {
return this.currentLanguage === "en" ? en : ru;
}
render() {
return (
<IntlProvider
messages={this.currentLanguage === "en" ? en : ru}
locale={this.currentLanguage}
defaultLocale="en"
>
<div
style={{
display: "flex",
flexDirection: "column",
overflow: "auto",
alignItems: "stretch",
height: "100%",
}}
>
<div
style={{
padding: 15,
fontSize: 12,
}}
>
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
}}
>
<div
style={{
display: "flex",
alignItems: "center",
fontWeight: "bold",
}}
>
<FormattedMessage
id="title"
defaultMessage="Turn your design into code "
/>
<a
style={{
color: themeVars.colors.primary,
marginLeft: 5,
fontWeight: "bold",
position: "relative",
}}
href="https://www.builder.io/c/docs/import-from-figma"
target="_blank"
rel="noopenner"
>
<HelpOutline style={{ fontSize: 18 }} />
</a>
</div>
</div>
{!this.initialized ? (
<div>
<div style={{ display: "flex", padding: 20 }}>
<CircularProgress
size={30}
disableShrink
style={{ margin: "auto" }}
/>
</div>
<div
style={{
textAlign: "center",
fontSize: 12,
opacity: 0.6,
fontStyle: "italic",
}}
>
<FormattedMessage
id="initExport"
defaultMessage="Initializing for export, this can take about a minute..."
/>
</div>
</div>
) : this.generatingCode ? (
<div style={{ padding: 20 }}>
<div style={{ display: "flex", padding: 20 }}>
<CircularProgress
size={30}
disableShrink
style={{ margin: "auto" }}
/>
</div>
<Typography
variant="caption"
style={{
textAlign: "center",
marginTop: 10,
color: themeVars.colors.primaryLight,
marginBottom: -10,
fontStyle: "italic",
}}
>
<FormattedMessage
id="processing"
defaultMessage="Processing..."
/>{" "}
<br />
<FormattedMessage
id="processing2"
defaultMessage="This can take about a minute..."
/>
</Typography>
</div>
) : (
<>
{this.showImportInvalidError && (
<div>
<div
style={{
color: "rgb(200, 0, 0)",
marginTop: 10,
marginBottom: 10,
}}
>
<FormattedMessage
id="importLayerHelp"
defaultMessage="To import a layer, that layer and all children must use "
/>
<a
style={{
color: themeVars.colors.primary,
}}
href="https://help.figma.com/hc/en-us/articles/360040451373-Create-dynamic-designs-with-Auto-layout"
target="_blank"
rel="noopenner"
>
<FormattedMessage
id="autolayout"
defaultMessage="autolayout"
/>
</a>
</div>
<div>
<Button
size="small"
href="https://www.builder.io/c/docs/import-from-figma"
target="_blank"
color="primary"
rel="noopenner"
>
<FormattedMessage
id="learnMore"
defaultMessage="Learn more"
/>
</Button>
<Button
size="small"
style={{ opacity: 0.5 }}
onClick={() => {
parent.postMessage(
{
pluginMessage: {
type: "clearErrors",
data: true,
},
},
"*"
);
this.showImportInvalidError = false;
}}
>
<FormattedMessage
id="clearErrors"
defaultMessage="Clear errors"
/>
</Button>
</div>
</div>
)}
{this.showRequestFailedError && (
<div>
<div
style={{
color: "rgb(200, 0, 0)",
marginTop: 10,
marginBottom: 10,
}}
>
<FormattedMessage
id="errorMessage"
defaultMessage="Oh no, there was an error! To troubleshoot, if you are
importing a whole page, try importing a smaller part of the
page at a time, like one section or even one button"
/>
</div>
<div>
<Button
size="small"
color="primary"
href="https://www.builder.io/c/docs/import-from-figma#troubleshooting"
target="_blank"
rel="noopenner"
>
<FormattedMessage
id="learnMore"
defaultMessage="Learn more"
/>
</Button>
<Button
size="small"
style={{ opacity: 0.5 }}
onClick={() => {
this.showRequestFailedError = false;
}}
>
<FormattedMessage
id="clearErrors"
defaultMessage="Clear errors"
/>
</Button>
</div>
</div>
)}
<Tooltip
disableHoverListener={Boolean(this.selection.length)}
title={this.getLang().selectLayerPop}
>
<div>
<Button
fullWidth
style={{ marginTop: 20 }}
variant="contained"
onClick={(e) => {
this.getCode(true);
}}
disabled={!this.selection.length}
color="primary"
>
<FormattedMessage
id="getCode"
defaultMessage="Get Code"
/>
</Button>
</div>
</Tooltip>
{this.displayFiddleUrl && (
<div style={{ margin: "15px 0 5px 0" }}>
<FormattedMessage id="done" defaultMessage="Done! " />
<a
style={{
color: themeVars.colors.primary,
fontWeight: "bold",
textDecoration: "none",
}}
rel="noopenner"
href={this.displayFiddleUrl}
target="_blank"
>
<FormattedMessage id="done" defaultMessage="Click here" />
</a>
<FormattedMessage
id="clickHere2"
defaultMessage=" to open your content in Builder.io and choose 'get code'"
/>
</div>
)}
<Button
fullWidth
style={{ marginTop: 10, opacity: 0.4 }}
onClick={(e) => {
this.getCode(false);
}}
disabled={!this.selection.length}
>
<FormattedMessage
id="downloadJson"
defaultMessage="Download json"
/>
</Button>
<div
style={{
textAlign: "center",
fontSize: 11,
color: "rgba(0, 0, 0, 0.5)",
fontStyle: "italic",
marginTop: 10,
}}
>
<FormattedMessage
id="feedback"
defaultMessage="This feature is in beta. Please send "
/>
<a
style={{
color: themeVars.colors.primary,
textDecoration: "none",
cursor: "pointer",
}}
target="_blank"
rel="noopener"
href="https://github.com/BuilderIO/figma-html/issues"
>
<FormattedMessage
id="feedback2"
defaultMessage="feedback"
/>
</a>
</div>
</>
)}
</div>
<div>
<Divider />
<div
style={{
display: "flex",
flexDirection: "column",
position: "relative",
zIndex: 3,
padding: 15,
backgroundColor: "#f8f8f8",
maxWidth: settings.ui.baseWidth,
fontWeight: 400,
}}
>
<form
ref={(ref) => (this.form = ref)}
// {...{ validate: 'true' }}
style={{
display: "flex",
flexDirection: "column",
// marginTop: 20
}}
onSubmit={(e) => {
e.preventDefault();
this.onCreate();
}}
>
<div
style={{
fontSize: 12,
paddingBottom: 18,
fontWeight: "bold",
}}
>
<FormattedMessage
id="importDesigns"
defaultMessage="Import designs from the web"
/>
</div>
<div style={{ display: "flex", flexDirection: "column" }}>
<div style={{ display: "flex", position: "relative" }}>
<TextField
inputProps={{
style: {
fontSize: 13,
},
}}
label={this.getLang().urlToImport}
fullWidth
inputRef={(ref) => (this.urlInputRef = ref)}
disabled={this.loading}
required
onKeyDown={(e) => {
// Default cmd + a functionality as weird
if ((e.metaKey || e.ctrlKey) && e.which === 65) {
e.stopPropagation();
e.preventDefault();
if (e.shiftKey) {
const input = this.urlInputRef!;
input.setSelectionRange(0, 0);
} else {
this.selectAllUrlInputText();
}
}
}}
placeholder="e.g. https://builder.io"
type="url"
value={this.urlValue}
onChange={(e) => {
let value = e.target.value.trim();
if (!value.match(/^https?:\/\//)) {
value = "http://" + value;
}
this.urlValue = value;
}}
/>
</div>
{this.showMoreOptions && (
<div
style={{
display: "flex",
alignItems: "flex-end",
marginTop: 15,
}}
>
<div style={{ position: "relative", flexGrow: 1 }}>
<TextField
label={this.getLang().width}
required
inputProps={{
min: "200",
max: "3000",
step: "10",
style: {
fontSize: 13,
},
}}
disabled={this.loading}
onKeyDown={(e) => {
// Default cmd + a functionality as weird
if ((e.metaKey || e.ctrlKey) && e.which === 65) {
e.stopPropagation();
e.preventDefault();
if (e.shiftKey) {
const input = this.urlInputRef!;
input.setSelectionRange(0, 0);
} else {
const input = this.urlInputRef!;
input.setSelectionRange(
0,
input.value.length - 1
);
}
}
}}
placeholder="1200"
// style={{ marginLeft: 20 , width: 100 }}
fullWidth
type="number"
value={this.width}
onChange={(e) => {
this.width = String(
parseInt(e.target.value) || 1200
);
}}
/>
<div
style={{
position: "absolute",
right: -4,
top: 18,
borderRadius: 100,
display: "flex",
...(this.loading && {
pointerEvents: "none",
opacity: 0.5,
}),
}}
>
<IconButton
style={{
padding: 5,
color: this.width === "1200" ? "#888" : "#ddd",
}}
onClick={() => (this.width = "1200")}
>
<LaptopMac style={{ fontSize: 14 }} />
</IconButton>
<IconButton
style={{
padding: 5,
color: this.width === "900" ? "#888" : "#ddd",
}}
onClick={() => (this.width = "900")}
>
<TabletMac style={{ fontSize: 14 }} />
</IconButton>
<IconButton
style={{
padding: 5,
color: this.width === "400" ? "#888" : "#ddd",
}}
onClick={() => (this.width = "400")}
>
<PhoneIphone style={{ fontSize: 14 }} />
</IconButton>
</div>
</div>
<Tooltip
PopperProps={{
modifiers: { flip: { behavior: ["top"] } },
}}
enterDelay={300}
placement="top"
title={this.getLang().framesPop}
>
<FormControlLabel
value="Use Frames"
disabled={this.loading}
style={{ marginLeft: 20 }}
control={
<Switch
// disabled={this.loading}
size="small"
// style={{ marginLeft: 20 }}
color="primary"
checked={this.useFrames}
onChange={(e) =>
(this.useFrames = e.target.checked)
}
/>
}
label={
<span
style={{
fontSize: 12,
opacity: 0.6,
position: "relative",
top: -5,
}}
>
<FormattedMessage
id="frames"
defaultMessage="Frames"
/>
</span>
}
labelPlacement="top"
/>
</Tooltip>
</div>
)}
</div>
{this.errorMessage && (
<div
style={{
color: "#721c24",
backgroundColor: "#f8d7da",
border: "1px solid #f5c6cb",
borderRadius: 4,
padding: ".75rem 1.25rem",
marginTop: 20,
}}
>
{this.errorMessage}
</div>
)}
{!this.online && (
<div
style={{
color: "#721c24",
backgroundColor: "#f8d7da",
border: "1px solid #f5c6cb",
borderRadius: 4,
padding: ".75rem 1.25rem",
marginTop: 20,
}}
>
<FormattedMessage
id="needOnline"
defaultMessage="You need to be online to use this plugin"
/>
</div>
)}
{this.loading ? (
<>
<div style={{ margin: "0 auto" }} className="lds-ellipsis">
<div
style={{ background: themeVars.colors.primaryLight }}
/>
<div
style={{ background: themeVars.colors.primaryLight }}
/>
<div
style={{ background: themeVars.colors.primaryLight }}
/>
<div
style={{ background: themeVars.colors.primaryLight }}
/>
</div>
<Typography
variant="caption"
style={{
textAlign: "center",
// marginTop: 10,
color: themeVars.colors.primaryLight,
marginBottom: -10,
// fontStyle: "italic"
}}
>
<FormattedMessage
id="processingCode"
defaultMessage="Processing code..."
/>
<br />
<FormattedMessage
id="processingCode2"
defaultMessage="This can take a couple minutes..."
/>
</Typography>
</>
) : (
<>
<Button
type="submit"
disabled={Boolean(
this.errorMessage || this.loading || !this.online
)}
style={{ marginTop: 20 }}
fullWidth
color="primary"
variant="outlined"
onClick={this.onCreate}
>
<FormattedMessage id="import" defaultMessage="Import" />
</Button>
<div
style={{
color: "#888",
fontSize: 12,
textAlign: "center",
marginTop: 15,
userSelect: "none",
marginBottom: -10,
}}
>
<FormattedMessage
id="orTry"
defaultMessage="Or try our "
/>
<a
style={{
color: themeVars.colors.primary,
cursor: "pointer",
textDecoration: "none",
}}
href="https://chrome.google.com/webstore/detail/efjcmgblfpkhbjpkpopkgeomfkokpaim"
target="_blank"
>
<FormattedMessage
id="orTry2"
defaultMessage="chrome extension"
/>
</a>
<FormattedMessage
id="orTry3"
defaultMessage=" to capture a page in your browser and"
/>
<a
onClick={() => {
const input = document.createElement("input");
input.type = "file";
document.body.appendChild(input);
input.style.visibility = "hidden";
input.click();
const onFocus = () => {
setTimeout(() => {
if (
input.parentElement &&
(!input.files || input.files.length === 0)
) {
done();
}
}, 200);
};
const done = () => {
input.remove();
this.loading = false;
window.removeEventListener("focus", onFocus);
};
window.addEventListener("focus", onFocus);
// TODO: parse and upload images!
input.addEventListener("change", (event) => {
const file = (event.target as HTMLInputElement)
.files![0];
if (file) {
this.loading = true;
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (e) => {
const text = (e.target as any).result;
try {
const json = JSON.parse(text);
Promise.all(
json.layers.map(async (rootLayer: Node) => {
await traverseLayers(
rootLayer,
(layer: any) => {
if (getImageFills(layer)) {
return processImages(layer).catch(
(err) => {
console.warn(
"Could not process image",
err
);
}
);
}
}
);
})
)
.then(() => {
parent.postMessage(
{
pluginMessage: {
type: "import",
data: json,
},
},
"*"
);
setTimeout(() => {
done();
}, 1000);
})
.catch((err) => {
done();
console.error(err);
alert(err);
});
} catch (err) {
alert("File read error: " + err);
done();
}
};
reader.readAsText(file);
} else {
done();
}
});
}}
style={{
color: themeVars.colors.primary,
cursor: "pointer",
}}
>
<FormattedMessage
id="orTry4"
defaultMessage=" upload here "
/>
</a>
</div>
</>
)}
</form>
</div>
<Divider />
{useDev && (
<div
onClick={() => {
lsSet("builder.env", "production");
}}
style={{
padding: 10,
color: "rgb(200, 0, 0)",
textAlign: "center",
}}
>
Using dev env. Click here to reset then reload the extension
</div>
)}
<div style={{ marginTop: 20, textAlign: "center", color: "#666" }}>
<FormattedMessage id="made" defaultMessage="Made with " />
<Favorite
style={{
color: "rgb(236, 55, 88)",
fontSize: 16,
marginTop: -2,
verticalAlign: "middle",
}}
/>
<FormattedMessage id="made2" defaultMessage=" by " />
<a
style={{ color: themeVars.colors.primary }}
href="https://www.builder.io?ref=figma"
target="_blank"
>
Builder.io
</a>
</div>
<div
style={{
marginTop: 15,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Select
style={{
opacity: 0.3,
fontSize: "11px",
fontWeight: 600,
}}
id="demo-simple-select"
value={this.currentLanguage}
onChange={(e) =>
(this.currentLanguage = (e.target as HTMLInputElement).value)
}
>
<StyledButton value="en">EN</StyledButton>
<StyledButton value="ru">RU</StyledButton>
</Select>
</div>
<div
style={{
marginTop: 20,
textAlign: "center",
color: "#999",
display: "flex",
alignItems: "center",
justifyContent: "center",
fontWeight: 400,
fontSize: 9,
paddingBottom: 10,
}}
>
<a
style={{
color: "#999",
textDecoration: "none",
}}
href="https://github.com/BuilderIO/html-to-figma/issues"
target="_blank"
>
<FormattedMessage
id="feedbackFooter"
defaultMessage="Feedback"
/>
</a>
<span
style={{
display: "inline-block",
height: 10,
width: 1,
background: "#999",
marginTop: 1,
opacity: 0.8,
marginLeft: 5,
}}
/>
<a
style={{
color: "#999",
textDecoration: "none",
marginLeft: 5,
}}
href="https://github.com/BuilderIO/html-to-figma"
target="_blank"
>
<FormattedMessage id="source" defaultMessage="Source" />
</a>
<span
style={{
display: "inline-block",
height: 10,
width: 1,
background: "#999",
marginTop: 1,
opacity: 0.8,
marginLeft: 5,
}}
/>
<a
style={{
color: "#999",
textDecoration: "none",
marginLeft: 5,
}}
href="https://github.com/BuilderIO/html-to-figma"
target="_blank"
>
<FormattedMessage id="help" defaultMessage="Help" />
</a>
</div>
</div>
</div>
</IntlProvider>
);
}
}
ReactDOM.render(
<MuiThemeProvider theme={theme}>
<>
<CssBaseline />
<App />
</>
</MuiThemeProvider>,
document.getElementById("react-page")
); | the_stack |
import { createElement, remove } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { Axis } from '../../../src/chart/axis/axis';
import { Series, Points } from '../../../src/chart/series/chart-series';
import { HistogramSeries } from '../../../src/chart/series/histogram-series';
import { ColumnSeries } from '../../../src/chart/series/column-series';
import { Tooltip } from '../../../src/chart/user-interaction/tooltip';
import { Crosshair } from '../../../src/chart/user-interaction/crosshair';
import { DataLabel } from '../../../src/chart/series/data-label';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { unbindResizeEvents } from '../base/data.spec';
import { MouseEvents } from '../base/events.spec';
import { bar } from '../base/data.spec';
import { EmitType } from '@syncfusion/ej2-base';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
import { ILoadedEventArgs, IAnimationCompleteEventArgs, IPointRenderEventArgs } from '../../../src/chart/model/chart-interface';
Chart.Inject(ColumnSeries, Tooltip, Crosshair, DataLabel,HistogramSeries);
describe('Chart Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Chart Histogram series', () => {
let chartObj: Chart;
let elem: HTMLElement;
let point: HTMLElement;
let histo: HTMLElement;
let svg: HTMLElement;
let targetElement: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>;
let done: Function;
let dataLabel: HTMLElement;
let trigger: MouseEvents = new MouseEvents();
let x: number;
let y: number;
let animationComplete: EmitType<IAnimationCompleteEventArgs>;
let values: number[] = [23,34,23,45,56,67,12,12,43,34,23,34,23,45,56,67,12,12,43,34,23,34,23,45,56,67,12,12,43,34
,23,34,23,45,56,67,12,12,43,34,23,34,23,45,56,67,12,12,43,34];
let chartData: Object[] = [];
for(let i: number=0; i< values.length; i++) {
chartData.push(
{ y: values[i] }
);
}
beforeAll(() => {
elem = createElement('div', { id: 'container' });
document.body.appendChild(elem);
chartObj = new Chart(
{
series: [{
dataSource: chartData, yName: 'y', animation: { enable: false },
type:'Histogram',
name: 'AgeCollections', fill: 'rgba(135,206,235,1)',
},
], width: '800',
tooltip: { enable: true, textStyle: { size: '12px' }},
legendSettings: { visible: false },
title: 'Histogram agecollections'
});
chartObj.appendTo('#container');
});
afterAll((): void => {
chartObj.destroy();
elem.remove();
});
it('Checking with default histogram series', (done: Function) => {
loaded = (args: Object): void => {
histo = document.getElementById('container_Series_0_Point_0');
expect(histo != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].type = 'Histogram';
chartObj.refresh();
});
it('Checking with series visibility', (done: Function) => {
loaded = (args: Object): void => {
histo = document.getElementById('container_Series_0_Point_0');
expect(histo != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].type = 'Histogram';
chartObj.refresh();
});
it('Checking with numeric axis', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_3');
expect(svg.getAttribute('d') != '').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].dataSource = chartData;
chartObj.primaryXAxis.valueType = 'Double';
chartObj.refresh();
});
it('Checking with default interval', (done: Function) => {
loaded = (args: Object): void => {
let svg1: HTMLElement = document.getElementById('container_Series_0_Point_0');
expect(svg1 != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with given interval', (done: Function) => {
loaded = (args: Object): void => {
let svg1: HTMLElement = document.getElementById('container_Series_0_Point_0');
expect(svg1 != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.interval = 4;
chartObj.refresh();
});
it('Checking with X-axis inversed', (done: Function) => {
loaded = (args: Object): void => {
let point1 : HTMLElement = document.getElementById('container_Series_0_Point_0');
expect(point1 != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.isInversed = true;
chartObj.primaryXAxis.valueType = 'Double';
chartObj.refresh();
});
it('Checking with Y-axis inversed', (done: Function) => {
loaded = (args: Object): void => {
let svg1: HTMLElement = document.getElementById('container_Series_0_Point_0');
expect(svg1 != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryYAxis.isInversed = true;
chartObj.refresh();
});
it('Checking with opposed position', (done: Function) => {
loaded = (args: Object): void => {
let svg1: HTMLElement = document.getElementById('container_Series_0_Point_0');
expect(svg1 != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.opposedPosition = true;
chartObj.refresh();
});
it('checking with border', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_1');
expect(svg.getAttribute('stroke') === 'red').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].border.color = 'red';
chartObj.series[0].border.width = 2;
chartObj.primaryXAxis.opposedPosition = false;
chartObj.primaryYAxis.isInversed = false;
chartObj.refresh();
});
it('checking with point fill', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_1');
expect(svg.getAttribute('stroke') === 'red').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].fill = 'red';
chartObj.refresh();
});
it('checking with default Tooltip', (done: Function) => {
loaded = (args: Object): void => {
let target: HTMLElement = document.getElementById('container_Series_0_Point_1');
let series: Series = <Series>chartObj.series[0];
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')) + elem.offsetTop;
x = series.points[1].regions[0].x + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
let tooltip: HTMLElement = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
expect(target.getAttribute('opacity') == '0.5').toBe(true);
expect(parseFloat(tooltip.style.left) > series.points[1].regions[0].y + parseFloat(chartArea.getAttribute('y')));
target = document.getElementById('container_Series_0_Point_3');
series = <Series>chartObj.series[0];
y = series.points[3].regions[0].y + parseFloat(chartArea.getAttribute('y')) + 30 + elem.offsetTop;
x = series.points[3].regions[0].x + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
tooltip = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
expect(target.getAttribute('opacity') == '0.5').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].type = 'Histogram';
chartObj.primaryXAxis.valueType = 'Double';
chartObj.series[0].dataSource = chartData;
chartObj.refresh();
});
it('checking with track ball', (done: Function) => {
loaded = (args: Object): void => {
let target: HTMLElement = document.getElementById('container_Series_0_Point_2');
let series: Series = <Series>chartObj.series[0];
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
series = <Series>chartObj.series[0];
y = series.points[3].regions[0].y + parseFloat(chartArea.getAttribute('y')) + 30 + elem.offsetTop;
x = series.points[3].regions[0].x + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
let tooltip: HTMLElement = document.getElementById('container_tooltip');
expect(tooltip != null).toBe(true);
expect(target.getAttribute('opacity') == '1').toBe(true);
done();
};
chartObj.series[0].type = 'Histogram';
chartObj.loaded = loaded;
chartObj.primaryXAxis.crosshairTooltip.enable = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.primaryXAxis.valueType = 'Double';
chartObj.crosshair.enable = true;
chartObj.tooltip.shared = true;
chartObj.refresh();
});
it('checking with cross hair', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
let series: Series = <Series>chartObj.series[0];
y = series.points[2].regions[0].y + parseFloat(chartArea.getAttribute('y')) + elem.offsetTop;
x = series.points[2].regions[0].x + series.points[2].regions[0].width / 2 + parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').childNodes[4];
let element1: HTMLElement;
expect(crosshair.childNodes.length == 3).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('x')) > 0).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[1];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('y')) > 0).toBe(true);
expect(crosshair.childNodes[2].childNodes.length == 4).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[0];
expect(element1.getAttribute('d') !== '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[2];
expect(element1.getAttribute('d') !== '').toBe(true);
done();
}
chartObj.loaded = loaded;
chartObj.series[0].dataSource = chartData;
chartObj.series[0].type = 'Histogram';
chartObj.primaryXAxis.valueType = 'Double';
chartObj.crosshair.enable = true;
chartObj.refresh();
});
it('checking with legend visbility', (done: Function) => {
loaded = (args: Object): void => {
let svg1: HTMLElement = document.getElementById('container_Series_0_Point_0');
expect(svg1 != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.legendSettings.visible = true;
chartObj.refresh();
});
it('Checking with normal distribution', (done: Function) => {
loaded = (args: Object): void => {
histo = document.getElementById('container_Series_0_Point_0');
expect(histo != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].type = 'Histogram';
chartObj.series[0].showNormalDistribution = true;
chartObj.refresh();
});
it('checking with bin interval', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_2');
expect(svg.getAttribute('d') != '').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.primaryXAxis.valueType = 'Double';
chartObj.series[0].dataSource = chartData;
chartObj.series[0].binInterval = 4;
chartObj.refresh();
});
it('Checking with normal distribution is transposed', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_2');
expect(svg.getAttribute('d') != '').toBe(true);
histo = document.getElementById('container_Series_0_Point_0');
expect(histo != null).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].type = 'Histogram';
chartObj.series[0].showNormalDistribution = true;
chartObj.isTransposed = true;
chartObj.refresh();
});
it('checking with multiple axes and panes', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('container_Series_0_Point_2');
expect(svg.getAttribute('d') != '').toBe(true);
histo = document.getElementById('container_Series_0_Point_0');
expect(histo != null).toBe(true);
done();
};
chartObj.primaryXAxis = { title: 'pyXAxis'};
chartObj.loaded = loaded;
chartObj.isTransposed = false;
chartObj.rows = [ { height: '50%'}, { height: '50%'}];
chartObj.axes = [{
rowIndex: 1, opposedPosition: true,
name: 'yAxis'
}];
chartObj.series = [
{
type: 'Histogram', animation : {enable : false}, dataSource:chartData,
yName: 'y', name: 'Germany'
},
{
type: 'Histogram', animation : {enable : false}, dataSource: chartData,
yName: 'y', yAxisName: 'yAxis', name: 'Japan'
}];
chartObj.refresh();
});
it('Checking with animation', (done: Function) => {
animationComplete = (args: IAnimationCompleteEventArgs): void => {
let point = document.getElementById('container_Series_' + args.series.index + '_Point_0');
expect(point.getAttribute('transform') === 'translate(0,0)').toBe(true);
let elem: HTMLElement = document.getElementById('container_Series_' + args.series.index + '_NDLine');
expect(elem.style.visibility).toBe('hidden');
done();
};
chartObj.series[0].showNormalDistribution = true;
chartObj.series[0].animation.enable = true;
chartObj.animationComplete = animationComplete;
chartObj.refresh();
});
});
describe('Histogram Series with data label', () => {
let chartObj: Chart;
let loaded: EmitType<ILoadedEventArgs>;
let animationComplete: EmitType<IAnimationCompleteEventArgs>;
let element: HTMLElement;
let values: number[] = [23,34,23,45,56,67,12,12,43,34,23,34,23,45,56,67,12,12,43,34,23,34,23,45,56,67,12,12,43,34
,23,34,23,45,56,67,12,12,43,34,23,34,23,45,56,67,12,12,43,34];
let chartData: Object[]=[];
for(let i: number=0; i< values.length; i++) {
chartData.push(
{ y: values[i] }
);
}
beforeAll(() => {
element = createElement('div', { id: 'container' });
document.body.appendChild(element);
chartObj = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis' },
primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'Normal' },
series: [{
animation: { enable: false },
name: 'AgeCollections', dataSource:chartData, yName: 'y',
type: 'Histogram',
fill: 'rgba(135,206,235,1)',
marker: { visible: false, dataLabel: { visible: true, fill: 'violet' } }
}],
width: '800',
title: 'Hisogram Age collections', loaded: loaded,
legendSettings: { visible: false }
});
chartObj.appendTo('#container');
});
afterAll((): void => {
chartObj.destroy();
element.remove();
});
it('With Label position Auto', (done: Function) => {
loaded = (args: Object): void => {
let svg: number = +document.getElementById('container_Series_0_Point_1_TextShape_0').getAttribute('x');
let point0Location = (<Points>(<Series>chartObj.series[0]).points[1]).symbolLocations[0].x;
expect(svg < point0Location).toBe(true);
let svg1: number = +document.getElementById('container_Series_0_Point_1_TextShape_0').getAttribute('x');
let pointLocation1 = (<Points>(<Series>chartObj.series[0]).points[0]).symbolLocations[0].x;
expect(svg > pointLocation1).toBe(true); done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Auto';
chartObj.refresh();
});
it('With Label position Bottom', (done: Function) => {
loaded = (args: Object): void => {
let svg: number = +document.getElementById('container_Series_0_Point_1_TextShape_0').getAttribute('x');
let point0Location: number = ((<Points>(<Series>chartObj.series[0]).points[1]).regions[0].x +
(<Points>(<Series>chartObj.series[0]).points[1]).regions[0].width);
expect(svg < point0Location).toBe(true);
let svg1: number = +document.getElementById('container_Series_0_Point_0_TextShape_0').getAttribute('x');
let point0Location1 = (<Points>(<Series>chartObj.series[0]).points[0]).regions[0].x;
expect(svg1 > point0Location1).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.position = 'Bottom';
chartObj.refresh();
});
it('Color saturation with data label fill color', (done: Function) => {
loaded = (args: ILoadedEventArgs): void => {
let element: HTMLElement = document.getElementById('container_Series_0_Point_1_TextShape_0');
expect(element.getAttribute('fill') === 'red').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.series[0].marker.dataLabel.fill = 'red';
chartObj.series[0].marker.dataLabel.position = 'Outer';
chartObj.series[0].type = 'Histogram';
chartObj.refresh();
});
it('Checking Events', (done: Function) => {
loaded = (args: Object): void => {
let element: HTMLElement = document.getElementById('container_Series_0_Point_2');
expect(element.getAttribute('fill') == 'brown').toBe(true);
done();
};
chartObj.pointRender = (args: IPointRenderEventArgs) => {
if (args.point.index === 2) {
args.fill = 'brown';
}
};
chartObj.loaded = loaded;
chartObj.title = 'Events Changed';
chartObj.dataBind();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
});
export interface series1 {
series: Series;
} | the_stack |
import { Maps } from '../../index';
import { SelectionSettingsModel, click, ISelectionEventArgs, itemSelection } from '../index';
import { getElement, createStyle, customizeStyle, removeClass, getTargetElement, getElementByID} from '../utils/helper';
import { isNullOrUndefined, Browser } from '@syncfusion/ej2-base';
import { BorderModel } from '../model/base-model';
/**
* Selection module class
*/
export class Selection {
private maps: Maps;
/**
* @private
*/
public selectionsettings: SelectionSettingsModel;
/**
* @private
*/
public selectionType: string;
constructor(maps: Maps) {
this.maps = maps;
this.addEventListener();
}
/**
* For binding events to selection module
*
* @returns {void}
*/
private addEventListener(): void {
if (!this.maps.isDestroyed) {
this.maps.on(click, this.mouseClick, this);
this.maps.on(Browser.touchEndEvent, this.mouseClick, this);
}
}
/**
* For removing events from selection modue
*
* @returns {void}
*/
private removeEventListener(): void {
if (this.maps.isDestroyed) {
return;
}
this.maps.off(click, this.mouseClick);
this.maps.off(Browser.touchEndEvent, this.mouseClick);
}
private mouseClick(targetElement: Element): void {
if (!isNullOrUndefined(targetElement['type']) && targetElement['type'].indexOf('touch') !== -1 &&
isNullOrUndefined(targetElement.id)) {
targetElement = targetElement['target'];
}
if (!isNullOrUndefined(targetElement.id) && (targetElement.id.indexOf('LayerIndex') > -1 ||
targetElement.id.indexOf('NavigationIndex') > -1)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let shapeData: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let data: any;
let shapeIndex: number;
let dataIndex: number;
const layerIndex: number = parseInt(targetElement.id.split('_LayerIndex_')[1].split('_')[0], 10);
if (targetElement.id.indexOf('shapeIndex') > -1) {
shapeIndex = parseInt(targetElement.id.split('_shapeIndex_')[1].split('_')[0], 10);
shapeData = this.maps.layers[layerIndex].shapeData['features']['length'] > shapeIndex ?
this.maps.layers[layerIndex].shapeData['features'][shapeIndex]['properties'] : null;
dataIndex = parseInt(targetElement.id.split('_dataIndex_')[1].split('_')[0], 10);
data = isNullOrUndefined(dataIndex) ? null : this.maps.layers[layerIndex].dataSource[dataIndex];
this.selectionsettings = this.maps.layers[layerIndex].selectionSettings;
this.selectionType = 'Shape';
} else if (targetElement.id.indexOf('BubbleIndex') > -1) {
const bubbleIndex: number = parseInt(targetElement.id.split('_BubbleIndex_')[1].split('_')[0], 10);
dataIndex = parseInt(targetElement.id.split('_dataIndex_')[1].split('_')[0], 10);
data = this.maps.layers[layerIndex].bubbleSettings[bubbleIndex].dataSource[dataIndex];
this.selectionsettings = this.maps.layers[layerIndex].bubbleSettings[bubbleIndex].selectionSettings;
this.selectionType = 'Bubble';
} else if (targetElement.id.indexOf('MarkerIndex') > -1) {
const markerIndex: number = parseInt(targetElement.id.split('_MarkerIndex_')[1].split('_')[0], 10);
dataIndex = parseInt(targetElement.id.split('_dataIndex_')[1].split('_')[0], 10);
data = this.maps.layers[layerIndex].markerSettings[markerIndex].dataSource[dataIndex];
this.selectionsettings = this.maps.layers[layerIndex].markerSettings[markerIndex].selectionSettings;
this.selectionType = 'Marker';
} else {
const index: number = parseInt(targetElement.id.split('_NavigationIndex_')[1].split('_')[0], 10);
shapeData = null;
data = {
latitude: this.maps.layers[layerIndex].navigationLineSettings[index].latitude,
longitude: this.maps.layers[layerIndex].navigationLineSettings[index].longitude
};
this.selectionsettings = this.maps.layers[layerIndex].navigationLineSettings[index].selectionSettings;
this.selectionType = 'navigationline';
}
if (this.selectionsettings.enable) {
this.selectElement(targetElement, layerIndex, data, shapeData);
}
} else if ((this.maps.legendSettings.visible && !this.maps.legendSettings.toggleLegendSettings.enable && this.maps.legendModule) &&
!isNullOrUndefined(targetElement.id) && targetElement.id.indexOf('_Text') === -1 &&
(targetElement.id.indexOf(this.maps.element.id + '_Legend_Shape_Index') > -1 ||
targetElement.id.indexOf(this.maps.element.id + '_Legend_Index') !== -1)) {
this.maps.legendModule.legendHighLightAndSelection(targetElement, 'selection');
}
}
/**
* @private
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public selectElement(targetElement: Element, layerIndex: number, data: any, shapeData: any): void {
this.maps.mapSelect = targetElement ? true : false;
if (this.maps.legendModule && this.maps.legendSettings.visible && targetElement.id.indexOf('_MarkerIndex_') === -1) {
this.maps.legendModule.shapeHighLightAndSelection(
targetElement, data, this.selectionsettings, 'selection', layerIndex);
}
const shapeToggled: boolean = (targetElement.id.indexOf('shapeIndex') > -1 && this.maps.legendSettings.visible && this.maps.legendModule) ?
this.maps.legendModule.shapeToggled : true;
if (shapeToggled) {
this.selectMap(targetElement, shapeData, data);
}
}
// eslint-disable-next-line valid-jsdoc
/**
* Public method for selection
*/
public addSelection(layerIndex: number, name: string, enable: boolean): void {
const targetElement: Element = getTargetElement(layerIndex, name, enable, this.maps);
if (enable) {
this.selectMap(targetElement, null, null);
} else {
removeClass(targetElement);
}
}
/**
* Method for selection
*
* @param {Element} targetElement - Specifies the target element
* @param {any} shapeData - Specifies the shape data
* @param {any} data - Specifies the data
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private selectMap(targetElement: Element, shapeData: any, data: any): void {
const layerIndex: number = parseInt(targetElement.id.split('_LayerIndex_')[1].split('_')[0], 10);
let parentElement: Element;
let children: HTMLCollection;
let selectionClass: Element;
const selectionsettings: SelectionSettingsModel = this.selectionsettings;
const border: BorderModel = {
color: (targetElement.parentElement.id.indexOf('LineString') === -1) ? this.selectionsettings.border.color : (this.selectionsettings.border.color || this.selectionsettings.fill),
width: (targetElement.parentElement.id.indexOf('LineString') === -1) ? (this.selectionsettings.border.width / (this.selectionType === 'Marker' ? 1 : this.maps.scale)) : (this.selectionsettings.border.width / this.maps.scale),
opacity: this.selectionsettings.border.opacity
};
const eventArgs: ISelectionEventArgs = {
opacity: this.selectionsettings.opacity,
fill: (targetElement.parentElement.id.indexOf('LineString') === -1) ? (this.selectionType !== 'navigationline' ? this.selectionsettings.fill : 'none') : 'transparent',
border: border,
name: itemSelection,
target: targetElement.id,
cancel: false,
shapeData: shapeData,
data: data,
maps: this.maps
};
this.maps.trigger('itemSelection', eventArgs, (observedArgs: ISelectionEventArgs) => {
eventArgs.border.opacity = isNullOrUndefined(this.selectionsettings.border.opacity) ? this.selectionsettings.opacity : this.selectionsettings.border.opacity;
if (!eventArgs.cancel) {
if (targetElement.getAttribute('class') === this.selectionType + 'selectionMapStyle') {
removeClass(targetElement);
this.removedSelectionList(targetElement);
for (let m: number = 0; m < this.maps.shapeSelectionItem.length; m++) {
if (this.maps.shapeSelectionItem[m] === eventArgs.shapeData) {
this.maps.shapeSelectionItem.splice(m, 1);
break;
}
}
if (targetElement.id.indexOf('NavigationIndex') > -1) {
const index: number = parseInt(targetElement.id.split('_NavigationIndex_')[1].split('_')[0], 10);
const layerIndex: number = parseInt(targetElement.parentElement.id.split('_LayerIndex_')[1].split('_')[0], 10);
targetElement.setAttribute(
'stroke-width', this.maps.layers[layerIndex].navigationLineSettings[index].width.toString()
);
targetElement.setAttribute('stroke', this.maps.layers[layerIndex].navigationLineSettings[index].color);
}
} else {
const layetElement: Element = getElementByID(this.maps.element.id + '_Layer_Collections');
if (!this.selectionsettings.enableMultiSelect &&
layetElement.getElementsByClassName(this.selectionType + 'selectionMapStyle').length > 0) {
const eleCount : number = layetElement.getElementsByClassName(this.selectionType + 'selectionMapStyle').length;
let ele : Element;
for (let k : number = 0 ; k < eleCount; k++) {
ele = layetElement.getElementsByClassName(this.selectionType + 'selectionMapStyle')[0];
removeClass(ele);
this.removedSelectionList(ele);
}
if (this.selectionType === 'Shape') {
this.maps.shapeSelectionItem = [];
const selectionLength: number = this.maps.selectedElementId.length;
for (let i: number = 0; i < selectionLength; i++) {
ele = layetElement.getElementsByClassName(this.selectionType + 'selectionMapStyle')[0];
removeClass(ele);
const selectedElementIdIndex: number = this.maps.selectedElementId.indexOf(ele.getAttribute('id'));
this.maps.selectedElementId.splice(selectedElementIdIndex, 1);
}
}
if (ele.id.indexOf('NavigationIndex') > -1) {
const index: number = parseInt(targetElement.id.split('_NavigationIndex_')[1].split('_')[0], 10);
const layerIndex: number = parseInt(targetElement.parentElement.id.split('_LayerIndex_')[1].split('_')[0], 10);
ele.setAttribute('stroke-width', this.maps.layers[layerIndex].navigationLineSettings[index].width.toString());
ele.setAttribute('stroke', this.maps.layers[layerIndex].navigationLineSettings[index].color);
}
}
if (!getElement(this.selectionType + 'selectionMap')) {
document.body.appendChild(createStyle(this.selectionType + 'selectionMap',
this.selectionType + 'selectionMapStyle', eventArgs));
} else {
customizeStyle(this.selectionType + 'selectionMap', this.selectionType + 'selectionMapStyle', eventArgs);
}
targetElement.setAttribute('class', this.selectionType + 'selectionMapStyle');
if (targetElement.getAttribute('class') === 'ShapeselectionMapStyle') {
this.maps.shapeSelectionClass = getElement(this.selectionType + 'selectionMap');
this.maps.selectedElementId.push(targetElement.getAttribute('id'));
this.maps.shapeSelectionItem.push(eventArgs.shapeData);
}
if (targetElement.getAttribute('class') === 'MarkerselectionMapStyle') {
this.maps.markerSelectionClass = getElement(this.selectionType + 'selectionMap');
this.maps.selectedMarkerElementId.push(targetElement.getAttribute('id'));
}
if (targetElement.getAttribute('class') === 'BubbleselectionMapStyle') {
this.maps.bubbleSelectionClass = getElement(this.selectionType + 'selectionMap');
this.maps.selectedBubbleElementId.push(targetElement.getAttribute('id'));
}
if (targetElement.getAttribute('class') === 'navigationlineselectionMapStyle') {
this.maps.navigationSelectionClass = getElement(this.selectionType + 'selectionMap');
this.maps.selectedNavigationElementId.push(targetElement.getAttribute('id'));
}
}
}
});
}
/**
* Remove legend selection
*/
// private removeLegendSelection(legendCollection: Object[], targetElement: Element): void {
// let shape: Element;
// if (!this.selectionsettings.enableMultiSelect) {
// for (let i: number = 0; i < legendCollection.length; i++) {
// for (let data of legendCollection[i]['data']) {
// shape = getElement(this.maps.element.id + '_LayerIndex_' + data['layerIndex'] +
// '_shapeIndex_' + data['shapeIndex'] + '_dataIndex_' + data['dataIndex']);
// removeClass(shape);
// }
// }
// }
// }
/**
* Get module name.
*
* @param {Element} targetElement - Specifies the target element
* @returns {void}
* @private
*/
public removedSelectionList(targetElement: Element): void {
if (this.selectionType === 'Shape') {
this.maps.selectedElementId.splice(this.maps.selectedElementId.indexOf(targetElement.getAttribute('id')), 1);
}
if (this.selectionType === 'Bubble') {
this.maps.selectedBubbleElementId.splice(this.maps.selectedBubbleElementId.indexOf(targetElement.getAttribute('id')), 1);
}
if (this.selectionType === 'Marker') {
this.maps.selectedMarkerElementId.splice(this.maps.selectedMarkerElementId.indexOf(targetElement.getAttribute('id')), 1);
}
if (this.selectionType === 'navigationline') {
this.maps.selectedBubbleElementId.splice(this.maps.selectedBubbleElementId.indexOf(targetElement.getAttribute('id')), 1);
}
}
/**
* Get module name.
*
* @returns {string} - Returns the module name
*/
protected getModuleName(): string {
return 'Selection';
}
/**
* To destroy the selection.
*
* @param {Maps} maps - Specifies the maps instance.
* @returns {void}
* @private
*/
public destroy(maps: Maps): void {
/**
* Destroy method performed here
*/
this.removeEventListener();
}
} | the_stack |
import events from "events";
import fs from "fs";
import { strict as assert } from "assert";
import Docker from "dockerode";
import { ZonedDateTime } from "@js-joda/core";
import got from "got";
import {
createTempfile,
globalTestSuiteSetupOnce,
httpTimeoutSettings,
log,
logHTTPResponse,
mtime,
mtimeDeadlineInSeconds,
readDockerDNSSettings,
readFirstNBytes,
rndstring,
sleep,
TENANT_DEFAULT_API_TOKEN_FILEPATH,
TENANT_DEFAULT_CORTEX_API_BASE_URL,
TENANT_DEFAULT_DD_API_BASE_URL
} from "./testutils";
import { waitForCortexMetricResult } from "./testutils/metrics";
function ddApiSeriesUrl() {
let url = `${TENANT_DEFAULT_DD_API_BASE_URL}/api/v1/series`;
if (TENANT_DEFAULT_API_TOKEN_FILEPATH !== undefined) {
const token = fs.readFileSync(TENANT_DEFAULT_API_TOKEN_FILEPATH, {
encoding: "utf8"
});
url = `${url}?api_key=${token}`;
}
return url;
}
function copyLEcertToHost() {
const src = `${__dirname}/containers/letsencrypt-stg-root-x1.pem`;
const dst = createTempfile("le-staging-root-ca", ".pem");
log.info("copy %s to %s", src, dst);
fs.copyFileSync(src, dst);
return dst;
}
export async function startDDagentContainer() {
log.info("start containerized DD agent");
const docker = new Docker({ socketPath: "/var/run/docker.sock" });
const dockerDNS = readDockerDNSSettings();
log.info(`docker container dns settings: ${dockerDNS}`);
// Prepare for mounting Let's Encrypt Staging root CA into the DD agent
// container (the goal is that the Golang-based HTTP client used in the DD
// agent discovers it when doing HTTP requests). Note: the path
// `${__dirname}/containers/letsencrypt-stg-root-x1.pem` is valid _in the
// container_ running the test runner, but not on the host running the test
// runner container. For being able to mount this file into the DD agent
// container, first copy it to a location that's known to be shared between
// the test runner container and the host.
const leStagingRootCAFilePathOnHost = copyLEcertToHost();
// Use magic DD agent environment variables to point the DD agent to
// the tested cluster's DD API implementation. Set the 'default' tenant's
// API authentication token as DD API key. The environnment variables
// supported by the DD agent are documented here:
// https://docs.datadoghq.com/agent/guide/environment-variables/
let ddApiKey = "none";
if (TENANT_DEFAULT_API_TOKEN_FILEPATH !== undefined) {
ddApiKey = fs.readFileSync(TENANT_DEFAULT_API_TOKEN_FILEPATH, {
encoding: "utf8"
});
}
const ddEnv = [
`DD_API_KEY=${ddApiKey}`,
`DD_DD_URL=${TENANT_DEFAULT_DD_API_BASE_URL}`
];
log.info("DD agent container env: %s", ddEnv);
// Prepare file for capturing DD agent stdout/err.
const outerrfilePath = createTempfile("dd-agent-container-", ".outerr");
const outstream = fs.createWriteStream(outerrfilePath);
await events.once(outstream, "open");
const cont = await docker.createContainer({
Image: "gcr.io/datadoghq/agent:7",
AttachStdin: false,
AttachStdout: false,
AttachStderr: false,
Tty: false,
Env: ddEnv,
HostConfig: {
Mounts: [
{
Type: "bind",
Source: leStagingRootCAFilePathOnHost,
// /etc/ssl/ca-bundle.pem is a place where the Golang-based HTTP
// client in the DD agent discovers and uses the CA file when doing
// HTTP requests. It does however not overwrite the system store
// baked into the container image, because that path is not used by
// the distro in the DD agent container image. Kudos to
// https://stackoverflow.com/a/40051432/145400 for showing the paths
// that Golang walks through.
Target: "/etc/ssl/ca-bundle.pem",
ReadOnly: true
},
{
Type: "bind",
Source: "/var/run/docker.sock",
Target: "/var/run/docker.sock",
ReadOnly: true
},
{
Type: "bind",
Source: "/proc/",
Target: "/host/proc/",
ReadOnly: true
},
{
Type: "bind",
Source: "/sys/fs/cgroup/",
Target: "/host/sys/fs/cgroup",
ReadOnly: true
},
{
Type: "bind",
Source: "/tmp",
Target: "/tmp",
ReadOnly: false
}
],
Dns: readDockerDNSSettings()
}
});
log.info("attach file-backed stream");
const stream = await cont.attach({
stream: true,
stdout: true,
stderr: true
});
stream.pipe(outstream);
log.info("container start()");
await cont.start();
// Expect a special log messaged emitted by the DD agent to confirm that time
// series fragments were successfully POSTed (2xx-acked) to the Opstrace
// cluster's DD API implementation.
// The first confirmation may either be for /series or for /check_run, see
// https://github.com/opstrace/opstrace/issues/405
const logNeedle = `Successfully posted payload to "${TENANT_DEFAULT_DD_API_BASE_URL}/api/v1`;
// It's known that this may take a while after DD agent startup.
// Note: also see https://github.com/opstrace/opstrace/issues/384
const maxWaitSeconds = 120;
const deadline = mtimeDeadlineInSeconds(maxWaitSeconds);
log.info(
"Waiting for needle to appear in container log, deadline in %s s. Needle: %s",
maxWaitSeconds,
logNeedle
);
async function terminateContainer() {
log.info("terminate container");
try {
await cont.kill({ signal: "SIGTERM" });
} catch (err: any) {
log.warning("could not kill container: %s", err.message);
}
log.info("wait for container to stop");
try {
await cont.wait();
} catch (err: any) {
log.warning("error waiting for container: %s", err.message);
}
log.info("force-remove container");
try {
await cont.remove({ force: true });
} catch (err: any) {
log.warning("could not remove container: %s", err.message);
}
log.info(
"log output emitted by container (stdout/err from %s):\n%s",
outerrfilePath,
fs.readFileSync(outerrfilePath, {
encoding: "utf-8"
})
);
}
while (true) {
if (mtime() > deadline) {
log.info("deadline hit");
await terminateContainer();
throw new Error(
"DD agent container setup failed: deadline hit waiting for log needle"
);
}
const fileHeadBytes = await readFirstNBytes(outerrfilePath, 10 ** 5);
if (fileHeadBytes.includes(Buffer.from(logNeedle, "utf-8"))) {
log.info("log needle found in container log, proceed");
break;
}
await sleep(0.2);
}
return terminateContainer;
}
suite("DD API test suite", function () {
suiteSetup(async function () {
log.info("suite setup");
globalTestSuiteSetupOnce();
});
suiteTeardown(async function () {
// Note: this does not seem to be run upon Node shutdown, e.g. triggered
// with SIGINT. Make cleanup better.
log.info("suite teardown");
});
test("dd_api_insert_single_ts_fragment", async function () {
const rndstr = rndstring(5);
const metricname = `opstrace.dd.test-remote-${rndstr}`;
const metricnameSanitized = `opstrace_dd_test_remote_${rndstr}`;
const now = ZonedDateTime.now();
const tsnow = now.toEpochSecond();
const payload = {
series: [
{
metric: metricname,
// Note: these samples are descending in time, which is
// the order that the DD agent sends fragments with. This order
// is currently strictly required by the receiving end.
points: [
[tsnow, 2],
[tsnow - 120, 1],
[tsnow - 240, 0]
],
tags: ["version:7.24.1", "testtag:testvalue"],
host: "somehost",
type: "rate",
interval: 5
}
]
};
log.info("POST body doc:\n%s", JSON.stringify(payload, null, 2));
const payloadBytes = Buffer.from(JSON.stringify(payload), "utf-8");
const headers = {
"Content-Type": "application/json"
};
const response = await got.post(ddApiSeriesUrl(), {
body: payloadBytes,
throwHttpErrors: false,
headers: headers,
timeout: httpTimeoutSettings,
https: { rejectUnauthorized: false }
});
logHTTPResponse(response);
// now query cortex
const searchStart = now.minusMinutes(45);
const searchEnd = now.plusMinutes(10);
const queryParams = {
query: `${metricnameSanitized}{job="ddagent"}`,
start: searchStart.toEpochSecond().toString(),
end: searchEnd.toEpochSecond().toString(),
step: "60s"
};
const resultArray = await waitForCortexMetricResult(
TENANT_DEFAULT_CORTEX_API_BASE_URL,
queryParams,
"query_range"
);
log.info("resultArray: %s", JSON.stringify(resultArray, null, 2));
// Check that all three values in the original submit request are
// covered by the query response.
const valuesSeen = resultArray[0].values.map(
(sample: Array<[number, string]>) => sample[1]
);
log.info("values seen: %s", valuesSeen);
for (const v of ["0", "1", "2"]) {
log.info("check for presence of value %s", v);
assert(valuesSeen.includes(v));
}
// pragmatic criterion for starters: expect a number of values. with the
// 1-second step size there should be tens or hundreds of values/samples.
assert.strictEqual(resultArray[0]["values"].length > 5, true);
});
test("dd_api_run_agent_container_query_sysuptime", async function () {
const now = ZonedDateTime.now();
// The DD agent container is currently configured to send metrics to the DD
// API endpoint for the 'default' tenant.
const terminateContainer = await startDDagentContainer();
// Wait for some more samples to be pushed. Terminate container before
// starting the query phase, so that the termination happens more or less
// reliably (regardless of errors during query phase).
await sleep(15);
await terminateContainer();
const searchStart = now.minusMinutes(45);
const searchEnd = now.plusMinutes(10);
// Note that this current setup does not insert a unique metric stream,
// i.e. if the test passes it does only guarantee that the insertion
// succeeded when the cluster is fresh (when this test was not run before,
// against the same cluster). TODO: think about how to set a unique label
// here.
const queryParams = {
// This implicitly tests for two labels to be set by the translation
// layer. Change with care!
query: `system_uptime{job="ddagent", type="gauge"}`,
start: searchStart.toEpochSecond().toString(),
end: searchEnd.toEpochSecond().toString(),
step: "60s"
};
const resultArray = await waitForCortexMetricResult(
TENANT_DEFAULT_CORTEX_API_BASE_URL,
queryParams,
"query_range"
);
log.info("resultArray: %s", JSON.stringify(resultArray, null, 2));
assert(resultArray[0].values.length > 1);
// confirm that there is just one stream (set of labels)
assert(resultArray.length == 1);
// Expected structure:
// "metric": {
// "__name__": "system_uptime",
// "instance": "x1carb6",
// "job": "ddagent",
// "source_type_name": "System",
// "type": "gauge"
// },
assert(resultArray[0].metric.source_type_name === "System");
log.info("values seen: %s", JSON.stringify(resultArray[0].values, null, 2));
});
}); | the_stack |
import { createSpan } from "../tracing";
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { SparkConfigurationOperations } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as coreTracing from "@azure/core-tracing";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ArtifactsClientContext } from "../artifactsClientContext";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
SparkConfigurationResource,
SparkConfigurationGetSparkConfigurationsByWorkspaceNextOptionalParams,
SparkConfigurationGetSparkConfigurationsByWorkspaceOptionalParams,
SparkConfigurationGetSparkConfigurationsByWorkspaceResponse,
SparkConfigurationCreateOrUpdateSparkConfigurationOptionalParams,
SparkConfigurationCreateOrUpdateSparkConfigurationResponse,
SparkConfigurationGetSparkConfigurationOptionalParams,
SparkConfigurationGetSparkConfigurationResponse,
SparkConfigurationDeleteSparkConfigurationOptionalParams,
ArtifactRenameRequest,
SparkConfigurationRenameSparkConfigurationOptionalParams,
SparkConfigurationGetSparkConfigurationsByWorkspaceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing SparkConfigurationOperations operations. */
export class SparkConfigurationOperationsImpl
implements SparkConfigurationOperations {
private readonly client: ArtifactsClientContext;
/**
* Initialize a new instance of the class SparkConfigurationOperations class.
* @param client Reference to the service client
*/
constructor(client: ArtifactsClientContext) {
this.client = client;
}
/**
* Lists sparkconfigurations.
* @param options The options parameters.
*/
public listSparkConfigurationsByWorkspace(
options?: SparkConfigurationGetSparkConfigurationsByWorkspaceOptionalParams
): PagedAsyncIterableIterator<SparkConfigurationResource> {
const iter = this.getSparkConfigurationsByWorkspacePagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.getSparkConfigurationsByWorkspacePagingPage(options);
}
};
}
private async *getSparkConfigurationsByWorkspacePagingPage(
options?: SparkConfigurationGetSparkConfigurationsByWorkspaceOptionalParams
): AsyncIterableIterator<SparkConfigurationResource[]> {
let result = await this._getSparkConfigurationsByWorkspace(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._getSparkConfigurationsByWorkspaceNext(
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *getSparkConfigurationsByWorkspacePagingAll(
options?: SparkConfigurationGetSparkConfigurationsByWorkspaceOptionalParams
): AsyncIterableIterator<SparkConfigurationResource> {
for await (const page of this.getSparkConfigurationsByWorkspacePagingPage(
options
)) {
yield* page;
}
}
/**
* Lists sparkconfigurations.
* @param options The options parameters.
*/
private async _getSparkConfigurationsByWorkspace(
options?: SparkConfigurationGetSparkConfigurationsByWorkspaceOptionalParams
): Promise<SparkConfigurationGetSparkConfigurationsByWorkspaceResponse> {
const { span } = createSpan(
"ArtifactsClient-_getSparkConfigurationsByWorkspace",
options || {}
);
try {
const result = await this.client.sendOperationRequest(
{ options },
getSparkConfigurationsByWorkspaceOperationSpec
);
return result as SparkConfigurationGetSparkConfigurationsByWorkspaceResponse;
} catch (error) {
span.setStatus({
code: coreTracing.SpanStatusCode.UNSET,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Creates or updates a sparkconfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param sparkConfiguration SparkConfiguration resource definition.
* @param options The options parameters.
*/
async beginCreateOrUpdateSparkConfiguration(
sparkConfigurationName: string,
sparkConfiguration: SparkConfigurationResource,
options?: SparkConfigurationCreateOrUpdateSparkConfigurationOptionalParams
): Promise<
PollerLike<
PollOperationState<
SparkConfigurationCreateOrUpdateSparkConfigurationResponse
>,
SparkConfigurationCreateOrUpdateSparkConfigurationResponse
>
> {
const { span } = createSpan(
"ArtifactsClient-beginCreateOrUpdateSparkConfiguration",
options || {}
);
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<SparkConfigurationCreateOrUpdateSparkConfigurationResponse> => {
try {
const result = await this.client.sendOperationRequest(args, spec);
return result as SparkConfigurationCreateOrUpdateSparkConfigurationResponse;
} catch (error) {
span.setStatus({
code: coreTracing.SpanStatusCode.UNSET,
message: error.message
});
throw error;
} finally {
span.end();
}
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ sparkConfigurationName, sparkConfiguration, options },
createOrUpdateSparkConfigurationOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Creates or updates a sparkconfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param sparkConfiguration SparkConfiguration resource definition.
* @param options The options parameters.
*/
async beginCreateOrUpdateSparkConfigurationAndWait(
sparkConfigurationName: string,
sparkConfiguration: SparkConfigurationResource,
options?: SparkConfigurationCreateOrUpdateSparkConfigurationOptionalParams
): Promise<SparkConfigurationCreateOrUpdateSparkConfigurationResponse> {
const poller = await this.beginCreateOrUpdateSparkConfiguration(
sparkConfigurationName,
sparkConfiguration,
options
);
return poller.pollUntilDone();
}
/**
* Gets a sparkConfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param options The options parameters.
*/
async getSparkConfiguration(
sparkConfigurationName: string,
options?: SparkConfigurationGetSparkConfigurationOptionalParams
): Promise<SparkConfigurationGetSparkConfigurationResponse> {
const { span } = createSpan(
"ArtifactsClient-getSparkConfiguration",
options || {}
);
try {
const result = await this.client.sendOperationRequest(
{ sparkConfigurationName, options },
getSparkConfigurationOperationSpec
);
return result as SparkConfigurationGetSparkConfigurationResponse;
} catch (error) {
span.setStatus({
code: coreTracing.SpanStatusCode.UNSET,
message: error.message
});
throw error;
} finally {
span.end();
}
}
/**
* Deletes a sparkConfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param options The options parameters.
*/
async beginDeleteSparkConfiguration(
sparkConfigurationName: string,
options?: SparkConfigurationDeleteSparkConfigurationOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const { span } = createSpan(
"ArtifactsClient-beginDeleteSparkConfiguration",
options || {}
);
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
try {
const result = await this.client.sendOperationRequest(args, spec);
return result as void;
} catch (error) {
span.setStatus({
code: coreTracing.SpanStatusCode.UNSET,
message: error.message
});
throw error;
} finally {
span.end();
}
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ sparkConfigurationName, options },
deleteSparkConfigurationOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Deletes a sparkConfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param options The options parameters.
*/
async beginDeleteSparkConfigurationAndWait(
sparkConfigurationName: string,
options?: SparkConfigurationDeleteSparkConfigurationOptionalParams
): Promise<void> {
const poller = await this.beginDeleteSparkConfiguration(
sparkConfigurationName,
options
);
return poller.pollUntilDone();
}
/**
* Renames a sparkConfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param request proposed new name.
* @param options The options parameters.
*/
async beginRenameSparkConfiguration(
sparkConfigurationName: string,
request: ArtifactRenameRequest,
options?: SparkConfigurationRenameSparkConfigurationOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const { span } = createSpan(
"ArtifactsClient-beginRenameSparkConfiguration",
options || {}
);
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
try {
const result = await this.client.sendOperationRequest(args, spec);
return result as void;
} catch (error) {
span.setStatus({
code: coreTracing.SpanStatusCode.UNSET,
message: error.message
});
throw error;
} finally {
span.end();
}
};
const sendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
) => {
let currentRawResponse:
| coreClient.FullOperationResponse
| undefined = undefined;
const providedCallback = args.options?.onResponse;
const callback: coreClient.RawResponseCallback = (
rawResponse: coreClient.FullOperationResponse,
flatResponse: unknown
) => {
currentRawResponse = rawResponse;
providedCallback?.(rawResponse, flatResponse);
};
const updatedArgs = {
...args,
options: {
...args.options,
onResponse: callback
}
};
const flatResponse = await directSendOperation(updatedArgs, spec);
return {
flatResponse,
rawResponse: {
statusCode: currentRawResponse!.status,
body: currentRawResponse!.parsedBody,
headers: currentRawResponse!.headers.toJSON()
}
};
};
const lro = new LroImpl(
sendOperation,
{ sparkConfigurationName, request, options },
renameSparkConfigurationOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs
});
}
/**
* Renames a sparkConfiguration.
* @param sparkConfigurationName The spark Configuration name.
* @param request proposed new name.
* @param options The options parameters.
*/
async beginRenameSparkConfigurationAndWait(
sparkConfigurationName: string,
request: ArtifactRenameRequest,
options?: SparkConfigurationRenameSparkConfigurationOptionalParams
): Promise<void> {
const poller = await this.beginRenameSparkConfiguration(
sparkConfigurationName,
request,
options
);
return poller.pollUntilDone();
}
/**
* GetSparkConfigurationsByWorkspaceNext
* @param nextLink The nextLink from the previous successful call to the
* GetSparkConfigurationsByWorkspace method.
* @param options The options parameters.
*/
private async _getSparkConfigurationsByWorkspaceNext(
nextLink: string,
options?: SparkConfigurationGetSparkConfigurationsByWorkspaceNextOptionalParams
): Promise<SparkConfigurationGetSparkConfigurationsByWorkspaceNextResponse> {
const { span } = createSpan(
"ArtifactsClient-_getSparkConfigurationsByWorkspaceNext",
options || {}
);
try {
const result = await this.client.sendOperationRequest(
{ nextLink, options },
getSparkConfigurationsByWorkspaceNextOperationSpec
);
return result as SparkConfigurationGetSparkConfigurationsByWorkspaceNextResponse;
} catch (error) {
span.setStatus({
code: coreTracing.SpanStatusCode.UNSET,
message: error.message
});
throw error;
} finally {
span.end();
}
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getSparkConfigurationsByWorkspaceOperationSpec: coreClient.OperationSpec = {
path: "/sparkconfigurations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SparkConfigurationListResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateSparkConfigurationOperationSpec: coreClient.OperationSpec = {
path: "/sparkconfigurations/{sparkConfigurationName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.SparkConfigurationResource
},
201: {
bodyMapper: Mappers.SparkConfigurationResource
},
202: {
bodyMapper: Mappers.SparkConfigurationResource
},
204: {
bodyMapper: Mappers.SparkConfigurationResource
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.sparkConfiguration,
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.endpoint, Parameters.sparkConfigurationName],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const getSparkConfigurationOperationSpec: coreClient.OperationSpec = {
path: "/sparkconfigurations/{sparkConfigurationName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SparkConfigurationResource
},
304: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.endpoint, Parameters.sparkConfigurationName],
headerParameters: [Parameters.accept, Parameters.ifNoneMatch],
serializer
};
const deleteSparkConfigurationOperationSpec: coreClient.OperationSpec = {
path: "/sparkconfigurations/{sparkConfigurationName}",
httpMethod: "DELETE",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.endpoint, Parameters.sparkConfigurationName],
headerParameters: [Parameters.accept],
serializer
};
const renameSparkConfigurationOperationSpec: coreClient.OperationSpec = {
path: "/sparkconfigurations/{sparkConfigurationName}/rename",
httpMethod: "POST",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.request,
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.endpoint, Parameters.sparkConfigurationName],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getSparkConfigurationsByWorkspaceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SparkConfigurationListResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion1],
urlParameters: [Parameters.endpoint, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
* This file was automatically generated by json-schema-to-typescript.
* DO NOT MODIFY IT BY HAND. Instead, run "npm run codegen" to regenerate this file.
*/
export interface CensysIpv4Data {
p11211?: {
memcached?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
certificate?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* All server stats, formatted 'key=value key2=value2'
*/
stats?: string;
/**
* What protocol the scanner used when connecting to the server (tcp/tls/udp)
*/
connected_on?: string;
/**
* Is the server willing to use the binary protocol to communicate
*/
binary_protocol_running?: boolean;
/**
* If true, Memcached was detected on this machine.
*/
supported?: boolean;
/**
* Is SASL running on the server
*/
sasl_enabled?: boolean;
/**
* Is the server willing to use the ascii protocol to communicate
*/
ascii_protocol_running?: boolean;
/**
* Memcached version
*/
version?: string;
/**
* libevent version being used by the server
*/
libevent?: string;
/**
* Server responds to UDP
*/
responds_to_udp?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p20000?: {
dnp3?: {
status?: {
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
raw_response?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p3306?: {
mysql?: {
banner?: {
/**
* If the server allows upgrading the session to use TLS, this is the log of the handshake.
*/
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, MySQL was detected on this machine.
*/
supported?: boolean;
/**
* Optional string describing the error. Only set if there is an error.
*/
error_message?: string;
/**
* The set of capability flags the server returned in the initial HandshakePacket. Each entry corresponds to a bit being set in the flags; key names correspond to the #defines in the MySQL docs.
*/
capability_flags?: {
CLIENT_IGNORE_SPACE?: boolean;
CLIENT_RESERVED?: boolean;
CLIENT_PLUGIN_AUTH?: boolean;
CLIENT_INTERACTIVE?: boolean;
CLIENT_SECURE_CONNECTION?: boolean;
CLIENT_MULTI_RESULTS?: boolean;
CLIENT_CONNECT_ATTRS?: boolean;
CLIENT_IGNORE_SIGPIPE?: boolean;
CLIENT_TRANSACTIONS?: boolean;
CLIENT_NO_SCHEMA?: boolean;
CLIENT_LONG_FLAG?: boolean;
CLIENT_CONNECT_WITH_DB?: boolean;
CLIENT_SSL?: boolean;
CLIENT_FOUND_ROWS?: boolean;
CLIENT_COMPRESS?: boolean;
CLIENT_LOCAL_FILES?: boolean;
CLIENT_ODBC?: boolean;
CLIENT_PLUGIN_AUTH_LEN_ENC_CLIENT_DATA?: boolean;
CLIENT_LONG_PASSWORD?: boolean;
CLIENT_MULTI_STATEMENTS?: boolean;
CLIENT_SESSION_TRACK?: boolean;
CLIENT_PS_MULTI_RESULTS?: boolean;
CLIENT_PROTOCOL_41?: boolean;
CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS?: boolean;
CLIENT_DEPRECATED_EOF?: boolean;
[k: string]: unknown;
};
/**
* The set of status flags the server returned in the initial HandshakePacket. Each entry corresponds to a bit being set in the flags; key names correspond to the #defines in the MySQL docs.
*/
status_flags?: {
SERVER_STATUS_DB_DROPPED?: boolean;
SERVER_STATUS_IN_TRANS_READONLY?: boolean;
SERVER_STATUS_CURSOR_EXISTS?: boolean;
SERVER_SESSION_STATE_CHANGED?: boolean;
SERVER_QUERY_NO_INDEX_USED?: boolean;
SERVER_STATUS_IN_TRANS?: boolean;
SERVER_QUERY_NO_GOOD_INDEX_USED?: boolean;
SERVER_MORE_RESULTS_EXISTS?: boolean;
SERVER_STATUS_NO_BACKSLASH_ESCAPES?: boolean;
SERVER_PS_OUT_PARAMS?: boolean;
SERVER_STATUS_METADATA_CHANGED?: boolean;
SERVER_STATUS_AUTOCOMMIT?: boolean;
SERVER_STATUS_LAST_ROW_SENT?: boolean;
SERVER_QUERY_WAS_SLOW?: boolean;
[k: string]: unknown;
};
/**
* 8-bit unsigned integer representing the server's protocol version sent in the initial HandshakePacket from the server.
*/
protocol_version?: string;
/**
* The friendly name for the error code as defined at https://dev.mysql.com/doc/refman/8.0/en/error-messages-server.html, or UNKNOWN.
*/
error_id?: string;
/**
* Only set if there is an error returned by the server, for example if the scanner is not on the allowed hosts list.
*/
error_code?: string;
/**
* The specific server version returned in the initial HandshakePacket. Often in the form x.y.z, but not always.
*/
server_version?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p161?: {
snmp?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
certificate?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, SNMP was detected on this machine.
*/
supported?: boolean;
/**
* 1.3.6.1.2.1.1 - System Variables
*/
oid_system?: {
/**
* 1.3.6.1.2.1.1.3 - 1/100ths of sec
*/
uptime?: string;
/**
* 1.3.6.1.2.1.1.5 - Name, usually FQDN
*/
name?: string;
/**
* 1.3.6.1.2.1.1.1 - Description of entity
*/
descr?: string;
/**
* 1.3.6.1.2.1.1.2 - Vendor ID
*/
object_id?: string;
/**
* 1.3.6.1.2.1.1.4 - Contact info
*/
contact?: string;
/**
* 1.3.6.1.2.1.1.6 - Physical location
*/
location?: string;
/**
* 1.3.6.1.2.1.1.7 - Set of services offered by entity
*/
services?: {
/**
* Physical (e.g. repeaters)
*/
layer_1?: boolean;
/**
* Internet (e.g. IP gateways)
*/
layer_3?: boolean;
/**
* Datalink/subnetwork (e.g. bridges)
*/
layer_2?: boolean;
/**
* OSI layer 5
*/
layer_5?: boolean;
/**
* End-to-end (e.g. IP hosts)
*/
layer_4?: boolean;
/**
* Applications (e.g. mail relays)
*/
layer_7?: boolean;
/**
* OSI layer 6
*/
layer_6?: boolean;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* 1.3.6.1.2.1.47.1.1.1.1 - Entity Physical
*/
oid_physical?: {
/**
* 1.3.6.1.2.1.47.1.1.1.1.12 - Name of mfg
*/
manufacturer_name?: string;
/**
* 1.3.6.1.2.1.47.1.1.1.1.9 - Firmware revision string
*/
firmware_rev?: string;
/**
* 1.3.6.1.2.1.47.1.1.1.1.10 - Software revision string
*/
software_rev?: string;
/**
* 1.3.6.1.2.1.47.1.1.1.1.11 - Serial number string
*/
serial_number?: string;
/**
* 1.3.6.1.2.1.47.1.1.1.1.8 - Hardware revision string
*/
hardware_rev?: string;
/**
* 1.3.6.1.2.1.47.1.1.1.1.13 - Model name of component
*/
model_name?: string;
/**
* 1.3.6.1.2.1.47.1.1.1.1.7 - Entity name
*/
name?: string;
[k: string]: unknown;
};
/**
* 1.3.6.1.2.1.2 - Interfaces
*/
oid_interfaces?: {
/**
* 1.3.6.1.2.1.2.1 - Number of network interfaces
*/
num_interfaces?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p80?: {
http?: {
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
updated_at?: string;
p1900?: {
upnp?: {
discovery?: {
x_user_agent?: string;
usn?: string;
agent?: string;
server?: string;
ext?: string;
location?: string;
st?: string;
cache_control?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p25?: {
smtp?: {
starttls?: {
/**
* The response to the EHLO command.
*/
ehlo?: string;
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The response to the STARTTLS command.
*/
starttls?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The initial SMTP command sent by the server (e.g. "220 localhost.localdomain ESMTP Postfix (Ubuntu)\r\n"
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p2323?: {
telnet?: {
banner?: {
/**
* The server refuses to perform the listed options, see https://tools.ietf.org/html/rfc854.
*/
wont?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server requests the client to perform the listed options, see https://tools.ietf.org/html/rfc854.
*/
do?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server requests the client not perform the listed options, see https://tools.ietf.org/html/rfc854.
*/
dont?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* Indicates whether the server supports telnet.
*/
support?: boolean;
/**
* The server will perform (or is performing) the listed options, see https://tools.ietf.org/html/rfc854.
*/
will?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* The banner sent by the server after negotiating the connection options. Truncated at 8kb.
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
zdb_version?: string;
/**
* Integer value of IP address in host order
*/
ipint?: string;
p21?: {
ftp?: {
banner?: {
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The banner returned by the FTP server (zero or more lines, followed by three decimal digits and optionally a human readable command followed by a final LF, see https://tools.ietf.org/html/rfc354
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p8888?: {
http?: {
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p23?: {
telnet?: {
banner?: {
/**
* The server refuses to perform the listed options, see https://tools.ietf.org/html/rfc854.
*/
wont?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server requests the client to perform the listed options, see https://tools.ietf.org/html/rfc854.
*/
do?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server requests the client not perform the listed options, see https://tools.ietf.org/html/rfc854.
*/
dont?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* Indicates whether the server supports telnet.
*/
support?: boolean;
/**
* The server will perform (or is performing) the listed options, see https://tools.ietf.org/html/rfc854.
*/
will?: {
/**
* The friendly name of the telnet option.
*/
name?: string;
/**
* The integer value of the telnet option.
*/
value?: string;
[k: string]: unknown;
};
/**
* The banner sent by the server after negotiating the connection options. Truncated at 8kb.
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p22?: {
ssh?: {
v2?: {
/**
* See https://tools.ietf.org/html/rfc4253#section-7
*/
key_exchange?: {
curve25519_sha256_params?: {
server_public?: string;
client_public?: string;
client_private?: string;
[k: string]: unknown;
};
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* Supported options advertised by the server during key exchange algorithm negotiation. See https://tools.ietf.org/html/rfc4253#section-7
*/
support?: {
/**
* An ssh public key algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-19 for standard values.
*/
host_key_algorithms?: string;
/**
* Indicates whether a guessed key exchange packet follows, see https://tools.ietf.org/html/rfc4253#section-7.1.
*/
first_kex_follows?: boolean;
/**
* An ssh key exchange algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-15 for standard values.
*/
kex_algorithms?: string;
/**
* Server's supported settings for communications flowing from the server to the client. See https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml
*/
server_to_client?: {
/**
* A name-list of language tags in order of preference.
*/
languages?: string;
/**
* An ssh cipher algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-16 for standard values.
*/
ciphers?: string;
/**
* An ssh MAC algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-18 for standard values.
*/
macs?: string;
/**
* An ssh compression algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-20 for standard values.
*/
compressions?: string;
[k: string]: unknown;
};
/**
* Server's supported settings for communications flowing from the client to the server. See https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml
*/
client_to_server?: {
/**
* A name-list of language tags in order of preference.
*/
languages?: string;
/**
* An ssh cipher algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-16 for standard values.
*/
ciphers?: string;
/**
* An ssh MAC algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-18 for standard values.
*/
macs?: string;
/**
* An ssh compression algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-20 for standard values.
*/
compressions?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
selected?: {
/**
* The selected host key algorithm
*/
host_key_algorithm?: string;
/**
* The selected key exchange algorithm
*/
kex_algorithm?: string;
server_to_client?: {
/**
* An ssh MAC algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-18 for standard values.
*/
mac?: string;
/**
* An ssh cipher algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-16 for standard values.
*/
cipher?: string;
/**
* An ssh compression algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-20 for standard values.
*/
compression?: string;
[k: string]: unknown;
};
client_to_server?: {
/**
* An ssh MAC algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-18 for standard values.
*/
mac?: string;
/**
* An ssh cipher algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-16 for standard values.
*/
cipher?: string;
/**
* An ssh compression algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-20 for standard values.
*/
compression?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
server_host_key?: {
/**
* The server host key algorithm.
*/
key_algorithm?: string;
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_public_key?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
/**
* The SHA2-256 digest calculated over the encoded key (algorithm + key data)
*/
fingerprint_sha256?: string;
ed25519_public_key?: {
public_bytes?: string;
[k: string]: unknown;
};
/**
* OpenSSH certificate for host key, see https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.certkeys?rev=1.8
*/
certkey_public_key?: {
nonce?: string;
/**
* The hostnames for which this key is valid (empty string=any).
*/
valid_principals?: string;
reserved?: string;
/**
* The OpenSSH certificate signature generated using the signature_key.
*/
signature?: {
value?: string;
signature_algorithm?: {
/**
* An ssh public key algorithm identifier, named according to section 6 of https://www.ietf.org/rfc/rfc4251.txt; see https://www.iana.org/assignments/ssh-parameters/ssh-parameters.xhtml#ssh-parameters-19 for standard values.
*/
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Critical OpenSSL certificate options.
*/
critical_options?: {
/**
* A list of any unrecognized critical options in the form "replaced_option_name: option_value", where replaced_option_name is the option name with any hyphens replaced by underscores.
*/
unknown?: string;
/**
* True if and only if the force-command extension is present.
*/
force_command?: boolean;
/**
* True if and only if the source-address extension is present.
*/
source_address?: boolean;
[k: string]: unknown;
};
validity?: {
/**
* The length of time, in seconds, that the certificate is valid.
*/
length?: string;
/**
* Timestamp of when certificate expires. Timezone is UTC.
*/
valid_before?: string;
/**
* Timestamp of when certificate is first valid. Timezone is UTC.
*/
valid_after?: string;
[k: string]: unknown;
};
/**
* The CA key used to sign this certificate.
*/
signature_key?: {
/**
* CA key algorithm.
*/
key_algorithm?: string;
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_public_key?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
/**
* SHA2-256 digest calculated over the CA key algorithm identifier + raw CA key data.
*/
fingerprint_sha256?: string;
ed25519_public_key?: {
public_bytes?: string;
[k: string]: unknown;
};
/**
* The public portion of an ECDSA asymmetric key.
*/
ecdsa_public_key?: {
b?: string;
curve?: string;
gy?: string;
n?: string;
p?: string;
length?: string;
pub?: string;
y?: string;
x?: string;
gx?: string;
[k: string]: unknown;
};
/**
* The public portion of a DSA asymmetric key.
*/
dsa_public_key?: {
q?: string;
p?: string;
y?: string;
g?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Non-critical OpenSSH certificate extensions.
*/
extensions?: {
/**
* True if and only if the permit-X11-forwarding extension is present.
*/
permit_X11_forwarding?: boolean;
/**
* True if and only if the permit-port-forwarding extension is present.
*/
permit_port_forwarding?: boolean;
/**
* A list of any unrecognized extensions in the form "replaced_extension_name: extension_value", where replaced_extension_name is the extension name with any hyphens replaced by underscores.
*/
unknown?: string;
/**
* True if and only if the permit-pty extension is present.
*/
permit_pty?: boolean;
/**
* True if and only if the permit-user-rc extension is present.
*/
permit_user_rc?: boolean;
/**
* True if and only if the permit-agent-forwarding extension is present.
*/
permit_agent_forwarding?: boolean;
[k: string]: unknown;
};
key?: {
key_algorithm?: string;
algorithm?: string;
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_public_key?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
fingerprint_sha256?: string;
raw?: string;
ed25519_public_key?: {
public_bytes?: string;
[k: string]: unknown;
};
/**
* The public portion of an ECDSA asymmetric key.
*/
ecdsa_public_key?: {
b?: string;
curve?: string;
gy?: string;
n?: string;
p?: string;
length?: string;
pub?: string;
y?: string;
x?: string;
gx?: string;
[k: string]: unknown;
};
/**
* The public portion of a DSA asymmetric key.
*/
dsa_public_key?: {
q?: string;
p?: string;
y?: string;
g?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Free-form text field set by the CA during issuance; used to identify the principal in log messages.
*/
key_id?: string;
/**
* If present, a description of the error parsing the certificate.
*/
parse_error?: string;
/**
* Certificate serial number (decimal encoded 64-bit integer).
*/
serial?: string;
[k: string]: unknown;
};
/**
* The public portion of an ECDSA asymmetric key.
*/
ecdsa_public_key?: {
b?: string;
curve?: string;
gy?: string;
n?: string;
p?: string;
length?: string;
pub?: string;
y?: string;
x?: string;
gx?: string;
[k: string]: unknown;
};
/**
* The public portion of a DSA asymmetric key.
*/
dsa_public_key?: {
q?: string;
p?: string;
y?: string;
g?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The server endpoint ID.
*/
banner?: {
comment?: string;
raw?: string;
version?: string;
software?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p27017?: {
mongodb?: {
banner?: {
/**
* Result of issuing the isMaster command see https://docs.mongodb.com/manual/reference/command/isMaster
*/
is_master?: {
/**
* Indicates whether the server is running in read-only mode.
*/
read_only?: boolean;
/**
* The earliest version of the wire protocol that this server can use.
*/
min_wire_version?: string;
/**
* The latest version of the wire protocol that this server can use.
*/
max_wire_version?: string;
/**
* The time in minutes that a session remains active after its most recent use
*/
logical_session_timeout_minutes?: string;
/**
* Indicates if this node is writable.
*/
is_master?: boolean;
/**
* The maximum number of writes in a single write batch.
*/
max_write_batch_size?: string;
/**
* The maximum size (in bytes) of a BSON wire protocol message.
*/
max_message_size_bytes?: string;
/**
* The maximum size (in bytes) of a BSON object.
*/
max_bson_object_size?: string;
[k: string]: unknown;
};
/**
* If true, MongoDB was detected on this machine.
*/
supported?: boolean;
/**
* Result of issuing the buildInfo command see https://docs.mongodb.com/manual/reference/command/buildInfo
*/
build_info?: {
/**
* DEPRECATED.
*/
max_wire_version?: string;
/**
* Version of mongodb server
*/
version?: string;
/**
* Git Version of mongodb server
*/
git_version?: string;
/**
* Various debugging information about the build environment.
*/
build_environment?: {
/**
* The buildEnvironment.linkflags field.
*/
link_flags?: string;
/**
* The buildEnvironment.ccflags field.
*/
cc_flags?: string;
/**
* The buildEnvironment.distmod field.
*/
dist_mod?: string;
/**
* The buildEnvironment.cc field.
*/
cc?: string;
/**
* The buildEnvironment.cxxflags field.
*/
cxx_flags?: string;
/**
* The buildEnvironment.cxx field.
*/
cxx?: string;
/**
* The buildEnvironment.distarch field.
*/
dist_arch?: string;
/**
* The buildEnvironment.target_arch field.
*/
target_arch?: string;
/**
* The buildEnvironment.target_os field.
*/
target_os?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
autonomous_system?: {
/**
* The friendly name of the autonomous system.
*/
name?: string;
/**
* DEPRECATED.
*/
rir?: string;
/**
* The autonomous system's CIDR.
*/
routed_prefix?: string;
/**
* The autonomous system's two-letter ISO 3166-1 alpha-2 country code (US, CN, GB, RU, ...).
*/
country_code?: string;
/**
* The name of the organization managning the autonomous system.
*/
organization?: string;
/**
* The ASNs of the autonomous systems between a fixed starting point and the host.
*/
path?: string;
/**
* The ASN (autonomous system number) of the host's autonomous system.
*/
asn?: string;
/**
* Brief description of the autonomous system.
*/
description?: string;
[k: string]: unknown;
};
p8883?: {
mqtt?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, MQTT was detected on this machine.
*/
supported?: boolean;
/**
* Raw CONNACK response packet
*/
raw_conn_ack?: string;
connack?: {
/**
* Raw connect status value
*/
raw?: string;
/**
* Connection status
*/
connect_return?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5903?: {
vnc?: {
banner?: {
/**
* If server terminates handshake, the reason offered (if any)
*/
connection_fail_reason?: string;
screen?: {
framebuffer_width?: string;
server_pixel_format?: {
/**
* If false, color maps are used
*/
true_color_flag?: string;
/**
* Max value of red pixel
*/
red_max?: string;
/**
* Max value of blue pixel
*/
blue_max?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
blue_shift?: string;
padding_byte_3?: string;
padding_byte_2?: string;
padding_byte_1?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
red_shift?: string;
/**
* Color depth
*/
depth?: string;
/**
* How many bits in a single full pixel datum. Valid values are: 8, 16, 32
*/
bits_per_pixel?: string;
/**
* If pixel RGB data are in big-endian
*/
big_endian_flag?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
green_shift?: string;
/**
* Max value of green pixel
*/
green_max?: string;
[k: string]: unknown;
};
/**
* Server advertised desktop name length
*/
desktop_name_len?: string;
framebuffer_height?: string;
[k: string]: unknown;
};
/**
* If true, VNC was detected on this machine.
*/
supported?: boolean;
pixel_encoding?: {
/**
* server-preferred pixel encoding
*/
name?: string;
/**
* binary value of server-preferred pixel encoding
*/
value?: string;
[k: string]: unknown;
};
framebuffer_grab_stats?: {
/**
* Number of pixel bytes received
*/
bytes_received?: string;
/**
* True if a framebuffer grab was saved
*/
framebuffer_saved?: boolean;
/**
* Full frames received. Currently capped at 1
*/
full_frames_received?: string;
/**
* Number of rects sent to re-assemble for one full frame
*/
rects_received?: string;
[k: string]: unknown;
};
security_types?: {
/**
* server-specified security option
*/
name?: string;
/**
* binary value of server-specified security option
*/
value?: string;
[k: string]: unknown;
};
server_protocol_version?: {
/**
* Full VNC Protocol Version String
*/
version_string?: string;
/**
* Version minor
*/
version_minor?: string;
/**
* Version major
*/
version_major?: string;
[k: string]: unknown;
};
/**
* Desktop name provided by the server, capped at 255 bytes
*/
desktop_name?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5902?: {
vnc?: {
banner?: {
/**
* If server terminates handshake, the reason offered (if any)
*/
connection_fail_reason?: string;
screen?: {
framebuffer_width?: string;
server_pixel_format?: {
/**
* If false, color maps are used
*/
true_color_flag?: string;
/**
* Max value of red pixel
*/
red_max?: string;
/**
* Max value of blue pixel
*/
blue_max?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
blue_shift?: string;
padding_byte_3?: string;
padding_byte_2?: string;
padding_byte_1?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
red_shift?: string;
/**
* Color depth
*/
depth?: string;
/**
* How many bits in a single full pixel datum. Valid values are: 8, 16, 32
*/
bits_per_pixel?: string;
/**
* If pixel RGB data are in big-endian
*/
big_endian_flag?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
green_shift?: string;
/**
* Max value of green pixel
*/
green_max?: string;
[k: string]: unknown;
};
/**
* Server advertised desktop name length
*/
desktop_name_len?: string;
framebuffer_height?: string;
[k: string]: unknown;
};
/**
* If true, VNC was detected on this machine.
*/
supported?: boolean;
pixel_encoding?: {
/**
* server-preferred pixel encoding
*/
name?: string;
/**
* binary value of server-preferred pixel encoding
*/
value?: string;
[k: string]: unknown;
};
framebuffer_grab_stats?: {
/**
* Number of pixel bytes received
*/
bytes_received?: string;
/**
* True if a framebuffer grab was saved
*/
framebuffer_saved?: boolean;
/**
* Full frames received. Currently capped at 1
*/
full_frames_received?: string;
/**
* Number of rects sent to re-assemble for one full frame
*/
rects_received?: string;
[k: string]: unknown;
};
security_types?: {
/**
* server-specified security option
*/
name?: string;
/**
* binary value of server-specified security option
*/
value?: string;
[k: string]: unknown;
};
server_protocol_version?: {
/**
* Full VNC Protocol Version String
*/
version_string?: string;
/**
* Version minor
*/
version_minor?: string;
/**
* Version major
*/
version_major?: string;
[k: string]: unknown;
};
/**
* Desktop name provided by the server, capped at 255 bytes
*/
desktop_name?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5901?: {
vnc?: {
banner?: {
/**
* If server terminates handshake, the reason offered (if any)
*/
connection_fail_reason?: string;
screen?: {
framebuffer_width?: string;
server_pixel_format?: {
/**
* If false, color maps are used
*/
true_color_flag?: string;
/**
* Max value of red pixel
*/
red_max?: string;
/**
* Max value of blue pixel
*/
blue_max?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
blue_shift?: string;
padding_byte_3?: string;
padding_byte_2?: string;
padding_byte_1?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
red_shift?: string;
/**
* Color depth
*/
depth?: string;
/**
* How many bits in a single full pixel datum. Valid values are: 8, 16, 32
*/
bits_per_pixel?: string;
/**
* If pixel RGB data are in big-endian
*/
big_endian_flag?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
green_shift?: string;
/**
* Max value of green pixel
*/
green_max?: string;
[k: string]: unknown;
};
/**
* Server advertised desktop name length
*/
desktop_name_len?: string;
framebuffer_height?: string;
[k: string]: unknown;
};
/**
* If true, VNC was detected on this machine.
*/
supported?: boolean;
pixel_encoding?: {
/**
* server-preferred pixel encoding
*/
name?: string;
/**
* binary value of server-preferred pixel encoding
*/
value?: string;
[k: string]: unknown;
};
framebuffer_grab_stats?: {
/**
* Number of pixel bytes received
*/
bytes_received?: string;
/**
* True if a framebuffer grab was saved
*/
framebuffer_saved?: boolean;
/**
* Full frames received. Currently capped at 1
*/
full_frames_received?: string;
/**
* Number of rects sent to re-assemble for one full frame
*/
rects_received?: string;
[k: string]: unknown;
};
security_types?: {
/**
* server-specified security option
*/
name?: string;
/**
* binary value of server-specified security option
*/
value?: string;
[k: string]: unknown;
};
server_protocol_version?: {
/**
* Full VNC Protocol Version String
*/
version_string?: string;
/**
* Version minor
*/
version_minor?: string;
/**
* Version major
*/
version_major?: string;
[k: string]: unknown;
};
/**
* Desktop name provided by the server, capped at 255 bytes
*/
desktop_name?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5900?: {
vnc?: {
banner?: {
/**
* If server terminates handshake, the reason offered (if any)
*/
connection_fail_reason?: string;
screen?: {
framebuffer_width?: string;
server_pixel_format?: {
/**
* If false, color maps are used
*/
true_color_flag?: string;
/**
* Max value of red pixel
*/
red_max?: string;
/**
* Max value of blue pixel
*/
blue_max?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
blue_shift?: string;
padding_byte_3?: string;
padding_byte_2?: string;
padding_byte_1?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
red_shift?: string;
/**
* Color depth
*/
depth?: string;
/**
* How many bits in a single full pixel datum. Valid values are: 8, 16, 32
*/
bits_per_pixel?: string;
/**
* If pixel RGB data are in big-endian
*/
big_endian_flag?: string;
/**
* how many bits to right shift a pixel datum to get red bits in lsb
*/
green_shift?: string;
/**
* Max value of green pixel
*/
green_max?: string;
[k: string]: unknown;
};
/**
* Server advertised desktop name length
*/
desktop_name_len?: string;
framebuffer_height?: string;
[k: string]: unknown;
};
/**
* If true, VNC was detected on this machine.
*/
supported?: boolean;
pixel_encoding?: {
/**
* server-preferred pixel encoding
*/
name?: string;
/**
* binary value of server-preferred pixel encoding
*/
value?: string;
[k: string]: unknown;
};
framebuffer_grab_stats?: {
/**
* Number of pixel bytes received
*/
bytes_received?: string;
/**
* True if a framebuffer grab was saved
*/
framebuffer_saved?: boolean;
/**
* Full frames received. Currently capped at 1
*/
full_frames_received?: string;
/**
* Number of rects sent to re-assemble for one full frame
*/
rects_received?: string;
[k: string]: unknown;
};
security_types?: {
/**
* server-specified security option
*/
name?: string;
/**
* binary value of server-specified security option
*/
value?: string;
[k: string]: unknown;
};
server_protocol_version?: {
/**
* Full VNC Protocol Version String
*/
version_string?: string;
/**
* Version minor
*/
version_minor?: string;
/**
* Version major
*/
version_major?: string;
[k: string]: unknown;
};
/**
* Desktop name provided by the server, capped at 255 bytes
*/
desktop_name?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p1521?: {
oracle?: {
/**
* The log of the Oracle / TDS handshake process.
*/
banner?: {
/**
* The TLS handshake with the server (if applicable).
*/
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The data from the Refuse packet returned by the server; it is empty if the server does not return a Refuse packet.
*/
refuse_error_raw?: string;
/**
* The protocol version number from the Accept packet.
*/
accept_version?: string;
/**
* The parsed connect descriptor returned by the server in the redirect packet, if one is sent. Otherwise, omitted. The parsed descriptor is a list of objects with key and value, where the keys strings like 'DESCRIPTION.CONNECT_DATA.SERVICE_NAME'.
*/
redirect_target?: {
/**
* The descriptor value.
*/
value?: string;
/**
* The dot-separated path to the descriptor
*/
key?: string;
[k: string]: unknown;
};
/**
* The 'SysReason' returned by the server in the RefusePacket, as an 8-bit unsigned hex string. Omitted if the server did not send a Refuse packet.
*/
refuse_reason_sys?: string;
/**
* The parsed DESCRIPTION.VSNNUM field from the RefuseError descriptor returned by the server in the Refuse packet, in dotted-decimal format.
*/
refuse_version?: string;
/**
* If true, Oracle was detected on this machine.
*/
supported?: boolean;
/**
* A map from the native Service Negotation service names to the ReleaseVersion (in dotted-decimal format) in that service packet.
*/
nsn_service_versions?: {
DataIntegrity?: string;
Encryption?: string;
Authentication?: string;
Supervisor?: string;
[k: string]: unknown;
};
/**
* Set of flags that the server returns in the Accept packet.
*/
global_service_options?: {
HEADER_CHECKSUM?: boolean;
HALF_DUPLEX?: boolean;
UNKNOWN_0001?: boolean;
PACKET_CHECKSUM?: boolean;
CAN_SEND_ATTENTION?: boolean;
FULL_DUPLEX?: boolean;
ATTENTION_PROCESSING?: boolean;
UNKNOWN_0040?: boolean;
UNKNOWN_0100?: boolean;
UNKNOWN_0080?: boolean;
UNKNOWN_0020?: boolean;
BROKEN_CONNECT_NOTIFY?: boolean;
CAN_RECEIVE_ATTENTION?: boolean;
DIRECT_IO?: boolean;
[k: string]: unknown;
};
/**
* True if the server sent a Resend packet request in response to the client's first Connect packet.
*/
did_resend?: boolean;
/**
* The parsed descriptor returned by the server in the Refuse packet; it is empty if the server does not return a Refuse packet. The keys are strings like 'DESCRIPTION.ERROR_STACK.ERROR.CODE'.
*/
refuse_error?: {
/**
* The descriptor value.
*/
value?: string;
/**
* The dot-separated path to the descriptor
*/
key?: string;
[k: string]: unknown;
};
/**
* The 'AppReason' returned by the server in the RefusePacket, as an 8-bit unsigned hex string. Omitted if the server did not send a Refuse packet.
*/
refuse_reason_app?: string;
/**
* The connect descriptor returned by the server in the Redirect packet, if one is sent. Otherwise, omitted.
*/
redirect_target_raw?: string;
/**
* The ReleaseVersion string (in dotted-decimal format) in the root of the Native Service Negotiation packet.
*/
nsn_version?: string;
/**
* The first set of ConnectFlags returned in the Accept packet.
*/
connect_flags0?: {
INTERCHANGE_INVOLVED?: boolean;
SERVICES_WANTED?: boolean;
SERVICES_ENABLED?: boolean;
SERVICES_LINKED_IN?: boolean;
SERVICES_REQUIRED?: boolean;
UNKNOWN_40?: boolean;
UNKNOWN_20?: boolean;
UNKNOWN_80?: boolean;
[k: string]: unknown;
};
/**
* The second set of ConnectFlags returned in the Accept packet.
*/
connect_flags1?: {
INTERCHANGE_INVOLVED?: boolean;
SERVICES_WANTED?: boolean;
SERVICES_ENABLED?: boolean;
SERVICES_LINKED_IN?: boolean;
SERVICES_REQUIRED?: boolean;
UNKNOWN_40?: boolean;
UNKNOWN_20?: boolean;
UNKNOWN_80?: boolean;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p3389?: {
rdp?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
selected_security_protocol?: {
tls?: boolean;
/**
* Set for both error and success. 0 = PROTOCOL_RDP.
*/
raw_value?: string;
rdstls?: boolean;
standard_rdp?: boolean;
error_hybrid_required?: boolean;
credssp_early_auth?: boolean;
error_bad_flags?: boolean;
error_ssl_forbidden?: boolean;
error_ssl_cert_missing?: boolean;
credssp?: boolean;
error_ssl_user_auth_required?: boolean;
error?: boolean;
error_ssl_required?: boolean;
error_unknown?: boolean;
[k: string]: unknown;
};
connect_response?: {
connect_id?: string;
domain_parameters?: {
max_mcspdu_size?: string;
max_user_id_channels?: string;
min_octets_per_second?: string;
domain_protocol_ver?: string;
tcs_per_mcs?: string;
max_token_ids?: string;
max_provider_height?: string;
max_channel_ids?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, RDP was detected on this machine.
*/
supported?: boolean;
version?: {
raw_value?: string;
major?: string;
minor?: string;
[k: string]: unknown;
};
protocol_supported_flags?: {
dynvc_graphics_pipeline?: boolean;
neg_resp_reserved?: boolean;
redirected_auth_mode?: boolean;
restricted_admin_mode?: boolean;
extended_client_data_supported?: boolean;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p623?: {
ipmi?: {
/**
* The IPMI scan response. All section numbers refer to https://www.intel.com/content/dam/www/public/us/en/documents/product-briefs/ipmi-second-gen-interface-spec-v2-rev1-1.pdf.
*/
banner?: {
/**
* The RMCP header of the response, (section 13.1.3)
*/
rmcp_header?: {
/**
* The version. This scanner supports version 6.
*/
version?: string;
/**
* Reserved for future use. 0 for version 6.
*/
reserved?: string;
/**
* The class of the message
*/
message_class?: {
/**
* True if the message is an acknowledgment to a previous message, omitted otherwise
*/
is_ack?: boolean;
/**
* The raw message class byte.
*/
raw?: string;
/**
* Reserved. Omitted if 0.
*/
reserved?: string;
/**
* Just the class part of the byte (lower 5 bits of raw)
*/
class?: string;
/**
* The human-readable name of the message class
*/
name?: string;
[k: string]: unknown;
};
/**
* Sequence number of this packet in the session.
*/
sequence_number?: string;
[k: string]: unknown;
};
/**
* If true, IPMI was detected on this machine.
*/
supported?: boolean;
/**
* The Get Channel Authentication Capabilities response (section 22.13)
*/
capabilities?: {
/**
* The status code of the response
*/
completion_code?: {
/**
* The raw completion code
*/
raw?: string;
/**
* The human-readable name of the code
*/
name?: string;
[k: string]: unknown;
};
/**
* The auth types supported by the server
*/
supported_auth_types?: {
/**
* True if the OEM Proprietary AuthType is supported. Omitted otherwise.
*/
oem_proprietary?: boolean;
/**
* True if the None AuthType is supported. Omitted otherwise.
*/
none?: boolean;
/**
* True if the Extended authentication is supported. Omitted otherwise.
*/
extended?: boolean;
/**
* The reserved bits. Omitted if zero.
*/
reserved?: string;
/**
* The raw byte, with the bit mask etc
*/
raw?: string;
/**
* True if the MD2 AuthType is supported. Omitted otherwise.
*/
md2?: boolean;
/**
* True if the Password AuthType is supported. Omitted otherwise.
*/
password?: boolean;
/**
* True if the MD5 AuthType is supported. Omitted otherwise.
*/
md5?: boolean;
[k: string]: unknown;
};
/**
* The OEM-specific data
*/
oem_data?: string;
/**
* The response channel number
*/
channel_number?: string;
/**
* The 3-byte OEM identifier
*/
oem_id?: string;
/**
* Extended auth capabilities (if present)
*/
extended_capabilities?: {
/**
* True if IPMI v1.5 is supported
*/
supports_ipmi_v1_5?: boolean;
/**
* Reserved. Omitted if 0.
*/
reserved?: string;
/**
* True if IPMI v2.0 is supported
*/
supports_ipmi_v2_0?: boolean;
[k: string]: unknown;
};
/**
* The authentication status
*/
auth_status?: {
/**
* If true, the server allows anonymous login. Otherwise omitted.
*/
anonymous_login_enabled?: boolean;
/**
* If true, the server has anonymous users. Otherwise omitted.
*/
has_anonymous_users?: boolean;
/**
* If true, each message must be authenticated. Otherwise omitted.
*/
auth_each_message?: boolean;
/**
* Reserved. Omitted if zero.
*/
reserved?: string;
/**
* The KG field. true if present, otherwise omitted.
*/
two_key_login_required?: boolean;
/**
* If true, user authentication is disabled. Otherwise omitted.
*/
user_auth_disabled?: boolean;
/**
* If true, the server supports named users. Otherwise omitted.
*/
has_named_users?: boolean;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The raw data returned by the server
*/
raw?: string;
/**
* The IPMI sesssion header of the response
*/
ipmi_header?: {
/**
* The authentication type for this request (see section 13.6)
*/
auth_type?: {
/**
* The raw value of the auth_type
*/
raw?: string;
/**
* Reserved. Omitted if zero.
*/
reserved?: string;
/**
* The human-readable name of the auth type.
*/
name?: string;
/**
* Just the auth type (reserved bits omitted)
*/
type?: string;
[k: string]: unknown;
};
/**
* The expected length of the IPMI payload. Omitted if zero.
*/
length?: string;
/**
* The ID of this session; omitted if zero.
*/
session_id?: string;
/**
* The session sequence number of this packet in the session
*/
sequence_number?: string;
/**
* The 16-byte authentication code; not present if auth_type is None
*/
auth_code?: string;
[k: string]: unknown;
};
/**
* The IPMI command payload
*/
ipmi_payload?: {
/**
* The NetFn and LUN
*/
net_fn?: {
/**
* The raw value of the (NetFn << 2) | LUN
*/
raw?: string;
/**
* The parsed NetFn value (the upper 6 bits of raw)
*/
net_fn?: {
/**
* True if the least-significant bit is one, omitted otherwise.
*/
is_response?: boolean;
/**
* True if the least-significant bit is zero, omitted otherwise.
*/
is_request?: boolean;
/**
* The human-readable name of the NetFn
*/
name?: string;
/**
* The normalized value of the NetFn (i.e. raw & 0xfe, so it is always even)
*/
value?: string;
/**
* The raw value of the NetFn (6 bits, least significant indicates request/response)
*/
raw?: string;
[k: string]: unknown;
};
/**
* The parsed LUN (logical unit number -- the lower 2 bits of raw)
*/
lun?: {
/**
* The value of the LUN (3 bits)
*/
raw?: string;
/**
* The human-readable name of the LUN
*/
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is set to true if the values of chk1 / chk2 do not match the command data; otherwise it is omitted.
*/
checksum_error?: boolean;
/**
* The parsed IPMI command number
*/
cmd?: {
/**
* The raw value of the cmd value
*/
raw?: string;
/**
* The human-readable name of the cmd + NetFn
*/
name?: string;
[k: string]: unknown;
};
/**
* The chk1 field (chk1 = -((RsAddr + NetFn) & 0xff)
*/
chk1?: string;
/**
* The chk2 field (chk2 = -((rq_addr + rq_seq + cmd + data[:]) & 0xff)
*/
chk2?: string;
/**
* The request sequence number.
*/
rq_seq?: string;
/**
* The response address
*/
rs_addr?: {
/**
* The raw address byte (including the slave/software_id bit)
*/
raw?: string;
/**
* Indicates that the address refers to a software identifier. Set to true if the least significant bit of raw is one, otherwise absent.
*/
software_id?: boolean;
/**
* Indicates that the address refers to a slave device. Set to true if the least significant bit of raw is zero, otherwise absent.
*/
slave?: boolean;
/**
* The address, with the slave/software_id bit removed.
*/
address?: string;
[k: string]: unknown;
};
/**
* The request address
*/
rq_addr?: {
/**
* The raw address byte (including the slave/software_id bit)
*/
raw?: string;
/**
* Indicates that the address refers to a software identifier. Set to true if the least significant bit of raw is one, otherwise absent.
*/
software_id?: boolean;
/**
* Indicates that the address refers to a slave device. Set to true if the least significant bit of raw is zero, otherwise absent.
*/
slave?: boolean;
/**
* The address, with the slave/software_id bit removed.
*/
address?: string;
[k: string]: unknown;
};
/**
* The raw data. On success, this should be the value of the GetAuthenticationCapabilities resopnse.
*/
data?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p16993?: {
https?: {
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p53?: {
dns?: {
lookup?: {
errors?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
open_resolver?: boolean;
answers?: {
type?: string;
name?: string;
response?: string;
[k: string]: unknown;
};
resolves_correctly?: boolean;
additionals?: {
type?: string;
name?: string;
response?: string;
[k: string]: unknown;
};
questions?: {
type?: string;
name?: string;
[k: string]: unknown;
};
authorities?: {
type?: string;
name?: string;
response?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
location?: {
/**
* The state or province name of the detected location.
*/
province?: string;
/**
* The English name of the detected city.
*/
city?: string;
/**
* The English name of the detected country.
*/
country?: string;
/**
* The estimated longitude of the detected location.
*/
longitude?: number;
/**
* The English name of the registered country.
*/
registered_country?: string;
/**
* The registered country's two-letter ISO 3166-1 alpha-2 country code (US, CN, GB, RU, ...).
*/
registered_country_code?: string;
/**
* The postal code (if applicable) of the detected location.
*/
postal_code?: string;
/**
* The detected two-letter ISO 3166-1 alpha-2 country code (US, CN, GB, RU, ...).
*/
country_code?: string;
/**
* The estimated latitude of the detected location.
*/
latitude?: number;
/**
* The IANA time zone database name of the detected location.
*/
timezone?: string;
/**
* The English name of the detected continent (North America, Europe, Asia, South America, Africa, Oceania, Antarctica)
*/
continent?: string;
[k: string]: unknown;
};
ip?: string;
p110?: {
pop3?: {
starttls?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The response to the starttls command.
*/
starttls?: string;
/**
* The IMAP/POP3 command sent by the server immediately upon connection.
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5672?: {
amqp?: {
banner?: {
/**
* If true, AMQP was detected on this machine.
*/
supported?: boolean;
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
protocol_id?: {
/**
* Protocol ID
*/
id?: string;
/**
* Decoded protocol ID
*/
name?: string;
[k: string]: unknown;
};
version?: {
/**
* version major
*/
major?: string;
/**
* version minor
*/
minor?: string;
/**
* version revision
*/
revision?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p6443?: {
kubernetes?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
certificate?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
roles?: {
roles?: {
/**
* individual rules set for a specific role
*/
rules?: {
/**
* Verbs is a list of Verbs that apply to ALL the ResourceKinds and AttributeRestrictions contained in this rule. VerbAll represents all kinds
*/
verbs?: string;
/**
* APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed
*/
api_groups?: string;
/**
* Resources is a list of resources this rule applies to. ResourceAll represents all resources
*/
resources?: string;
[k: string]: unknown;
};
/**
* Name of a role
*/
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Information about this version of kubernetes
*/
version_info?: {
/**
* Date version was built
*/
build_date?: string;
/**
* Kubernetes major version
*/
major?: string;
/**
* Version of GO used for kubernetes
*/
go_version?: string;
git_version?: string;
/**
* Platform it was compiled for
*/
platform?: string;
/**
* Hash of git commit version is built from
*/
git_commit?: string;
/**
* State of the tree when build
*/
git_tree_state?: string;
/**
* Kubernetes minor version
*/
minor?: string;
/**
* Go Compiler user
*/
compiler?: string;
[k: string]: unknown;
};
/**
* If true, Kubernetes was detected on this machine.
*/
supported?: boolean;
/**
* True if the dashboard is running and accessible
*/
dashboard_running?: boolean;
nodes?: {
items?: {
/**
* Status of the Node
*/
status?: {
/**
* AttachedVolume describes a volume attached to a node
*/
volumes_attached?: {
/**
* DevicePath represents the device path where the volume should be available
*/
device_path?: string;
/**
* Name of the attached volume
*/
name?: string;
[k: string]: unknown;
};
/**
* NodeDaemonEndpoints lists ports opened by daemons running on the Node.
*/
daemon_endpoints?: {
/**
* Endpoint on which Kubelet is listening
*/
kubelet_endpoint?: {
/**
* port on which Kubelet is listening
*/
port?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* address reachable to the node. Queried from cloud provider, if available. More info: https://kubernetes.io/docs/concepts/nodes/node/#addresses
*/
addresses?: {
/**
* Node address type, one of Hostname, ExternalIP or InternalIP.
*/
type?: string;
/**
* the node address, IP/URL
*/
address?: string;
[k: string]: unknown;
};
/**
* General information about the node, such as kernel version, Kubernetes version (kubelet and kube-proxy version), Docker version (if used), OS name. The information is gathered by Kubelet from the node
*/
node_info?: {
/**
* kube Proxy Version
*/
kube_proxy_version?: string;
/**
* OS family running on the container
*/
operating_system?: string;
/**
* Container Software version
*/
container_runtime_version?: string;
/**
* Kernel running on the node
*/
kernel_version?: string;
/**
* Docker OS image running on the node
*/
os_image?: string;
/**
* node's architecture
*/
architecture?: string;
/**
* kubelet version
*/
kubelet_version?: string;
[k: string]: unknown;
};
/**
* List of attachable volumes in use (mounted) by the node
*/
volumes_in_use?: string;
/**
* List of container images on this node
*/
images?: {
/**
* Names by which this image is known. e.g. ['k8s.gcr.io/hyperkube:v1.0.7', 'dockerhub.io/google_containers/hyperkube:v1.0.7']
*/
names?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
*/
metadata?: {
/**
* Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: http://kubernetes.io/docs/user-guide/identifiers#names
*/
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
endpoints?: {
items?: {
subsets?: {
addresses?: {
ip?: string;
hostname?: string;
node_name?: string;
[k: string]: unknown;
};
ports?: {
protocol?: string;
name?: string;
port?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
self_link?: string;
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
pods?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p587?: {
smtp?: {
starttls?: {
/**
* The response to the EHLO command.
*/
ehlo?: string;
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The response to the STARTTLS command.
*/
starttls?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The initial SMTP command sent by the server (e.g. "220 localhost.localdomain ESMTP Postfix (Ubuntu)\r\n"
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
tags?: string;
p1911?: {
fox?: {
device_id?: {
vm_name?: string;
version?: string;
host_address?: string;
vm_version?: string;
app_name?: string;
language?: string;
os_version?: string;
auth_agent_type?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
hostname?: string;
time_zone?: string;
brand_id?: string;
os_name?: string;
vm_uuid?: string;
sys_info?: string;
host_id?: string;
station_name?: string;
app_version?: string;
id?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p1883?: {
mqtt?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, MQTT was detected on this machine.
*/
supported?: boolean;
/**
* Raw CONNACK response packet
*/
raw_conn_ack?: string;
connack?: {
/**
* Raw connect status value
*/
raw?: string;
/**
* Connection status
*/
connect_return?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5632?: {
pca?: {
banner?: {
status?: {
/**
* Full 'ST' query response
*/
st_raw?: string;
/**
* Workstation is In Use if true, Available if false
*/
in_use?: boolean;
[k: string]: unknown;
};
/**
* Workstation Name, with padding bytes removed
*/
workstation_name?: string;
/**
* If true, PCA was detected on this machine.
*/
supported?: boolean;
/**
* Full 'NR' query response
*/
nr_raw?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p1433?: {
mssql?: {
banner?: {
/**
* The TLS handshake with the server (for non-encrypted connections, this used only for the authentication phase).
*/
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, MSSQL was detected on this machine.
*/
supported?: boolean;
/**
* The negotiated encryption mode for the session. See https://msdn.microsoft.com/en-us/library/dd357559.aspx for details.
*/
encrypt_mode?: string;
/**
* The value of the INSTANCE field returned by the server in the PRELOGIN response.
*/
instance_name?: string;
/**
* The MSSQL version returned by the server in the PRELOGIN response. Its format is 'MAJOR.MINOR.BUILD_NUMBER'.
*/
version?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p8080?: {
http?: {
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p102?: {
s7?: {
/**
* Parsed response data from the Siemens S7 scan.
*/
szl?: {
/**
* The seventh string in the response to the S7_SZL_MODULE_IDENTIFICATION request.
*/
firmware?: string;
/**
* The eighth string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
memory_serial_number?: string;
/**
* The seventh string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
reserved_for_os?: string;
/**
* The fourth string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
copyright?: string;
/**
* The third string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
plant_id?: string;
/**
* Indicates that the scanner was able to successfully negotiate a Siemens S7 session with the server.
*/
support?: boolean;
/**
* The ninth string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
cpu_profile?: string;
/**
* The fifth string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
serial_number?: string;
/**
* The second string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
module?: string;
/**
* The first string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
system?: string;
/**
* The sixth string in the response to the S7_SZL_MODULE_IDENTIFICATION request.
*/
hardware?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The sixth string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
module_type?: string;
/**
* The eleventh string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
location?: string;
/**
* The tenth string in the response to the S7_SZL_COMPONENT_IDENTIFICATION request.
*/
oem_id?: string;
/**
* The first string in the response to the S7_SZL_MODULE_IDENTIFICATION request.
*/
module_id?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
protocols?: string;
p47808?: {
bacnet?: {
device_id?: {
vendor?: {
reported_name?: string;
id?: string;
official_name?: string;
[k: string]: unknown;
};
description?: string;
firmware_revision?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
instance_number?: string;
object_name?: string;
location?: string;
application_software_revision?: string;
model_name?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p6379?: {
redis?: {
banner?: {
/**
* Major is the version's major number.
*/
major?: string;
/**
* If true, Redis was detected on this machine.
*/
supported?: boolean;
/**
* The Sha-1 Git commit hash the Redis server used.
*/
git_sha1?: string;
/**
* The Build ID of the Redis server.
*/
build_id?: string;
/**
* The version of the GCC compiler used to compile the Redis server.
*/
gcc_version?: string;
/**
* The total number of bytes allocated by Redis using its allocator.
*/
used_memory?: string;
/**
* The response from the NONEXISTENT command.
*/
nonexistent_response?: string;
/**
* The version string, read from the the info_response (if available).
*/
version?: string;
/**
* The total number of commands processed by the server.
*/
total_commands_processed?: string;
/**
* The response from the INFO command. Should be a series of key:value pairs separated by CRLFs.
*/
info_response?: string;
/**
* Minor is the version's minor number.
*/
minor?: string;
/**
* The mode the Redis server is running (standalone or cluster), read from the the info_response (if available).
*/
mode?: string;
/**
* The total number of connections accepted by the server.
*/
total_connections_received?: string;
/**
* The response to the QUIT command.
*/
quit_response?: string;
/**
* The architecture bits (32 or 64) the Redis server used to build.
*/
arch_bits?: string;
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
certificate?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The memory allocator.
*/
mem_allocator?: string;
/**
* The number of seconds since Redis server start.
*/
uptime_in_seconds?: string;
/**
* The response from the PING command; should either be "PONG" or an authentication error.
*/
ping_response?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
/**
* The OS the Redis server is running, read from the the info_response (if available).
*/
os?: string;
/**
* Patchlevel is the version's patchlevel number.
*/
patchlevel?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p5432?: {
postgres?: {
banner?: {
/**
* If the server allows upgrading the session to use TLS, this is the log of the handshake.
*/
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
backend_key_data?: {
secret_key?: string;
process_id?: string;
[k: string]: unknown;
};
/**
* The error string returned by the server in response to a StartupMessage with ProtocolVersion = 0.0
*/
supported_versions?: string;
protocol_error?: {
code?: string;
severity?: string;
internal_position?: string;
constraint?: string;
routine?: string;
table?: string;
hint?: string;
internal_query?: string;
detail?: string;
where?: string;
severity_v?: string;
file?: string;
_unknown_error_tag?: string;
position?: string;
line?: string;
data?: string;
message?: string;
schema?: string;
[k: string]: unknown;
};
/**
* If the server supports TLS and the session was updated to use TLS, this is true.
*/
is_ssl?: boolean;
/**
* If true, PostgreSQL was detected on this machine.
*/
supported?: boolean;
startup_error?: {
code?: string;
severity?: string;
internal_position?: string;
constraint?: string;
routine?: string;
table?: string;
hint?: string;
internal_query?: string;
detail?: string;
where?: string;
severity_v?: string;
file?: string;
_unknown_error_tag?: string;
position?: string;
line?: string;
data?: string;
message?: string;
schema?: string;
[k: string]: unknown;
};
authentication_mode?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
notes?: string;
p502?: {
modbus?: {
device_id?: {
/**
* Requested function type; see http://www.modbus.org/docs/Modbus_Application_Protocol_V1_1b.pdf
*/
function_code?: string;
/**
* Indicates whether the server supports modbus.
*/
support?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* See http://www.modbus.org/docs/Modbus_Application_Protocol_V1_1b.pdf
*/
mei_response?: {
objects?: {
user_application_name?: string;
/**
* Mandatory ASCII string on all objects. Names the vendor.
*/
vendor?: string;
product_name?: string;
product_code?: string;
model_name?: string;
vendor_url?: string;
revision?: string;
[k: string]: unknown;
};
/**
* Identification conformity level of the device and type of supported access
*/
conformity_level?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
product?: string;
description?: string;
revision?: string;
os_version?: string;
version?: string;
device_type?: string;
manufacturer?: string;
os?: string;
os_description?: string;
[k: string]: unknown;
};
p7547?: {
cwmp?: {
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
ports?: string;
p993?: {
imaps?: {
tls?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The IMAP/POP3 command sent by the server as soon as the TLS handshake completes.
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p143?: {
imap?: {
starttls?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The response to the starttls command.
*/
starttls?: string;
/**
* The IMAP/POP3 command sent by the server immediately upon connection.
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p9200?: {
elasticsearch?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
nodes_info?: {
cluster?: {
status?: string;
timestamp?: string;
uuid?: string;
name?: string;
filesystem?: {
/**
* Human-friendly available size
*/
available?: string;
/**
* Total size in bytes
*/
total_in_bytes?: string;
/**
* Free size in bytes
*/
free_in_bytes?: string;
/**
* Human-friendly free size
*/
free?: string;
/**
* Human-friendly total size
*/
total?: string;
/**
* Available size in bytes
*/
available_in_bytes?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
nodes?: {
node_info?: {
name?: string;
roles?: string;
settings?: {
node?: {
attr?: {
ml?: {
enabled?: string;
machine_memory?: string;
max_open_jobs?: string;
[k: string]: unknown;
};
xpack?: {
installed?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
name?: string;
[k: string]: unknown;
};
cluster?: {
name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
thread_pool_list?: {
thread_name?: string;
min?: string;
max?: string;
keep_alive?: string;
queue_size?: string;
type?: string;
[k: string]: unknown;
};
ip?: string;
build_flavor?: string;
modules?: {
has_native_controller?: boolean;
description?: string;
java_version?: string;
classname?: string;
version?: string;
elasticsearch_version?: string;
extended_plugins?: string;
name?: string;
[k: string]: unknown;
};
ingest?: {
processors?: {
type?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
total_indexing_buffer?: string;
host?: string;
version?: string;
jvm?: {
vm_name?: string;
vm_version?: string;
start_time?: string;
gc_collectors?: string;
input_arguments?: string;
vm_vendor?: string;
version?: string;
memory_pools?: string;
start_time_in_millis?: string;
[k: string]: unknown;
};
build_hash?: string;
os?: {
name?: string;
pretty_name?: string;
allocated_processors?: string;
version?: string;
arch?: string;
refresh_interval_in_millis?: string;
available_processors?: string;
[k: string]: unknown;
};
build_type?: string;
[k: string]: unknown;
};
node_name?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* If true, Elasticsearch was detected on this machine.
*/
supported?: boolean;
system_info?: {
/**
* Cluster UUID
*/
cluster_uuid?: string;
/**
* Elasticsearch identifying tagline
*/
tagline?: string;
version?: {
build_date?: string;
minimum_wire_compatibility_version?: string;
build_hash?: string;
/**
* ES Cluster version
*/
number?: string;
build_type?: string;
minimum_index_compatibility_version?: string;
build_flavor?: string;
build_snapshot?: boolean;
lucene_version?: string;
[k: string]: unknown;
};
/**
* Cluster Name
*/
name?: string;
[k: string]: unknown;
};
http_info?: {
headers?: {
content_length?: string;
x_ua_compatible?: string;
via?: string;
pragma?: string;
set_cookie?: string;
x_powered_by?: string;
vary?: string;
retry_after?: string;
warning?: string;
content_language?: string;
content_location?: string;
p3p?: string;
server?: string;
proxy_authenticate?: string;
proxy_agent?: string;
upgrade?: string;
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
x_content_type_options?: string;
x_content_security_policy?: string;
www_authenticate?: string;
content_range?: string;
content_encoding?: string;
access_control_allow_origin?: string;
content_md5?: string;
content_disposition?: string;
cache_control?: string;
location?: string;
status?: string;
strict_transport_security?: string;
expires?: string;
accept_patch?: string;
last_modified?: string;
link?: string;
content_type?: string;
date?: string;
x_frame_options?: string;
x_webkit_csp?: string;
x_real_ip?: string;
alternate_protocol?: string;
accept_ranges?: string;
age?: string;
x_xss_protection?: string;
x_forwarded_for?: string;
refresh?: string;
public_key_pins?: string;
connection?: string;
x_content_duration?: string;
alt_svc?: string;
allow?: string;
referer?: string;
content_security_policy?: string;
transfer_encoding?: string;
trailer?: string;
[k: string]: unknown;
};
status_line?: string;
status_code?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p16992?: {
http?: {
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p631?: {
ipp?: {
banner?: {
/**
* If the server allows upgrading the session to use TLS, this is the log of the handshake.
*/
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The specific IPP version returned in response to an IPP get-printer-attributes request. Always in the form 'IPP/x.y'
*/
version_string?: string;
/**
* If true, IPP was detected on this machine.
*/
supported?: boolean;
/**
* Major component of IPP version listed in the Server header of a response to an IPP get-printer-attributes request.
*/
version_major?: string;
/**
* The CUPS version, if any, specified in the list of attributes returned in a get-printer-attributes response or CUPS-get-printers response. Generally in the form 'x.y.z'.
*/
attr_cups_version?: string;
/**
* Each IPP version, if any, specified in the list of attributes returned in a get-printer-attributes response or CUPS-get-printers response. Always in the form 'x.y'.
*/
attr_ipp_versions?: string;
/**
* The CUPS version, if any, specified in the Server header of an IPP get-attributes response.
*/
cups_version?: string;
/**
* Each printer URI, if any, specified in the list of attributes returned in a get-printer-attributes response or CUPS-get-printers response. Uses ipp(s) or http(s) scheme, followed by a hostname or IP, and then the path to a particular printer.
*/
attr_printer_uris?: string;
/**
* All IPP attributes included in any contentful responses obtained. Each has a name, list of values (potentially only one), and a tag denoting how the value should be interpreted.
*/
attributes?: {
tag?: string;
values?: {
memberAttrName?: string;
octetString?: string;
charset?: string;
keyword?: string;
bagCollection?: string;
rangeOfInteger?: string;
enum?: string;
uri?: string;
dateTime?: string;
raw?: string;
nameWithoutLanguage?: string;
boolean?: boolean;
endCollection?: string;
mimeMediaType?: string;
integer?: string;
naturalLanguage?: string;
textWithLanguage?: string;
resolution?: string;
uriScheme?: string;
textWithoutLanguage?: string;
nameWithLanguage?: string;
[k: string]: unknown;
};
name?: string;
[k: string]: unknown;
};
/**
* Minor component of IPP version listed in the Server header of a response to an IPP get-printer-attributes request.
*/
version_minor?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p995?: {
pop3s?: {
tls?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The IMAP/POP3 command sent by the server as soon as the TLS handshake completes.
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p445?: {
smb?: {
banner?: {
smbv1_support?: boolean;
/**
* If true, SMB was detected on this machine.
*/
supported?: boolean;
negotiation_log?: {
status?: string;
security_mode?: string;
system_time?: string;
server_start_time?: string;
protocol_id?: string;
capabilities?: string;
server_guid?: string;
credits?: string;
dialect_revision?: string;
command?: string;
authentication_types?: string;
flags?: string;
[k: string]: unknown;
};
smb_version?: {
/**
* Major version
*/
major?: string;
/**
* Full SMB Version String
*/
version_string?: string;
/**
* Minor version
*/
minor?: string;
/**
* Protocol Revision
*/
revision?: string;
[k: string]: unknown;
};
session_setup_log?: {
status?: string;
protocol_id?: string;
target_name?: string;
negotiate_flags?: string;
setup_flags?: string;
credits?: string;
command?: string;
flags?: string;
[k: string]: unknown;
};
/**
* Capabilities flags for the connection. See [MS-SMB2] Sect. 2.2.4.
*/
smb_capabilities?: {
/**
* Server supports multi-credit operations
*/
smb_multicredit_support?: boolean;
/**
* Server supports multiple channels per session
*/
smb_multchan_support?: boolean;
/**
* Server supports persistent handles
*/
smb_persistent_handle_support?: boolean;
/**
* Server supports Distributed File System
*/
smb_dfs_support?: boolean;
/**
* Server supports Leasing
*/
smb_leasing_support?: boolean;
/**
* Server supports encryption
*/
smb_encryption_support?: boolean;
/**
* Server supports directory leasing
*/
smb_directory_leasing_support?: boolean;
[k: string]: unknown;
};
has_ntlm?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p443?: {
https?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Additional certificates provided by the server.
*/
chain?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
dhe_export?: {
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* True if the host supports export-grade Diffie-Hellman in TLS handshakes.
*/
support?: boolean;
/**
* The parameters for the key.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
get?: {
/**
* The HTTP body, truncated according to configured MaxSize (default 256kb).
*/
body?: string;
/**
* HTTP response headers. Names are normalized by converting them to lowercase and replacing hyphens with underscores. When a header is returned multiple times, only the first is included. Values are truncated to 256 bytes.
*/
headers?: {
/**
* The value of the content_length header.
*/
content_length?: string;
/**
* The value of the x-ua-compatible header.
*/
x_ua_compatible?: string;
/**
* The value of the via header.
*/
via?: string;
/**
* The value of the pragma header.
*/
pragma?: string;
/**
* The value of the set_cookie header.
*/
set_cookie?: string;
/**
* The value of the x-powered-by header.
*/
x_powered_by?: string;
/**
* The value of the vary header.
*/
vary?: string;
/**
* The value of the retry_after header.
*/
retry_after?: string;
/**
* The value of the www-authenticate header.
*/
www_authenticate?: string;
/**
* The value of the warning header.
*/
warning?: string;
/**
* The value of the content_language header.
*/
content_language?: string;
/**
* The value of the content_location header.
*/
content_location?: string;
/**
* The value of the p3p header.
*/
p3p?: string;
/**
* The value of the server header.
*/
server?: string;
/**
* The value of the proxy-authenticate header.
*/
proxy_authenticate?: string;
/**
* The value of the proxy-agent header.
*/
proxy_agent?: string;
/**
* The value of the upgrade header.
*/
upgrade?: string;
/**
* Other headers are included as a list of key, value pairs.
*/
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
/**
* The value of the x-content-type-options header.
*/
x_content_type_options?: string;
/**
* The value of the x-content-security-policy header.
*/
x_content_security_policy?: string;
/**
* The value of the etag header.
*/
etag?: string;
/**
* The value of the content_range header.
*/
content_range?: string;
/**
* The value of the content_encoding header.
*/
content_encoding?: string;
/**
* The value of the access-control-allow-origin header.
*/
access_control_allow_origin?: string;
/**
* The value of the content_md5 header.
*/
content_md5?: string;
/**
* The value of the content_disposition header.
*/
content_disposition?: string;
/**
* The value of the cache_control header.
*/
cache_control?: string;
/**
* The value of the location header.
*/
location?: string;
/**
* The value of the status header.
*/
status?: string;
/**
* The value of the strict-transport-security header.
*/
strict_transport_security?: string;
/**
* The value of the expires header.
*/
expires?: string;
/**
* The value of the accept-patch header.
*/
accept_patch?: string;
/**
* The value of the last_modified header.
*/
last_modified?: string;
/**
* The value of the link header.
*/
link?: string;
/**
* The value of the content_type header.
*/
content_type?: string;
/**
* The value of the date header.
*/
date?: string;
/**
* The value of the x-frame-options header.
*/
x_frame_options?: string;
/**
* The value of the x-webkit-csp header.
*/
x_webkit_csp?: string;
/**
* The value of the x-real-ip header.
*/
x_real_ip?: string;
/**
* The value of the alternate_protocol header.
*/
alternate_protocol?: string;
/**
* The value of the accept-ranges header.
*/
accept_ranges?: string;
/**
* The value of the age header.
*/
age?: string;
/**
* The value of the x-xss-protection header.
*/
x_xss_protection?: string;
/**
* The value of the x-forwarded-for header.
*/
x_forwarded_for?: string;
/**
* The value of the refresh header.
*/
refresh?: string;
/**
* The value of the public-key-pins header.
*/
public_key_pins?: string;
/**
* The value of the connection header.
*/
connection?: string;
/**
* The value of the x-content-duration header.
*/
x_content_duration?: string;
/**
* The value of the alt-svc header.
*/
alt_svc?: string;
/**
* The value of the allow header.
*/
allow?: string;
/**
* The value of the referer header.
*/
referer?: string;
/**
* The value of the content-security-policy header.
*/
content_security_policy?: string;
/**
* The value of the transfer_encoding header.
*/
transfer_encoding?: string;
/**
* The value of the trailer header.
*/
trailer?: string;
[k: string]: unknown;
};
/**
* The HTTP status code (e.g. 200, 404, 503).
*/
status_code?: string;
/**
* The contents of the first TITLE tag in the body (stripped of any surrounding whitespace and truncated to 1024 characters).
*/
title?: string;
/**
* The full status line returned by the server (e.g. "200 OK" or "401 UNAUTHORIZED")
*/
status_line?: string;
/**
* The SHA2-256 digest of the body. NOTE: This digest is calculated using the same data returned in the body field, so if that was truncated, this will be calculated over the truncated body, rather than full data stored on the server.
*/
body_sha256?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
dhe?: {
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* True if the host supports Diffie-Hellman in TLS handshakes.
*/
support?: boolean;
/**
* The parameters for the key.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
tls_1_2?: {
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
ssl_3?: {
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
heartbleed?: {
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The server response to the Heartbeat extension
*/
heartbeat_enabled?: boolean;
/**
* Indicates if the server is vulnerable to the Heartbleed attack.
*/
heartbleed_vulnerable?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
rsa_export?: {
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* True if the host supports export-grade RSA in TLS handshakes.
*/
support?: boolean;
/**
* The parameters for the key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
ecdhe?: {
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The parameters for the key.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* True if the host supports ECDH in TLS handshakes.
*/
support?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
tls_1_1?: {
/**
* Time the scan was run.
*/
timestamp?: string;
support?: boolean;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p9090?: {
prometheus?: {
banner?: {
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
certificate?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* List of all errors encountered during scan.
*/
errors?: string;
/**
* If true, Prometheus was detected on this machine.
*/
supported?: boolean;
http_info?: {
headers?: {
content_length?: string;
x_ua_compatible?: string;
via?: string;
pragma?: string;
set_cookie?: string;
x_powered_by?: string;
vary?: string;
retry_after?: string;
warning?: string;
content_language?: string;
content_location?: string;
p3p?: string;
server?: string;
proxy_authenticate?: string;
proxy_agent?: string;
upgrade?: string;
unknown?: {
value?: string;
key?: string;
[k: string]: unknown;
};
x_content_type_options?: string;
x_content_security_policy?: string;
www_authenticate?: string;
content_range?: string;
content_encoding?: string;
access_control_allow_origin?: string;
content_md5?: string;
content_disposition?: string;
cache_control?: string;
location?: string;
status?: string;
strict_transport_security?: string;
expires?: string;
accept_patch?: string;
last_modified?: string;
link?: string;
content_type?: string;
date?: string;
x_frame_options?: string;
x_webkit_csp?: string;
x_real_ip?: string;
alternate_protocol?: string;
accept_ranges?: string;
age?: string;
x_xss_protection?: string;
x_forwarded_for?: string;
refresh?: string;
public_key_pins?: string;
connection?: string;
x_content_duration?: string;
alt_svc?: string;
allow?: string;
referer?: string;
content_security_policy?: string;
transfer_encoding?: string;
trailer?: string;
[k: string]: unknown;
};
/**
* Status message received from hitting /api/v1/targets
*/
status_line?: string;
/**
* Status code received from hitting /api/v1/targets
*/
status_code?: string;
[k: string]: unknown;
};
/**
* Information Prometheus captured as well as build information.
*/
response?: {
/**
* List of the versions and revisions of Prometheus.
*/
prometheus_build_info?: {
/**
* Version of Prometheus.
*/
version?: string;
/**
* Version of Go used to build Prometheus.
*/
go_version?: string;
/**
* Revision of Prometheus.
*/
revision?: string;
[k: string]: unknown;
};
/**
* List of dropped targets.
*/
dropped_targets?: {
discovered_labels?: {
/**
* URL scheme.
*/
scheme?: string;
/**
* Job of target.
*/
job?: string;
/**
* Path to metrics of target.
*/
metrics_path?: string;
/**
* Address of target.
*/
address?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* List of the versions of everything that Prometheus finds (i.e., version of Prometheus, Go, Node, cAdvisor, etc.)
*/
all_versions?: string;
/**
* List of the versions of Go.
*/
go_versions?: string;
/**
* List of active targets.
*/
active_targets?: {
discovered_labels?: {
/**
* URL scheme.
*/
scheme?: string;
/**
* Job of target.
*/
job?: string;
/**
* Path to metrics of target.
*/
metrics_path?: string;
/**
* Address of target.
*/
address?: string;
[k: string]: unknown;
};
labels?: {
/**
* Instance after relabelling has occurred
*/
instance?: string;
/**
* Job of target after relabelling has occurred
*/
job?: string;
[k: string]: unknown;
};
/**
* URL that Prometheus scraped.
*/
scrape_url?: string;
/**
* Whether target is up or down.
*/
health?: string;
/**
* Last error that occurred within target.
*/
last_error?: string;
/**
* Last time Prometheus scraped target.
*/
last_scrape?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
p465?: {
smtp?: {
tls?: {
/**
* The response to the EHLO command.
*/
ehlo?: string;
tls?: {
/**
* The key data sent by the server in the TLS key exchange message.
*/
server_key_exchange?: {
/**
* Parameters for the Diffie-Hellman key exchange.
*/
dh_params?: {
/**
* The shared prime number.
*/
prime?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's public key.
*/
server_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The generator of the DH group.
*/
generator?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's private key. Usually does not coexist with server_private.
*/
client_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The server's private key. Usually does not coexist with client_private.
*/
server_private?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The client's public key.
*/
client_public?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* The session key.
*/
session_key?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Container for the public portion (modulus and exponent) of an RSA asymmetric key.
*/
rsa_params?: {
/**
* Bit-length of modulus.
*/
length?: string;
/**
* The RSA key's modulus (n) in big-endian encoding.
*/
modulus?: string;
/**
* The RSA key's public exponent (e).
*/
exponent?: string;
[k: string]: unknown;
};
signature?: {
raw?: string;
tls_version?: {
/**
* A human-readable version of the TLS version.
*/
name?: string;
/**
* The TLS version identifier.
*/
value?: string;
[k: string]: unknown;
};
valid?: boolean;
type?: string;
/**
* mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See RFC 5246, section A.4.1.
*/
signature_and_hash_type?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* Parameters for ECDH key exchange.
*/
ecdh_params?: {
/**
* An elliptic curve point.
*/
server_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* An elliptic curve algorithm identifier.
*/
curve_id?: {
/**
* The numeric value of the curve identifier. See http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8
*/
id?: string;
/**
* The name of the curve algorithm (e.g. sect163kr1, secp192r1). Unrecognized curves are 'unknown'.
*/
name?: string;
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
server_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
/**
* An elliptic curve point.
*/
client_public?: {
/**
* Generic parameter for a cryptographic algorithm.
*/
y?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
/**
* Generic parameter for a cryptographic algorithm.
*/
x?: {
/**
* The length of the parameter.
*/
length?: string;
/**
* The value of the parameter.
*/
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* TLS key exchange parameters for ECDH keys.
*/
client_private?: {
length?: string;
value?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The signature error, if one occurred.
*/
signature_error?: string;
/**
* The digest that is signed.
*/
digest?: string;
[k: string]: unknown;
};
/**
* The server's TLS certificate.
*/
certificate?: {
parsed?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
fingerprint_sha256?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
chain?: {
fingerprints?: {
/**
* The SHA2-256 digest over the DER encoding of the certificate's SubjectPublicKeyInfo, as a hexadecimal string.
*/
spki_subject?: string;
/**
* The SHA1 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha1?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, as a hexadecimal string.
*/
tbs?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate's TBSCertificate, *with any CT extensions omitted*, as a hexadecimal string.
*/
tbs_noct?: string;
/**
* The SHA2-256 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
sha256?: string;
/**
* The MD5 digest over the DER encoding of the certificate, as a hexadecimal string.
*/
md5?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* This is true if the client has the Secure Renegotiation extension (see https://tools.ietf.org/html/rfc5746).
*/
secure_renegotiation?: boolean;
/**
* Time the scan was run.
*/
timestamp?: string;
session_ticket?: {
/**
* The length of the session ticket, in bytes.
*/
length?: string;
/**
* A hint from the server as to how long the ticket should be stored (in seconds relative to when the ticket is received).
*/
lifetime_hint?: string;
/**
* The session ticket (an opaque binary blob).
*/
value?: string;
[k: string]: unknown;
};
cipher_suite?: {
/**
* The hexadecimal string representation of the numeric cipher algorithm identifier.
*/
id?: string;
/**
* The algorithm identifier for the cipher algorithm identifier, see e.g. https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml.
*/
name?: string;
[k: string]: unknown;
};
/**
* A human-readable version of the TLS version.
*/
version?: string;
/**
* This is true if the OCSP Stapling extension is set (see https://www.ietf.org/rfc/rfc6961.txt for details).
*/
ocsp_stapling?: boolean;
signature?: {
/**
* The name of the hash algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
hash_algorithm?: string;
/**
* The signature error, if one occurred.
*/
signature_error?: string;
valid?: boolean;
/**
* The name of the signature algorithm, as defined in RFC5246 section 7.4.1.4.1. Unrecognized values are of the form 'unknown.255'.
*/
signature_algorithm?: string;
[k: string]: unknown;
};
/**
* The values in the SignedCertificateTimestampList of the Signed Certificate Timestamp, if present.
*/
scts?: {
/**
* The SHA-256 hash of the log's public key, calculated over the DER encoding of the key's SubjectPublicKeyInfo.
*/
log_id?: string;
/**
* Time at which the SCT was issued (in seconds since the Unix epoch).
*/
timestamp?: string;
/**
* Version of the protocol to which the SCT conforms.
*/
version?: string;
/**
* For future extensions to the protocol.
*/
extensions?: string;
/**
* The log's signature for this SCT.
*/
signature?: string;
[k: string]: unknown;
};
validation?: {
/**
* Indicates whether the server's domain name matches that in the certificate.
*/
matches_domain?: boolean;
/**
* Indicates whether the certificate is trusted by the standard browser certificate stores.
*/
browser_trusted?: boolean;
/**
* Description of the reason browser_trusted == false.
*/
browser_error?: string;
[k: string]: unknown;
};
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
/**
* The response to the STARTTLS command.
*/
starttls?: string;
/**
* Time the scan was run.
*/
timestamp?: string;
/**
* The initial SMTP command sent by the server (e.g. "220 localhost.localdomain ESMTP Postfix (Ubuntu)\r\n"
*/
banner?: string;
metadata?: {
product?: string;
revision?: string;
description?: string;
version?: string;
manufacturer?: string;
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
};
[k: string]: unknown;
} | the_stack |
'use babel'
/*!
* XAtom Debug
* Copyright(c) 2017 Williams Medina <williams.medinaa@gmail.com>
* MIT Licensed
*/
import {
createIcon,
createText,
createInput,
createButton,
createElement,
insertElement,
attachEventFromObject
} from '../element'
import { BreakpointManager, Breakpoint, Breakpoints } from './BreakpointManager'
import { PluginManager } from '../plugin/index'
import { InspectorView } from '../InspectorView'
import { EventEmitter } from 'events'
import { get } from 'lodash'
export interface EditorOptions {
pluginManager: PluginManager,
didAddBreakpoint?: Function,
didRemoveBreakpoint?: Function,
didEvaluateExpression?: Function,
didBreak?: Function,
didChange?: Function
}
export class EditorManager {
private currentEditor: any
private currentBreakMarker: any
private currentExpressionMarker: any
private currentEvaluationMarker: any
private currentEvaluationElement: HTMLElement
private activateExpressionListerner: boolean = true
private evaluateHandler: any
public breakpointManager: BreakpointManager
private pluginManager: PluginManager
private events: EventEmitter
constructor (options: EditorOptions) {
this.events = new EventEmitter()
this.breakpointManager = new BreakpointManager()
this.pluginManager = options.pluginManager
attachEventFromObject(this.events, [
'didAddBreakpoint',
'didRemoveBreakpoint',
'didChangeBreakpoint',
'didEvaluateExpression',
'didBreak',
'didChange'
], options)
}
restoreBreakpoints (breakpoints: Breakpoints) {
breakpoints.forEach(({filePath, lineNumber, condition}) => {
let marker
if (get(this, 'currentEditor.getPath') && filePath === this.currentEditor.getPath()) {
marker = this.createBreakpointMarkerForEditor(this.currentEditor, lineNumber)
}
this.breakpointManager.addBreakpoint(marker, lineNumber, filePath, condition)
this.events.emit('didAddBreakpoint', filePath, lineNumber)
})
}
getBreakpointFromEvent (event: any) {
let line: HTMLElement = event.target
let lineNumber = parseInt(line.getAttribute('data-buffer-row'), 0)
let editor = atom.workspace.getActiveTextEditor()
let filePath = editor.getPath()
return this.breakpointManager.getBreakpoint(filePath, lineNumber)
}
removeBreakpointFromEvent (event: any) {
let breakpoint = this.getBreakpointFromEvent(event)
if (breakpoint) {
this.removeBreakpoint(breakpoint)
}
}
editBreakpointFromEvent (event: any) {
let editor = atom.workspace.getActiveTextEditor()
let breakpoint = this.getBreakpointFromEvent(event)
if (breakpoint) {
let range = [[breakpoint.lineNumber, 0], [breakpoint.lineNumber, 0]]
let marker: any = editor.markBufferRange(range)
let conditionInput = document.createElement('atom-text-editor')
conditionInput.setAttribute('mini', 'true')
let miniEditor = conditionInput['getModel']()
miniEditor.setText(breakpoint.condition)
miniEditor.setGrammar(editor.getGrammar())
let conditionButton = createButton({
click: () => {
let miniEditor = conditionInput['getModel']()
let conditionText = miniEditor.getText()
breakpoint.condition = conditionText
setTimeout(() => {
this.events.emit('didChangeBreakpoint', breakpoint.filePath, breakpoint.lineNumber, breakpoint.condition)
this.pluginManager.changeBreakpoint(breakpoint.filePath, breakpoint.lineNumber, breakpoint.condition)
this.events.emit('didChange')
}, 500)
breakpointEditor.remove()
marker.destroy()
}
}, createIcon('check'))
// conditionButton.classList.add('btn-success')
let breakpointEditor: HTMLElement = createElement('div', {
elements: [
conditionInput,
conditionButton,
createElement('xatom-breakpoint-edit-arrow')
]
})
let decorator = editor.decorateMarker(marker, {
type: 'overlay',
class: 'xatom-breakpoint-edit',
item: breakpointEditor
})
setTimeout(() => {
conditionInput.focus()
conditionInput.addEventListener('blur', (e: FocusEvent) => {
if(e.relatedTarget !== conditionButton) {
breakpointEditor.remove()
marker.destroy()
}
})
}, 0)
}
}
destroy () {
this.currentBreakMarker = undefined
this.currentExpressionMarker = undefined
this.currentEvaluationMarker = undefined
this.removeMarkers()
}
breakOnFile (filePath: string, lineNumber: number) {
// this.createConsoleLine('', [
// createText('Break on'),
// createText(`${filePath}:${lineNumber}`)
// ])
this.events.emit('didBreak', filePath, lineNumber)
}
createBreakMarker (editor, lineNumber: number) {
this.removeBreakMarker()
let range = [[lineNumber, 0], [lineNumber, 0]]
this.currentBreakMarker = editor.markBufferRange(range)
editor.decorateMarker(this.currentBreakMarker, {
type: 'line',
class: 'xatom-break-line'
})
}
removeMarkers () {
this.removeBreakMarker()
this.removeExpressionMarker()
this.removeEvaluationMarker()
}
removeBreakMarker () {
if (this.currentBreakMarker) {
this.currentBreakMarker.destroy()
}
}
removeExpressionMarker () {
if (this.currentExpressionMarker) {
this.currentExpressionMarker.destroy()
}
}
async addFeatures (editor) {
// restore breakpoints
if (get(editor, 'getPath', false)) {
let sourceFile = editor.getPath()
let breakpoints = await this.breakpointManager.getBreakpointsFromFile(sourceFile)
breakpoints.forEach((breakpoint: Breakpoint) => {
if (breakpoint.marker) breakpoint.marker.destroy()
breakpoint.marker = this.createBreakpointMarkerForEditor(editor, breakpoint.lineNumber)
})
this.currentEditor = editor
if (get(editor, 'element.addEventListener', false) &&
!get(editor, 'element.__atomBugsEnabledFeatures', false)) {
let breakpointHandler = (e) => this.addBreakpointFromEvent(e, editor)
let expressionHandler = (e) => this.listenExpressionEvaluations(e, editor)
// add breakpoint handler
editor.element.__atomBugsEnabledFeatures = true
editor.element.addEventListener('click', breakpointHandler)
editor.element.addEventListener('mousemove', expressionHandler)
editor.onDidDestroy(() => {
editor.element.removeEventListener('click', breakpointHandler)
editor.element.removeEventListener('mousemove', expressionHandler)
})
}
}
}
private removeBreakpoint (breakpoint: Breakpoint) {
let sourceFile = breakpoint.filePath
let lineNumber = breakpoint.lineNumber
return this
.breakpointManager
.removeBreakpoint(breakpoint)
.then(() => {
this.events.emit('didRemoveBreakpoint', sourceFile, lineNumber)
this.pluginManager.removeBreakpoint(sourceFile, lineNumber)
})
}
private addBreakpointFromEvent (e: MouseEvent, editor: any) {
let element = e.target as HTMLElement
if (element.classList.contains('line-number')) {
// toggle breakpoints
let lineNumber = Number(element.textContent) - 1
if (lineNumber >= 0) {
let sourceFile = editor.getPath()
let exists = this.breakpointManager.getBreakpoint(sourceFile, lineNumber)
if (exists) {
this.removeBreakpoint(exists)
} else {
let marker = this.createBreakpointMarkerForEditor(editor, lineNumber)
this
.breakpointManager
.addBreakpoint(marker, lineNumber, sourceFile)
.then(() => {
this.events.emit('didAddBreakpoint', sourceFile, lineNumber)
this.pluginManager.addBreakpoint(sourceFile, lineNumber)
})
}
this.events.emit('didChange')
}
}
}
private createBreakpointMarkerForEditor (editor: any, lineNumber: any) {
let range = [[lineNumber, 0], [lineNumber, 0]]
let marker = editor.markBufferRange(range)
let decorator = editor.decorateMarker(marker, {
type: 'line-number',
class: 'xatom-breakpoint'
})
return marker
}
private getEditorPositionFromEvent (editor, e: MouseEvent) {
let lines = editor.element.querySelector('.lines')
var clientX = e.clientX
var clientY = e.clientY
let clientRect = lines.getBoundingClientRect()
let screenPosition = editor.element.screenPositionForPixelPosition({
top: (clientY - clientRect.top) + editor.element.getScrollTop(),
left: (clientX - clientRect.left) + editor.element.getScrollLeft()
})
return editor.bufferPositionForScreenPosition(screenPosition)
}
private getEditorWordRangeFromPosition (editor, position) {
let prevRow = editor.buffer.previousNonBlankRow(position.row)
let endRow = editor.buffer.nextNonBlankRow(position.row)
if (!endRow) {
endRow = position.row
}
let startWord = position
let endWord = position
// /\()"':,.<>~!@#$%^&*|+=[]{}`?-…
editor.scanInBufferRange(/[ \,\{\}\(\\)\[\]^\n]+/gm, [[prevRow, 0], position], (s) => {
if (s.matchText) {
startWord = s.range.end
}
})
editor.scanInBufferRange(/[ \,\{\}\(\.\\)\[\]\:\/\n]+/g, [position, [endRow, 50]], (s) => {
if (s.matchText) {
endWord = s.range.start
s.stop()
}
})
return [startWord, endWord]
}
private listenExpressionEvaluations (e: MouseEvent, editor: any) {
let sourceFile = editor.getPath()
let bufferPosition = this.getEditorPositionFromEvent(editor, e)
let scanRange = this.getEditorWordRangeFromPosition(editor, bufferPosition)
let expression = editor.getTextInBufferRange(scanRange)
clearTimeout(this.evaluateHandler)
this.evaluateHandler = setTimeout(() => {
let isEvaluationOverlay = this.currentEvaluationElement && this.currentEvaluationElement.contains(e.target as Node)
let isValidExpression = expression && expression.toString().trim().length > 0
if (!isEvaluationOverlay && isValidExpression) {
let evaluationView = this.createEditorEvaluationView(editor, scanRange)
this.pluginManager.evaluateExpression(expression, evaluationView)
} else if (!isEvaluationOverlay) {
this.removeEvaluationMarker()
this.removeExpressionMarker()
}
}, 2000)
}
createEditorEvaluationView (editor: any, range: any) {
return {
insertFromResult: (result) => {
this.addEditorEvaluationMarker(editor, result, range)
}
}
}
createInspectorOverlay (result: any) {
let element = createElement('xatom-debug-overlay', {
className: 'native-key-bindings'
})
element.setAttribute('tabindex', '0')
let inspector = new InspectorView({
result,
didRequestProperties: (result, inspectorView) => {
this.pluginManager.requestProperties(result, inspectorView)
}
})
return insertElement(element, [
createElement('xatom-debug-overlay-header', {
elements: [ createText(result.className || result.type) ]
}),
inspector.getElement()
])
}
addEditorEvaluationMarker (editor: any, result: any, range) {
// highlight expression
this.removeExpressionMarker()
this.currentExpressionMarker = editor.markBufferRange(range)
editor.decorateMarker(this.currentExpressionMarker, {
type: 'highlight',
class: 'xatom-expression'
})
// overlay inspector
this.removeEvaluationMarker()
this.currentEvaluationElement = this.createInspectorOverlay(result)
this.currentEvaluationMarker = editor.markBufferRange(range)
editor.decorateMarker(this.currentEvaluationMarker, {
type: 'overlay',
class: 'xatom-expression-overlay',
item: this.currentEvaluationElement
})
}
removeEvaluationMarker () {
if (this.currentEvaluationMarker) {
this.currentEvaluationMarker.destroy()
this.currentEvaluationMarker = undefined
}
}
} | the_stack |
import { newSpecPage, SpecPage } from '@stencil/core/testing';
import { BarChart } from './bar-chart';
import { BarChartDefaultValues } from './bar-chart-default-values';
import { scaleBand, scaleOrdinal, scaleLinear } from 'd3-scale';
// we need to bring in our nested components as well, was required to bring in the source vs dist folder to get it to mount
import { KeyboardInstructions } from '../../../node_modules/@visa/keyboard-instructions/src/components/keyboard-instructions/keyboard-instructions';
import { DataTable } from '../../../node_modules/@visa/visa-charts-data-table/src/components/data-table/data-table';
import Utils from '@visa/visa-charts-utils';
import UtilsDev from '@visa/visa-charts-utils-dev';
const { getColors, visaColors, formatStats, getContrastingStroke } = Utils;
const {
asyncForEach,
flushTransitions,
unitTestAccessibility,
unitTestEvent,
unitTestGeneric,
unitTestInteraction,
unitTestTooltip
} = UtilsDev;
describe('<bar-chart>', () => {
// TECH DEBT: Need to revisit class-logic-testing post PURE function refactor.
// Class-logic-testing is TDD and BDD friendly.
describe('class-logic', () => {
it('should build', () => {
expect(new BarChart()).toBeTruthy();
});
});
describe('rendered-html', () => {
let page: SpecPage;
let component;
// START:minimal props need to be passed to component
const EXPECTEDDATA = [
{ month: 'Apr-17', value: 1407543, cat: 'A' },
{ month: 'May-17', value: 6042320, cat: 'A' },
{ month: 'Jun-17', value: 3234002, cat: 'A' },
{ month: 'Jul-17', value: 2221233, cat: 'B' },
{ month: 'Aug-17', value: 4476321, cat: 'A' },
{ month: 'Sep-17', value: 3789221, cat: 'B' },
{ month: 'Oct-17', value: 6543535, cat: 'B' },
{ month: 'Nov-17', value: 7457432, cat: 'A' },
{ month: 'Dec-17', value: 2636346, cat: 'B' },
{ month: 'Jan-18', value: 2340000, cat: 'C' },
{ month: 'Feb-18', value: 3202340, cat: 'A' },
{ month: 'Mar-18', value: 8503536, cat: 'B' }
];
const EXPECTEDORDINALACCESSOR = 'month';
const EXPECTEDVALUEACCESSOR = 'value';
const MINVALUE = 1407543;
const MAXVALUE = 8503536;
// END:minimal props need to be passed to component
// disable accessibility validation to keep output stream(terminal) clean
const EXPECTEDACCESSIBILITY = { ...BarChartDefaultValues.accessibility, disableValidation: true };
beforeEach(async () => {
page = await newSpecPage({
components: [BarChart, KeyboardInstructions, DataTable],
html: '<div></div>'
});
component = page.doc.createElement('bar-chart');
component.data = [...EXPECTEDDATA];
component.ordinalAccessor = EXPECTEDORDINALACCESSOR;
component.valueAccessor = EXPECTEDVALUEACCESSOR;
component.accessibility = EXPECTEDACCESSIBILITY;
component.uniqueID = 'bar-chart-unit-test';
component.unitTest = true;
});
it('should build', () => {
expect(new BarChart()).toBeTruthy();
});
describe('render', () => {
beforeEach(() => {
// MOCK MATH.Random TO HANDLE UNIQUE ID CODE FROM ACCESSIBILITY UTIL
jest.spyOn(global.Math, 'random').mockReturnValue(0.123456789);
});
afterEach(() => {
// RESTORE GLOBAL FUNCTION FROM MOCK AFTER TEST
jest.spyOn(global.Math, 'random').mockRestore();
});
it('should render with minimal props[data,oridnalAccessor,valueAccessor] given', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// flush labels for testing to ensure opacity of 1 on initial render
const elements = page.doc.querySelectorAll('[data-testid=dataLabel]');
await asyncForEach(elements, async element => {
flushTransitions(element);
await page.waitForChanges();
});
// ASSERT
expect(page.root).toMatchSnapshot();
});
});
describe('generic test suite', () => {
Object.keys(unitTestGeneric).forEach(test => {
const innerTestProps = unitTestGeneric[test].testDefault
? { [unitTestGeneric[test].prop]: BarChartDefaultValues[unitTestGeneric[test].prop] }
: unitTestGeneric[test].prop === 'data'
? { data: EXPECTEDDATA }
: unitTestGeneric[test].testProps;
const innerTestSelector =
unitTestGeneric[test].testSelector === 'component-name'
? 'bar-chart'
: unitTestGeneric[test].testSelector === '[data-testid=mark]'
? '[data-testid=bar]'
: unitTestGeneric[test].testSelector;
it(`${unitTestGeneric[test].prop}: ${unitTestGeneric[test].name}`, () =>
unitTestGeneric[test].testFunc(component, page, innerTestProps, innerTestSelector));
});
});
describe('accessibility', () => {
describe('generic accessibility test suite', () => {
// PROBABLY WANT TO CREATE SEPARATE TEST FOR ENTER EXIT? LEAVING THOSE COMMENTED OUT FOR NOW
// WHAT ABOUT GROUP SIBLING NAVIGATION?
const accessibilityTestMarks = {
// accessibility_keyboard_nav_group_enter_entry: {
// name: 'keyboard nav: group - enter will enter group',
// testSelector: '[data-testid=bar-group]',
// nextTestSelector: '[data-testid=bar][data-id=bar-Apr-17]',
// keyDownObject: { key: 'Enter', code: 'Enter', keyCode: 13 }
// },
accessibility_keyboard_nav_group_esc_exit: {
name: 'keyboard nav: group - escape will exit group',
testSelector: '[data-testid=bar][data-id=bar-Apr-17]',
nextTestSelector: '[data-testid=bar-group]',
keyDownObject: { key: 'Escape', code: 'Escape', keyCode: 27 },
testProps: {
selectorAriaLabel: 'month Apr-17. value 1.4m. Bar 1 of 12.',
nextSelectorAriaLabel: 'Bar group which contains 12 interactive bars.',
accessibility: { ...EXPECTEDACCESSIBILITY, includeDataKeyNames: true }
}
},
accessibility_keyboard_nav_right_arrow: {
name: 'keyboard nav: sibling - right arrow goes to next',
testSelector: '[data-testid=bar][data-id=bar-Apr-17]',
nextTestSelector: '[data-testid=bar][data-id=bar-May-17]',
keyDownObject: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
testProps: {
selectorAriaLabel: 'month Apr-17. value 1.4m. Bar 1 of 12.',
nextSelectorAriaLabel: 'month May-17. value 6m. Bar 2 of 12.',
accessibility: { ...EXPECTEDACCESSIBILITY, includeDataKeyNames: true }
}
},
accessibility_keyboard_nav_right_arrow_loop: {
name: 'keyboard nav: sibling - right arrow goes to first from last',
testSelector: '[data-testid=bar][data-id=bar-Mar-18]',
nextTestSelector: '[data-testid=bar][data-id=bar-Apr-17]',
keyDownObject: { key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 },
testProps: {
selectorAriaLabel: 'Mar-18. 8.5m. Bar 12 of 12.',
nextSelectorAriaLabel: 'Apr-17. 1.4m. Bar 1 of 12.'
}
},
accessibility_keyboard_nav_left_arrow_sibling: {
name: 'keyboard nav: sibling - left arrow goes to next',
testSelector: '[data-testid=bar][data-id=bar-May-17]',
nextTestSelector: '[data-testid=bar][data-id=bar-Apr-17]',
keyDownObject: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
testProps: {
selectorAriaLabel: 'month May-17. value 6m. Bar 2 of 12.',
nextSelectorAriaLabel: 'month Apr-17. value 1.4m. Bar 1 of 12.',
accessibility: { ...EXPECTEDACCESSIBILITY, includeDataKeyNames: true }
}
},
accessibility_keyboard_nav_left_arrow_loop: {
name: 'keyboard nav: sibling - left arrow loops to last from first',
testSelector: '[data-testid=bar][data-id=bar-Apr-17]',
nextTestSelector: '[data-testid=bar][data-id=bar-Mar-18]',
keyDownObject: { key: 'ArrowLeft', code: 'ArrowLeft', keyCode: 37 },
testProps: {
selectorAriaLabel: 'Apr-17. 1.4m. Bar 1 of 12.',
nextSelectorAriaLabel: 'Mar-18. 8.5m. Bar 12 of 12.'
}
},
accessibility_keyboard_nav_up_arrow_cousin: {
name: 'keyboard nav: cousin - up arrow goes to next',
testSelector: '[data-testid=bar][data-id=bar-Sep-17]',
nextTestSelector: '[data-testid=bar][data-id=bar-Jul-17]',
keyDownObject: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
testProps: {
groupAccessor: 'cat',
selectorAriaLabel: 'Sep-17. 3.8m. B. Bar 6 of 12.',
nextSelectorAriaLabel: 'Jul-17. 2.2m. B. Bar 4 of 12.'
}
},
accessibility_keyboard_nav_up_arrow_cousin_loop: {
name: 'keyboard nav: cousin - up arrow loops to last',
testSelector: '[data-testid=bar][data-id=bar-Jul-17]',
nextTestSelector: '[data-testid=bar][data-id=bar-Mar-18]',
keyDownObject: { key: 'ArrowUp', code: 'ArrowUp', keyCode: 38 },
testProps: {
groupAccessor: 'cat',
selectorAriaLabel: 'Jul-17. 2.2m. B. Bar 4 of 12.',
nextSelectorAriaLabel: 'Mar-18. 8.5m. B. Bar 12 of 12.'
}
},
accessibility_keyboard_nav_down_arrow_cousin: {
name: 'keyboard nav: cousin - down arrow goes to next',
testSelector: '[data-testid=bar][data-id=bar-Jul-17]',
nextTestSelector: '[data-testid=bar][data-id=bar-Sep-17]',
keyDownObject: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
testProps: {
groupAccessor: 'cat',
selectorAriaLabel: 'month Jul-17. value 2.2m. cat B. Bar 4 of 12.',
nextSelectorAriaLabel: 'month Sep-17. value 3.8m. cat B. Bar 6 of 12.',
accessibility: { ...EXPECTEDACCESSIBILITY, includeDataKeyNames: true }
}
},
accessibility_keyboard_nav_down_arrow_cousin_loop: {
name: 'keyboard nav: cousin - down arrow loops to first',
testSelector: '[data-testid=bar][data-id=bar-Mar-18]',
nextTestSelector: '[data-testid=bar][data-id=bar-Jul-17]',
keyDownObject: { key: 'ArrowDown', code: 'ArrowDown', keyCode: 40 },
testProps: {
groupAccessor: 'cat',
selectorAriaLabel: 'month Mar-18. value 8.5m. cat B. Bar 12 of 12.',
nextSelectorAriaLabel: 'month Jul-17. value 2.2m. cat B. Bar 4 of 12.',
accessibility: { ...EXPECTEDACCESSIBILITY, includeDataKeyNames: true }
}
}
};
Object.keys(unitTestAccessibility).forEach(test => {
const tempTestProps = unitTestAccessibility[test].testDefault
? { [unitTestAccessibility[test].prop]: BarChartDefaultValues[unitTestAccessibility[test].prop] }
: unitTestAccessibility[test].testProps;
const innerTestProps = {
...tempTestProps,
geometryType: 'Bar',
geometryPlacementAttributes: ['x', 'y', 'height', 'width'],
geometryAdjustmentValues: [
{ f: 'x', b: 7, w: 3, s: -1 },
{ f: 'y', b: 7, w: 3, s: -1 },
{ f: 'height', b: 7 * 2, w: 3 * 2, s: 1 },
{ f: 'width', b: 7 * 2, w: 3 * 2, s: 1 }
],
annotations:
unitTestAccessibility[test].prop === 'annotations'
? [
{
note: {
label: "May's volume is here.",
bgPadding: 20,
title: 'The month of may',
align: 'middle',
wrap: 210
},
accessibilityDescription: 'This annotation is a callout to May, which is for testing purposes.',
data: { month: 'May-17', value: 6042320, cat: 'A' },
dy: '-20%',
color: 'pri_blue'
},
{
note: {
label: "June's volume is here.",
bgPadding: 20,
title: 'The month of june',
align: 'middle',
wrap: 210
},
data: { month: 'Jun-17', value: 3234002, cat: 'A' },
dy: '-20%',
color: 'pri_blue'
}
]
: []
};
const innerTestSelector =
unitTestAccessibility[test].testSelector === 'component-name'
? 'bar-chart'
: unitTestAccessibility[test].testSelector === '[data-testid=controller]'
? '.VCL-controller'
: unitTestAccessibility[test].testSelector === '[data-testid=svg]'
? '[data-testid=root-svg]'
: unitTestAccessibility[test].testSelector === '[data-testid=padding]'
? '[data-testid=padding-container]'
: unitTestAccessibility[test].testSelector === '[data-testid=mark]'
? '[data-testid=bar]'
: unitTestAccessibility[test].testSelector === '[data-testid=group]'
? '[data-testid=bar-group]'
: unitTestAccessibility[test].testSelector === '[data-id=mark-id]'
? accessibilityTestMarks[test]
? accessibilityTestMarks[test].testSelector
: '[data-testid=bar][data-id=bar-Apr-17]'
: unitTestAccessibility[test].testSelector;
const innerNextTestSelector =
unitTestAccessibility[test].nextTestSelector === '[data-testid=svg]'
? '[data-testid=root-svg]'
: unitTestAccessibility[test].nextTestSelector === '[data-id=mark-id]'
? accessibilityTestMarks[test]
? accessibilityTestMarks[test].nextTestSelector
: '[data-testid=bar][data-id=bar-May-17]'
: unitTestAccessibility[test].nextTestSelector;
if (test === 'accessibility_keyboard_nav_generic_test') {
// run keyboard nav test for each scenario above
// skipping these by default as the target.focus() code in accessibilityController breaks them
Object.keys(accessibilityTestMarks).forEach(keyboardTest => {
it(`${unitTestAccessibility[test].prop}: ${accessibilityTestMarks[keyboardTest].name}`, () =>
unitTestAccessibility[test].testFunc(
component,
page,
accessibilityTestMarks[keyboardTest].testProps
? { ...innerTestProps, ...accessibilityTestMarks[keyboardTest].testProps }
: innerTestProps,
accessibilityTestMarks[keyboardTest].testSelector,
accessibilityTestMarks[keyboardTest].nextTestSelector,
accessibilityTestMarks[keyboardTest].keyDownObject
));
});
} else if (
// these accessibility tests need a group accessor for bar-chart
test === 'accessibility_categorical_textures_created_by_default' ||
test === 'accessibility_group_aria_label_add_update' ||
test === 'accessibility_group_aria_label_remove_update'
) {
it(`${unitTestAccessibility[test].prop}: ${unitTestAccessibility[test].name}`, () =>
unitTestAccessibility[test].testFunc(
component,
page,
{ ...innerTestProps, groupAccessor: 'cat' },
innerTestSelector,
innerNextTestSelector
));
// update this test to check out just one of them
} else if (test === 'accessibility_focus_marker_style') {
it(`${unitTestAccessibility[test].prop}: ${unitTestAccessibility[test].name}`, () =>
unitTestAccessibility[test].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNextTestSelector
));
// skipping these by default as the target.focus() code in accessibilityController breaks them
} else if (test === 'accessibility_focus_marker_style') {
it.skip(`${unitTestAccessibility[test].prop}: ${unitTestAccessibility[test].name}`, () =>
unitTestAccessibility[test].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNextTestSelector
));
} else {
// these tests can just be run straight away
it(`${unitTestAccessibility[test].prop}: ${unitTestAccessibility[test].name}`, () =>
unitTestAccessibility[test].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNextTestSelector
));
}
});
});
describe('validation', () => {
it('refer to generic results above for accessibility validation tests', () => {
expect(true).toBeTruthy();
});
});
});
describe('base', () => {
it('refer to generic results above for base tests', () => {
expect(true).toBeTruthy();
});
describe('layout', () => {
it('should render chart horizontally when layout prop is horizontal', async () => {
// ARRANGE
const EXPECTEDSCALE = scaleBand()
.domain(EXPECTEDDATA.map(d => d.month))
.range([0, 500])
.padding(0.2);
component.width = 500;
component.height = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
component.layout = 'horizontal';
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('height', EXPECTEDSCALE.bandwidth());
});
});
it('should render chart vertically when layout prop is vertical', async () => {
// ARRANGE
const EXPECTEDSCALE = scaleBand()
.domain(EXPECTEDDATA.map(d => d.month))
.range([0, 500])
.padding(0.2);
component.width = 500;
component.height = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('width', EXPECTEDSCALE.bandwidth());
});
});
});
});
describe('margin & padding', () => {
it('refer to generic results above for margin & padding tests', () => {
expect(true).toBeTruthy();
});
});
// annotations break in jsdom due to their text wrapping function in d3-annotation
// describe('annotations', () => {
// // TODO: need to add more precise test case for annotations label and text
// it('should pass annotation prop', async () => {
// // ARRANGE
// const annotations = [
// {
// note: {
// label: 'Social Media Intern returned to college',
// bgPadding: 20,
// title: 'Staff Change',
// align: 'middle',
// wrap: 130
// },
// accessibilityDescription:
// 'This is an annotation that explains a drop in tweet ACTivity due to staff change.',
// y: [2600],
// x: '62%',
// dy: -85,
// type: 'annotationCallout',
// connector: { end: 'dot', endScale: 10 },
// color: 'pri_blue'
// }
// ];
// const data = [
// { label: 'Q1', value: 1125 },
// { label: 'Q2', value: 3725 },
// { label: 'Q3', value: 2125 },
// { label: 'Q4', value: 4125 }
// ];
// const dataLabel = { visible: true, placement: 'top', labelAccessor: 'value', format: '0,0' };
// component.data = data;
// component.ordinalAccessor = 'label';
// component.valueAccessor = 'value';
// component.dataLabel = dataLabel;
// component.annotations = annotations;
// // ACT
// page.root.append(component);
// await page.waitForChanges();
// // ASSERT
// const annotationGroup = page.doc.querySelector('[data-testid=annotation-group]');
// expect(annotationGroup).toMatchSnapshot();
// });
// });
describe('axes', () => {
describe('barIntervalRatio', () => {
it('should have ratio of 0.2 by default', async () => {
// ARRANGE
const EXPECTEDSCALE = scaleBand()
.domain(EXPECTEDDATA.map(d => d.month))
.range([0, 500])
.padding(0.2);
component.width = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('width', EXPECTEDSCALE.bandwidth());
});
});
it('should have ratio of 0.5 when passed on load', async () => {
// ARRANGE
const EXPECTEDSCALE = scaleBand()
.domain(EXPECTEDDATA.map(d => d.month))
.range([0, 500])
.padding(0.5);
component.width = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
component.barIntervalRatio = 0.5;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('width', EXPECTEDSCALE.bandwidth());
});
});
it('should have ratio of 0.5 when passed on update', async () => {
// ARRANGE
const EXPECTEDSCALE = scaleBand()
.domain(EXPECTEDDATA.map(d => d.month))
.range([0, 500])
.padding(0.5);
component.width = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
// ACT LOAD
page.root.appendChild(component);
await page.waitForChanges();
// ACT UPDATE
component.barIntervalRatio = 0.5;
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('width', EXPECTEDSCALE.bandwidth());
});
});
});
describe('minValueOverride', () => {
it('should have no effect on bar chart when passed', async () => {
const EXPECTEDSCALE = scaleLinear()
.domain([Math.min(0, MINVALUE), MAXVALUE])
.range([500, 0]);
component.minValueOverride = 100000;
component.height = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async (bar, i) => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('height', EXPECTEDSCALE(0) - EXPECTEDSCALE(EXPECTEDDATA[i].value));
});
});
});
describe('maxValueOverride', () => {
it('should effect bar size when maxValueOverride is passed on load', async () => {
const MAXVALUEOVERRIDE = 10000000;
const EXPECTEDSCALE = scaleLinear()
.domain([Math.min(0, MINVALUE), MAXVALUEOVERRIDE])
.range([500, 0]);
component.maxValueOverride = MAXVALUEOVERRIDE;
component.height = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async (bar, i) => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('height', EXPECTEDSCALE(0) - EXPECTEDSCALE(EXPECTEDDATA[i].value));
});
});
it('should effect bar size when maxValueOverride is passed on update', async () => {
const MAXVALUEOVERRIDE = 10000000;
const EXPECTEDSCALE = scaleLinear()
.domain([Math.min(0, MINVALUE), MAXVALUEOVERRIDE])
.range([500, 0]);
component.height = 500;
component.margin = { bottom: 0, left: 0, right: 0, top: 0 };
component.padding = { bottom: 0, left: 0, right: 0, top: 0 };
// ACT LOAD
page.root.appendChild(component);
await page.waitForChanges();
// ACT UPDATE
component.maxValueOverride = MAXVALUEOVERRIDE;
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async (bar, i) => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('height', EXPECTEDSCALE(0) - EXPECTEDSCALE(EXPECTEDDATA[i].value));
});
});
});
describe('axis.visible', () => {
it('xAxis and yAxis should be visible by default', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxis = page.doc.querySelector('[data-testid=x-axis]');
const yAxis = page.doc.querySelector('[data-testid=y-axis]');
flushTransitions(xAxis);
flushTransitions(yAxis);
expect(xAxis).toEqualAttribute('opacity', 1);
expect(yAxis).toEqualAttribute('opacity', 1);
});
it('should not render when false is passed', async () => {
// ARRANGE
component.xAxis = {
visible: false,
gridVisible: true,
label: 'X Axis',
format: '0[.][0][0]a',
tickInterval: 1
};
component.yAxis = {
visible: false,
gridVisible: true,
label: 'Y Axis',
format: '0[.][0][0]a',
tickInterval: 1
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxis = page.doc.querySelector('[data-testid=x-axis]');
const yAxis = page.doc.querySelector('[data-testid=y-axis]');
flushTransitions(xAxis);
flushTransitions(yAxis);
expect(xAxis).toEqualAttribute('opacity', 0);
expect(yAxis).toEqualAttribute('opacity', 0);
});
});
describe('axis.gridVisible', () => {
it('should not render when false or layout is vertical (default)', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const gridBottom = page.doc.querySelector('[data-testid=grid-bottom]');
const gridLeft = page.doc.querySelector('[data-testid=grid-left]');
flushTransitions(gridBottom);
flushTransitions(gridLeft);
expect(gridBottom).toEqualAttribute('opacity', 0);
expect(gridLeft).toEqualAttribute('opacity', 1);
});
it('should render when true and layout is horizontal', async () => {
component.layout = 'horizontal';
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
// ASSERT
const gridBottom = page.doc.querySelector('[data-testid=grid-bottom]');
const gridLeft = page.doc.querySelector('[data-testid=grid-left]');
flushTransitions(gridBottom);
flushTransitions(gridLeft);
expect(gridBottom).toEqualAttribute('opacity', 1);
expect(gridLeft).toEqualAttribute('opacity', 0);
});
});
describe('axis.label', () => {
it('should place axis label when passed', async () => {
// ARRANGE
const EXPECTEDXAXIS = {
format: '0[.][0][0]a',
gridVisible: true,
label: 'Custom X Axis Label',
tickInterval: 1,
visible: true
};
const EXPECTEDYAXIS = {
visible: true,
gridVisible: true,
label: 'Custom Y Axis Label',
format: '0[.][0][0]a',
tickInterval: 1
};
component.xAxis = EXPECTEDXAXIS;
component.yAxis = EXPECTEDYAXIS;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisLabel = page.doc.querySelector('[data-testid=x-axis-label]');
const yAxisLabel = page.doc.querySelector('[data-testid=y-axis-label]');
expect(xAxisLabel).toEqualText(EXPECTEDXAXIS.label);
expect(yAxisLabel).toEqualText(EXPECTEDYAXIS.label);
});
});
describe('axis.format', () => {
it('yAxis should have default format applied to numbers', async () => {
// ARRANGE
component.wrapLabel = false;
const EXPECTEDTICKS = ['0', '1m', '2m', '3m', '4m', '5m', '6m', '7m', '8m'];
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const yAxisTicks = page.doc.querySelectorAll('[data-testid=y-axis] [data-testid=axis-tick]');
yAxisTicks.forEach((tick, i) => {
expect(tick).toEqualText(EXPECTEDTICKS[i]);
});
});
it('xAxis should have default format applied to numbers', async () => {
// ARRANGE
component.wrapLabel = false;
component.layout = 'horizontal';
const EXPECTEDTICKS = ['0', '1m', '2m', '3m', '4m', '5m', '6m', '7m', '8m'];
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisTicks = page.doc.querySelectorAll('[data-testid=x-axis] [data-testid=axis-tick]');
xAxisTicks.forEach((tick, i) => {
expect(tick).toEqualText(EXPECTEDTICKS[i]);
});
});
it('yAxis should have custom format applied to numbers if passed', async () => {
// ARRANGE
component.wrapLabel = false;
const EXPECTEDYAXIS = {
format: '$0[.][0][0]a',
gridVisible: true,
label: 'Custom Y Axis Label',
tickInterval: 1,
visible: true
};
component.yAxis = EXPECTEDYAXIS;
const EXPECTEDTICKS = ['$0', '$1m', '$2m', '$3m', '$4m', '$5m', '$6m', '$7m', '$8m'];
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const yAxisTicks = page.doc.querySelectorAll('[data-testid=y-axis] [data-testid=axis-tick]');
yAxisTicks.forEach((tick, i) => {
expect(tick).toEqualText(EXPECTEDTICKS[i]);
});
});
it('xAxis should have custom format applied to numbers if passed', async () => {
// ARRANGE
component.wrapLabel = false;
component.layout = 'horizontal';
const EXPECTEDXAXIS = {
format: '$0[.][0][0]a',
gridVisible: true,
label: 'Custom X Axis Label',
tickInterval: 1,
visible: true
};
component.xAxis = EXPECTEDXAXIS;
const EXPECTEDTICKS = ['$0', '$1m', '$2m', '$3m', '$4m', '$5m', '$6m', '$7m', '$8m'];
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisTicks = page.doc.querySelectorAll('[data-testid=x-axis] [data-testid=axis-tick]');
xAxisTicks.forEach((tick, i) => {
expect(tick).toEqualText(EXPECTEDTICKS[i]);
});
});
});
describe('axis.tickInterval', () => {
it('should have tick interval one by default', async () => {
// ARRANGE
const EXPECTEDTICKS = ['0', '1m', '2m', '3m', '4m', '5m', '6m', '7m', '8m'];
component.wrapLabel = false;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisTicks = page.doc.querySelectorAll('[data-testid=x-axis] [data-testid=axis-tick]');
const yAxisTicks = page.doc.querySelectorAll('[data-testid=y-axis] [data-testid=axis-tick]');
xAxisTicks.forEach((tick, i) => {
expect(tick).toEqualText(EXPECTEDDATA[i].month);
});
yAxisTicks.forEach((tick, i) => {
expect(tick).toEqualText(EXPECTEDTICKS[i]);
});
});
it('should have tick interval 2 when passed', async () => {
// ARRANGE
const EXPECTEDXAXIS = {
format: '0[.][0][0]a',
gridVisible: true,
label: 'Custom X Axis Label',
tickInterval: 2,
visible: true
};
const EXPECTEDTICKS = ['0', '1m', '2m', '3m', '4m', '5m', '6m', '7m', '8m'];
component.wrapLabel = false;
component.xAxis = EXPECTEDXAXIS;
component.yAxis = EXPECTEDXAXIS;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisTicks = page.doc.querySelectorAll('[data-testid=x-axis] [data-testid=axis-tick]');
const yAxisTicks = page.doc.querySelectorAll('[data-testid=y-axis] [data-testid=axis-tick]');
xAxisTicks.forEach((tick, i) => {
const expectedAxisText = i % 2 === 0 ? EXPECTEDDATA[i].month : '';
expect(tick).toEqualText(expectedAxisText);
});
yAxisTicks.forEach((tick, i) => {
const expectedAxisText = i % 2 === 0 ? EXPECTEDTICKS[i] : '';
expect(tick).toEqualText(expectedAxisText);
});
});
});
});
describe('interaction', () => {
describe('bar based interaction tests', () => {
const innerTestProps = {
transitionEndAllSelector: '[data-testid=bar]'
};
const innerTestSelector = '[data-testid=bar][data-id=bar-Apr-17]';
const innerNegTestSelector = '[data-testid=bar][data-id=bar-May-17]';
Object.keys(unitTestInteraction).forEach(test => {
it(`[${unitTestInteraction[test].group}] ${unitTestInteraction[test].prop}: ${
unitTestInteraction[test].name
}`, () =>
unitTestInteraction[test].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNegTestSelector
));
});
});
describe('clickStyle with interaction keys', () => {
const testLoad = 'interaction_clickStyle_custom_load';
const testUpdate = 'interaction_clickStyle_custom_update';
const innerTestSelector = '[data-testid=bar][data-id=bar-Apr-17]';
const innerNegTestSelector = '[data-testid=bar][data-id=bar-Jul-17]';
const CUSTOMCLICKSTYLE = {
color: visaColors.categorical_light_purple, // this has to be light enough to require a contrasting stroke
strokeWidth: 1
};
const EXPECTEDHOVEROPACITY = 0.25;
const innerTestProps = {
clickStyle: CUSTOMCLICKSTYLE,
hoverOpacity: EXPECTEDHOVEROPACITY,
interactionKeys: ['cat'],
transitionEndAllSelector: '[data-testid=bar]'
};
it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${
unitTestInteraction[testLoad].name
} interactionKey group`, () =>
unitTestInteraction[testLoad].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNegTestSelector
));
it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${
unitTestInteraction[testUpdate].name
} interactionKey group`, () =>
unitTestInteraction[testUpdate].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNegTestSelector
));
const newInnerTestProps = {
clickStyle: CUSTOMCLICKSTYLE,
hoverOpacity: EXPECTEDHOVEROPACITY,
interactionKeys: ['cat', 'month'],
transitionEndAllSelector: '[data-testid=bar]'
};
it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${
unitTestInteraction[testLoad].name
} interactionKey value`, () =>
unitTestInteraction[testLoad].testFunc(
component,
page,
newInnerTestProps,
'[data-testid=bar][data-id=bar-Apr-17]',
'[data-testid=bar][data-id=bar-May-17]'
));
it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${
unitTestInteraction[testUpdate].name
} interactionKey value`, () =>
unitTestInteraction[testUpdate].testFunc(
component,
page,
newInnerTestProps,
'[data-testid=bar][data-id=bar-Apr-17]',
'[data-testid=bar][data-id=bar-May-17]'
));
});
describe('hoverStyle custom with interaction keys', () => {
const testLoad = 'interaction_hoverStyle_custom_load';
const testUpdate = 'interaction_hoverStyle_custom_update';
const innerTestSelector = '[data-testid=bar][data-id=bar-Apr-17]';
const innerNegTestSelector = '[data-testid=bar][data-id=bar-Jul-17]';
const CUSTOMCLICKSTYLE = {
color: visaColors.categorical_light_purple, // this has to be light enough to require a contrasting stroke
strokeWidth: 1
};
const EXPECTEDHOVEROPACITY = 0.25;
const innerTestProps = {
clickStyle: CUSTOMCLICKSTYLE,
hoverOpacity: EXPECTEDHOVEROPACITY,
interactionKeys: ['cat'],
transitionEndAllSelector: '[data-testid=bar]'
};
it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${
unitTestInteraction[testLoad].name
} interactionKey group`, () =>
unitTestInteraction[testLoad].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNegTestSelector
));
it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${
unitTestInteraction[testUpdate].name
} interactionKey group`, () =>
unitTestInteraction[testUpdate].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerNegTestSelector
));
const newInnerTestProps = {
clickStyle: CUSTOMCLICKSTYLE,
hoverOpacity: EXPECTEDHOVEROPACITY,
interactionKeys: ['cat', 'month'],
transitionEndAllSelector: '[data-testid=bar]'
};
it(`[${unitTestInteraction[testLoad].group}] ${unitTestInteraction[testLoad].prop}: ${
unitTestInteraction[testLoad].name
} interactionKey value`, () =>
unitTestInteraction[testLoad].testFunc(
component,
page,
newInnerTestProps,
'[data-testid=bar][data-id=bar-Apr-17]',
'[data-testid=bar][data-id=bar-May-17]'
));
it(`[${unitTestInteraction[testUpdate].group}] ${unitTestInteraction[testUpdate].prop}: ${
unitTestInteraction[testUpdate].name
} interactionKey value`, () =>
unitTestInteraction[testUpdate].testFunc(
component,
page,
newInnerTestProps,
'[data-testid=bar][data-id=bar-Apr-17]',
'[data-testid=bar][data-id=bar-May-17]'
));
});
});
describe('event-emitter', () => {
// Open issue: https://github.com/ionic-team/stencil/issues/1964
// Jest throwing TypeError : mouseover,mouseout, focus, blur etc.
// TECH-DEBT: Once above issue is resolved, write more precise test for event params.
describe('generic event testing', () => {
describe('bar based events', () => {
Object.keys(unitTestEvent).forEach(test => {
const innerTestProps = {
showTooltip: false
};
const innerTestSelector = '[data-testid=bar]';
it(`[${unitTestEvent[test].group}] ${unitTestEvent[test].prop}: ${unitTestEvent[test].name}`, () =>
unitTestEvent[test].testFunc(component, page, innerTestProps, innerTestSelector, EXPECTEDDATA[0]));
});
});
});
});
describe('data', () => {
describe('uniqueId', () => {
it('refer to generic results above for uniqueID tests', () => {
expect(true).toBeTruthy();
});
});
describe('data', () => {
it('refer to generic results above for data tests', () => {
expect(true).toBeTruthy();
});
});
describe('sort', () => {
it('should render data in ascending order when sortOrder is asc', async () => {
// ARRANGE
const EXPECTEDSORTORDER = 'asc';
const EXPECTEDDATAASC = [
{ month: 'Apr-17', value: 1407543 },
{ month: 'Jul-17', value: 2221233 },
{ month: 'Jan-18', value: 2340000 },
{ month: 'Dec-17', value: 2636346 },
{ month: 'Feb-18', value: 3202340 },
{ month: 'Jun-17', value: 3234002 },
{ month: 'Sep-17', value: 3789221 },
{ month: 'Aug-17', value: 4476321 },
{ month: 'May-17', value: 6042320 },
{ month: 'Oct-17', value: 6543535 },
{ month: 'Nov-17', value: 7457432 },
{ month: 'Mar-18', value: 8503536 }
];
component.sortOrder = EXPECTEDSORTORDER;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const elements = page.doc.querySelectorAll('[data-testid=bar]');
elements.forEach((element, i) => {
expect(element['__data__'].month).toEqual(EXPECTEDDATAASC[i].month); // tslint:disable-line: no-string-literal
});
});
it('should render data in descending order when sortOrder is desc', async () => {
// ARRANGE
const EXPECTEDSORTORDER = 'desc';
const EXPECTEDDATADESC = [
{ month: 'Mar-18', value: 8503536 },
{ month: 'Nov-17', value: 7457432 },
{ month: 'Oct-17', value: 6543535 },
{ month: 'May-17', value: 6042320 },
{ month: 'Aug-17', value: 4476321 },
{ month: 'Sep-17', value: 3789221 },
{ month: 'Jun-17', value: 3234002 },
{ month: 'Feb-18', value: 3202340 },
{ month: 'Dec-17', value: 2636346 },
{ month: 'Jan-18', value: 2340000 },
{ month: 'Jul-17', value: 2221233 },
{ month: 'Apr-17', value: 1407543 }
];
component.sortOrder = EXPECTEDSORTORDER;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const elements = page.doc.querySelectorAll('[data-testid=bar]');
elements.forEach((element, i) => {
expect(element['__data__'].month).toEqual(EXPECTEDDATADESC[i].month); // tslint:disable-line: no-string-literal
});
});
it('should render data in default order when sortOrder is default', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const elements = page.doc.querySelectorAll('[data-testid=bar]');
elements.forEach((element, i) => {
expect(element['__data__'].month).toEqual(EXPECTEDDATA[i].month); // tslint:disable-line: no-string-literal
});
});
});
describe('wrapLabel', () => {
it('should render wrapped ordinal tick labels when wrapLabel is true (default)', async () => {
component.width = 500;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisTicksText = page.doc.querySelectorAll('[data-testid=x-axis] [data-testid=axis-tick-text]');
xAxisTicksText.forEach((text, i) => {
const textTspans = text.querySelectorAll('[data-testid=axis-tick-text-tspan]');
expect(textTspans.length).toBeGreaterThanOrEqual(1);
expect(text['__data__']).toEqual(EXPECTEDDATA[i].month); // tslint:disable-line: no-string-literal
});
});
it('should render unwrapped ordinal tick labels when wrapLabel is false', async () => {
const EXPECTEDWRAPLABEL = false;
component.wrapLabel = EXPECTEDWRAPLABEL;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const xAxisTicksText = page.doc.querySelectorAll('[data-testid=x-axis] [data-testid=axis-tick-text]');
xAxisTicksText.forEach((text, i) => {
expect(text).toEqualText(EXPECTEDDATA[i].month);
});
});
});
});
describe('labels', () => {
describe('tooltip', () => {
const tooltip1 = {
tooltipLabel: {
format: [],
labelAccessor: ['month'],
labelTitle: ['Testing123']
}
};
const tooltip2 = {
tooltipLabel: {
format: ['', '$0[.][0]a'],
labelAccessor: ['cat', 'value'],
labelTitle: ['Testing123', 'Count']
}
};
describe('generic tooltip tests', () => {
Object.keys(unitTestTooltip).forEach(test => {
const innerTestSelector = '[data-testid=bar][data-id=bar-Apr-17]';
const innerTooltipProps = {
tooltip_tooltipLabel_custom_load: tooltip1,
tooltip_tooltipLabel_custom_update: tooltip1,
tooltip_tooltipLabel_custom_format_load: tooltip2,
tooltip_tooltipLabel_custom_format_update: tooltip2
};
const innerTooltipContent = {
tooltip_tooltipLabel_default:
'<p style="margin: 0;"><b></b>X Axis:<b>Apr-17</b><br>Y Axis:<b>1.4m</b></p>',
tooltip_tooltipLabel_custom_load: '<p style="margin: 0;">Testing123:<b>Apr-17</b><br></p>',
tooltip_tooltipLabel_custom_update: '<p style="margin: 0;">Testing123:<b>Apr-17</b><br></p>',
tooltip_tooltipLabel_custom_format_load:
'<p style="margin: 0;">Testing123:<b>A</b><br>Count:<b>$1.4m</b><br></p>',
tooltip_tooltipLabel_custom_format_update:
'<p style="margin: 0;">Testing123:<b>A</b><br>Count:<b>$1.4m</b><br></p>'
};
const innerTestProps = { ...unitTestTooltip[test].testProps, ...innerTooltipProps[test] };
// we have to handle clickFunc separately due to this.zooming boolean in circle-packing load
it(`${unitTestTooltip[test].prop}: ${unitTestTooltip[test].name}`, () =>
unitTestTooltip[test].testFunc(
component,
page,
innerTestProps,
innerTestSelector,
innerTooltipContent[test]
));
});
});
});
describe('dataLabel', () => {
describe('visible', () => {
it('should render dataLabel by default', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
const dataLabel = page.doc.querySelector('[data-testid=dataLabel]');
flushTransitions(dataLabel);
await page.waitForChanges();
expect(dataLabel).toEqualAttribute('opacity', 1);
});
it('should not render the bar data labels if visible is false', async () => {
// ARRANGE // equal earth is the default this should match without setting prop
component.dataLabel = {
visible: false,
labelAccessor: ''
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
const dataLabel = page.doc.querySelector('[data-testid=dataLabel]');
expect(dataLabel).toEqualAttribute('opacity', 0);
});
});
describe('labelAccessor', () => {
it('should default to the value accessor if default', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const dataLabels = page.doc.querySelectorAll('[data-testid=dataLabel]');
dataLabels.forEach((label, i) => {
const expectedLabelValue = formatStats(EXPECTEDDATA[i].value, '0[.][0]a'); // tslint:disable-line: no-string-literal
expect(label).toEqualText(expectedLabelValue);
});
});
it('should render the data labels if visible is true', async () => {
// ARRANGE // equal earth is the default this should match without setting prop
const EXPECTEDDATARANDOM = [
{ month: 'Jan', value: 1250000, random: Math.random() },
{ month: 'Feb', value: 202340, random: Math.random() },
{ month: 'Mar', value: 803536, random: Math.random() },
{ month: 'Apr', value: 1407543, random: Math.random() },
{ month: 'May', value: 6042320, random: Math.random() },
{ month: 'Jun', value: 3234002, random: Math.random() }
];
component.dataLabel = {
visible: true,
labelAccessor: 'random',
format: '0[.][0]%',
position: 'top'
};
component.data = EXPECTEDDATARANDOM;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const dataLabels = page.doc.querySelectorAll('[data-testid=dataLabel]');
dataLabels.forEach((label, i) => {
const expectedLabelValue = formatStats(EXPECTEDDATARANDOM[i].random, '0[.][0]%'); // tslint:disable-line: no-string-literal
expect(label).toEqualText(expectedLabelValue);
});
});
});
describe('format', () => {
it('should format number if passed as prop', async () => {
component.dataLabel = {
visible: true,
labelAccessor: 'value',
format: '$0[.][0]a',
position: 'top'
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const dataLabels = page.doc.querySelectorAll('[data-testid=dataLabel]');
dataLabels.forEach((label, i) => {
const expectedLabelValue = formatStats(EXPECTEDDATA[i].value, '$0[.][0]a'); // tslint:disable-line: no-string-literal
expect(label).toEqualText(expectedLabelValue);
});
});
});
describe('placement', () => {
it('should place labels on top of bars by default', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const label = page.doc.querySelector('[data-testid=dataLabel]');
const bar = page.doc.querySelector('[data-testid=bar]');
flushTransitions(label);
flushTransitions(bar);
await page.waitForChanges();
expect(parseFloat(label.getAttribute('y'))).toBeLessThanOrEqual(parseFloat(bar.getAttribute('y')));
});
it('should place labels on bottom of bars if passed', async () => {
// ARRANGE
component.dataLabel = {
visible: true,
labelAccessor: 'value',
format: '$0[.][0]a',
placement: 'bottom'
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const label = page.doc.querySelector('[data-testid=dataLabel]');
const bar = page.doc.querySelector('[data-testid=bar]');
flushTransitions(label);
flushTransitions(bar);
expect(parseFloat(label.getAttribute('y'))).toBeGreaterThan(parseFloat(bar.getAttribute('y')));
});
});
});
describe('legend', () => {
describe('visible', () => {
it('by default the legend should not render due to lack of group accessor', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendContainer = legendSVG.parentElement;
const legendPaddingG = legendSVG.querySelector('g');
const legendG = legendPaddingG.querySelector('g');
expect(legendContainer.getAttribute('style')).toEqual('display: none;');
expect(legendContainer).toHaveClass('bar-legend');
expect(legendSVG).toEqualAttribute('opacity', 0);
expect(legendPaddingG).toHaveClass('legend-padding-wrapper');
expect(legendG).toHaveClass('legend');
expect(legendG).toHaveClass('bar');
});
it('should render, but not be visible if false is passed', async () => {
component.legend = {
visible: false,
interactive: false,
type: 'bar',
format: '0[.][0][0]a',
labels: ''
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendContainer = legendSVG.parentElement;
expect(legendContainer.getAttribute('style')).toEqual('display: none;');
expect(legendSVG).toEqualAttribute('opacity', 0);
expect(legendSVG.getAttribute('style')).toEqual('display: none;');
});
it('should render, and be visible if groupAccessor is passed', async () => {
component.groupAccessor = 'cat';
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendContainer = legendSVG.parentElement;
const legendPaddingG = legendSVG.querySelector('g');
const legendG = legendPaddingG.querySelectorAll('g');
expect(legendContainer.getAttribute('style')).toEqual('display: block;');
expect(legendSVG).toEqualAttribute('opacity', 1);
expect(legendG.length).toEqual(3);
});
});
describe('type', () => {
it('should be bar default type by default', async () => {
component.groupAccessor = 'cat';
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendG = legendPaddingG.querySelector('g');
expect(legendG).toHaveClass('legend');
expect(legendG).toHaveClass('bar');
});
it('should be bar type even if another type is passed', async () => {
component.groupAccessor = 'cat';
component.legend = {
visible: true,
interactive: false,
type: 'key',
format: '0[.][0][0]a',
labels: ''
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendG = legendPaddingG.querySelector('g');
expect(legendG).toHaveClass('legend');
expect(legendG).toHaveClass('bar');
});
});
describe('interactive', () => {
it('should not be interactive by deafult', async () => {
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendG = legendPaddingG.querySelector('g');
expect(legendG['__on']).toBeUndefined(); // tslint:disable-line: no-string-literal
});
it('should be interactive when interactive prop is true', async () => {
component.groupAccessor = 'cat';
component.legend = {
visible: true,
interactive: true,
type: 'bar',
format: '0[.][0][0]a',
labels: ''
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendG = legendPaddingG.querySelector('g');
expect(legendG['__on'].length).toEqual(3); // tslint:disable-line: no-string-literal
});
});
describe('format', () => {
it('should format number if passed as prop', async () => {
component.groupAccessor = 'cat';
component.legend = {
visible: true,
interactive: true,
type: 'bar',
format: '$0[.][0]a',
labels: [15, 30]
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendGText = legendPaddingG.querySelector('g text');
flushTransitions(legendGText);
expect(legendGText).toEqualText('$15');
});
});
describe('labels', () => {
it('should be equal to data values by default', async () => {
// ARRANGE
component.groupAccessor = 'cat';
const EXPECTEDLABELS = ['A', 'B', 'C'];
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendGs = legendPaddingG.querySelectorAll('g');
await asyncForEach(legendGs, async (legendG, i) => {
const legendGText = legendG.querySelector('text');
flushTransitions(legendGText);
await page.waitForChanges();
expect(legendGText).toEqualText(EXPECTEDLABELS[i]);
});
});
it('should have custom labels when passed as prop', async () => {
const EXPECTEDLABELS = ['D', 'E', 'F'];
component.legend = {
visible: true,
interactive: true,
type: 'bar',
format: '',
labels: EXPECTEDLABELS
};
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const legendSVG = page.doc.querySelector('[data-testid=legend-container]');
const legendPaddingG = legendSVG.querySelector('g');
const legendGs = legendPaddingG.querySelectorAll('g');
await asyncForEach(legendGs, async (legendG, i) => {
const legendGText = legendG.querySelector('text');
flushTransitions(legendGText);
await page.waitForChanges();
expect(legendGText).toEqualText(EXPECTEDLABELS[i]);
});
});
});
});
});
describe('reference line', () => {
it('should pass referenceLines prop', async () => {
// ARRANGE
const referenceLines = [
{ label: 'Market', labelPlacementHorizontal: 'left', labelPlacementVertical: 'bottom', value: 7000000 }
];
component.referenceLines = referenceLines;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const referenceLinesGroup = page.doc.querySelector('[data-testid=reference-line-group]');
expect(referenceLinesGroup).toMatchSnapshot();
});
it('should pass referenceStyle prop', async () => {
// ARRANGE
const referenceLines = [
{ label: 'Market', labelPlacementHorizontal: 'left', labelPlacementVertical: 'bottom', value: 7000000 }
];
const referenceStyle = { color: 'pri_grey', dashed: '', opacity: 0.65, strokeWidth: '1px' };
component.referenceLines = referenceLines;
component.referenceStyle = referenceStyle;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const referenceLine = page.doc.querySelector('[data-testid=reference-line]');
expect(referenceLine).toMatchSnapshot();
});
});
describe('style with textures', () => {
describe('colorPalette', () => {
it('should render texture single blue by default', async () => {
const EXPECTEDFILLCOLOR = getColors('single_blue');
const EXPECTEDTEXTURECOLOR = getContrastingStroke(EXPECTEDFILLCOLOR);
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const patterns = page.doc.querySelector('[data-testid=pattern-defs]').querySelectorAll('pattern');
const bars = page.doc.querySelectorAll('[data-testid=bar]');
const barFillURL = patterns[0].getAttribute('id');
// check pattern settings
expect(patterns[0].querySelector('rect')).toEqualAttribute('fill', EXPECTEDFILLCOLOR);
expect(patterns[0].querySelector('path')).toEqualAttribute('stroke', EXPECTEDTEXTURECOLOR);
bars.forEach(bar => {
expect(bar).toEqualAttribute('fill', `url(#${barFillURL})`);
});
});
it('should load texture single supplement Pink when colorPalette is sequential_suppPink', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'single_suppPink';
component.colorPalette = EXPECTEDCOLORPALETTE;
const EXPECTEDFILLCOLOR = getColors(EXPECTEDCOLORPALETTE);
const EXPECTEDTEXTURECOLOR = getContrastingStroke(EXPECTEDFILLCOLOR);
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const patterns = page.doc.querySelector('[data-testid=pattern-defs]').querySelectorAll('pattern');
const bars = page.doc.querySelectorAll('[data-testid=bar]');
const barFillURL = patterns[0].getAttribute('id');
// check pattern settings
expect(patterns[0].querySelector('rect')).toEqualAttribute('fill', EXPECTEDFILLCOLOR);
expect(patterns[0].querySelector('path')).toEqualAttribute('stroke', EXPECTEDTEXTURECOLOR);
bars.forEach(bar => {
expect(bar).toEqualAttribute('fill', `url(#${barFillURL})`);
});
});
it('should update texture to single supplement Pink when colorPalette is sequential_suppPink', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'single_suppPink';
const EXPECTEDFILLCOLOR = getColors(EXPECTEDCOLORPALETTE);
const EXPECTEDTEXTURECOLOR = getContrastingStroke(EXPECTEDFILLCOLOR);
// ACT LOAD
page.root.appendChild(component);
await page.waitForChanges();
// ACT UPDATE
component.colorPalette = EXPECTEDCOLORPALETTE;
await page.waitForChanges();
// ASSERT
const patterns = page.doc.querySelector('[data-testid=pattern-defs]').querySelectorAll('pattern');
const bars = page.doc.querySelectorAll('[data-testid=bar]');
const barFillURL = patterns[0].getAttribute('id');
// check pattern settings
expect(patterns[0].querySelector('rect')).toEqualAttribute('fill', EXPECTEDFILLCOLOR);
expect(patterns[0].querySelector('path')).toEqualAttribute('stroke', EXPECTEDTEXTURECOLOR);
bars.forEach(bar => {
expect(bar).toEqualAttribute('fill', `url(#${barFillURL})`);
});
});
it('should render categorical textures and color when colorPalette is categorical', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'categorical';
const EXPECTEDSCALE = getColors(
EXPECTEDCOLORPALETTE,
scaleOrdinal()
.domain(EXPECTEDDATA.map(d => d.cat))
.domain()
);
component.groupAccessor = 'cat';
component.colorPalette = EXPECTEDCOLORPALETTE;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const patterns = page.doc.querySelector('[data-testid=pattern-defs]').querySelectorAll('pattern');
const bars = page.doc.querySelectorAll('[data-testid=bar]');
bars.forEach((bar, i) => {
const barColor = EXPECTEDSCALE(EXPECTEDDATA[i].cat);
const barPattern = patterns[EXPECTEDSCALE.domain().findIndex(o => o === EXPECTEDDATA[i].cat)];
const patternFill = barPattern.childNodes[0];
const patternStroke = barPattern.childNodes[1];
const barFillURL = barPattern.getAttribute('id');
// check pattern settings
expect(patternFill).toEqualAttribute('fill', barColor);
const patternStrokeColorTest =
patternStroke.getAttribute('stroke') === getContrastingStroke(barColor) ||
patternStroke.getAttribute('fill') === getContrastingStroke(barColor);
expect(patternStrokeColorTest).toBeTruthy();
expect(bar).toEqualAttribute('fill', `url(#${barFillURL})`);
});
});
});
describe('colors', () => {
it('should render colors texture instead of palette when passed', async () => {
const colors = ['#829e46', '#c18174', '#7a6763', '#796aaf'];
const EXPECTEDSCALE = getColors(
colors,
scaleOrdinal()
.domain(EXPECTEDDATA.map(d => d.cat))
.domain()
);
component.groupAccessor = 'cat';
component.colors = colors;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const patterns = page.doc.querySelector('[data-testid=pattern-defs]').querySelectorAll('pattern');
const bars = page.doc.querySelectorAll('[data-testid=bar]');
bars.forEach((bar, i) => {
const barColor = EXPECTEDSCALE(EXPECTEDDATA[i].cat);
const barPattern = patterns[EXPECTEDSCALE.domain().findIndex(o => o === EXPECTEDDATA[i].cat)];
const patternFill = barPattern.childNodes[0];
const patternStroke = barPattern.childNodes[1];
const barFillURL = barPattern.getAttribute('id');
// check pattern settings
expect(patternFill).toEqualAttribute('fill', barColor);
const patternStrokeColorTest =
patternStroke.getAttribute('stroke') === getContrastingStroke(barColor) ||
patternStroke.getAttribute('fill') === getContrastingStroke(barColor);
expect(patternStrokeColorTest).toBeTruthy();
expect(bar).toEqualAttribute('fill', `url(#${barFillURL})`);
});
});
});
});
describe('style no textures', () => {
beforeEach(() => {
component.accessibility = { ...component.accessibility, hideTextures: true };
});
describe('colorPalette', () => {
it('should render single blue by default', async () => {
const EXPECTEDFILLCOLOR = getColors('single_blue');
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
bars.forEach(bar => {
expect(bar).toEqualAttribute('fill', EXPECTEDFILLCOLOR);
});
});
it('should load single supplement Pink when colorPalette is sequential_suppPink', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'single_suppPink';
component.colorPalette = EXPECTEDCOLORPALETTE;
const EXPECTEDFILLCOLOR = getColors(EXPECTEDCOLORPALETTE);
// component.data = EXPECTEDDATALARGE;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('fill', EXPECTEDFILLCOLOR);
});
});
it('should update to single supplement Pink when colorPalette is sequential_suppPink', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'single_suppPink';
const EXPECTEDFILLCOLOR = getColors(EXPECTEDCOLORPALETTE);
// component.data = EXPECTEDDATALARGE;
// ACT LOAD
page.root.appendChild(component);
await page.waitForChanges();
// ACT UPDATE
component.colorPalette = EXPECTEDCOLORPALETTE;
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async bar => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('fill', EXPECTEDFILLCOLOR);
});
});
it('should render sequential blue when colorPalette is sequential_orange', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'sequential_secOrange';
const EXPECTEDSCALE = getColors(EXPECTEDCOLORPALETTE, [MINVALUE, MAXVALUE]);
component.colorPalette = EXPECTEDCOLORPALETTE;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async (bar, i) => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('fill', EXPECTEDSCALE(EXPECTEDDATA[i].value));
});
});
it('should render categorical color when colorPalette is categorical', async () => {
// ARRANGE
const EXPECTEDCOLORPALETTE = 'categorical';
const EXPECTEDSCALE = getColors(
EXPECTEDCOLORPALETTE,
scaleOrdinal()
.domain(EXPECTEDDATA.map(d => d.cat))
.domain()
);
component.groupAccessor = 'cat';
component.colorPalette = EXPECTEDCOLORPALETTE;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async (bar, i) => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('fill', EXPECTEDSCALE(EXPECTEDDATA[i].cat));
});
});
});
describe('colors', () => {
it('should render colors instead of palette when passed', async () => {
const colors = ['#829e46', '#c18174', '#7a6763', '#796aaf'];
const EXPECTEDSCALE = getColors(
colors,
scaleOrdinal()
.domain(EXPECTEDDATA.map(d => d.cat))
.domain()
);
component.groupAccessor = 'cat';
component.colors = colors;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
await asyncForEach(bars, async (bar, i) => {
flushTransitions(bar);
await page.waitForChanges();
expect(bar).toEqualAttribute('fill', EXPECTEDSCALE(EXPECTEDDATA[i].cat));
});
});
});
describe('cursor', () => {
it('refer to generic interaction results above for cursor tests', () => {
expect(true).toBeTruthy();
});
});
describe('roundedCorner', () => {
it('should render rectangle bars when roundedCorner is zero (default)', async () => {
// ARRANGE
const EXPECTEDROUNDEDCORNER = 0;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
bars.forEach(bar => {
expect(bar).toEqualAttribute('rx', EXPECTEDROUNDEDCORNER);
expect(bar).toEqualAttribute('ry', EXPECTEDROUNDEDCORNER);
});
});
it('should render rounded bars when roundedCorner is non-zero positive number', async () => {
// ARRANGE
const EXPECTEDROUNDEDCORNER = 5;
component.roundedCorner = EXPECTEDROUNDEDCORNER;
// ACT
page.root.appendChild(component);
await page.waitForChanges();
// ASSERT
const bars = page.doc.querySelectorAll('[data-testid=bar]');
bars.forEach(bar => {
expect(bar).toEqualAttribute('rx', EXPECTEDROUNDEDCORNER);
expect(bar).toEqualAttribute('ry', EXPECTEDROUNDEDCORNER);
});
});
});
});
describe('aria-property', () => {
// TODO: write unit test cases for aria-property
});
describe('methods', () => {
// TODO: write unit test cases for component methods if any
});
});
}); | the_stack |
import { line as d3Line, Line } from 'd3-shape'
import { format as d3Format } from 'd3-format'
import { scaleLinear as d3ScaleLinear, scaleLog as d3ScaleLog, ScaleLinear, ScaleLogarithmic } from 'd3-scale'
import { axisLeft as d3AxisLeft, axisBottom as d3AxisBottom, Axis } from 'd3-axis'
import { zoom as d3Zoom } from 'd3-zoom'
// @ts-ignore
import { select as d3Select, pointer as d3Pointer, Selection } from 'd3-selection'
import { interpolateRound as d3InterpolateRound } from 'd3-interpolate'
import EventEmitter from 'events'
import { FunctionPlotOptions, FunctionPlotDatum } from './types'
import annotations from './helpers/annotations'
import mousetip from './tip'
import helpers from './helpers'
import datumDefaults from './datum-defaults'
import globals from './globals'
import * as graphTypes from './graph-types'
import * as $eval from './helpers/eval'
require('./polyfills')
const d3Scale = { linear: d3ScaleLinear, log: d3ScaleLog }
interface ChartMetaMargin {
left?: number
right?: number
top?: number
bottom?: number
}
export interface ChartMeta {
/**
* graph's left, right, top, bottom margins
*/
margin?: ChartMetaMargin
/**
* width of the canvas (minus the margins)
*/
width?: number
/**
* height of the canvas (minus the margins)
*/
height?: number
zoomBehavior?: any
xScale?: ScaleLinear<number, number> // | ScaleLogarithmic<number, number>
yScale?: ScaleLinear<number, number> // | ScaleLogarithmic<number, number>
xAxis?: Axis<any>
yAxis?: Axis<any>
xDomain?: number[]
yDomain?: number[]
}
/**
* An instance can subscribe to any of the following events by doing `instance.on([eventName], callback)`,
* events can be triggered by doing `instance.emit([eventName][, params])`
*
* - `mouseover` fired whenever the mouse is over the canvas
* - `mousemove` fired whenever the mouse is moved inside the canvas, callback params: a single object `{x: number, y: number}` (in canvas space
coordinates)
* - `mouseout` fired whenever the mouse is moved outside the canvas
* - `before:draw` fired before drawing all the graphs
* - `after:draw` fired after drawing all the graphs
* - `zoom:scaleUpdate` fired whenever the scale of another graph is updated, callback params `xScale`, `yScale`
(x-scale and y-scale of another graph whose scales were updated)
* - `tip:update` fired whenever the tip position is updated, callback params `{x, y, index}` (in canvas
space coordinates, `index` is the index of the graph where the tip is on top of)
* - `eval` fired whenever the sampler evaluates a function, callback params `data` (an array of segment/points),
`index` (the index of datum in the `data` array), `isHelper` (true if the data is created for a helper e.g.
for the derivative/secant)
*
* The following events are dispatched to all the linked graphs
*
* - `all:mouseover` same as `mouseover` but it's dispatched in each linked graph
* - `all:mousemove` same as `mousemove` but it's dispatched in each linked graph
* - `all:mouseout` same as `mouseout` but it's dispatched in each linked graph
* - `all:zoom:scaleUpdate` same as `zoom:scaleUpdate` but it's dispatched in each linked graph
* - `all:zoom` fired whenever there's scaling/translation on the graph, dispatched on all the linked graphs
*/
export class Chart extends EventEmitter.EventEmitter {
static cache: Record<string, Chart> = {}
private readonly id: string
readonly markerId: string
public options: FunctionPlotOptions
public meta: ChartMeta
/**
* Array of function-plot instances linked to the events of this instance,
i.e. when the zoom event is dispatched on this instance it's also dispatched on all the instances of
this array
*/
private linkedGraphs: Array<Chart>
private line: Line<[number, number]>
/**
* `svg` element that holds the graph (canvas + title + axes)
*/
public root: any
/**
* Element that holds the tip
*/
public tip: any
/**
* `g.canvas` element that holds the area where the graphs are plotted (clipped with a mask)
*/
public canvas: any
/**
* Element that holds the canvas where the functions are drawn
*/
public content: any
/**
* Draggable element that receives zoom and pan events
*/
public draggable: any
constructor(options: FunctionPlotOptions) {
super()
const n = Math.random()
const letter = String.fromCharCode(Math.floor(n * 26) + 97)
this.options = options
this.id = letter + n.toString(16).substr(2)
this.options.id = this.id
this.markerId = this.id + '-marker'
Chart.cache[this.id] = this
this.linkedGraphs = [this]
this.meta = {}
this.setUpEventListeners()
}
/**
* Rebuilds the entire graph from scratch recomputing
*
* - the inner width/height
* - scales/axes
*
* After this is done it does a complete redraw of all the datums,
* if only the datums need to be redrawn call `instance.draw()` instead
*
* @returns {Chart}
*/
build() {
this.internalVars()
this.drawGraphWrapper()
return this
}
private getDraggableNode() {
return d3Select(this.options.target).select('.zoom-and-drag').node()
}
/**
* The draggable container won't change across different instances of Chart,
* therefore multiple instances will share the draggable container, to avoid dispatching
* the event from the old instance grab it in runtime with this function
*/
private getEmitInstance() {
let cachedInstance = this
const cachedNode = this.getDraggableNode()
if (cachedNode) {
cachedInstance = (cachedNode as any).instance
}
return cachedInstance
}
internalVars() {
const self = this
const margin = this.meta.margin = { left: 40, right: 20, top: 20, bottom: 20 }
// if there's a title make the top margin bigger
if (this.options.title) {
this.meta.margin.top = 40
}
// inner width/height
this.meta.width = (this.options.width || globals.DEFAULT_WIDTH) - margin.left - margin.right
this.meta.height = (this.options.height || globals.DEFAULT_HEIGHT) - margin.top - margin.bottom
this.initializeAxes()
}
initializeAxes() {
const self = this
const integerFormat = d3Format('~s')
const floatFormat = d3Format('~e')
function formatter (d: number): string {
// take only the decimal part of the number
const frac = Math.abs(d) - Math.floor(Math.abs(d))
if (frac > 0) {
return d.toString()
} else {
return integerFormat(d)
}
}
function computeYScale (xScale: number[]) {
// assumes that xScale is a linear scale
const xDiff = xScale[1] - xScale[0]
return self.meta.height * xDiff / self.meta.width
}
this.options.xAxis = this.options.xAxis || {}
this.options.xAxis.type = this.options.xAxis.type || 'linear'
this.options.yAxis = this.options.yAxis || {}
this.options.yAxis.type = this.options.yAxis.type || 'linear'
const xDomain = this.meta.xDomain = (function (axis) {
if (axis.domain) {
return axis.domain
}
if (axis.type === 'linear') {
const xLimit = 12
return [-xLimit / 2, xLimit / 2]
} else if (axis.type === 'log') {
return [1, 10]
}
throw Error('axis type ' + axis.type + ' unsupported')
})(this.options.xAxis)
const yDomain = this.meta.yDomain = (function (axis) {
if (axis.domain) {
return axis.domain
}
const yLimit = computeYScale(xDomain)
if (axis.type === 'linear') {
return [-yLimit / 2, yLimit / 2]
} else if (axis.type === 'log') {
return [1, 10]
}
throw Error('axis type ' + axis.type + ' unsupported')
})(this.options.yAxis)
if (!this.meta.xScale) {
this.meta.xScale = d3Scale[this.options.xAxis.type]()
}
this.meta.xScale
.domain(xDomain)
.range(this.options.xAxis.invert ? [this.meta.width, 0] : [0, this.meta.width])
if (!this.meta.yScale) {
this.meta.yScale = d3Scale[this.options.yAxis.type]()
}
this.meta.yScale
.domain(yDomain)
.range(this.options.yAxis.invert ? [0, this.meta.height] : [this.meta.height, 0])
if (!this.meta.xAxis) {
this.meta.xAxis = d3AxisBottom(this.meta.xScale)
}
this.meta.xAxis
.tickSize(this.options.grid ? -this.meta.height : 0)
.tickFormat(formatter)
if (!this.meta.yAxis) {
this.meta.yAxis = d3AxisLeft(this.meta.yScale)
}
this.meta.yAxis
.tickSize(this.options.grid ? -this.meta.width : 0)
.tickFormat(formatter)
this.line = d3Line()
.x(function (d) { return self.meta.xScale(d[0]) })
.y(function (d) { return self.meta.yScale(d[1]) })
}
drawGraphWrapper () {
const root = this.root = d3Select(this.options.target)
.selectAll('svg')
.data([this.options])
// enter
this.root.enter = root.enter()
.append('svg')
.attr('class', 'function-plot')
.attr('font-size', this.getFontSize())
// enter + update
root.merge(this.root.enter)
.attr('width', this.meta.width + this.meta.margin.left + this.meta.margin.right)
.attr('height', this.meta.height + this.meta.margin.top + this.meta.margin.bottom)
this.buildTitle()
this.buildLegend()
this.buildCanvas()
this.buildClip()
this.buildAxis()
this.buildAxisLabel()
// draw each datum after the wrapper was set up
this.draw()
// helper to detect the closest fn to the cursor's current abscissa
const tip = this.tip = mousetip(Object.assign(this.options.tip || {}, { owner: this }))
this.canvas.merge(this.canvas.enter)
.call(tip)
this.buildZoomHelper()
this.setUpPlugins()
}
buildTitle() {
// join
const selection = this.root.merge(this.root.enter)
.selectAll('text.title')
.data(function (d: FunctionPlotOptions) {
return [d.title].filter(Boolean)
})
// enter
const selectionEnter = selection.enter()
.append('text')
selectionEnter.merge(selection)
.attr('class', 'title')
.attr('y', this.meta.margin.top / 2)
.attr('x', this.meta.margin.left + this.meta.width / 2)
.attr('font-size', 25)
.attr('text-anchor', 'middle')
.attr('alignment-baseline', 'middle')
.text(this.options.title)
// exit
selection.exit().remove()
}
buildLegend() {
// enter
this.root.enter
.append('text')
.attr('class', 'top-right-legend')
.attr('text-anchor', 'end')
// update + enter
this.root.merge(this.root.enter)
.select('.top-right-legend')
.attr('y', this.meta.margin.top / 2)
.attr('x', this.meta.width + this.meta.margin.left)
}
buildCanvas() {
// enter
const canvas = this.canvas = this.root.merge(this.root.enter)
.selectAll('.canvas')
.data(function (d: FunctionPlotOptions) {
return [d]
})
this.canvas.enter = canvas.enter()
.append('g')
.attr('class', 'canvas')
// enter + update
}
buildClip() {
// (so that the functions don't overflow on zoom or drag)
const id = this.id
const defs = this.canvas.enter
.append('defs')
defs.append('clipPath')
.attr('id', 'function-plot-clip-' + id)
.append('rect')
.attr('class', 'clip static-clip')
// enter + update
this.canvas.merge(this.canvas.enter)
.selectAll('.clip')
.attr('width', this.meta.width)
.attr('height', this.meta.height)
// marker clip (for vectors)
defs.append('clipPath')
.append('marker')
.attr('id', this.markerId)
.attr('viewBox', '0 -5 10 10')
.attr('refX', 10)
.attr('markerWidth', 5)
.attr('markerHeight', 5)
.attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5L0,0')
.attr('stroke-width', '0px')
.attr('fill-opacity', 1)
.attr('fill', '#777')
}
buildAxis() {
// axis creation
const canvasEnter = this.canvas.enter
canvasEnter.append('g')
.attr('class', 'x axis')
canvasEnter.append('g')
.attr('class', 'y axis')
// update
this.canvas.merge(this.canvas.enter)
.select('.x.axis')
.attr('transform', 'translate(0,' + this.meta.height + ')')
.call(this.meta.xAxis)
this.canvas.merge(this.canvas.enter)
.select('.y.axis')
.call(this.meta.yAxis)
}
buildAxisLabel() {
// axis labeling
const canvas = this.canvas
const xLabel = canvas.merge(canvas.enter)
.selectAll('text.x.axis-label')
.data(function (d: FunctionPlotOptions) {
return [d.xAxis.label].filter(Boolean)
})
const xLabelEnter = xLabel.enter()
.append('text')
.attr('class', 'x axis-label')
.attr('text-anchor', 'end')
xLabel.merge(xLabelEnter)
.attr('x', this.meta.width)
.attr('y', this.meta.height - 6)
.text(function (d: string) { return d })
xLabel.exit().remove()
const yLabel = canvas.merge(canvas.enter)
.selectAll('text.y.axis-label')
.data(function (d: FunctionPlotOptions) {
return [d.yAxis.label].filter(Boolean)
})
const yLabelEnter = yLabel.enter()
.append('text')
.attr('class', 'y axis-label')
.attr('y', 6)
.attr('dy', '.75em')
.attr('text-anchor', 'end')
.attr('transform', 'rotate(-90)')
yLabel.merge(yLabelEnter)
.text(function (d: string) { return d })
yLabel.exit().remove()
}
/**
* @private
*
* Draws each of the datums stored in data.options, to do a full
* redraw call `instance.draw()`
*/
buildContent() {
const self = this
const canvas = this.canvas
canvas.merge(canvas.enter)
.attr('transform', 'translate(' + this.meta.margin.left + ',' + this.meta.margin.top + ')')
const content = this.content = canvas.merge(canvas.enter)
.selectAll(':scope > g.content')
.data(function (d: FunctionPlotOptions) { return [d] })
// g tag clipped to hold the data
const contentEnter = content.enter()
.append('g')
.attr('clip-path', 'url(#function-plot-clip-' + this.id + ')')
.attr('class', 'content')
// helper line, x = 0
if (this.options.xAxis.type === 'linear') {
const yOrigin = content.merge(contentEnter).selectAll(':scope > path.y.origin')
.data([[
[0, this.meta.yScale.domain()[0]],
[0, this.meta.yScale.domain()[1]]
]])
const yOriginEnter = yOrigin.enter()
.append('path')
.attr('class', 'y origin')
.attr('stroke', 'black')
.attr('opacity', 0.2)
yOrigin.merge(yOriginEnter)
.attr('d', this.line)
}
// helper line y = 0
if (this.options.yAxis.type === 'linear') {
const xOrigin = content.merge(contentEnter).selectAll(':scope > path.x.origin')
.data([[[this.meta.xScale.domain()[0], 0], [this.meta.xScale.domain()[1], 0]]])
const xOriginEnter = xOrigin.enter()
.append('path')
.attr('class', 'x origin')
.attr('stroke', 'black')
.attr('opacity', 0.2)
xOrigin.merge(xOriginEnter)
.attr('d', this.line)
}
// annotations
content.merge(contentEnter)
.call(annotations({ owner: self }))
// content construction
// - join options.data to <g class='graph'> elements
// - for each datum determine the sampler to use
const graphs = content.merge(contentEnter)
.selectAll(':scope > g.graph')
.data((d: FunctionPlotOptions) => d.data.map(datumDefaults))
// enter
const graphsEnter = graphs
.enter()
.append('g')
.attr('class', 'graph')
// enter + update
graphs.merge(graphsEnter)
.each(function (d: FunctionPlotDatum, index: number) {
// additional options needed in the graph-types/helpers
d.index = index
const selection = d3Select(this)
selection.call(graphTypes[d.graphType](self))
selection.call(helpers(self))
})
}
buildZoomHelper() {
// dummy rect (detects the zoom + drag)
const self = this
if (!this.meta.zoomBehavior) {
this.meta.zoomBehavior = d3Zoom()
.on('zoom', function onZoom (ev) {
self.getEmitInstance().emit('all:zoom', ev)
})
// the zoom behavior must work with a copy of the scale, the zoom behavior has its own state and assumes
// that its updating the original scale!
// things that failed when I tried rescaleX(self.meta.xScale), the state of self.meta.xScale was a multiplied
// for zoom/mousemove operations
//
// this copy should only be created once when the application starts
self.meta.zoomBehavior.xScale = self.meta.xScale.copy()
self.meta.zoomBehavior.yScale = self.meta.yScale.copy()
}
// in the case where the original scale domains were updated (because of a change in the size of the canvas)
// update the range only but not the domain, the domain is going to be updated
self.meta.zoomBehavior.xScale.range(self.meta.xScale.range())
self.meta.zoomBehavior.yScale.range(self.meta.yScale.range())
// enter
this.canvas.enter
.append('rect')
.call(this.meta.zoomBehavior)
.attr('class', 'zoom-and-drag')
.style('fill', 'none')
.style('pointer-events', 'all')
.on('mouseover', function (event: any) {
self.getEmitInstance().emit('all:mouseover', event)
})
.on('mouseout', function (event: any) {
self.getEmitInstance().emit('all:mouseout', event)
})
.on('mousemove', function (event: any) {
self.getEmitInstance().emit('all:mousemove', event)
})
// update + enter
this.draggable = this.canvas.merge(this.canvas.enter).select('.zoom-and-drag')
.call((selection: any) => {
if (selection.node()) {
// store the instance for the next run
selection.node().instance = self
}
})
.attr('width', this.meta.width)
.attr('height', this.meta.height)
}
setUpPlugins() {
const plugins = this.options.plugins || []
const self = this
plugins.forEach(function (plugin) {
plugin(self)
})
}
addLink() {
for (let i = 0; i < arguments.length; i += 1) {
this.linkedGraphs.push(arguments[i])
}
}
updateAxes() {
const instance = this
const canvas = instance.canvas.merge(instance.canvas.enter)
canvas.select('.x.axis').call(instance.meta.xAxis)
canvas.select('.y.axis').call(instance.meta.yAxis)
// updates the style of the axes
canvas
.selectAll('.axis path, .axis line')
.attr('fill', 'none')
.attr('stroke', 'black')
.attr('shape-rendering', 'crispedges')
.attr('opacity', 0.1)
}
syncOptions() {
// update the original options yDomain and xDomain, this is done so that next calls to functionPlot()
// with the same object preserve some of the computed state
this.options.xAxis.domain = this.meta.xScale.domain()
this.options.yAxis.domain = this.meta.yScale.domain()
}
getFontSize() {
return Math.max(Math.max(this.meta.width, this.meta.height) / 50, 8)
}
draw() {
const instance = this
instance.emit('before:draw')
instance.syncOptions()
instance.updateAxes()
instance.buildContent()
instance.emit('after:draw')
}
setUpEventListeners() {
const self = this
// before setting up the listeners, remove any listeners set on the previous instance, this happens because
// the draggable container is shared across instances
const prevInstance = this.getEmitInstance()
if (prevInstance) {
prevInstance.removeAllListeners()
}
const events = {
mousemove: function (coordinates: {x: number, y: number}) {
self.tip.move(coordinates)
},
mouseover: function () {
self.tip.show()
},
mouseout: function () {
self.tip.hide()
},
zoom: function zoom ({ transform }: any) {
// disable zoom
if (self.options.disableZoom) return
const xScaleClone = transform.rescaleX(self.meta.zoomBehavior.xScale).interpolate(d3InterpolateRound)
const yScaleClone = transform.rescaleY(self.meta.zoomBehavior.yScale).interpolate(d3InterpolateRound)
// update the scales's metadata
// NOTE: setting self.meta.xScale = self.meta.zoomBehavior.xScale creates artifacts and weird lines
self.meta.xScale
.domain(xScaleClone.domain())
.range(xScaleClone.range())
self.meta.yScale
.domain(yScaleClone.domain())
.range(yScaleClone.range())
},
'tip:update': function ({ x, y, index }: any) {
const meta = self.root.merge(self.root.enter).datum().data[index]
const title = meta.title || ''
const format = meta.renderer || function (x: number, y: number) {
return x.toFixed(3) + ', ' + y.toFixed(3)
}
const text = []
title && text.push(title)
text.push(format(x, y))
self.root.select('.top-right-legend')
.attr('fill', globals.COLORS[index])
.text(text.join(' '))
}
}
// all represents events that can be propagated to all the instances (including this one)
const all = {
mousemove: function (event: any) {
const mouse = d3Pointer(event, self.draggable.node())
const coordinates = {
x: self.meta.xScale.invert(mouse[0]),
y: self.meta.yScale.invert(mouse[1])
}
self.linkedGraphs.forEach(function (graph) {
graph.emit('before:mousemove', coordinates)
graph.emit('mousemove', coordinates)
})
},
zoom: function (event: any) {
self.linkedGraphs.forEach(function (graph) {
// hack to synchronize the zoom state across all the instances
graph.draggable.node().__zoom = self.draggable.node().__zoom
graph.emit('zoom', event)
graph.draw()
})
// emit the position of the mouse to all the registered graphs
self.emit('all:mousemove', event)
}
}
Object.keys(events).forEach(function (e) {
// create an event for each event existing on `events` in the form 'all:' event
// e.g. all:mouseover all:mouseout
// the objective is that all the linked graphs receive the same event as the current graph
// @ts-ignore
!all[e] && self.on('all:' + e, function () {
const args = Array.prototype.slice.call(arguments)
self.linkedGraphs.forEach(function (graph) {
const localArgs = args.slice()
localArgs.unshift(e)
graph.emit.apply(graph, localArgs)
})
})
// @ts-ignore
self.on(e, events[e])
})
Object.keys(all).forEach(function (e) {
// @ts-ignore
self.on('all:' + e, all[e])
})
}
}
function functionPlot (options: FunctionPlotOptions = {target: null}) {
options.data = options.data || []
let instance = Chart.cache[options.id]
if (!instance) {
instance = new Chart(options)
}
return instance.build()
}
functionPlot.globals = globals
functionPlot.$eval = $eval
functionPlot.graphTypes = graphTypes
export default functionPlot | the_stack |
import React, { memo, useMemo } from 'react';
import { ViewProps } from 'react-native';
//#region reanimated & gesture handler
import {
TapGestureHandler,
LongPressGestureHandler,
TapGestureHandlerGestureEvent,
LongPressGestureHandlerGestureEvent,
} from 'react-native-gesture-handler';
import Animated, {
measure,
runOnJS,
useAnimatedGestureHandler,
useAnimatedProps,
useAnimatedRef,
useAnimatedStyle,
useSharedValue,
withDelay,
withTiming,
withSequence,
withSpring,
useAnimatedReaction,
} from 'react-native-reanimated';
//#endregion
//#region dependencies
import { Portal } from '@gorhom/portal';
import { nanoid } from 'nanoid/non-secure';
import * as Haptics from 'expo-haptics';
//#endregion
//#region utils & types
import {
TransformOriginAnchorPosition,
getTransformOrigin,
calculateMenuHeight,
} from '../../utils/calculations';
import {
HOLD_ITEM_TRANSFORM_DURATION,
HOLD_ITEM_SCALE_DOWN_DURATION,
HOLD_ITEM_SCALE_DOWN_VALUE,
SPRING_CONFIGURATION,
WINDOW_HEIGHT,
WINDOW_WIDTH,
CONTEXT_MENU_STATE,
} from '../../constants';
import { useDeviceOrientation } from '../../hooks';
import styles from './styles';
import type { HoldItemProps, GestureHandlerProps } from './types';
import styleGuide from '../../styleGuide';
import { useInternal } from '../../hooks';
//#endregion
type Context = { didMeasureLayout: boolean };
const HoldItemComponent = ({
items,
bottom,
containerStyles,
disableMove,
menuAnchorPosition,
activateOn,
hapticFeedback,
actionParams,
closeOnTap,
children,
}: HoldItemProps) => {
//#region hooks
const { state, menuProps } = useInternal();
const deviceOrientation = useDeviceOrientation();
//#endregion
//#region variables
const isActive = useSharedValue(false);
const isAnimationStarted = useSharedValue(false);
const itemRectY = useSharedValue<number>(0);
const itemRectX = useSharedValue<number>(0);
const itemRectWidth = useSharedValue<number>(0);
const itemRectHeight = useSharedValue<number>(0);
const itemScale = useSharedValue<number>(1);
const transformValue = useSharedValue<number>(0);
const transformOrigin = useSharedValue<TransformOriginAnchorPosition>(
menuAnchorPosition || 'top-right'
);
const key = useMemo(() => `hold-item-${nanoid()}`, []);
const menuHeight = useMemo(() => {
const itemsWithSeparator = items.filter(item => item.withSeparator);
return calculateMenuHeight(items.length, itemsWithSeparator.length);
}, [items]);
const isHold = !activateOn || activateOn === 'hold';
//#endregion
//#region refs
const containerRef = useAnimatedRef<Animated.View>();
//#endregion
//#region functions
const hapticResponse = () => {
const style = !hapticFeedback ? 'Medium' : hapticFeedback;
switch (style) {
case `Selection`:
Haptics.selectionAsync();
break;
case `Light`:
case `Medium`:
case `Heavy`:
Haptics.impactAsync(Haptics.ImpactFeedbackStyle[style]);
break;
case `Success`:
case `Warning`:
case `Error`:
Haptics.notificationAsync(Haptics.NotificationFeedbackType[style]);
break;
default:
}
};
//#endregion
//#region worklet functions
const activateAnimation = (ctx: any) => {
'worklet';
if (!ctx.didMeasureLayout) {
const measured = measure(containerRef);
itemRectY.value = measured.pageY;
itemRectX.value = measured.pageX;
itemRectHeight.value = measured.height;
itemRectWidth.value = measured.width;
if (!menuAnchorPosition) {
const position = getTransformOrigin(
measured.pageX,
itemRectWidth.value,
deviceOrientation === 'portrait' ? WINDOW_WIDTH : WINDOW_HEIGHT,
bottom
);
transformOrigin.value = position;
}
}
};
const calculateTransformValue = () => {
'worklet';
const height =
deviceOrientation === 'portrait' ? WINDOW_HEIGHT : WINDOW_WIDTH;
const isAnchorPointTop = transformOrigin.value.includes('top');
let tY = 0;
if (!disableMove) {
if (isAnchorPointTop) {
const topTransform =
itemRectY.value +
itemRectHeight.value +
menuHeight +
styleGuide.spacing * 2;
tY = topTransform > height ? height - topTransform : 0;
} else {
const bototmTransform = itemRectY.value - menuHeight;
tY =
bototmTransform < 0 ? -bototmTransform + styleGuide.spacing * 2 : 0;
}
}
return tY;
};
const setMenuProps = () => {
'worklet';
menuProps.value = {
itemHeight: itemRectHeight.value,
itemWidth: itemRectWidth.value,
itemY: itemRectY.value,
itemX: itemRectX.value,
anchorPosition: transformOrigin.value,
menuHeight: menuHeight,
items,
transformValue: transformValue.value,
actionParams: actionParams || {},
};
};
const scaleBack = () => {
'worklet';
itemScale.value = withTiming(1, {
duration: HOLD_ITEM_TRANSFORM_DURATION / 2,
});
};
const onCompletion = (isFinised: boolean) => {
'worklet';
const isListValid = items && items.length > 0;
if (isFinised && isListValid) {
state.value = CONTEXT_MENU_STATE.ACTIVE;
isActive.value = true;
scaleBack();
if (hapticFeedback !== 'None') {
runOnJS(hapticResponse)();
}
}
isAnimationStarted.value = false;
// TODO: Warn user if item list is empty or not given
};
const scaleHold = () => {
'worklet';
itemScale.value = withTiming(
HOLD_ITEM_SCALE_DOWN_VALUE,
{ duration: HOLD_ITEM_SCALE_DOWN_DURATION },
onCompletion
);
};
const scaleTap = () => {
'worklet';
isAnimationStarted.value = true;
itemScale.value = withSequence(
withTiming(HOLD_ITEM_SCALE_DOWN_VALUE, {
duration: HOLD_ITEM_SCALE_DOWN_DURATION,
}),
withTiming(
1,
{
duration: HOLD_ITEM_TRANSFORM_DURATION / 2,
},
onCompletion
)
);
};
/**
* When use tap activation ("tap") and trying to tap multiple times,
* scale animation is called again despite it is started. This causes a bug.
* To prevent this, it is better to check is animation already started.
*/
const canCallActivateFunctions = () => {
'worklet';
const willActivateWithTap =
activateOn === 'double-tap' || activateOn === 'tap';
return (
(willActivateWithTap && !isAnimationStarted.value) || !willActivateWithTap
);
};
//#endregion
//#region gesture events
const gestureEvent = useAnimatedGestureHandler<
LongPressGestureHandlerGestureEvent | TapGestureHandlerGestureEvent,
Context
>({
onActive: (_, context) => {
if (canCallActivateFunctions()) {
if (!context.didMeasureLayout) {
activateAnimation(context);
transformValue.value = calculateTransformValue();
setMenuProps();
context.didMeasureLayout = true;
}
if (!isActive.value) {
if (isHold) {
scaleHold();
} else {
scaleTap();
}
}
}
},
onFinish: (_, context) => {
context.didMeasureLayout = false;
if (isHold) {
scaleBack();
}
},
});
const overlayGestureEvent = useAnimatedGestureHandler<
TapGestureHandlerGestureEvent,
Context
>({
onActive: _ => {
if (closeOnTap) state.value = CONTEXT_MENU_STATE.END;
},
});
//#endregion
//#region animated styles & props
const animatedContainerStyle = useAnimatedStyle(() => {
const animateOpacity = () =>
withDelay(HOLD_ITEM_TRANSFORM_DURATION, withTiming(1, { duration: 0 }));
return {
opacity: isActive.value ? 0 : animateOpacity(),
transform: [
{
scale: isActive.value
? withTiming(1, { duration: HOLD_ITEM_TRANSFORM_DURATION })
: itemScale.value,
},
],
};
});
const containerStyle = React.useMemo(
() => [containerStyles, animatedContainerStyle],
[containerStyles, animatedContainerStyle]
);
const animatedPortalStyle = useAnimatedStyle(() => {
const animateOpacity = () =>
withDelay(HOLD_ITEM_TRANSFORM_DURATION, withTiming(0, { duration: 0 }));
let tY = calculateTransformValue();
const transformAnimation = () =>
disableMove
? 0
: isActive.value
? withSpring(tY, SPRING_CONFIGURATION)
: withTiming(-0.1, { duration: HOLD_ITEM_TRANSFORM_DURATION });
return {
zIndex: 10,
position: 'absolute',
top: itemRectY.value,
left: itemRectX.value,
width: itemRectWidth.value,
height: itemRectHeight.value,
opacity: isActive.value ? 1 : animateOpacity(),
transform: [
{
translateY: transformAnimation(),
},
{
scale: isActive.value
? withTiming(1, { duration: HOLD_ITEM_TRANSFORM_DURATION })
: itemScale.value,
},
],
};
});
const portalContainerStyle = useMemo(
() => [styles.holdItem, animatedPortalStyle],
[animatedPortalStyle]
);
const animatedPortalProps = useAnimatedProps<ViewProps>(() => ({
pointerEvents: isActive.value ? 'auto' : 'none',
}));
//#endregion
//#region animated effects
useAnimatedReaction(
() => state.value,
_state => {
if (_state === CONTEXT_MENU_STATE.END) {
isActive.value = false;
}
}
);
//#endregion
//#region components
const GestureHandler = useMemo(() => {
switch (activateOn) {
case `double-tap`:
return ({ children: handlerChildren }: GestureHandlerProps) => (
<TapGestureHandler
numberOfTaps={2}
onHandlerStateChange={gestureEvent}
>
{handlerChildren}
</TapGestureHandler>
);
case `tap`:
return ({ children: handlerChildren }: GestureHandlerProps) => (
<TapGestureHandler
numberOfTaps={1}
onHandlerStateChange={gestureEvent}
>
{handlerChildren}
</TapGestureHandler>
);
// default is hold
default:
return ({ children: handlerChildren }: GestureHandlerProps) => (
<LongPressGestureHandler
minDurationMs={150}
onHandlerStateChange={gestureEvent}
>
{handlerChildren}
</LongPressGestureHandler>
);
}
}, [activateOn, gestureEvent]);
const PortalOverlay = useMemo(() => {
return () => (
<TapGestureHandler
numberOfTaps={1}
onHandlerStateChange={overlayGestureEvent}
>
<Animated.View style={styles.portalOverlay} />
</TapGestureHandler>
);
}, [overlayGestureEvent]);
//#endregion
//#region render
return (
<>
<GestureHandler>
<Animated.View ref={containerRef} style={containerStyle}>
{children}
</Animated.View>
</GestureHandler>
<Portal key={key} name={key}>
<Animated.View
key={key}
style={portalContainerStyle}
animatedProps={animatedPortalProps}
>
<PortalOverlay />
{children}
</Animated.View>
</Portal>
</>
);
//#endregion
};
const HoldItem = memo(HoldItemComponent);
export default HoldItem; | the_stack |
import type { FaultDelay as _envoy_extensions_filters_common_fault_v3_FaultDelay, FaultDelay__Output as _envoy_extensions_filters_common_fault_v3_FaultDelay__Output } from '../../../../../../envoy/extensions/filters/common/fault/v3/FaultDelay';
import type { FaultAbort as _envoy_extensions_filters_http_fault_v3_FaultAbort, FaultAbort__Output as _envoy_extensions_filters_http_fault_v3_FaultAbort__Output } from '../../../../../../envoy/extensions/filters/http/fault/v3/FaultAbort';
import type { HeaderMatcher as _envoy_config_route_v3_HeaderMatcher, HeaderMatcher__Output as _envoy_config_route_v3_HeaderMatcher__Output } from '../../../../../../envoy/config/route/v3/HeaderMatcher';
import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from '../../../../../../google/protobuf/UInt32Value';
import type { FaultRateLimit as _envoy_extensions_filters_common_fault_v3_FaultRateLimit, FaultRateLimit__Output as _envoy_extensions_filters_common_fault_v3_FaultRateLimit__Output } from '../../../../../../envoy/extensions/filters/common/fault/v3/FaultRateLimit';
/**
* [#next-free-field: 15]
*/
export interface HTTPFault {
/**
* If specified, the filter will inject delays based on the values in the
* object.
*/
'delay'?: (_envoy_extensions_filters_common_fault_v3_FaultDelay | null);
/**
* If specified, the filter will abort requests based on the values in
* the object. At least *abort* or *delay* must be specified.
*/
'abort'?: (_envoy_extensions_filters_http_fault_v3_FaultAbort | null);
/**
* Specifies the name of the (destination) upstream cluster that the
* filter should match on. Fault injection will be restricted to requests
* bound to the specific upstream cluster.
*/
'upstream_cluster'?: (string);
/**
* Specifies a set of headers that the filter should match on. The fault
* injection filter can be applied selectively to requests that match a set of
* headers specified in the fault filter config. The chances of actual fault
* injection further depend on the value of the :ref:`percentage
* <envoy_api_field_extensions.filters.http.fault.v3.FaultAbort.percentage>` field.
* The filter will check the request's headers against all the specified
* headers in the filter config. A match will happen if all the headers in the
* config are present in the request with the same values (or based on
* presence if the *value* field is not in the config).
*/
'headers'?: (_envoy_config_route_v3_HeaderMatcher)[];
/**
* Faults are injected for the specified list of downstream hosts. If this
* setting is not set, faults are injected for all downstream nodes.
* Downstream node name is taken from :ref:`the HTTP
* x-envoy-downstream-service-node
* <config_http_conn_man_headers_downstream-service-node>` header and compared
* against downstream_nodes list.
*/
'downstream_nodes'?: (string)[];
/**
* The maximum number of faults that can be active at a single time via the configured fault
* filter. Note that because this setting can be overridden at the route level, it's possible
* for the number of active faults to be greater than this value (if injected via a different
* route). If not specified, defaults to unlimited. This setting can be overridden via
* `runtime <config_http_filters_fault_injection_runtime>` and any faults that are not injected
* due to overflow will be indicated via the `faults_overflow
* <config_http_filters_fault_injection_stats>` stat.
*
* .. attention::
* Like other :ref:`circuit breakers <arch_overview_circuit_break>` in Envoy, this is a fuzzy
* limit. It's possible for the number of active faults to rise slightly above the configured
* amount due to the implementation details.
*/
'max_active_faults'?: (_google_protobuf_UInt32Value | null);
/**
* The response rate limit to be applied to the response body of the stream. When configured,
* the percentage can be overridden by the :ref:`fault.http.rate_limit.response_percent
* <config_http_filters_fault_injection_runtime>` runtime key.
*
* .. attention::
* This is a per-stream limit versus a connection level limit. This means that concurrent streams
* will each get an independent limit.
*/
'response_rate_limit'?: (_envoy_extensions_filters_common_fault_v3_FaultRateLimit | null);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.delay.fixed_delay_percent
*/
'delay_percent_runtime'?: (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.abort.abort_percent
*/
'abort_percent_runtime'?: (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.delay.fixed_duration_ms
*/
'delay_duration_runtime'?: (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.abort.http_status
*/
'abort_http_status_runtime'?: (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.max_active_faults
*/
'max_active_faults_runtime'?: (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.rate_limit.response_percent
*/
'response_rate_limit_percent_runtime'?: (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.abort.grpc_status
*/
'abort_grpc_status_runtime'?: (string);
}
/**
* [#next-free-field: 15]
*/
export interface HTTPFault__Output {
/**
* If specified, the filter will inject delays based on the values in the
* object.
*/
'delay': (_envoy_extensions_filters_common_fault_v3_FaultDelay__Output | null);
/**
* If specified, the filter will abort requests based on the values in
* the object. At least *abort* or *delay* must be specified.
*/
'abort': (_envoy_extensions_filters_http_fault_v3_FaultAbort__Output | null);
/**
* Specifies the name of the (destination) upstream cluster that the
* filter should match on. Fault injection will be restricted to requests
* bound to the specific upstream cluster.
*/
'upstream_cluster': (string);
/**
* Specifies a set of headers that the filter should match on. The fault
* injection filter can be applied selectively to requests that match a set of
* headers specified in the fault filter config. The chances of actual fault
* injection further depend on the value of the :ref:`percentage
* <envoy_api_field_extensions.filters.http.fault.v3.FaultAbort.percentage>` field.
* The filter will check the request's headers against all the specified
* headers in the filter config. A match will happen if all the headers in the
* config are present in the request with the same values (or based on
* presence if the *value* field is not in the config).
*/
'headers': (_envoy_config_route_v3_HeaderMatcher__Output)[];
/**
* Faults are injected for the specified list of downstream hosts. If this
* setting is not set, faults are injected for all downstream nodes.
* Downstream node name is taken from :ref:`the HTTP
* x-envoy-downstream-service-node
* <config_http_conn_man_headers_downstream-service-node>` header and compared
* against downstream_nodes list.
*/
'downstream_nodes': (string)[];
/**
* The maximum number of faults that can be active at a single time via the configured fault
* filter. Note that because this setting can be overridden at the route level, it's possible
* for the number of active faults to be greater than this value (if injected via a different
* route). If not specified, defaults to unlimited. This setting can be overridden via
* `runtime <config_http_filters_fault_injection_runtime>` and any faults that are not injected
* due to overflow will be indicated via the `faults_overflow
* <config_http_filters_fault_injection_stats>` stat.
*
* .. attention::
* Like other :ref:`circuit breakers <arch_overview_circuit_break>` in Envoy, this is a fuzzy
* limit. It's possible for the number of active faults to rise slightly above the configured
* amount due to the implementation details.
*/
'max_active_faults': (_google_protobuf_UInt32Value__Output | null);
/**
* The response rate limit to be applied to the response body of the stream. When configured,
* the percentage can be overridden by the :ref:`fault.http.rate_limit.response_percent
* <config_http_filters_fault_injection_runtime>` runtime key.
*
* .. attention::
* This is a per-stream limit versus a connection level limit. This means that concurrent streams
* will each get an independent limit.
*/
'response_rate_limit': (_envoy_extensions_filters_common_fault_v3_FaultRateLimit__Output | null);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.delay.fixed_delay_percent
*/
'delay_percent_runtime': (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.abort.abort_percent
*/
'abort_percent_runtime': (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.delay.fixed_duration_ms
*/
'delay_duration_runtime': (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.abort.http_status
*/
'abort_http_status_runtime': (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.max_active_faults
*/
'max_active_faults_runtime': (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.rate_limit.response_percent
*/
'response_rate_limit_percent_runtime': (string);
/**
* The runtime key to override the :ref:`default <config_http_filters_fault_injection_runtime>`
* runtime. The default is: fault.http.abort.grpc_status
*/
'abort_grpc_status_runtime': (string);
} | the_stack |
// Example use:
//
// === background.js ===
// function myFunc(arg) {
// return arg*2
// }
// makeRemotelyCallable({myFunc})
//
// === content_script.js ===
// const myRemoteFunc = remoteFunction('myFunc')
// myRemoteFunc(21).then(result => { ... result is 42! ... })
import mapValues from 'lodash/fp/mapValues'
import { browser } from 'webextension-polyfill-ts'
import { EventEmitter } from 'events'
import { PortBasedRPCManager, RpcSideName, RpcRole } from 'src/util/rpc/rpc'
import type { RemoteFunctionImplementations } from 'src/util/remote-functions-background'
import type { Arguments, default as TypedEventEmitter } from 'typed-emitter'
import type { AuthRemoteEvents } from 'src/authentication/background/types'
import type { ContentSharingEvents } from 'src/content-sharing/background/types'
import type { PersonalCloudBackgroundEvents } from '../personal-cloud/background/types'
export class RpcError extends Error {
constructor(message) {
super(message)
this.name = this.constructor.name
}
}
export class RemoteError extends Error {
constructor(message) {
super(message)
this.name = this.constructor.name
}
}
export type RemoteFunctionRole = 'provider' | 'caller'
export type RemoteFunction<
Role extends RemoteFunctionRole,
Params,
Returns = void
> = Role extends 'provider'
? (info: { tab: { id: number } }, params: Params) => Promise<Returns>
: (params: Params) => Promise<Returns>
export type RemotePositionalFunction<
Role extends RemoteFunctionRole,
Params extends Array<any>,
Returns = void
> = Role extends 'provider'
? (info: { tab: { id: number } }, ...params: Params) => Promise<Returns>
: (...params: Params) => Promise<Returns>
export type RemoteFunctionWithExtraArgs<
Role extends RemoteFunctionRole,
Params,
Returns = void
> = Role extends 'provider'
? {
withExtraArgs: true
function: RemoteFunction<Role, Params, Returns>
}
: RemoteFunction<Role, Params, Returns>
export type RemoteFunctionWithoutExtraArgs<
Role extends RemoteFunctionRole,
Params,
Returns = void
> = Role extends 'provider'
? {
withExtraArgs: false
function: (params: Params) => Promise<Returns>
}
: (params: Params) => Promise<Returns>
export function remoteFunctionWithExtraArgs<Params, Returns = void>(
f: RemoteFunction<'provider', Params, Returns>,
): RemoteFunctionWithExtraArgs<'provider', Params, Returns> {
return { withExtraArgs: true, function: f }
}
export function remoteFunctionWithoutExtraArgs<Params, Returns = void>(
f: (params: Params) => Promise<Returns>,
): RemoteFunctionWithoutExtraArgs<'provider', Params, Returns> {
return { withExtraArgs: false, function: f }
}
export function registerRemoteFunctions<Functions>(
functions: {
[Name in keyof Functions]:
| RemoteFunctionWithExtraArgs<'provider', any, any>
| RemoteFunctionWithoutExtraArgs<'provider', any, any>
},
) {
for (const [name, metadata] of Object.entries(functions)) {
const typedMetadata = metadata as
| RemoteFunctionWithExtraArgs<'provider', any, any>
| RemoteFunctionWithoutExtraArgs<'provider', any, any>
makeRemotelyCallable(
{ [name]: typedMetadata.function },
{ insertExtraArg: typedMetadata.withExtraArgs },
)
}
}
// === Initiating side ===
// The extra options available when calling a remote function
interface RPCOpts {
tabId?: number
}
// runInBackground and runInTab create a Proxy object that look like the real interface but actually call remote functions
//
// When the Proxy is asked for a property (such as a method)
// return a function that executes the requested method over the RPC interface
//
// Example Usage:
// interface AnalyticsInterface { trackEvent({}) => any }
// const analytics = runInBackground<AnalyticsInterface>()
// analytics.trackEvent(...)
// Runs a remoteFunction in the background script
export function runInBackground<T extends object>(): T {
return new Proxy<T>({} as T, {
get(target, property): (...args: any[]) => Promise<any> {
return async (...args) =>
rpcConnection.postMessageRequestToExtension(
property.toString(),
args,
)
},
})
}
// Runs a remoteFunction in the content script on a certain tab
export function runInTab<T extends object>(tabId): T {
return new Proxy<T>({} as T, {
get(target, property): any {
return (...args) =>
rpcConnection.postMessageRequestToTab(
tabId,
property.toString(),
args,
)
},
})
}
// Runs a remoteFunction in the content script on a certain tab by asking the background script to do so
export function runInTabViaBg<T extends object>(tabId): T {
return new Proxy<T>({} as T, {
get(target, property): any {
return (...args) =>
rpcConnection.postMessageRequestToTabViaExtension(
tabId,
property.toString(),
args,
)
},
})
}
// @depreciated - Don't call this function directly. Instead use the above typesafe version runInBackground
export function remoteFunction(
funcName: string,
{ tabId }: { tabId?: number } = {},
): any {
// console.log(`depreciated: remoteFunction call for: ${funcName}`)
if (tabId) {
return (...args) =>
rpcConnection.postMessageRequestToTab(tabId, funcName, args)
} else {
return (...args) =>
rpcConnection.postMessageRequestToExtension(funcName, args)
}
}
// === Executing side ===
const remotelyCallableFunctions =
typeof window !== 'undefined' ? window['remoteFunctions'] || {} : {}
if (typeof window !== 'undefined') {
window['remoteFunctions'] = remotelyCallableFunctions
}
export function setupRemoteFunctionsImplementations<T>(
implementations: RemoteFunctionImplementations<'provider'>,
): void {
for (const [group, functions] of Object.entries(implementations)) {
makeRemotelyCallableType<typeof functions>(functions)
}
}
// Register a function to allow remote scripts to call it.
// Arguments:
// - functions (required):
// An object with a {functionName: function} mapping.
// Each function will be callable with the given name.
// - options (optional): {
// insertExtraArg:
// If truthy, each executed function also receives, as its first
// argument before the arguments it was invoked with, an object with
// the details of the tab that sent the message.
// }
export function makeRemotelyCallableType<T = never>(
functions: { [P in keyof T]: T[P] },
{ insertExtraArg = false } = {},
) {
return makeRemotelyCallable(functions, { insertExtraArg })
}
// @Depreciated to call this directly. Should use the above typesafe version
export function makeRemotelyCallable<T>(
functions: { [P in keyof T]: T[P] },
{ insertExtraArg = false } = {},
) {
// Every function is passed an extra argument with sender information,
// so remove this from the call if this was not desired.
if (!insertExtraArg) {
// Replace each func with...
// @ts-ignore
const wrapFunctions = mapValues((func) =>
// ...a function that calls func, but hides the inserted argument.
// @ts-ignore
(extraArg, ...args) => func(...args),
)
// @ts-ignore
functions = wrapFunctions(functions)
}
for (const functionName of Object.keys(functions)) {
if (remotelyCallableFunctions.hasOwnProperty(functionName)) {
const error = `RPC function with name ${functionName} has already been registered `
console.warn(error)
}
}
// Add the functions to our global repetoir.
Object.assign(remotelyCallableFunctions, functions)
// console.log('assigned to remotelyCallableFunctions this new functions', {
// functions,
// })
}
export function clearRemotelyCallableFunctions() {
for (const key of Object.keys(remotelyCallableFunctions)) {
delete remotelyCallableFunctions[key]
}
}
export class RemoteFunctionRegistry {
registerRemotelyCallable(functions, { insertExtraArg = false } = {}) {
makeRemotelyCallable(functions, { insertExtraArg })
}
}
export function fakeRemoteFunctions(functions: {
[name: string]: (...args) => any
}) {
return (name) => {
if (!functions[name]) {
throw new Error(
`Tried to call fake remote function '${name}' for which no implementation was provided`,
)
}
return (...args) => {
return Promise.resolve(functions[name](...args))
}
}
}
export interface RemoteEventEmitter<T extends keyof RemoteEvents> {
emit<EventName extends keyof RemoteEvents[T]>(
eventName: EventName,
...args: Arguments<RemoteEvents[T][EventName]>
): Promise<void>
}
const __REMOTE_EVENT__ = '__REMOTE_EVENT__'
const __REMOTE_EVENT_TYPE__ = '__REMOTE_EVENT_TYPE__'
const __REMOTE_EVENT_NAME__ = '__REMOTE_EVENT_NAME__'
// Sending Side, (e.g. background script)
export function remoteEventEmitter<ModuleName extends keyof RemoteEvents>(
moduleName: ModuleName,
{ broadcastToTabs = false } = {},
): RemoteEventEmitter<ModuleName> {
const message = {
__REMOTE_EVENT__,
__REMOTE_EVENT_TYPE__: moduleName,
}
if (broadcastToTabs) {
return {
emit: async (eventName, ...args: any[]) => {
const tabs = (await browser.tabs.query({})) ?? []
for (const { id: tabId } of tabs) {
browser.tabs.sendMessage(tabId, {
...message,
__REMOTE_EVENT_NAME__: eventName,
data: args[0],
})
}
},
}
}
return {
emit: async (eventName, ...args: any[]) =>
browser.runtime.sendMessage({
...message,
__REMOTE_EVENT_NAME__: eventName,
data: args[0],
}),
}
}
// Receiving Side (e.g. content script, options page, etc)
const remoteEventEmitters: RemoteEventEmitters = {} as RemoteEventEmitters
type RemoteEventEmitters = {
[K in keyof RemoteEvents]?: TypedRemoteEventEmitter<K>
}
export type TypedRemoteEventEmitter<
T extends keyof RemoteEvents
> = TypedEventEmitter<RemoteEvents[T]>
// Statically defined types for now, move this to a registry
export interface RemoteEvents {
auth: AuthRemoteEvents
contentSharing: ContentSharingEvents
personalCloud: PersonalCloudBackgroundEvents
}
function registerRemoteEventForwarder() {
if (browser.runtime.onMessage.hasListener(remoteEventForwarder)) {
return
}
browser.runtime.onMessage.addListener(remoteEventForwarder)
}
const remoteEventForwarder = (message, _) => {
if (message == null || message[__REMOTE_EVENT__] !== __REMOTE_EVENT__) {
return
}
const emitterType = message[__REMOTE_EVENT_TYPE__]
const emitter = remoteEventEmitters[emitterType]
if (emitter == null) {
return
}
emitter.emit(message[__REMOTE_EVENT_NAME__], message.data)
}
export function getRemoteEventEmitter<EventType extends keyof RemoteEvents>(
eventType: EventType,
): RemoteEventEmitters[EventType] {
const existingEmitter = remoteEventEmitters[eventType]
if (existingEmitter) {
return existingEmitter
}
const newEmitter = new EventEmitter() as any
remoteEventEmitters[eventType] = newEmitter
registerRemoteEventForwarder()
return newEmitter
}
// Containing the evil globals here
let rpcConnection: PortBasedRPCManager
export const setupRpcConnection = (options: {
sideName: RpcSideName
role: RpcRole
paused?: boolean
}) => {
rpcConnection = new PortBasedRPCManager({
sideName: options.sideName,
role: options.role,
getRegisteredRemoteFunction: (name) => remotelyCallableFunctions[name],
connect: browser.runtime.connect,
onConnect: browser.runtime.onConnect,
paused: options.paused,
})
rpcConnection.setup()
return rpcConnection
} | the_stack |
import * as angular from '../allowlist_bypasses/angular';
import * as flash from '../allowlist_bypasses/flash';
import * as jsonp from '../allowlist_bypasses/jsonp';
import * as csp from '../csp';
import {Csp, Directive, Keyword} from '../csp';
import {Finding, Severity, Type} from '../finding';
import * as utils from '../utils';
/**
* A list of CSP directives that can allow XSS vulnerabilities if they fail
* validation.
*/
export const DIRECTIVES_CAUSING_XSS: Directive[] =
[Directive.SCRIPT_SRC, Directive.OBJECT_SRC, Directive.BASE_URI];
/**
* A list of URL schemes that can allow XSS vulnerabilities when requests to
* them are made.
*/
export const URL_SCHEMES_CAUSING_XSS: string[] = ['data:', 'http:', 'https:'];
/**
* Checks if passed csp allows inline scripts.
* Findings of this check are critical and FP free.
* unsafe-inline is ignored in the presence of a nonce or a hash. This check
* does not account for this and therefore the effectiveCsp needs to be passed.
*
* Example policy where this check would trigger:
* script-src 'unsafe-inline'
*
* @param effectiveCsp A parsed csp that only contains values which
* are active in a certain version of CSP (e.g. no unsafe-inline if a nonce
* is present).
*/
export function checkScriptUnsafeInline(effectiveCsp: Csp): Finding[] {
const directiveName =
effectiveCsp.getEffectiveDirective(Directive.SCRIPT_SRC);
const values: string[] = effectiveCsp.directives[directiveName] || [];
// Check if unsafe-inline is present.
if (values.includes(Keyword.UNSAFE_INLINE)) {
return [new Finding(
Type.SCRIPT_UNSAFE_INLINE,
`'unsafe-inline' allows the execution of unsafe in-page scripts ` +
'and event handlers.',
Severity.HIGH, directiveName, Keyword.UNSAFE_INLINE)];
}
return [];
}
/**
* Checks if passed csp allows eval in scripts.
* Findings of this check have a medium severity and are FP free.
*
* Example policy where this check would trigger:
* script-src 'unsafe-eval'
*
* @param parsedCsp Parsed CSP.
*/
export function checkScriptUnsafeEval(parsedCsp: Csp): Finding[] {
const directiveName = parsedCsp.getEffectiveDirective(Directive.SCRIPT_SRC);
const values: string[] = parsedCsp.directives[directiveName] || [];
// Check if unsafe-eval is present.
if (values.includes(Keyword.UNSAFE_EVAL)) {
return [new Finding(
Type.SCRIPT_UNSAFE_EVAL,
`'unsafe-eval' allows the execution of code injected into DOM APIs ` +
'such as eval().',
Severity.MEDIUM_MAYBE, directiveName, Keyword.UNSAFE_EVAL)];
}
return [];
}
/**
* Checks if plain URL schemes (e.g. http:) are allowed in sensitive directives.
* Findings of this check have a high severity and are FP free.
*
* Example policy where this check would trigger:
* script-src https: http: data:
*
* @param parsedCsp Parsed CSP.
*/
export function checkPlainUrlSchemes(parsedCsp: Csp): Finding[] {
const violations: Finding[] = [];
const directivesToCheck =
parsedCsp.getEffectiveDirectives(DIRECTIVES_CAUSING_XSS);
for (const directive of directivesToCheck) {
const values = parsedCsp.directives[directive] || [];
for (const value of values) {
if (URL_SCHEMES_CAUSING_XSS.includes(value)) {
violations.push(new Finding(
Type.PLAIN_URL_SCHEMES,
value + ' URI in ' + directive + ' allows the execution of ' +
'unsafe scripts.',
Severity.HIGH, directive, value));
}
}
}
return violations;
}
/**
* Checks if csp contains wildcards in sensitive directives.
* Findings of this check have a high severity and are FP free.
*
* Example policy where this check would trigger:
* script-src *
*
* @param parsedCsp Parsed CSP.
*/
export function checkWildcards(parsedCsp: Csp): Finding[] {
const violations: Finding[] = [];
const directivesToCheck =
parsedCsp.getEffectiveDirectives(DIRECTIVES_CAUSING_XSS);
for (const directive of directivesToCheck) {
const values = parsedCsp.directives[directive] || [];
for (const value of values) {
const url = utils.getSchemeFreeUrl(value);
if (url === '*') {
violations.push(new Finding(
Type.PLAIN_WILDCARD, directive + ` should not allow '*' as source`,
Severity.HIGH, directive, value));
continue;
}
}
}
return violations;
}
/**
* Checks if object-src is restricted to none either directly or via a
* default-src.
*/
export function checkMissingObjectSrcDirective(parsedCsp: Csp): Finding[] {
let objectRestrictions: string[]|undefined = [];
if (Directive.OBJECT_SRC in parsedCsp.directives) {
objectRestrictions = parsedCsp.directives[Directive.OBJECT_SRC];
} else if (Directive.DEFAULT_SRC in parsedCsp.directives) {
objectRestrictions = parsedCsp.directives[Directive.DEFAULT_SRC];
}
if (objectRestrictions !== undefined && objectRestrictions.length >= 1) {
return [];
}
return [new Finding(
Type.MISSING_DIRECTIVES,
`Missing object-src allows the injection of plugins which can execute JavaScript. Can you set it to 'none'?`,
Severity.HIGH, Directive.OBJECT_SRC)];
}
/**
* Checks if script-src is restricted either directly or via a default-src.
*/
export function checkMissingScriptSrcDirective(parsedCsp: Csp): Finding[] {
if (Directive.SCRIPT_SRC in parsedCsp.directives ||
Directive.DEFAULT_SRC in parsedCsp.directives) {
return [];
}
return [new Finding(
Type.MISSING_DIRECTIVES, 'script-src directive is missing.',
Severity.HIGH, Directive.SCRIPT_SRC)];
}
/**
* Checks if the base-uri needs to be restricted and if so, whether it has been
* restricted.
*/
export function checkMissingBaseUriDirective(parsedCsp: Csp): Finding[] {
return checkMultipleMissingBaseUriDirective([parsedCsp]);
}
/**
* Checks if the base-uri needs to be restricted and if so, whether it has been
* restricted.
*/
export function checkMultipleMissingBaseUriDirective(parsedCsps: Csp[]):
Finding[] {
// base-uri can be used to bypass nonce based CSPs and hash based CSPs that
// use strict dynamic
const needsBaseUri = (csp: Csp) =>
(csp.policyHasScriptNonces() ||
(csp.policyHasScriptHashes() && csp.policyHasStrictDynamic()));
const hasBaseUri = (csp: Csp) => Directive.BASE_URI in csp.directives;
if (parsedCsps.some(needsBaseUri) && !parsedCsps.some(hasBaseUri)) {
const description = 'Missing base-uri allows the injection of base tags. ' +
'They can be used to set the base URL for all relative (script) ' +
'URLs to an attacker controlled domain. ' +
`Can you set it to 'none' or 'self'?`;
return [new Finding(
Type.MISSING_DIRECTIVES, description, Severity.HIGH,
Directive.BASE_URI)];
}
return [];
}
/**
* Checks if all necessary directives for preventing XSS are set.
* Findings of this check have a high severity and are FP free.
*
* Example policy where this check would trigger:
* script-src 'none'
*
* @param parsedCsp Parsed CSP.
*/
export function checkMissingDirectives(parsedCsp: Csp): Finding[] {
return [
...checkMissingObjectSrcDirective(parsedCsp),
...checkMissingScriptSrcDirective(parsedCsp),
...checkMissingBaseUriDirective(parsedCsp),
];
}
/**
* Checks if allowlisted origins are bypassable by JSONP/Angular endpoints.
* High severity findings of this check are FP free.
*
* Example policy where this check would trigger:
* default-src 'none'; script-src www.google.com
*
* @param parsedCsp Parsed CSP.
*/
export function checkScriptAllowlistBypass(parsedCsp: Csp): Finding[] {
const violations: Finding[] = [];
const effectiveScriptSrcDirective =
parsedCsp.getEffectiveDirective(Directive.SCRIPT_SRC);
const scriptSrcValues =
parsedCsp.directives[effectiveScriptSrcDirective] || [];
if (scriptSrcValues.includes(Keyword.NONE)) {
return violations;
}
for (const value of scriptSrcValues) {
if (value === Keyword.SELF) {
violations.push(new Finding(
Type.SCRIPT_ALLOWLIST_BYPASS,
`'self' can be problematic if you host JSONP, AngularJS or user ` +
'uploaded files.',
Severity.MEDIUM_MAYBE, effectiveScriptSrcDirective, value));
continue;
}
// Ignore keywords, nonces and hashes (they start with a single quote).
if (value.startsWith('\'')) {
continue;
}
// Ignore standalone schemes and things that don't look like URLs (no dot).
if (csp.isUrlScheme(value) || value.indexOf('.') === -1) {
continue;
}
const url = '//' + utils.getSchemeFreeUrl(value);
const angularBypass = utils.matchWildcardUrls(url, angular.URLS);
let jsonpBypass = utils.matchWildcardUrls(url, jsonp.URLS);
// Some JSONP bypasses only work in presence of unsafe-eval.
if (jsonpBypass) {
const evalRequired = jsonp.NEEDS_EVAL.includes(jsonpBypass.hostname);
const evalPresent = scriptSrcValues.includes(Keyword.UNSAFE_EVAL);
if (evalRequired && !evalPresent) {
jsonpBypass = null;
}
}
if (jsonpBypass || angularBypass) {
let bypassDomain = '';
let bypassTxt = '';
if (jsonpBypass) {
bypassDomain = jsonpBypass.hostname;
bypassTxt = ' JSONP endpoints';
}
if (angularBypass) {
bypassDomain = angularBypass.hostname;
bypassTxt += (bypassTxt.trim() === '') ? '' : ' and';
bypassTxt += ' Angular libraries';
}
violations.push(new Finding(
Type.SCRIPT_ALLOWLIST_BYPASS,
bypassDomain + ' is known to host' + bypassTxt +
' which allow to bypass this CSP.',
Severity.HIGH, effectiveScriptSrcDirective, value));
} else {
violations.push(new Finding(
Type.SCRIPT_ALLOWLIST_BYPASS,
`No bypass found; make sure that this URL doesn't serve JSONP ` +
'replies or Angular libraries.',
Severity.MEDIUM_MAYBE, effectiveScriptSrcDirective, value));
}
}
return violations;
}
/**
* Checks if allowlisted object-src origins are bypassable.
* Findings of this check have a high severity and are FP free.
*
* Example policy where this check would trigger:
* default-src 'none'; object-src ajax.googleapis.com
*
* @param parsedCsp Parsed CSP.
*/
export function checkFlashObjectAllowlistBypass(parsedCsp: Csp): Finding[] {
const violations = [];
const effectiveObjectSrcDirective =
parsedCsp.getEffectiveDirective(Directive.OBJECT_SRC);
const objectSrcValues =
parsedCsp.directives[effectiveObjectSrcDirective] || [];
// If flash is not allowed in plugin-types, continue.
const pluginTypes = parsedCsp.directives[Directive.PLUGIN_TYPES];
if (pluginTypes && !pluginTypes.includes('application/x-shockwave-flash')) {
return [];
}
for (const value of objectSrcValues) {
// Nothing to do here if 'none'.
if (value === Keyword.NONE) {
return [];
}
const url = '//' + utils.getSchemeFreeUrl(value);
const flashBypass = utils.matchWildcardUrls(url, flash.URLS);
if (flashBypass) {
violations.push(new Finding(
Type.OBJECT_ALLOWLIST_BYPASS,
flashBypass.hostname +
' is known to host Flash files which allow to bypass this CSP.',
Severity.HIGH, effectiveObjectSrcDirective, value));
} else if (effectiveObjectSrcDirective === Directive.OBJECT_SRC) {
violations.push(new Finding(
Type.OBJECT_ALLOWLIST_BYPASS,
`Can you restrict object-src to 'none' only?`, Severity.MEDIUM_MAYBE,
effectiveObjectSrcDirective, value));
}
}
return violations;
}
/**
* Returns whether the given string "looks" like an IP address. This function
* only uses basic heuristics and does not accept all valid IPs nor reject all
* invalid IPs.
*/
export function looksLikeIpAddress(maybeIp: string): boolean {
if (maybeIp.startsWith('[') && maybeIp.endsWith(']')) {
// Looks like an IPv6 address and not a hostname (though it may be some
// nonsense like `[foo]`)
return true;
}
if (/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/.test(maybeIp)) {
// Looks like an IPv4 address (though it may be something like
// `500.600.700.800`
return true;
}
// Won't match IP addresses encoded in other manners (eg octal or
// decimal)
return false;
}
/**
* Checks if csp contains IP addresses.
* Findings of this check are informal only and are FP free.
*
* Example policy where this check would trigger:
* script-src 127.0.0.1
*
* @param parsedCsp Parsed CSP.
*/
export function checkIpSource(parsedCsp: Csp): Finding[] {
const violations: Finding[] = [];
// Function for checking if directive values contain IP addresses.
const checkIp = (directive: string, directiveValues: string[]) => {
for (const value of directiveValues) {
const host = utils.getHostname(value);
if (looksLikeIpAddress(host)) {
// Check if localhost.
// See 4.8 in https://www.w3.org/TR/CSP2/#match-source-expression
if (host === '127.0.0.1') {
violations.push(new Finding(
Type.IP_SOURCE,
directive + ' directive allows localhost as source. ' +
'Please make sure to remove this in production environments.',
Severity.INFO, directive, value));
} else {
violations.push(new Finding(
Type.IP_SOURCE,
directive + ' directive has an IP-Address as source: ' + host +
' (will be ignored by browsers!). ',
Severity.INFO, directive, value));
}
}
}
};
// Apply check to values of all directives.
utils.applyCheckFunktionToDirectives(parsedCsp, checkIp);
return violations;
}
/**
* Checks if csp contains directives that are deprecated in CSP3.
* Findings of this check are informal only and are FP free.
*
* Example policy where this check would trigger:
* report-uri foo.bar/csp
*
* @param parsedCsp Parsed CSP.
*/
export function checkDeprecatedDirective(parsedCsp: Csp): Finding[] {
const violations = [];
// More details: https://www.chromestatus.com/feature/5769374145183744
if (Directive.REFLECTED_XSS in parsedCsp.directives) {
violations.push(new Finding(
Type.DEPRECATED_DIRECTIVE,
'reflected-xss is deprecated since CSP2. ' +
'Please, use the X-XSS-Protection header instead.',
Severity.INFO, Directive.REFLECTED_XSS));
}
// More details: https://www.chromestatus.com/feature/5680800376815616
if (Directive.REFERRER in parsedCsp.directives) {
violations.push(new Finding(
Type.DEPRECATED_DIRECTIVE,
'referrer is deprecated since CSP2. ' +
'Please, use the Referrer-Policy header instead.',
Severity.INFO, Directive.REFERRER));
}
// More details: https://github.com/w3c/webappsec-csp/pull/327
if (Directive.DISOWN_OPENER in parsedCsp.directives) {
violations.push(new Finding(
Type.DEPRECATED_DIRECTIVE,
'disown-opener is deprecated since CSP3. ' +
'Please, use the Cross Origin Opener Policy header instead.',
Severity.INFO, Directive.DISOWN_OPENER));
}
return violations;
}
/**
* Checks if csp nonce is at least 8 characters long.
* Findings of this check are of medium severity and are FP free.
*
* Example policy where this check would trigger:
* script-src 'nonce-short'
*
* @param parsedCsp Parsed CSP.
*/
export function checkNonceLength(parsedCsp: Csp): Finding[] {
const noncePattern = new RegExp('^\'nonce-(.+)\'$');
const violations: Finding[] = [];
utils.applyCheckFunktionToDirectives(
parsedCsp, (directive, directiveValues) => {
for (const value of directiveValues) {
const match = value.match(noncePattern);
if (!match) {
continue;
}
// Not a nonce.
const nonceValue = match[1];
if (nonceValue.length < 8) {
violations.push(new Finding(
Type.NONCE_LENGTH,
'Nonces should be at least 8 characters long.', Severity.MEDIUM,
directive, value));
}
if (!csp.isNonce(value, true)) {
violations.push(new Finding(
Type.NONCE_CHARSET,
'Nonces should only use the base64 charset.', Severity.INFO,
directive, value));
}
}
});
return violations;
}
/**
* Checks if CSP allows sourcing from http://
* Findings of this check are of medium severity and are FP free.
*
* Example policy where this check would trigger:
* report-uri http://foo.bar/csp
*
* @param parsedCsp Parsed CSP.
*/
export function checkSrcHttp(parsedCsp: Csp): Finding[] {
const violations: Finding[] = [];
utils.applyCheckFunktionToDirectives(
parsedCsp, (directive, directiveValues) => {
for (const value of directiveValues) {
const description = directive === Directive.REPORT_URI ?
'Use HTTPS to send violation reports securely.' :
'Allow only resources downloaded over HTTPS.';
if (value.startsWith('http://')) {
violations.push(new Finding(
Type.SRC_HTTP, description, Severity.MEDIUM, directive, value));
}
}
});
return violations;
}
/**
* Checks if the policy has configured reporting in a robust manner.
*/
export function checkHasConfiguredReporting(parsedCsp: Csp): Finding[] {
const reportUriValues: string[] =
parsedCsp.directives[Directive.REPORT_URI] || [];
if (reportUriValues.length > 0) {
return [];
}
const reportToValues: string[] =
parsedCsp.directives[Directive.REPORT_TO] || [];
if (reportToValues.length > 0) {
return [new Finding(
Type.REPORT_TO_ONLY,
`This CSP policy only provides a reporting destination via the 'report-to' directive. This directive is only supported in Chromium-based browsers so it is recommended to also use a 'report-uri' directive.`,
Severity.INFO, Directive.REPORT_TO)];
}
return [new Finding(
Type.REPORTING_DESTINATION_MISSING,
'This CSP policy does not configure a reporting destination. This makes it difficult to maintain the CSP policy over time and monitor for any breakages.',
Severity.INFO, Directive.REPORT_URI)];
} | the_stack |
import {
PullRequestDatabase,
IPullRequest,
IPullRequestStatus,
} from '../databases'
import { GitHubRepository } from '../../models/github-repository'
import { Account } from '../../models/account'
import { API, IAPIPullRequest } from '../api'
import { fatalError, forceUnwrap } from '../fatal-error'
import { RepositoriesStore } from './repositories-store'
import {
PullRequest,
PullRequestRef,
PullRequestStatus,
} from '../../models/pull-request'
import { TypedBaseStore } from './base-store'
import { Repository } from '../../models/repository'
import { getRemotes, removeRemote } from '../git'
import { IRemote, ForkedRemotePrefix } from '../../models/remote'
const Decrement = (n: number) => n - 1
const Increment = (n: number) => n + 1
/** The store for GitHub Pull Requests. */
export class PullRequestStore extends TypedBaseStore<GitHubRepository> {
private readonly pullRequestDatabase: PullRequestDatabase
private readonly repositoryStore: RepositoriesStore
private readonly activeFetchCountPerRepository = new Map<number, number>()
public constructor(
db: PullRequestDatabase,
repositoriesStore: RepositoriesStore
) {
super()
this.pullRequestDatabase = db
this.repositoryStore = repositoriesStore
}
/** Loads all pull requests against the given repository. */
public async fetchAndCachePullRequests(
repository: Repository,
account: Account
): Promise<void> {
const githubRepo = forceUnwrap(
'Can only refresh pull requests for GitHub repositories',
repository.gitHubRepository
)
const apiClient = API.fromAccount(account)
this.updateActiveFetchCount(githubRepo, Increment)
try {
const apiResult = await apiClient.fetchPullRequests(
githubRepo.owner.login,
githubRepo.name,
'open'
)
await this.cachePullRequests(apiResult, githubRepo)
const prs = await this.fetchPullRequestsFromCache(githubRepo)
await this.fetchAndCachePullRequestStatus(prs, githubRepo, account)
await this.pruneForkedRemotes(repository, prs)
this.emitUpdate(githubRepo)
} catch (error) {
log.warn(`Error refreshing pull requests for '${repository.name}'`, error)
this.emitError(error)
} finally {
this.updateActiveFetchCount(githubRepo, Decrement)
}
}
/** Is the store currently fetching the list of open pull requests? */
public isFetchingPullRequests(repository: GitHubRepository): boolean {
const repoDbId = forceUnwrap(
'Cannot fetch PRs for a repository which is not in the database',
repository.dbID
)
const currentCount = this.activeFetchCountPerRepository.get(repoDbId) || 0
return currentCount > 0
}
/** Loads the status for the given pull request. */
public async fetchPullRequestStatus(
repository: GitHubRepository,
account: Account,
pullRequest: PullRequest
): Promise<void> {
await this.fetchAndCachePullRequestStatus(
[pullRequest],
repository,
account
)
}
/** Loads the status for all pull request against a given repository. */
public async fetchPullRequestStatuses(
repository: GitHubRepository,
account: Account
): Promise<void> {
const prs = await this.fetchPullRequestsFromCache(repository)
await this.fetchAndCachePullRequestStatus(prs, repository, account)
}
/** Gets the pull requests against the given repository. */
public async fetchPullRequestsFromCache(
repository: GitHubRepository
): Promise<ReadonlyArray<PullRequest>> {
const gitHubRepositoryID = repository.dbID
if (gitHubRepositoryID == null) {
return fatalError(
"Cannot get pull requests for a repository that hasn't been inserted into the database!"
)
}
const records = await this.pullRequestDatabase.pullRequests
.where('base.repoId')
.equals(gitHubRepositoryID)
.reverse()
.sortBy('number')
const result = new Array<PullRequest>()
for (const record of records) {
const repositoryDbId = record.head.repoId
let githubRepository: GitHubRepository | null = null
if (repositoryDbId != null) {
githubRepository = await this.repositoryStore.findGitHubRepositoryByID(
repositoryDbId
)
}
// We know the base repo ID can't be null since it's the repository we
// fetched the PR from in the first place.
const parentRepositoryDbId = forceUnwrap(
'A pull request cannot have a null base repo id',
record.base.repoId
)
const parentGitGubRepository: GitHubRepository | null = await this.repositoryStore.findGitHubRepositoryByID(
parentRepositoryDbId
)
const parentGitHubRepository = forceUnwrap(
'PR cannot have a null base repo',
parentGitGubRepository
)
// We can be certain the PR ID is valid since we just got it from the
// database.
const pullRequestDbId = forceUnwrap(
'PR cannot have a null ID after being retrieved from the database',
record.id
)
const pullRequestStatus = await this.findPullRequestStatus(
record.head.sha,
pullRequestDbId
)
result.push(
new PullRequest(
pullRequestDbId,
new Date(record.createdAt),
pullRequestStatus,
record.title,
record.number,
new PullRequestRef(
record.head.ref,
record.head.sha,
githubRepository
),
new PullRequestRef(
record.base.ref,
record.base.sha,
parentGitHubRepository
),
record.author
)
)
}
return result
}
private async pruneForkedRemotes(
repository: Repository,
pullRequests: ReadonlyArray<PullRequest>
) {
const remotes = await getRemotes(repository)
const forkedRemotesToDelete = this.getRemotesToDelete(remotes, pullRequests)
await this.deleteRemotes(repository, forkedRemotesToDelete)
}
private getRemotesToDelete(
remotes: ReadonlyArray<IRemote>,
openPullRequests: ReadonlyArray<PullRequest>
): ReadonlyArray<IRemote> {
const forkedRemotes = remotes.filter(remote =>
remote.name.startsWith(ForkedRemotePrefix)
)
const remotesOfPullRequests = new Set<string>()
openPullRequests.forEach(pr => {
const { gitHubRepository } = pr.head
if (gitHubRepository != null && gitHubRepository.cloneURL != null) {
remotesOfPullRequests.add(gitHubRepository.cloneURL)
}
})
const result = forkedRemotes.filter(
forkedRemote => !remotesOfPullRequests.has(forkedRemote.url)
)
return result
}
private async deleteRemotes(
repository: Repository,
remotes: ReadonlyArray<IRemote>
) {
const promises: Array<Promise<void>> = []
remotes.forEach(r => promises.push(removeRemote(repository, r.name)))
await Promise.all(promises)
}
private updateActiveFetchCount(
repository: GitHubRepository,
update: (count: number) => number
) {
const repoDbId = forceUnwrap(
'Cannot fetch PRs for a repository which is not in the database',
repository.dbID
)
const currentCount = this.activeFetchCountPerRepository.get(repoDbId) || 0
const newCount = update(currentCount)
this.activeFetchCountPerRepository.set(repoDbId, newCount)
this.emitUpdate(repository)
}
private async fetchAndCachePullRequestStatus(
pullRequests: ReadonlyArray<PullRequest>,
repository: GitHubRepository,
account: Account
): Promise<void> {
const apiClient = API.fromAccount(account)
const statuses: Array<IPullRequestStatus> = []
for (const pr of pullRequests) {
const combinedRefStatus = await apiClient.fetchCombinedRefStatus(
repository.owner.login,
repository.name,
pr.head.sha
)
statuses.push({
pullRequestId: pr.id,
state: combinedRefStatus.state,
totalCount: combinedRefStatus.total_count,
sha: pr.head.sha,
statuses: combinedRefStatus.statuses,
})
}
await this.cachePullRequestStatuses(statuses)
this.emitUpdate(repository)
}
private async findPullRequestStatus(
sha: string,
pullRequestId: number
): Promise<PullRequestStatus | null> {
const result = await this.pullRequestDatabase.pullRequestStatus
.where('[sha+pullRequestId]')
.equals([sha, pullRequestId])
.limit(1)
.first()
if (!result) {
return null
}
const combinedRefStatuses = (result.statuses || []).map(x => {
return {
id: x.id,
state: x.state,
}
})
return new PullRequestStatus(
result.pullRequestId,
result.state,
result.totalCount,
result.sha,
combinedRefStatuses
)
}
private async cachePullRequests(
pullRequestsFromAPI: ReadonlyArray<IAPIPullRequest>,
repository: GitHubRepository
): Promise<void> {
const repoDbId = repository.dbID
if (repoDbId == null) {
return fatalError(
"Cannot store pull requests for a repository that hasn't been inserted into the database!"
)
}
const table = this.pullRequestDatabase.pullRequests
const prsToInsert = new Array<IPullRequest>()
for (const pr of pullRequestsFromAPI) {
// `pr.head.repo` represents the source of the pull request. It might be
// a branch associated with the current repository, or a fork of the
// current repository.
//
// In cases where the user has removed the fork of the repository after
// opening a pull request, this can be `null`, and the app will not store
// this pull request.
if (pr.head.repo == null) {
log.debug(
`Unable to store pull request #${pr.number} for repository ${
repository.fullName
} as it has no head repository associated with it`
)
continue
}
const githubRepo = await this.repositoryStore.upsertGitHubRepository(
repository.endpoint,
pr.head.repo
)
const githubRepoDbId = forceUnwrap(
'PR cannot have non-existent repo',
githubRepo.dbID
)
// We know the base repo isn't null since that's where we got the PR from
// in the first place.
const parentRepo = forceUnwrap(
'PR cannot have a null base repo',
pr.base.repo
)
const parentGitHubRepo = await this.repositoryStore.upsertGitHubRepository(
repository.endpoint,
parentRepo
)
const parentGitHubRepoDbId = forceUnwrap(
'PR cannot have a null parent database id',
parentGitHubRepo.dbID
)
prsToInsert.push({
number: pr.number,
title: pr.title,
createdAt: pr.created_at,
head: {
ref: pr.head.ref,
sha: pr.head.sha,
repoId: githubRepoDbId,
},
base: {
ref: pr.base.ref,
sha: pr.base.sha,
repoId: parentGitHubRepoDbId,
},
author: pr.user.login,
})
}
return this.pullRequestDatabase.transaction('rw', table, async () => {
// we need to delete the stales PRs from the db
// so we remove all for a repo to avoid having to
// do diffing
await table
.where('base.repoId')
.equals(repoDbId)
.delete()
if (prsToInsert.length > 0) {
await table.bulkAdd(prsToInsert)
}
})
}
private async cachePullRequestStatuses(
statuses: Array<IPullRequestStatus>
): Promise<void> {
const table = this.pullRequestDatabase.pullRequestStatus
await this.pullRequestDatabase.transaction('rw', table, async () => {
for (const status of statuses) {
const record = await table
.where('[sha+pullRequestId]')
.equals([status.sha, status.pullRequestId])
.first()
if (record == null) {
await table.add(status)
} else {
await table.put({ id: record.id, ...status })
}
}
})
}
} | the_stack |
import Shape from '../Shape';
import Rectangle from '../Rectangle';
import {
DEFAULT_STARTSIZE,
DIRECTION,
LINE_ARCSIZE,
NONE,
RECTANGLE_ROUNDING_FACTOR,
} from '../../../util/Constants';
import { ColorValue } from '../../../types';
import AbstractCanvas2D from '../../canvas/AbstractCanvas2D';
/**
* Extends {@link Shape} to implement a swimlane shape.
* This shape is registered under {@link mxConstants.SHAPE_SWIMLANE} in {@link mxCellRenderer}.
* Use the {@link mxConstants.STYLE_STYLE_STARTSIZE} to define the size of the title
* region, `'swimLaneFillColor'` for the content area fill,
* `'separatorColor'` to draw an additional vertical separator and
* {@link mxConstants.STYLE_SWIMLANE_LINE} to hide the line between the title region and
* the content area.
* The {@link 'horizontal'} affects the orientation of this shape,
* not only its label.
*
* @class SwimlaneShape
* @extends {Shape}
*/
class SwimlaneShape extends Shape {
constructor(bounds: Rectangle, fill: ColorValue, stroke: ColorValue, strokeWidth = 1) {
super();
this.bounds = bounds;
this.fill = fill;
this.stroke = stroke;
this.strokeWidth = strokeWidth;
}
/**
* Default imagewidth and imageheight if an image but no imagewidth
* and imageheight are defined in the style. Value is 16.
* @type {number}
* @default 16
*/
imageSize = 16;
imageSrc: string | null = null;
/**
* Adds roundable support.
* @param {mxAbstractCanvas2D} c
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @returns {boolean}
*/
isRoundable(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
return true;
}
/**
* Returns the bounding box for the gradient box for this shape.
*/
getTitleSize() {
return Math.max(0, this.style?.startSize ?? DEFAULT_STARTSIZE);
}
/**
* Returns the bounding box for the gradient box for this shape.
*/
getLabelBounds(rect: Rectangle) {
const start = this.getTitleSize();
const bounds = new Rectangle(rect.x, rect.y, rect.width, rect.height);
const horizontal = this.isHorizontal();
const flipH = this.style?.flipH ?? false;
const flipV = this.style?.flipV ?? false;
// East is default
const shapeVertical =
this.direction === DIRECTION.NORTH || this.direction === DIRECTION.SOUTH;
const realHorizontal = horizontal == !shapeVertical;
const realFlipH =
!realHorizontal &&
flipH !== (this.direction === DIRECTION.SOUTH || this.direction === DIRECTION.WEST);
const realFlipV =
realHorizontal &&
flipV !== (this.direction === DIRECTION.SOUTH || this.direction === DIRECTION.WEST);
// Shape is horizontal
if (!shapeVertical) {
const tmp = Math.min(bounds.height, start * this.scale);
if (realFlipH || realFlipV) {
bounds.y += bounds.height - tmp;
}
bounds.height = tmp;
} else {
const tmp = Math.min(bounds.width, start * this.scale);
if (realFlipH || realFlipV) {
bounds.x += bounds.width - tmp;
}
bounds.width = tmp;
}
return bounds;
}
/**
* Returns the bounding box for the gradient box for this shape.
*/
getGradientBounds(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
let start = this.getTitleSize();
if (this.isHorizontal()) {
start = Math.min(start, h);
return new Rectangle(x, y, w, start);
}
start = Math.min(start, w);
return new Rectangle(x, y, start, h);
}
/**
* Returns the arcsize for the swimlane.
*/
getSwimlaneArcSize(w: number, h: number, start: number) {
if (this.style?.absoluteArcSize ?? false) {
return Math.min(w / 2, Math.min(h / 2, this.style?.arcSize ?? LINE_ARCSIZE / 2));
}
const f = (this.style?.arcSize ?? RECTANGLE_ROUNDING_FACTOR * 100) / 100;
return start * f * 3;
}
/**
* Paints the swimlane vertex shape.
*/
isHorizontal() {
return this.style?.horizontal ?? true;
}
/**
* Paints the swimlane vertex shape.
*/
paintVertexShape(c: AbstractCanvas2D, x: number, y: number, w: number, h: number) {
let start = this.getTitleSize();
const fill = this.style?.swimlaneFillColor ?? NONE;
const swimlaneLine = this.style?.swimlaneLine ?? true;
let r = 0;
if (this.isHorizontal()) {
start = Math.min(start, h);
} else {
start = Math.min(start, w);
}
c.translate(x, y);
if (!this.isRounded) {
this.paintSwimlane(c, x, y, w, h, start, fill, swimlaneLine);
} else {
r = this.getSwimlaneArcSize(w, h, start);
r = Math.min((this.isHorizontal() ? h : w) - start, Math.min(start, r));
this.paintRoundedSwimlane(c, x, y, w, h, start, r, fill, swimlaneLine);
}
const sep = this.style?.separatorColor ?? NONE;
this.paintSeparator(c, x, y, w, h, start, sep);
if (this.imageSrc) {
const bounds = this.getImageBounds(x, y, w, h);
c.image(
bounds.x - x,
bounds.y - y,
bounds.width,
bounds.height,
this.imageSrc,
false,
false,
false
);
}
if (this.glass) {
c.setShadow(false);
this.paintGlassEffect(c, 0, 0, w, start, r);
}
}
/**
* Paints the swimlane vertex shape.
*/
paintSwimlane(
c: AbstractCanvas2D,
x: number,
y: number,
w: number,
h: number,
start: number,
fill: ColorValue,
swimlaneLine: boolean
) {
c.begin();
let events = true;
if (this.style && this.style.pointerEvents != null) {
events = this.style.pointerEvents;
}
if (!events && this.fill === NONE) {
c.pointerEvents = false;
}
if (this.isHorizontal()) {
c.moveTo(0, start);
c.lineTo(0, 0);
c.lineTo(w, 0);
c.lineTo(w, start);
c.fillAndStroke();
if (start < h) {
if (fill === NONE || !events) {
c.pointerEvents = false;
}
if (fill !== NONE) {
c.setFillColor(fill);
}
c.begin();
c.moveTo(0, start);
c.lineTo(0, h);
c.lineTo(w, h);
c.lineTo(w, start);
if (fill === NONE) {
c.stroke();
} else {
c.fillAndStroke();
}
}
} else {
c.moveTo(start, 0);
c.lineTo(0, 0);
c.lineTo(0, h);
c.lineTo(start, h);
c.fillAndStroke();
if (start < w) {
if (fill === NONE || !events) {
c.pointerEvents = false;
}
if (fill !== NONE) {
c.setFillColor(fill);
}
c.begin();
c.moveTo(start, 0);
c.lineTo(w, 0);
c.lineTo(w, h);
c.lineTo(start, h);
if (fill === NONE) {
c.stroke();
} else {
c.fillAndStroke();
}
}
}
if (swimlaneLine) {
this.paintDivider(c, x, y, w, h, start, fill === NONE);
}
}
/**
* Paints the swimlane vertex shape.
*/
paintRoundedSwimlane(
c: AbstractCanvas2D,
x: number,
y: number,
w: number,
h: number,
start: number,
r: number,
fill: ColorValue,
swimlaneLine: boolean
) {
c.begin();
let events = true;
if (this.style && this.style.pointerEvents != null) {
events = this.style.pointerEvents;
}
if (!events && this.fill === NONE) {
c.pointerEvents = false;
}
if (this.isHorizontal()) {
c.moveTo(w, start);
c.lineTo(w, r);
c.quadTo(w, 0, w - Math.min(w / 2, r), 0);
c.lineTo(Math.min(w / 2, r), 0);
c.quadTo(0, 0, 0, r);
c.lineTo(0, start);
c.fillAndStroke();
if (start < h) {
if (fill === NONE || !events) {
c.pointerEvents = false;
}
if (fill !== NONE) {
c.setFillColor(fill);
}
c.begin();
c.moveTo(0, start);
c.lineTo(0, h - r);
c.quadTo(0, h, Math.min(w / 2, r), h);
c.lineTo(w - Math.min(w / 2, r), h);
c.quadTo(w, h, w, h - r);
c.lineTo(w, start);
if (fill === NONE) {
c.stroke();
} else {
c.fillAndStroke();
}
}
} else {
c.moveTo(start, 0);
c.lineTo(r, 0);
c.quadTo(0, 0, 0, Math.min(h / 2, r));
c.lineTo(0, h - Math.min(h / 2, r));
c.quadTo(0, h, r, h);
c.lineTo(start, h);
c.fillAndStroke();
if (start < w) {
if (fill === NONE || !events) {
c.pointerEvents = false;
}
if (fill !== NONE) {
c.setFillColor(fill);
}
c.begin();
c.moveTo(start, h);
c.lineTo(w - r, h);
c.quadTo(w, h, w, h - Math.min(h / 2, r));
c.lineTo(w, Math.min(h / 2, r));
c.quadTo(w, 0, w - r, 0);
c.lineTo(start, 0);
if (fill === NONE) {
c.stroke();
} else {
c.fillAndStroke();
}
}
}
if (swimlaneLine) {
this.paintDivider(c, x, y, w, h, start, fill === NONE);
}
}
/**
* Paints the divider between swimlane title and content area.
*/
paintDivider(
c: AbstractCanvas2D,
x: number,
y: number,
w: number,
h: number,
start: number,
shadow: boolean
) {
if (!shadow) {
c.setShadow(false);
}
c.begin();
if (this.isHorizontal()) {
c.moveTo(0, start);
c.lineTo(w, start);
} else {
c.moveTo(start, 0);
c.lineTo(start, h);
}
c.stroke();
}
/**
* Paints the vertical or horizontal separator line between swimlanes.
*/
paintSeparator(
c: AbstractCanvas2D,
x: number,
y: number,
w: number,
h: number,
start: number,
color: ColorValue
) {
if (color !== NONE) {
c.setStrokeColor(color);
c.setDashed(true);
c.begin();
if (this.isHorizontal()) {
c.moveTo(w, start);
c.lineTo(w, h);
} else {
c.moveTo(start, 0);
c.lineTo(w, 0);
}
c.stroke();
c.setDashed(false);
}
}
/**
* Paints the swimlane vertex shape.
*/
getImageBounds(x: number, y: number, w: number, h: number) {
if (this.isHorizontal()) {
return new Rectangle(x + w - this.imageSize, y, this.imageSize, this.imageSize);
}
return new Rectangle(x, y, this.imageSize, this.imageSize);
}
}
export default SwimlaneShape; | the_stack |
module TDev {
// ---------- Communication protocol
var dbg = /(dbg|test)=1/.test(window.location.href);
var allowedOrigins = [
/^http:\/\/localhost/,
/^https?:\/\/.*\.microbit\.co\.uk/,
/^https?:\/\/microbit\.co\.uk/,
];
function isAllowedOrigin(origin: string) {
return allowedOrigins.filter(x => !!origin.match(x)).length > 0;
}
// Both of these are written once when we receive the first (trusted)
// message.
var outer: Window = null;
var origin: string = null;
// A global that remembers the current version we're editing
var currentVersion: string;
var inMerge: boolean = false;
function debounce(func : () => void, wait : number, immediate : boolean) : () => void {
var timeout : any;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
window.addEventListener("message", (event) => {
if (!isAllowedOrigin(event.origin)) {
console.error("[inner message] not from the right origin!", event.origin);
return;
}
if (!outer || !origin) {
outer = event.source;
origin = event.origin;
}
receive(<External.Message>event.data);
});
var onResize = () => {};
function receive(message: External.Message) {
console.log("[inner message]", message);
switch (message.type) {
case External.MessageType.Init:
setupEditor(<External.Message_Init> message);
setupButtons();
setupCurrentVersion(<External.Message_Init> message);
break;
case External.MessageType.Resized:
onResize();
break;
case External.MessageType.SaveAck:
saveAck(<External.Message_SaveAck> message);
break;
case External.MessageType.Merge:
promptMerge((<External.Message_Merge> message).merge);
break;
case External.MessageType.CompileAck:
compileAck(<External.Message_CompileAck> message);
break;
case External.MessageType.NewBaseVersion:
newBaseVersion(<External.Message_NewBaseVersion> message);
break;
case External.MessageType.TypeCheck:
typeCheckError(<External.Message_TypeCheck>message);
break;
}
}
function post(message: External.Message) {
if (!outer)
console.error("Invalid state");
outer.postMessage(message, origin);
}
// ---------- Revisions
function prefix(where: External.SaveLocation) {
switch (where) {
case External.SaveLocation.Cloud:
return("☁ [cloud]");
case External.SaveLocation.Local:
return("⌂ [local]");
}
}
function statusIcon(icon: string) {
var i = $("#cloud-status i");
i.attr("class", "fa fa-"+icon);
switch (icon) {
case "cloud-upload":
i.attr("title", "Saved to cloud");
break;
case "floppy-o":
i.attr("title", "Saved locally");
break;
case "exclamation-triangle":
i.attr("title", "Error while saving -- see ⓘ for more information");
break;
case "pencil":
i.attr("title", "Local changes");
break;
default:
i.attr("title", "");
}
}
function saveAck(message: External.Message_SaveAck) {
switch (message.status) {
case External.Status.Error:
statusMsg(prefix(message.where)+" error: "+message.error, message.status);
statusIcon("exclamation-triangle");
break;
case External.Status.Ok:
if (message.where == External.SaveLocation.Cloud) {
statusMsg(prefix(message.where) + " successfully saved version (cloud in sync? " +
message.cloudIsInSync + ", " +
"from " + currentVersion + " to " + message.newBaseSnapshot + ")",
message.status);
currentVersion = message.newBaseSnapshot;
if (message.cloudIsInSync)
statusIcon("cloud-upload");
else
statusIcon("exclamation-triangle");
} else {
statusIcon("floppy-o");
statusMsg(prefix(message.where) + " successfully saved", message.status);
}
// if (message.changed) {
// statusMsg("changes detected, running...", message.status);
// doRun(true);
// }
break;
}
}
function compileAck(message: External.Message_CompileAck) {
$("#command-compile > .roundsymbol").removeClass("compiling");
switch (message.status) {
case External.Status.Error:
statusMsg("compilation error: "+message.error, message.status);
showPopup($("#link-log"), $("#popup-log"));
break;
case External.Status.Ok:
statusMsg("compilation successful", message.status);
break;
}
}
var mergeDisabled = true;
function typeCheckError(msg: External.Message_TypeCheck) {
statusMsg("! your script has errors", External.Status.Error);
}
function newBaseVersion(msg: External.Message_NewBaseVersion) {
statusMsg("✎ got assigned our first base version", External.Status.Ok);
// We've been assigned a base version number for the first time. All further
// save messages will be on top of that current version.
currentVersion = msg.baseSnapshot;
}
function promptMerge(merge: External.PendingMerge) {
if (mergeDisabled) {
inMerge = false;
currentVersion = merge.theirs.baseSnapshot;
statusMsg("✎ ignoring merge, forcing changes", External.Status.Ok);
doSave(true);
return;
}
console.log("[merge] merge request, base = "+merge.base.baseSnapshot +
", theirs = "+merge.theirs.baseSnapshot +
", mine = "+currentVersion);
var mkButton = function (symbol: string, label: string, f: () => void) {
return $("<div>").text(symbol+" "+label).click(f);
};
var box = $("#merge-commands");
var clearMerge = () => {
box.empty();
};
var mineText = saveBlockly();
var mineName = getName();
var mineButton = mkButton("🔍", "see mine", () => {
loadBlockly(mineText);
setName(mineName);
});
var theirsButton = mkButton("🔍", "see theirs", () => {
loadBlockly(merge.theirs.scriptText);
setName(merge.theirs.metadata.name);
});
var baseButton = mkButton("🔍", "see base", () => {
loadBlockly(merge.base.scriptText);
setName(merge.base.metadata.name);
});
var mergeButton = mkButton("👍", "finish merge", () => {
inMerge = false;
currentVersion = merge.theirs.baseSnapshot;
clearMerge();
doSave(true);
});
clearMerge();
inMerge = true;
box.append($("<div>").addClass("label").text("Merge conflict"));
[ mineButton, theirsButton, baseButton, mergeButton ].forEach(button => {
box.append(button);
box.append($(" "));
});
}
function setupCurrentVersion(message: External.Message_Init) {
currentVersion = message.script.baseSnapshot;
console.log("[revisions] current version is "+currentVersion);
if (message.merge)
promptMerge(message.merge);
}
// ---------- UI functions
interface EditorState {
lastSave: Date;
}
function statusMsg(s: string, st: External.Status) {
var box = $("#log");
var elt = $("<div>").addClass("status").text(s);
if (st == External.Status.Error)
elt.addClass("error");
else
elt.removeClass("error");
box.append(elt);
box.scrollTop(box.prop("scrollHeight"));
}
function loadBlockly(s: string) {
var text = s || "<xml></xml>";
var xml = Blockly.Xml.textToDom(text);
Blockly.mainWorkspace.clear();
try {
Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xml);
} catch (e) {
console.error("Cannot load saved Blockly script. Too recent?");
console.error(e);
}
}
function saveBlockly(): string {
var xml = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
var text = Blockly.Xml.domToPrettyText(xml);
return text;
}
function setName(x: string) {
$("#script-name").val(x);
}
function getName() {
return $("#script-name").val();
}
var dirty = false;
/* Some popup routines... */
function clearPopups() {
$(".popup").addClass("hidden");
}
function setupPopups() {
/* Hide all popups when user clicks elsewhere. */
$(document).click((e: Event) => {
if ($(e.target).closest(".popup, .roundbutton").length)
return;
clearPopups();
});
}
function setupPopup(link: JQuery, popup: JQuery) {
link.click((e: Event) => {
if (popup.hasClass("hidden"))
showPopup(link, popup);
else
popup.addClass("hidden");
e.stopPropagation();
});
}
function showPopup(link: JQuery, popup: JQuery) {
clearPopups();
popup.removeClass("hidden");
var x = link[0].offsetLeft;
var w = link[0].clientWidth;
var y = link[0].offsetTop;
var h = link[0].clientHeight;
var popupw = popup[0].clientWidth;
popup.css("left", Math.round(x - popupw + w/2 + 5 + 15)+"px");
popup.css("top", Math.round(y + h + 10 + 5)+"px");
}
var debouncedSave = debounce(doSave, 5000, false);
function markLocalChanges() {
statusMsg("✎ local changes", External.Status.Ok);
statusIcon("pencil");
dirty = true;
debouncedSave();
}
// Called once at startup
function setupEditor(message: External.Message_Init) {
var state = <MyEditorState> message.script.editorState;
var blocklyArea = document.getElementById('editor');
var blocklyDiv = document.getElementById('blocklyDiv');
var blocklyToolbox = document.getElementById("blockly-toolbox");
if (!dbg) {
var cats = blocklyToolbox.getElementsByTagName("category");
for (var i = 0; i < cats.length; ++i) {
var catEl = <any>cats.item(i);
if (catEl.getAttribute("debug")) catEl.parentElement.removeChild(catEl);
}
}
var workspace = Blockly.inject(blocklyDiv, {
toolbox: blocklyToolbox,
scrollbars: true,
media: "./media/",
zoom: {
enabled: true,
controls: true,
wheel: true,
maxScale: 2.5,
minScale: .1,
scaleSpeed: 1.1
},
});
// support for opening help on the side pane
(<any>Blockly).BlockSvg.prototype.showHelp_ = function() {
var url = goog.isFunction(this.helpUrl) ? this.helpUrl() : this.helpUrl;
var m = /^https:\/\/www.microbit.co.uk(.*)$/i.exec(url);
if (url) {
if (m && m[1])
post(<External.Message_Help>{
type: External.MessageType.Help,
path: m[1]
});
else window.open(url);
}
};
onResize = () => {
// Compute the absolute coordinates and dimensions of blocklyArea.
var element = blocklyArea;
var x = 0;
var y = 0;
do {
x += element.offsetLeft;
y += element.offsetTop;
element = <HTMLElement> element.offsetParent;
} while (element);
// Position blocklyDiv over blocklyArea.
blocklyDiv.style.left = x + 'px';
blocklyDiv.style.top = y + 'px';
blocklyDiv.style.width = blocklyArea.offsetWidth + 'px';
blocklyDiv.style.height = blocklyArea.offsetHeight + 'px';
};
window.addEventListener('resize', onresize, false);
window.addEventListener('orientationchange', onresize, false);
onResize();
loadBlockly(message.script.scriptText);
// Hack alert! Blockly's [fireUiEvent] function [setTimeout]'s (with a 0 delay) the actual
// firing of the event, meaning that the call to [inject] above schedule a change event to
// be fired immediately after the current function is done. To make sure our change handler
// does not receive that initial event, we schedule it for slightly later.
window.setTimeout(() => {
Blockly.mainWorkspace.addChangeListener(() => {
markLocalChanges();
});
}, 1);
$("#script-name").on("blur", () => {
if (getName().trim() == "")
setName("staggering program");
markLocalChanges();
});
$("#script-name").on("input keyup blur", () => {
markLocalChanges();
});
setName(message.script.metadata.name);
if (!message.script.baseSnapshot && !message.script.metadata.comment) {
markLocalChanges();
}
// That's triggered when the user closes or reloads the whole page, but
// doesn't help if the user hits the "back" button in our UI.
window.addEventListener("beforeunload", e => {
if (dirty) {
var confirmationMessage = "Some of your changes have not been saved. Quit anyway?";
(e || window.event).returnValue = confirmationMessage;
return confirmationMessage;
}
});
document.addEventListener("dragover", (event) => {
// This is mandatory to allow dropping...
event.preventDefault();
});
document.addEventListener("drop", (event) => {
event.preventDefault();
for (var i = 0; i < event.dataTransfer.files.length; ++i) {
var f = event.dataTransfer.files[i];
if (/\.(hex|json|jsz)$/.test(f.name))
post(<External.Message_Load> {
type: External.MessageType.Load,
file: f
});
}
});
setupPopup($("#link-log"), $("#popup-log"));
setupPopups();
// Run the program when loaded if it compiles and if the simulator is
// already visible.
var ast = compileOrError(false);
if (ast)
post(<External.Message_Run> {
type: External.MessageType.Run,
ast: <any> ast,
libs: libs,
onlyIfSplit: true,
});
console.log("[loaded] cloud version " + message.script.baseSnapshot +
"(dated from: "+state.lastSave+")");
}
interface MyEditorState extends External.EditorState {
lastSave: Date
}
function doSave(force = false) {
if (!dirty && !force) {
console.log('nothing to save...')
return;
}
var text = saveBlockly();
console.log("[saving] on top of: ", currentVersion);
post(<External.Message_Save>{
type: External.MessageType.Save,
script: {
scriptText: text,
editorState: <MyEditorState> {
// XXX test values
// tutorialStep: 1,
// tutorialNumSteps: 10,
lastSave: new Date()
},
baseSnapshot: currentVersion,
metadata: {
name: getName(),
comment: ''
}
},
});
dirty = false;
}
function compileOrError(appendSuffix: boolean, msgSel?: string) {
var ast: TDev.AST.Json.JApp;
$(".blocklySelected, .blocklyError").each((i, x) =>
x.setAttribute("class", x.getAttribute("class").replace(/(blocklySelected|blocklyError)/g, "")));
clearPopups();
$("#errorsGraduate").addClass("hidden");
$("#errorsCompile").addClass("hidden");
$("#errorsRun").addClass("hidden");
try {
ast = compile(Blockly.mainWorkspace, {
name: getName() + (appendSuffix ? " (converted)" : ""),
description: ''
});
} catch (e) {
statusMsg("⚠ compilation error: "+e, External.Status.Error);
showPopup($("#link-log"), $("#popup-log"));
}
var errors = Errors.get();
if (errors.length && msgSel) {
var text = "";
errors
.slice(0, 1) // Just display the first error
.forEach((e: Errors.CompilationError) => {
var block = e.block;
$(block.svgGroup_).attr("class", "blocklySelected blocklyError");
text += e.msg + "\n";
});
statusMsg(text, External.Status.Error);
$(msgSel).removeClass("hidden");
showPopup($("#link-log"), $("#popup-log"));
return null;
}
return ast;
}
var libs: { [index: string]: External.LibEntry } = {
"micro:bit": {
pubId: "lwhfye",
depends: []
},
"micro:bit game": {
pubId: "lwagkt",
depends: [ "micro:bit" ]
},
"micro:bit sprites": {
pubId: "vzkdcc",
depends: [ "micro:bit", "micro:bit game" ]
},
"micro:bit screen": {
pubId: "nzngii",
depends: [ "micro:bit" ]
},
"micro:bit senses": {
pubId: "vkmzfe",
depends: [ "micro:bit" ]
},
"micro:bit music": {
pubId: "zbiwoq",
depends: [ "micro:bit" ]
} /*,
"micro:bit radio": {
pubId: "fgkphf",
depends: [ "micro:bit" ]
}, */
};
if (!dbg) {
delete libs["micro:bit radio"];
}
function doGraduate(msgSel?: string) {
doSave();
var ast = compileOrError(true, msgSel);
if (!ast)
return;
post(<External.Message_Upgrade> {
type: External.MessageType.Upgrade,
ast: ast,
name: getName()+" (converted)",
libs: libs,
});
}
function doCompile(msgSel?: string) {
doSave();
var ast = compileOrError(false, msgSel);
if (!ast)
return;
$("#command-compile > .roundsymbol").addClass("compiling");
post(<External.Message_Compile> {
type: External.MessageType.Compile,
text: ast,
language: External.Language.TouchDevelop,
name: getName(),
libs: libs,
source: saveBlockly()
});
}
function doRun(auto : boolean) {
doSave();
var ast = compileOrError(false, "#errorsRun");
if (!ast)
return;
post(<External.Message_Run>{
type: External.MessageType.Run,
ast: <any>ast,
libs: libs,
onlyIfSplit: auto
});
}
function setupButtons() {
$("#command-quit").click(() => {
doSave();
post({ type: External.MessageType.Quit });
});
$("#command-force-compile").click(() => {
doCompile();
});
$("#command-compile").click((e: Event) => {
doCompile("#errorsCompile");
e.stopPropagation();
});
$("#command-force-graduate").click(() => {
doGraduate();
});
$("#command-graduate").click((e: Event) => {
doGraduate("#errorsGraduate");
e.stopPropagation();
});
$("#command-run").click(() => doRun(false));
}
}
// vim: set ts=2 sw=2 sts=2: | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages the Vulnerability Assessment for a Synapse SQL Pool.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* accountKind: "StorageV2",
* isHnsEnabled: "true",
* });
* const exampleDataLakeGen2Filesystem = new azure.storage.DataLakeGen2Filesystem("exampleDataLakeGen2Filesystem", {storageAccountId: exampleAccount.id});
* const exampleWorkspace = new azure.synapse.Workspace("exampleWorkspace", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* storageDataLakeGen2FilesystemId: exampleDataLakeGen2Filesystem.id,
* sqlAdministratorLogin: "sqladminuser",
* sqlAdministratorLoginPassword: "H@Sh1CoR3!",
* aadAdmin: {
* login: "AzureAD Admin",
* objectId: "00000000-0000-0000-0000-000000000000",
* tenantId: "00000000-0000-0000-0000-000000000000",
* },
* tags: {
* Env: "production",
* },
* });
* const exampleSqlPool = new azure.synapse.SqlPool("exampleSqlPool", {
* synapseWorkspaceId: exampleWorkspace.id,
* skuName: "DW100c",
* createMode: "Default",
* });
* const auditLogs = new azure.storage.Account("auditLogs", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleSqlPoolSecurityAlertPolicy = new azure.synapse.SqlPoolSecurityAlertPolicy("exampleSqlPoolSecurityAlertPolicy", {
* sqlPoolId: exampleSqlPool.id,
* policyState: "Enabled",
* storageEndpoint: auditLogs.primaryBlobEndpoint,
* storageAccountAccessKey: auditLogs.primaryAccessKey,
* disabledAlerts: [
* "Sql_Injection",
* "Data_Exfiltration",
* ],
* retentionDays: 20,
* });
* const exampleSqlPoolVulnerabilityAssessment = new azure.synapse.SqlPoolVulnerabilityAssessment("exampleSqlPoolVulnerabilityAssessment", {
* sqlPoolSecurityAlertPolicyId: exampleSqlPoolSecurityAlertPolicy.id,
* storageContainerPath: pulumi.interpolate`${exampleAccount.primaryBlobEndpoint}${azurerm_storage_container.example.name}/`,
* storageAccountAccessKey: exampleAccount.primaryAccessKey,
* recurringScans: {
* enabled: true,
* emailSubscriptionAdminsEnabled: true,
* emails: [
* "email@example1.com",
* "email@example2.com",
* ],
* },
* });
* ```
*
* ## Import
*
* Synapse SQL Pool Vulnerability Assessment can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:synapse/sqlPoolVulnerabilityAssessment:SqlPoolVulnerabilityAssessment example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Synapse/workspaces/workspace1/sqlPools/sqlPool1/vulnerabilityAssessments/default
* ```
*/
export class SqlPoolVulnerabilityAssessment extends pulumi.CustomResource {
/**
* Get an existing SqlPoolVulnerabilityAssessment resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: SqlPoolVulnerabilityAssessmentState, opts?: pulumi.CustomResourceOptions): SqlPoolVulnerabilityAssessment {
return new SqlPoolVulnerabilityAssessment(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:synapse/sqlPoolVulnerabilityAssessment:SqlPoolVulnerabilityAssessment';
/**
* Returns true if the given object is an instance of SqlPoolVulnerabilityAssessment. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is SqlPoolVulnerabilityAssessment {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === SqlPoolVulnerabilityAssessment.__pulumiType;
}
/**
* The recurring scans settings. The `recurringScans` block supports fields documented below.
*/
public readonly recurringScans!: pulumi.Output<outputs.synapse.SqlPoolVulnerabilityAssessmentRecurringScans>;
/**
* The ID of the security alert policy of the Synapse SQL Pool. Changing this forces a new resource to be created.
*/
public readonly sqlPoolSecurityAlertPolicyId!: pulumi.Output<string>;
/**
* Specifies the identifier key of the storage account for vulnerability assessment scan results. If `storageContainerSasKey` isn't specified, `storageAccountAccessKey` is required.
*/
public readonly storageAccountAccessKey!: pulumi.Output<string | undefined>;
/**
* A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/).
*/
public readonly storageContainerPath!: pulumi.Output<string>;
/**
* A shared access signature (SAS Key) that has write access to the blob container specified in `storageContainerPath` parameter. If `storageAccountAccessKey` isn't specified, `storageContainerSasKey` is required.
*/
public readonly storageContainerSasKey!: pulumi.Output<string | undefined>;
/**
* Create a SqlPoolVulnerabilityAssessment resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: SqlPoolVulnerabilityAssessmentArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: SqlPoolVulnerabilityAssessmentArgs | SqlPoolVulnerabilityAssessmentState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as SqlPoolVulnerabilityAssessmentState | undefined;
inputs["recurringScans"] = state ? state.recurringScans : undefined;
inputs["sqlPoolSecurityAlertPolicyId"] = state ? state.sqlPoolSecurityAlertPolicyId : undefined;
inputs["storageAccountAccessKey"] = state ? state.storageAccountAccessKey : undefined;
inputs["storageContainerPath"] = state ? state.storageContainerPath : undefined;
inputs["storageContainerSasKey"] = state ? state.storageContainerSasKey : undefined;
} else {
const args = argsOrState as SqlPoolVulnerabilityAssessmentArgs | undefined;
if ((!args || args.sqlPoolSecurityAlertPolicyId === undefined) && !opts.urn) {
throw new Error("Missing required property 'sqlPoolSecurityAlertPolicyId'");
}
if ((!args || args.storageContainerPath === undefined) && !opts.urn) {
throw new Error("Missing required property 'storageContainerPath'");
}
inputs["recurringScans"] = args ? args.recurringScans : undefined;
inputs["sqlPoolSecurityAlertPolicyId"] = args ? args.sqlPoolSecurityAlertPolicyId : undefined;
inputs["storageAccountAccessKey"] = args ? args.storageAccountAccessKey : undefined;
inputs["storageContainerPath"] = args ? args.storageContainerPath : undefined;
inputs["storageContainerSasKey"] = args ? args.storageContainerSasKey : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(SqlPoolVulnerabilityAssessment.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering SqlPoolVulnerabilityAssessment resources.
*/
export interface SqlPoolVulnerabilityAssessmentState {
/**
* The recurring scans settings. The `recurringScans` block supports fields documented below.
*/
recurringScans?: pulumi.Input<inputs.synapse.SqlPoolVulnerabilityAssessmentRecurringScans>;
/**
* The ID of the security alert policy of the Synapse SQL Pool. Changing this forces a new resource to be created.
*/
sqlPoolSecurityAlertPolicyId?: pulumi.Input<string>;
/**
* Specifies the identifier key of the storage account for vulnerability assessment scan results. If `storageContainerSasKey` isn't specified, `storageAccountAccessKey` is required.
*/
storageAccountAccessKey?: pulumi.Input<string>;
/**
* A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/).
*/
storageContainerPath?: pulumi.Input<string>;
/**
* A shared access signature (SAS Key) that has write access to the blob container specified in `storageContainerPath` parameter. If `storageAccountAccessKey` isn't specified, `storageContainerSasKey` is required.
*/
storageContainerSasKey?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a SqlPoolVulnerabilityAssessment resource.
*/
export interface SqlPoolVulnerabilityAssessmentArgs {
/**
* The recurring scans settings. The `recurringScans` block supports fields documented below.
*/
recurringScans?: pulumi.Input<inputs.synapse.SqlPoolVulnerabilityAssessmentRecurringScans>;
/**
* The ID of the security alert policy of the Synapse SQL Pool. Changing this forces a new resource to be created.
*/
sqlPoolSecurityAlertPolicyId: pulumi.Input<string>;
/**
* Specifies the identifier key of the storage account for vulnerability assessment scan results. If `storageContainerSasKey` isn't specified, `storageAccountAccessKey` is required.
*/
storageAccountAccessKey?: pulumi.Input<string>;
/**
* A blob storage container path to hold the scan results (e.g. https://myStorage.blob.core.windows.net/VaScans/).
*/
storageContainerPath: pulumi.Input<string>;
/**
* A shared access signature (SAS Key) that has write access to the blob container specified in `storageContainerPath` parameter. If `storageAccountAccessKey` isn't specified, `storageContainerSasKey` is required.
*/
storageContainerSasKey?: pulumi.Input<string>;
} | the_stack |
export interface ModifyMultiBizConfigResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateMultiBizAlert返回参数结构体
*/
export interface CreateMultiBizAlertResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 摄像头配置信息
*/
export interface CameraConfig {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 楼层ID
*/
FloorId: number;
/**
* 摄像头ID
*/
CameraId: number;
/**
* 摄像头IP
*/
CameraIp: string;
/**
* 摄像头Mac
*/
CameraMac: string;
/**
* 摄像头类型:
1: 码流机
2: AI相机
*/
CameraType: number;
/**
* 摄像头功能:
1: 人脸
2: 人体
*/
CameraFeature: number;
/**
* 摄像头是否启用:
0: 下线
1: 启用
*/
CameraState: number;
/**
* 点位ID
*/
ZoneId: number;
/**
* 点位类型:
1: 场门
3: 层门
5: 特殊区域
7: 门店
8: 补位
10: 开放式门店
11: 品类区
12: 公共区
*/
ZoneType: number;
/**
* 配置
*/
Config: Config;
/**
* 宽
*/
Width: number;
/**
* 高
*/
Height: number;
}
/**
* CreateServerState返回参数结构体
*/
export interface CreateServerStateResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 多边形
*/
export interface Polygon {
/**
* 标注列表
*/
Points: Array<Point>;
}
/**
* CreateCapture返回参数结构体
*/
export interface CreateCaptureResponse {
/**
* 原始应答报文
注意:此字段可能返回 null,表示取不到有效值。
*/
RspData?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeConfig请求参数结构体
*/
export interface DescribeConfigRequest {
/**
* 会话ID
*/
SessionId: string;
/**
* 摄像头签名
*/
CameraSign: string;
/**
* 摄像头app id
*/
CameraAppId: string;
/**
* 摄像头时间戳,毫秒
*/
CameraTimestamp: number;
/**
* MAC地址,字母大写
*/
ServerMac?: string;
/**
* 集团编码
*/
GroupCode?: string;
/**
* 广场ID
*/
MallId?: number;
}
/**
* DeleteTask请求参数结构体
*/
export interface DeleteTaskRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 任务ID
*/
TaskId: number;
}
/**
* CreateCameraAlerts请求参数结构体
*/
export interface CreateCameraAlertsRequest {
/**
* 告警信息列表
*/
Alerts?: Array<CreateCameraAlertAlert>;
}
/**
* CreateCameraAlerts返回参数结构体
*/
export interface CreateCameraAlertsResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteMultiBizAlert请求参数结构体
*/
export interface DeleteMultiBizAlertRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 点位ID
*/
ZoneId: number;
/**
* 摄像头ID
*/
CameraId: number;
/**
* 消警动作:
1: 误报
2: 正报合规
3: 正报不合规,整改完成
*/
ActionType: number;
/**
* 图片base64字符串
*/
Image?: string;
}
/**
* 服务器监控状态上报项
*/
export interface ServerStateItem {
/**
* 服务器状态
1: 在线
2: 离线
3: 重启
*/
ServerState: number;
/**
* 服务器IP
*/
ServerIp: string;
/**
* 硬盘监控信息列表
*/
DiskInfos: Array<DiskInfo>;
}
/**
* DescribeZones请求参数结构体
*/
export interface DescribeZonesRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
}
/**
* 摄像头配置
*/
export interface Config {
/**
* 摄像头厂商:
H: 海康
D: 大华
Y: 英飞拓
L: 联纵
*/
CameraProducer: string;
/**
* rtsp 地址
*/
RTSP: string;
/**
* 摄像头帧率
*/
Fps: number;
/**
* 解码帧率
*/
DecodeFps: number;
/**
* 是否做客流计算:
0: 否
1: 是
*/
PassengerFlow: number;
/**
* 是否打开人脸曝光:
0: 关闭
1: 开启
*/
FaceExpose: number;
/**
* 门线标注
*/
MallArea: Array<Point>;
/**
* 店门标注
*/
ShopArea: Array<Point>;
/**
* 检测区标注
*/
TrackAreas: Array<Polygon>;
/**
* 点位列表(品类区)
*/
Zones: Array<ZoneArea>;
}
/**
* 任务内容
*/
export interface TaskContent {
/**
* 摄像头ID
*/
CameraId: number;
/**
* rtsp 地址
*/
RTSP: string;
/**
* 图片上传地址
*/
Url: string;
}
/**
* SearchImage返回参数结构体
*/
export interface SearchImageResponse {
/**
* face id
*/
FaceId?: string;
/**
* 搜索结果列表
*/
Results?: Array<SearchResult>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateProgramState返回参数结构体
*/
export interface CreateProgramStateResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 用于服务注册时表示当前服务的具体信息
*/
export interface ServiceRegisterInfo {
/**
* 当前服务的回调地址
*/
CgiUrl: string;
/**
* 当前服务类型:
1: 多经服务
2: 相机误报警确认
3: 底图更新
*/
ServiceType: number;
}
/**
* DescribeTasks请求参数结构体
*/
export interface DescribeTasksRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 任务类型:
1: 底图拉取
*/
TaskType: number;
}
/**
* SearchImage请求参数结构体
*/
export interface SearchImageRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 图片base64字符串
*/
Image: string;
/**
* 时间戳,毫秒
*/
ImageTime: number;
}
/**
* DeleteMultiBizAlert返回参数结构体
*/
export interface DeleteMultiBizAlertResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ReportServiceRegister请求参数结构体
*/
export interface ReportServiceRegisterRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 服务上报当前的服务能力信息
*/
ServiceRegisterInfos: Array<ServiceRegisterInfo>;
/**
* 服务内网Ip
*/
ServerIp: string;
/**
* 上报服务所在服务器的唯一ID
*/
ServerNodeId: string;
/**
* 上报时间戳, 单位毫秒
*/
ReportTime: number;
}
/**
* DescribeImage返回参数结构体
*/
export interface DescribeImageResponse {
/**
* cos 临时 url,异步上传图片,client需要轮询
*/
ImageUrl?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 告警信息
*/
export interface CreateCameraAlertAlert {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 相机ID
*/
CameraId: number;
/**
* 时间戳,ms,默认为告警请求到达时间
*/
CaptureTime: number;
/**
* 图片base64编码
*/
Image?: string;
/**
* 移动告警
*/
MoveAlert?: CreateCameraAlertsMoveAlert;
/**
* 遮挡告警
*/
CoverAlert?: CreateCameraAlertsCoverAlert;
}
/**
* ReportServiceRegister返回参数结构体
*/
export interface ReportServiceRegisterResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* 硬盘监控信息
*/
export interface DiskInfo {
/**
* 硬盘名字
*/
DiskName: string;
/**
* 硬盘使用率
*/
Usage: number;
}
/**
* CreateCameraState返回参数结构体
*/
export interface CreateCameraStateResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* CreateMultiBizAlert请求参数结构体
*/
export interface CreateMultiBizAlertRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 点位ID
*/
ZoneId: number;
/**
* 摄像头ID
*/
CameraId: number;
/**
* 时间戳,毫秒
*/
CaptureTime: number;
/**
* 状态:
1: 侵占
2: 消失
3: 即侵占又消失
*/
State: number;
/**
* 图片base64字符串
*/
Image?: string;
/**
* 告警列表
*/
Warnings?: Array<MultiBizWarning>;
}
/**
* CreateProgramState请求参数结构体
*/
export interface CreateProgramStateRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 进程监控信息列表
*/
ProgramStateItems: Array<ProgramStateItem>;
/**
* 商场ID
*/
MallId?: number;
}
/**
* DescribeMultiBizBaseImage请求参数结构体
*/
export interface DescribeMultiBizBaseImageRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 摄像头ID
*/
CameraId: number;
/**
* 点位ID
*/
ZoneId: number;
}
/**
* 多经点位告警信息
*/
export interface MultiBizWarningInfo {
/**
* 告警类型:
0: 无变化
1: 侵占
2: 消失
*/
WarningType: number;
/**
* 告警侵占或消失面积
*/
WarningAreaSize: number;
/**
* 告警侵占或消失坐标
*/
WarningLocation: Point;
/**
* 告警侵占或消失轮廓
*/
WarningAreaContour: Array<Point>;
}
/**
* 任务信息
*/
export interface Task {
/**
* 任务ID
*/
TaskId: number;
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 任务内容
*/
TaskContent: TaskContent;
/**
* 任务类型:
1: 底图拉取
*/
TaskType: number;
}
/**
* 点位包含绑定、调试信息
*/
export interface ZoneConfig {
/**
* 点位ID
*/
ZoneId: number;
/**
* 点位名称
*/
ZoneName: string;
/**
* 点位类型:
1: 场门
3: 层门
5: 特殊区域
7: 门店
8: 补位
10: 开放式门店
11: 品类区
12: 公共区
*/
ZoneType: number;
/**
* 铺位编码
*/
BunkCodes: string;
/**
* 楼层名称
*/
FloorName: string;
/**
* 楼层ID
*/
FloorId: number;
/**
* 绑定数
*/
BindNum: number;
/**
* 调试数
*/
DebugNum: number;
/**
* 下发状态:
1: 不可下发
2: 可下发
3: 已下发
*/
State: number;
}
/**
* 进程状态监控项
*/
export interface ProgramStateItem {
/**
* 服务器IP
*/
ServerIp: string;
/**
* 进程名字
*/
ProgramName: string;
/**
* 在线个数
*/
OnlineCount: number;
/**
* 离线个数
*/
OfflineCount: number;
/**
* 上报状态:
1: 正常上报
2: 异常上报
注:此处异常上报是指本次上报由于场内服务内部原因导致上报数据不可信等。此时离线个数重置为1,在线个数重置为0
*/
State: number;
}
/**
* DescribeTasks返回参数结构体
*/
export interface DescribeTasksResponse {
/**
* 任务列表
*/
Tasks?: Array<Task>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeCameras请求参数结构体
*/
export interface DescribeCamerasRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
}
/**
* DescribeMultiBizBaseImage返回参数结构体
*/
export interface DescribeMultiBizBaseImageResponse {
/**
* cos 临时 url
*/
ImageUrl?: string;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeImage请求参数结构体
*/
export interface DescribeImageRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 摄像头ID
*/
CameraId: number;
}
/**
* 点位包含店门标注
*/
export interface ZoneArea {
/**
* 点位ID
*/
ZoneId: number;
/**
* 店门标注
*/
ShopArea: Array<Point>;
}
/**
* 以图搜图检索结果
*/
export interface SearchResult {
/**
* 图片base64数据
*/
Image: string;
/**
* 身份ID
*/
PersonId: string;
/**
* 相似度
*/
Similarity: number;
}
/**
* 用于场内上报当前相机的状态
*/
export interface CameraState {
/**
* 相机ID
*/
CameraId: number;
/**
* 相机状态:
10: 初始化
11: 未知状态
12: 网络异常
13: 未授权
14: 相机App异常
15: 相机取流异常
16: 状态正常
*/
State: number;
}
/**
* CreateCapture请求参数结构体
*/
export interface CreateCaptureRequest {
/**
* 原始抓拍报文
*/
Data: string;
}
/**
* 移动告警
*/
export interface CreateCameraAlertsMoveAlert {
/**
* 是否移动
*/
Move?: boolean;
/**
* 是否移动置信度
*/
MoveConfidence?: number;
}
/**
* CreateCameraState请求参数结构体
*/
export interface CreateCameraStateRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 场内所有相机的状态值
*/
CameraStates: Array<CameraState>;
}
/**
* DescribeCameras返回参数结构体
*/
export interface DescribeCamerasResponse {
/**
* 摄像头列表
*/
Cameras?: Array<CameraZones>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeConfig返回参数结构体
*/
export interface DescribeConfigResponse {
/**
* 会话ID
*/
SessionId?: string;
/**
* 配置版本号
*/
Version?: number;
/**
* 摄像头列表
*/
Cameras?: Array<CameraConfig>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DeleteTask返回参数结构体
*/
export interface DeleteTaskResponse {
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* DescribeZones返回参数结构体
*/
export interface DescribeZonesResponse {
/**
* 点位列表
*/
Zones?: Array<ZoneConfig>;
/**
* 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
*/
RequestId?: string;
}
/**
* ModifyMultiBizConfig请求参数结构体
*/
export interface ModifyMultiBizConfigRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 广场ID
*/
MallId: number;
/**
* 点位ID
*/
ZoneId: number;
/**
* 摄像头ID
*/
CameraId: number;
/**
* 监控区域
*/
MonitoringAreas: Array<Polygon>;
}
/**
* 摄像头包含简单的点位信息
*/
export interface CameraZones {
/**
* 摄像头ID
*/
CameraId: number;
/**
* 摄像头名称
*/
CameraName: string;
/**
* 摄像头功能:
1: 人脸
2: 人体
*/
CameraFeature: number;
/**
* 摄像头IP
*/
CameraIp: string;
/**
* 摄像头状态:
0: 异常 (不再使用)
1: 正常 (不再使用)
10: 初始化
11: 未知状态 (因服务内部错误产生)
12: 网络异常
13: 未授权
14: 相机App异常
15: 相机取流异常
16: 正常
*/
CameraState: number;
/**
* 点位列表
*/
Zones: Array<BunkZone>;
/**
* 像素:
130W(1280*960)
200W(1920*1080)
400W(2560*1440)
*/
Pixel: string;
/**
* 相机Rtsp地址
注意:此字段可能返回 null,表示取不到有效值。
*/
RTSP: string;
}
/**
* 遮挡告警
*/
export interface CreateCameraAlertsCoverAlert {
/**
* 是否遮挡
*/
Cover?: boolean;
/**
* 是否移动置信度
*/
CoverConfidence?: number;
}
/**
* 点位包含铺位信息
*/
export interface BunkZone {
/**
* 点位ID
*/
ZoneId: number;
/**
* 点位名称
*/
ZoneName: string;
/**
* 铺位编码
*/
BunkCodes: string;
}
/**
* 点
*/
export interface Point {
/**
* X坐标
*/
X: number;
/**
* Y坐标
*/
Y: number;
}
/**
* CreateServerState请求参数结构体
*/
export interface CreateServerStateRequest {
/**
* 集团编码
*/
GroupCode: string;
/**
* 服务器监控信息列表
*/
ServerStateItems: Array<ServerStateItem>;
/**
* 商场ID
*/
MallId?: number;
/**
* 服务器监控信息上报时间戳,单位毫秒
*/
ReportTime?: number;
}
/**
* 多经点位告警
*/
export interface MultiBizWarning {
/**
* 编号
*/
Id: number;
/**
* 监控区域
*/
MonitoringArea: Array<Point>;
/**
* 告警列表
*/
WarningInfos: Array<MultiBizWarningInfo>;
} | the_stack |
import { delay, inject, singleton } from "tsyringe";
import { TYPES } from "../types";
import {
Key,
KeyRing,
KeyRingStatus,
MultiKeyStoreInfoWithSelected,
} from "./keyring";
import {
Bech32Address,
checkAndValidateADR36AminoSignDoc,
makeADR36AminoSignDoc,
verifyADR36AminoSignDoc,
} from "@keplr-wallet/cosmos";
import { BIP44HDPath, CommonCrypto, ExportKeyRingData } from "./types";
import { KVStore } from "@keplr-wallet/common";
import { ChainsService } from "../chains";
import { LedgerService } from "../ledger";
import { BIP44, ChainInfo, KeplrSignOptions } from "@keplr-wallet/types";
import { APP_PORT, Env, KeplrError, WEBPAGE_PORT } from "@keplr-wallet/router";
import { InteractionService } from "../interaction";
import { PermissionService } from "../permission";
import {
encodeSecp256k1Signature,
serializeSignDoc,
AminoSignResponse,
StdSignDoc,
StdSignature,
} from "@cosmjs/launchpad";
import { DirectSignResponse, makeSignBytes } from "@cosmjs/proto-signing";
import { RNG } from "@keplr-wallet/crypto";
import { SignDoc } from "@keplr-wallet/proto-types/cosmos/tx/v1beta1/tx";
import Long from "long";
import { Buffer } from "buffer/";
@singleton()
export class KeyRingService {
private readonly keyRing: KeyRing;
constructor(
@inject(TYPES.KeyRingStore)
kvStore: KVStore,
@inject(TYPES.ChainsEmbedChainInfos)
embedChainInfos: ChainInfo[],
@inject(delay(() => InteractionService))
protected readonly interactionService: InteractionService,
@inject(delay(() => ChainsService))
public readonly chainsService: ChainsService,
@inject(delay(() => PermissionService))
public readonly permissionService: PermissionService,
@inject(LedgerService)
ledgerService: LedgerService,
@inject(TYPES.RNG)
protected readonly rng: RNG,
@inject(TYPES.CommonCrypto)
protected readonly crypto: CommonCrypto
) {
this.keyRing = new KeyRing(
embedChainInfos,
kvStore,
ledgerService,
rng,
crypto
);
}
async restore(): Promise<{
status: KeyRingStatus;
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
await this.keyRing.restore();
return {
status: this.keyRing.status,
multiKeyStoreInfo: this.keyRing.getMultiKeyStoreInfo(),
};
}
async enable(env: Env): Promise<KeyRingStatus> {
if (this.keyRing.status === KeyRingStatus.EMPTY) {
throw new KeplrError("keyring", 261, "key doesn't exist");
}
if (this.keyRing.status === KeyRingStatus.NOTLOADED) {
await this.keyRing.restore();
}
if (this.keyRing.status === KeyRingStatus.LOCKED) {
await this.interactionService.waitApprove(env, "/unlock", "unlock", {});
return this.keyRing.status;
}
return this.keyRing.status;
}
get keyRingStatus(): KeyRingStatus {
return this.keyRing.status;
}
async deleteKeyRing(
index: number,
password: string
): Promise<{
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
status: KeyRingStatus;
}> {
let keyStoreChanged = false;
try {
const result = await this.keyRing.deleteKeyRing(index, password);
keyStoreChanged = result.keyStoreChanged;
return {
multiKeyStoreInfo: result.multiKeyStoreInfo,
status: this.keyRing.status,
};
} finally {
if (keyStoreChanged) {
this.interactionService.dispatchEvent(
WEBPAGE_PORT,
"keystore-changed",
{}
);
}
}
}
async updateNameKeyRing(
index: number,
name: string
): Promise<{
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
const multiKeyStoreInfo = await this.keyRing.updateNameKeyRing(index, name);
return {
multiKeyStoreInfo,
};
}
async showKeyRing(index: number, password: string): Promise<string> {
return await this.keyRing.showKeyRing(index, password);
}
async createMnemonicKey(
kdf: "scrypt" | "sha256" | "pbkdf2",
mnemonic: string,
password: string,
meta: Record<string, string>,
bip44HDPath: BIP44HDPath
): Promise<{
status: KeyRingStatus;
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
// TODO: Check mnemonic checksum.
return await this.keyRing.createMnemonicKey(
kdf,
mnemonic,
password,
meta,
bip44HDPath
);
}
async createPrivateKey(
kdf: "scrypt" | "sha256" | "pbkdf2",
privateKey: Uint8Array,
password: string,
meta: Record<string, string>
): Promise<{
status: KeyRingStatus;
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
return await this.keyRing.createPrivateKey(kdf, privateKey, password, meta);
}
async createLedgerKey(
env: Env,
kdf: "scrypt" | "sha256" | "pbkdf2",
password: string,
meta: Record<string, string>,
bip44HDPath: BIP44HDPath
): Promise<{
status: KeyRingStatus;
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
return await this.keyRing.createLedgerKey(
env,
kdf,
password,
meta,
bip44HDPath
);
}
lock(): KeyRingStatus {
this.keyRing.lock();
return this.keyRing.status;
}
async unlock(password: string): Promise<KeyRingStatus> {
await this.keyRing.unlock(password);
return this.keyRing.status;
}
async getKey(chainId: string): Promise<Key> {
return this.keyRing.getKey(
chainId,
await this.chainsService.getChainCoinType(chainId)
);
}
getKeyStoreMeta(key: string): string {
return this.keyRing.getKeyStoreMeta(key);
}
getKeyRingType(): string {
return this.keyRing.type;
}
async requestSignAmino(
env: Env,
msgOrigin: string,
chainId: string,
signer: string,
signDoc: StdSignDoc,
signOptions: KeplrSignOptions & {
// Hack option field to detect the sign arbitrary for string
isADR36WithString?: boolean;
}
): Promise<AminoSignResponse> {
const coinType = await this.chainsService.getChainCoinType(chainId);
const key = await this.keyRing.getKey(chainId, coinType);
const bech32Prefix = (await this.chainsService.getChainInfo(chainId))
.bech32Config.bech32PrefixAccAddr;
const bech32Address = new Bech32Address(key.address).toBech32(bech32Prefix);
if (signer !== bech32Address) {
throw new KeplrError("keyring", 231, "Signer mismatched");
}
const isADR36SignDoc = checkAndValidateADR36AminoSignDoc(
signDoc,
bech32Prefix
);
if (isADR36SignDoc) {
if (signDoc.msgs[0].value.signer !== signer) {
throw new KeplrError("keyring", 233, "Unmatched signer in sign doc");
}
}
if (signOptions.isADR36WithString != null && !isADR36SignDoc) {
throw new KeplrError(
"keyring",
236,
'Sign doc is not for ADR-36. But, "isADR36WithString" option is defined'
);
}
const newSignDoc = (await this.interactionService.waitApprove(
env,
"/sign",
"request-sign",
{
msgOrigin,
chainId,
mode: "amino",
signDoc,
signer,
signOptions,
isADR36SignDoc,
isADR36WithString: signOptions.isADR36WithString,
}
)) as StdSignDoc;
if (isADR36SignDoc) {
// Validate the new sign doc, if it was for ADR-36.
if (checkAndValidateADR36AminoSignDoc(signDoc, bech32Prefix)) {
if (signDoc.msgs[0].value.signer !== signer) {
throw new KeplrError(
"keyring",
232,
"Unmatched signer in new sign doc"
);
}
} else {
throw new KeplrError(
"keyring",
237,
"Signing request was for ADR-36. But, accidentally, new sign doc is not for ADR-36"
);
}
}
try {
const signature = await this.keyRing.sign(
env,
chainId,
coinType,
serializeSignDoc(newSignDoc)
);
return {
signed: newSignDoc,
signature: encodeSecp256k1Signature(key.pubKey, signature),
};
} finally {
this.interactionService.dispatchEvent(APP_PORT, "request-sign-end", {});
}
}
async requestSignDirect(
env: Env,
msgOrigin: string,
chainId: string,
signer: string,
signDoc: SignDoc,
signOptions: KeplrSignOptions
): Promise<DirectSignResponse> {
const coinType = await this.chainsService.getChainCoinType(chainId);
const key = await this.keyRing.getKey(chainId, coinType);
const bech32Address = new Bech32Address(key.address).toBech32(
(await this.chainsService.getChainInfo(chainId)).bech32Config
.bech32PrefixAccAddr
);
if (signer !== bech32Address) {
throw new KeplrError("keyring", 231, "Signer mismatched");
}
const newSignDocBytes = (await this.interactionService.waitApprove(
env,
"/sign",
"request-sign",
{
msgOrigin,
chainId,
mode: "direct",
signDocBytes: SignDoc.encode(signDoc).finish(),
signer,
signOptions,
}
)) as Uint8Array;
const newSignDoc = SignDoc.decode(newSignDocBytes);
const {
accountNumber: newSignDocAccountNumber,
...newSignDocRest
} = newSignDoc;
const cosmJSSignDoc = {
...newSignDocRest,
accountNumber: Long.fromString(newSignDocAccountNumber),
};
try {
const signature = await this.keyRing.sign(
env,
chainId,
coinType,
makeSignBytes(cosmJSSignDoc)
);
return {
signed: cosmJSSignDoc,
signature: encodeSecp256k1Signature(key.pubKey, signature),
};
} finally {
this.interactionService.dispatchEvent(APP_PORT, "request-sign-end", {});
}
}
async verifyADR36AminoSignDoc(
chainId: string,
signer: string,
data: Uint8Array,
signature: StdSignature
): Promise<boolean> {
const coinType = await this.chainsService.getChainCoinType(chainId);
const key = await this.keyRing.getKey(chainId, coinType);
const bech32Prefix = (await this.chainsService.getChainInfo(chainId))
.bech32Config.bech32PrefixAccAddr;
const bech32Address = new Bech32Address(key.address).toBech32(bech32Prefix);
if (signer !== bech32Address) {
throw new KeplrError("keyring", 231, "Signer mismatched");
}
if (signature.pub_key.type !== "tendermint/PubKeySecp256k1") {
throw new KeplrError(
"keyring",
211,
`Unsupported type of pub key: ${signature.pub_key.type}`
);
}
if (
Buffer.from(key.pubKey).toString("base64") !== signature.pub_key.value
) {
throw new KeplrError("keyring", 210, "Pub key unmatched");
}
const signDoc = makeADR36AminoSignDoc(signer, data);
return verifyADR36AminoSignDoc(
bech32Prefix,
signDoc,
Buffer.from(signature.pub_key.value, "base64"),
Buffer.from(signature.signature, "base64")
);
}
async sign(
env: Env,
chainId: string,
message: Uint8Array
): Promise<Uint8Array> {
return this.keyRing.sign(
env,
chainId,
await this.chainsService.getChainCoinType(chainId),
message
);
}
async addMnemonicKey(
kdf: "scrypt" | "sha256" | "pbkdf2",
mnemonic: string,
meta: Record<string, string>,
bip44HDPath: BIP44HDPath
): Promise<{
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
return this.keyRing.addMnemonicKey(kdf, mnemonic, meta, bip44HDPath);
}
async addPrivateKey(
kdf: "scrypt" | "sha256" | "pbkdf2",
privateKey: Uint8Array,
meta: Record<string, string>
): Promise<{
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
return this.keyRing.addPrivateKey(kdf, privateKey, meta);
}
async addLedgerKey(
env: Env,
kdf: "scrypt" | "sha256" | "pbkdf2",
meta: Record<string, string>,
bip44HDPath: BIP44HDPath
): Promise<{
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
return this.keyRing.addLedgerKey(env, kdf, meta, bip44HDPath);
}
public async changeKeyStoreFromMultiKeyStore(
index: number
): Promise<{
multiKeyStoreInfo: MultiKeyStoreInfoWithSelected;
}> {
try {
return await this.keyRing.changeKeyStoreFromMultiKeyStore(index);
} finally {
this.interactionService.dispatchEvent(
WEBPAGE_PORT,
"keystore-changed",
{}
);
}
}
public checkPassword(password: string): boolean {
return this.keyRing.checkPassword(password);
}
getMultiKeyStoreInfo(): MultiKeyStoreInfoWithSelected {
return this.keyRing.getMultiKeyStoreInfo();
}
isKeyStoreCoinTypeSet(chainId: string): boolean {
return this.keyRing.isKeyStoreCoinTypeSet(chainId);
}
async setKeyStoreCoinType(chainId: string, coinType: number): Promise<void> {
const prevCoinType = this.keyRing.computeKeyStoreCoinType(
chainId,
await this.chainsService.getChainCoinType(chainId)
);
await this.keyRing.setKeyStoreCoinType(chainId, coinType);
if (prevCoinType !== coinType) {
this.interactionService.dispatchEvent(
WEBPAGE_PORT,
"keystore-changed",
{}
);
}
}
async getKeyStoreBIP44Selectables(
chainId: string,
paths: BIP44[]
): Promise<{ readonly path: BIP44; readonly bech32Address: string }[]> {
if (this.isKeyStoreCoinTypeSet(chainId)) {
return [];
}
const result = [];
const chainInfo = await this.chainsService.getChainInfo(chainId);
for (const path of paths) {
const key = await this.keyRing.getKeyFromCoinType(path.coinType);
const bech32Address = new Bech32Address(key.address).toBech32(
chainInfo.bech32Config.bech32PrefixAccAddr
);
result.push({
path,
bech32Address,
});
}
return result;
}
async exportKeyRingDatas(password: string): Promise<ExportKeyRingData[]> {
return await this.keyRing.exportKeyRingDatas(password);
}
} | the_stack |
import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from "@angular/core";
import { PanelWidgetAppearanceService } from "./panel-widget-appearance.service";
import { AppearanceModel, ConventionSiteModel, alignType } from "./model";
import { DraggablePort } from "@ng-public/directive/draggable/draggable.interface";
import { Subscription, BehaviorSubject } from "rxjs";
import { PanelScopeEnchantmentService } from "../panel-scope-enchantment/panel-scope-enchantment.service";
import { ProfileModel, OuterSphereHasAuxlModel, ScopeEnchantmentModel } from "../panel-scope-enchantment/model";
import { PanelWidgetModel } from "../panel-widget/model";
import { PanelExtendService } from "../panel-extend.service";
import { distinctUntilChanged, auditTime } from "rxjs/operators";
import { panelSiteComponentObj } from "../panel-widget-appearance-site";
import { cloneDeep } from "lodash";
import { PanelWidgetDetailsSiteService } from "../panel-widget-details/panel-widget-details.service";
@Component({
selector: "app-panel-widget-appearance",
templateUrl: "./panel-widget-appearance.component.html",
styleUrls: ["./panel-widget-appearance.component.scss"],
})
export class PanelWidgetAppearanceComponent implements OnInit {
// 主轮廓的可订阅对象
public profileOuterSphereRX$: Subscription;
// 主轮廓样式的值的变化可订阅对象
private profileValueChangeRX$: Subscription;
// 外观设置显示与否的可订阅对象
private appearanceIsShowRX$: Subscription;
// 订阅对齐方式
private alignWayRX$: Subscription;
public currentComponentRef: ComponentRef<any>;
// 是否允许设置水平等间距或垂直等间距
public get isEqualDistanceSet(): boolean {
return this.scopeEnchantment.outerSphereInsetWidgetList$.value.length > 2;
}
public get appearance(): AppearanceModel {
return this.panelWidgetAppearanceService.appearanceModel;
}
public get conventionSite(): ConventionSiteModel {
return this.panelWidgetAppearanceService.conventionSiteModel$.value;
}
public get scopeEnchantment(): ScopeEnchantmentModel {
return this.panelScopeEnchantmentService.scopeEnchantmentModel;
}
public get insetWidgetList(): Array<PanelWidgetModel> {
return this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$.value;
}
public get isOpenAnimation$(): BehaviorSubject<boolean> {
return this.panelWidgetAppearanceService.isOpenAnimation$;
}
public get isOpenRotate$(): BehaviorSubject<boolean> {
return this.panelWidgetAppearanceService.isOpenRotate$;
}
public get isOpenOpacity$(): BehaviorSubject<boolean> {
return this.panelWidgetAppearanceService.isOpenOpacity$;
}
public get isOpenOtherSite$(): BehaviorSubject<boolean> {
return this.panelWidgetAppearanceService.isOpenOtherSite$;
}
public get isOpenWidth$(): BehaviorSubject<boolean> {
return this.panelWidgetAppearanceService.isOpenWidth$;
}
public get isOpenHeight$(): BehaviorSubject<boolean> {
return this.panelWidgetAppearanceService.isOpenHeight$;
}
@ViewChild("otherSiteContainer", { read: ViewContainerRef, static: false })
public otherSiteContainer: ViewContainerRef;
constructor(
private readonly componentFactoryResolver: ComponentFactoryResolver,
private readonly panelWidgetAppearanceService: PanelWidgetAppearanceService,
private readonly panelWidgetDetailsSiteService: PanelWidgetDetailsSiteService,
private readonly panelScopeEnchantmentService: PanelScopeEnchantmentService,
private readonly panelExtendService: PanelExtendService
) {
this.profileOuterSphereRX$ = this.scopeEnchantment.profileOuterSphere$
.pipe(distinctUntilChanged())
.subscribe(value => {
if (value) {
this.appearance.isShow$.next(true);
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value;
if (Array.isArray(insetWidget) && insetWidget.length == 1) {
this.handleSetOnlyWidget();
} else if (Array.isArray(insetWidget) && insetWidget.length > 1) {
this.handleSetMoreWidget();
this.isOpenAnimation$.next(false);
}
this.subPruOuterSphereValueChange(value);
} else {
this.appearance.isShow$.next(false);
if (this.profileValueChangeRX$) this.profileValueChangeRX$.unsubscribe();
}
});
this.appearanceIsShowRX$ = this.panelWidgetAppearanceService.appearanceModel.isShow$.subscribe(bool => {
if (bool) {
setTimeout(() => {
if (Array.isArray(this.insetWidgetList) && this.insetWidgetList.length == 1) {
const widgetType = this.insetWidgetList[0].type;
if (panelSiteComponentObj[widgetType] && this.otherSiteContainer) {
if (this.currentComponentRef) this.currentComponentRef.destroy();
this.otherSiteContainer.clear();
this.currentComponentRef = this.otherSiteContainer.createComponent(
this.componentFactoryResolver.resolveComponentFactory(panelSiteComponentObj[widgetType])
);
this.currentComponentRef.instance.widget = this.insetWidgetList[0];
}
this.isOpenAnimation$.next(true);
this.isOpenRotate$.next(true);
this.isOpenOpacity$.next(true);
this.isOpenWidth$.next(true);
this.isOpenHeight$.next(true);
}
});
}
});
this.alignWayRX$ = this.panelWidgetAppearanceService.launchAlignWay$.subscribe(type => {
this.alignWay(type);
});
}
ngOnInit() {
// 根据窗口的大小重新定位外观设置的位置和高度
this.panelWidgetAppearanceService.appearanceModel.left = window.innerWidth - 490;
this.panelWidgetAppearanceService.appearanceModel.height = window.innerHeight - this.appearance.top - 10;
}
ngOnDestroy() {
if (this.profileOuterSphereRX$) this.profileOuterSphereRX$.unsubscribe();
if (this.profileValueChangeRX$) this.profileValueChangeRX$.unsubscribe();
if (this.appearanceIsShowRX$) this.appearanceIsShowRX$.unsubscribe();
if (this.currentComponentRef) this.currentComponentRef.destroy();
if (this.alignWayRX$) this.alignWayRX$.unsubscribe();
}
/**
* 开始订阅主轮廓的值观察对象
*/
public subPruOuterSphereValueChange(sphere: OuterSphereHasAuxlModel): void {
if (sphere) {
if (this.profileValueChangeRX$) this.profileValueChangeRX$.unsubscribe();
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value;
this.profileValueChangeRX$ = sphere.valueChange$.pipe(auditTime(10)).subscribe(value => {
if (insetWidget.length == 1) {
let conObj = cloneDeep<ProfileModel>(value);
this.conventionSite.setData(conObj);
} else {
this.handleSetMoreWidget();
}
});
}
}
/**
* 接收头部拖拽回来的数据
*/
public acceptDraggableData(data: DraggablePort): void {
if (data) {
this.appearance.top += data.top;
this.appearance.left += data.left;
}
}
/**
* 隐藏外观设置
*/
public closeAppearance(): void {
this.appearance.isShow$.next(false);
}
/**
* 对齐方式
* 如果主轮廓内的被选组件多余一个时则计算轮廓内的组件
* 否则只计算唯一的被选组件于主视图屏幕的对齐方式
* // 对齐之前保存一份到本地DB
*/
public alignWay(type: alignType): void {
this.panelExtendService.launchSaveIndexedDB$.next();
const panelInfo = this.panelExtendService.panelInfoModel;
const widgetList = this.scopeEnchantment.outerSphereInsetWidgetList$.value;
const pro = this.scopeEnchantment.valueProfileOuterSphere;
const calcProfile = (e: PanelWidgetModel, pro: OuterSphereHasAuxlModel | ProfileModel): void => {
let offsetCoord = { left: 0, top: 0 };
if (e.profileModel.rotate != 0) {
offsetCoord = this.panelScopeEnchantmentService.handleOuterSphereRotateOffsetCoord(e.profileModel);
}
const config = {
left: pro.left + offsetCoord.left * -1,
top: pro.top + offsetCoord.top * -1,
right: pro.left + pro.width - e.profileModel.width + offsetCoord.left,
bottom: pro.top + pro.height - e.profileModel.height + offsetCoord.top,
center: pro.left + pro.width / 2 - e.profileModel.width / 2,
trancenter: pro.top + pro.height / 2 - e.profileModel.height / 2,
};
if (config[type] != undefined) {
e.profileModel[type == "left" || type == "right" || type == "center" ? "left" : "top"] = config[type];
}
};
const equidistanceFn = (type: "width" | "height") => {
const allWidget = widgetList.map(e => e.profileModel[type]).reduce((a, b) => a + b);
// 计算间隙距离
const spaceBet = (pro[type] - allWidget) / (widgetList.length - 1);
const sortList = widgetList.sort((a, b) => {
return (
a.profileModel[type == "width" ? "left" : "top"] - b.profileModel[type == "width" ? "left" : "top"]
);
});
sortList.forEach((w, i) => {
if (i > 0) {
w.profileModel[type == "width" ? "left" : "top"] =
widgetList[i - 1].profileModel[type == "width" ? "left" : "top"] +
widgetList[i - 1].profileModel[type] +
spaceBet;
}
});
};
if (type != "crosswiseEquidistance" && type != "verticalEquidistance") {
widgetList.forEach(e => {
calcProfile(
e,
widgetList.length > 1
? pro
: <ProfileModel>{
left: 0,
width: panelInfo.width,
top: 0,
height: panelInfo.height,
}
);
});
} else if (type == "crosswiseEquidistance") {
equidistanceFn("width");
} else if (type == "verticalEquidistance") {
equidistanceFn("height");
}
this.scopeEnchantment.outerSphereInsetWidgetList$.next(widgetList);
this.panelScopeEnchantmentService.handleFromWidgetListToProfileOuterSphere({ isLaunch: false });
}
/**
* 只选中一个组件的时候设置对应的conventionSiteModel
*/
public handleSetOnlyWidget(): void {
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value[0];
if (insetWidget.conventionSiteModel instanceof ConventionSiteModel) {
const proValue = insetWidget.profileModel;
insetWidget.conventionSiteModel.setData(cloneDeep(proValue));
this.panelWidgetAppearanceService.conventionSiteModel$.next(insetWidget.conventionSiteModel);
}
}
/**
* 选中多个不同的widget组件时判断筛选相同的conventionSite数据
*/
public handleSetMoreWidget(): void {
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value;
// 如果选了多个组件则设置统一的样式数据
this.panelWidgetAppearanceService.conventionSiteModel$.next(new ConventionSiteModel());
// 同时查询是否所有被选的组件的样式是否有一致的
let firstP = new ProfileModel();
firstP.setData(insetWidget[0].profileModel);
let config: ConventionSiteModel = <ConventionSiteModel>{
rotate: firstP.rotate,
left: firstP.left,
top: firstP.top,
width: firstP.width,
height: firstP.height,
opacity: firstP.opacity,
};
insetWidget.forEach(w => {
["left", "top", "width", "height", "rotate", "opacity"].forEach(c => {
if (w.profileModel[c] != firstP[c]) {
config[c] = null;
}
});
});
this.conventionSite.setData(cloneDeep(config));
}
/**
* 接收输入框值的变化
* 不仅要改变主轮廓的位置变化,也要改变轮廓内被选组件的变化
*/
public acceptAllValueChange(type: string): void {
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value;
if (insetWidget.length == 1) {
this.handleOnlyWidgetStyleContent();
} else {
this.handleMoreWidgetStyleContent(type);
}
}
/**
* 处理只选中一个组件的时候设置主轮廓样式和当前被选的组件样式数据
*/
public handleOnlyWidgetStyleContent(): void {
const siteValue = this.conventionSite.valueKeys;
const pro = this.scopeEnchantment.valueProfileOuterSphere;
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value[0];
const drag = {
left: siteValue.left - pro.left,
top: siteValue.top - pro.top,
};
pro.setMouseCoord([pro.left, pro.top]);
insetWidget.profileModel.setMouseCoord([insetWidget.profileModel.left, insetWidget.profileModel.top]);
this.scopeEnchantment.handleProfileOuterSphereLocationInsetWidget(drag);
this.scopeEnchantment.handleLocationInsetWidget(drag);
pro.setData({
width: siteValue.width,
height: siteValue.height,
rotate: siteValue.rotate,
opacity: siteValue.opacity,
});
// 同时改变被选组件的样式、除了left和top外
insetWidget.profileModel.setData({
width: siteValue.width,
height: siteValue.height,
rotate: siteValue.rotate,
opacity: siteValue.opacity,
});
insetWidget.addStyleToUltimatelyStyle({
width: `${siteValue.width}px`,
height: `${siteValue.height}px`,
opacity: `${siteValue.opacity / 100}`,
});
}
/**
* 处理选中多个组件的时候设置主轮廓的样式以及被选组件的轮廓和样式
*/
public handleMoreWidgetStyleContent(type: string): void {
const value = this.conventionSite.valueKeys;
const insetWidget = this.scopeEnchantment.outerSphereInsetWidgetList$.value;
insetWidget.forEach(e => {
if (e.profileModel[type] != undefined) {
e.profileModel[type] = value[type];
e.addStyleToUltimatelyStyle({
width: `${value.width}px`,
height: `${value.height}px`,
opacity: `${value.opacity / 100}`,
});
}
});
this.panelScopeEnchantmentService.handleFromWidgetListToProfileOuterSphere({ isLaunch: false });
}
/**
* 只要点击外观设置的界面就取消ctr+a的全选快捷键
* 同时设置最高层级
*/
public appearanceDownEvent(): void {
this.panelWidgetAppearanceService.appearanceModel.zIndex =
this.panelWidgetDetailsSiteService.detailsModel.zIndex + 1;
}
/**
* 接收底部拖拽拉伸外观设置的高度,最低不能低于240px
*/
public acceptFooterDraggable(drag: DraggablePort): void {
if (drag) {
this.appearance.height += drag.top;
if (this.appearance.height < 240) {
this.appearance.height = 240;
}
}
}
} | the_stack |
import {Spec, Test, Exam} from "@swim/unit";
import {R2Curve, R2Spline} from "@swim/math";
export class R2SplineParserSpec extends Spec {
@Test
parseAbsoluteDegenerateSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2"), R2Spline.empty());
exam.equal(R2Spline.parse("M 1 -2"), R2Spline.empty());
}
@Test
parseRelativeDegenerateSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2"), R2Spline.empty());
exam.equal(R2Spline.parse("m 1 -2"), R2Spline.empty());
}
@Test
parseAbsoluteMoveSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2,-3,5"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
exam.equal(R2Spline.parse("M 1 -2 -3 5"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
}
@Test
parseExplicitAbsoluteMoveSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2,-3,5,-7,-11"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
exam.equal(R2Spline.parse("M 1,-2 -3,5 -7,-11"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
}
@Test
parseRelativeMoveSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2,-4,7"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
exam.equal(R2Spline.parse("m 1 -2 -4 7"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
}
@Test
parseExplicitRelativeMoveSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2,-4,7,-4,-16"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
exam.equal(R2Spline.parse("m 1,-2 -4,7 -4,-16"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
}
@Test
parseAbsoluteLinearSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2L-3,5"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
exam.equal(R2Spline.parse("M 1 -2 L -3 5"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
}
@Test
parseExplicitAbsoluteLinearSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2L-3,5L-7,-11"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
exam.equal(R2Spline.parse("M 1,-2 L -3,5 L -7,-11"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
}
@Test
parseImplicitAbsoluteLinearSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2L-3,5,-7,-11"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
exam.equal(R2Spline.parse("M 1,-2 L -3,5 -7,-11"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
}
@Test
parseRelativeLinearSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2l-4,7"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
exam.equal(R2Spline.parse("m 1 -2 l -4 7"), R2Spline.open(R2Curve.linear(1, -2, -3, 5)));
}
@Test
parseExplicitRelativeLinearSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2l-4,7l-4,-16"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
exam.equal(R2Spline.parse("m 1,-2 l -4,7 l -4,-16"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
}
@Test
parseImplicitRelativeLinearSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2l-4,7,-4,-16"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
exam.equal(R2Spline.parse("m 1,-2 l -4,7 -4,-16"),
R2Spline.open(R2Curve.linear(1, -2, -3, 5), R2Curve.linear(-3, 5, -7, -11)));
}
@Test
parseAbsoluteHorizontalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2H-3"), R2Spline.open(R2Curve.linear(1, -2, -3, -2)));
exam.equal(R2Spline.parse("M 1 -2 H -3"), R2Spline.open(R2Curve.linear(1, -2, -3, -2)));
}
@Test
parseExplicitAbsoluteHorizontalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2H-3H-7"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
exam.equal(R2Spline.parse("M 1,-2 H -3 H -7"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
}
@Test
parseImplicitAbsoluteHorizontalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2H-3,-7"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
exam.equal(R2Spline.parse("M 1,-2 H -3 -7"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
}
@Test
parseRelativeHorizontalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2h-4"), R2Spline.open(R2Curve.linear(1, -2, -3, -2)));
exam.equal(R2Spline.parse("m 1 -2 h -4"), R2Spline.open(R2Curve.linear(1, -2, -3, -2)));
}
@Test
parseExplicitRelativeHorizontalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2h-4h-4"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
exam.equal(R2Spline.parse("m 1,-2 h -4 h -4"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
}
@Test
parseImplicitRelativeHorizontalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2h-4,-4"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
exam.equal(R2Spline.parse("m 1,-2 h -4 -4"),
R2Spline.open(R2Curve.linear(1, -2, -3, -2), R2Curve.linear(-3, -2, -7, -2)));
}
@Test
parseAbsoluteVerticalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2V5"), R2Spline.open(R2Curve.linear(1, -2, 1, 5)));
exam.equal(R2Spline.parse("M 1 -2 V 5"), R2Spline.open(R2Curve.linear(1, -2, 1, 5)));
}
@Test
parseExplicitAbsoluteVerticalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2V5V-11"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
exam.equal(R2Spline.parse("M 1,-2 V 5 V -11"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
}
@Test
parseImplicitAbsoluteVerticalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2V5,-11"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
exam.equal(R2Spline.parse("M 1,-2 V 5 -11"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
}
@Test
parseRelativeVerticalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2v7"), R2Spline.open(R2Curve.linear(1, -2, 1, 5)));
exam.equal(R2Spline.parse("m 1 -2 v 7"), R2Spline.open(R2Curve.linear(1, -2, 1, 5)));
}
@Test
parseExplicitRelativeVerticalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2v7v-16"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
exam.equal(R2Spline.parse("m 1,-2 v 7 v -16"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
}
@Test
parseImplicitRelativeVerticalSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2v7,-16"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
exam.equal(R2Spline.parse("m 1,-2 v 7 -16"),
R2Spline.open(R2Curve.linear(1, -2, 1, 5), R2Curve.linear(1, 5, 1, -11)));
}
@Test
parseAbsoluteQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2Q-3,5,-7,-11"), R2Spline.open(R2Curve.quadratic(1, -2, -3, 5, -7, -11)));
exam.equal(R2Spline.parse("M 1 -2 Q -3 5 -7 -11"), R2Spline.open(R2Curve.quadratic(1, -2, -3, 5, -7, -11)));
}
@Test
parseExplicitAbsoluteQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0Q-1,1,0,1Q1,1,1,0"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
exam.equal(R2Spline.parse("M -1,0 Q -1,1 0,1 Q 1,1 1,0"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
}
@Test
parseImplicitAbsoluteQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0Q-1,1,0,1,1,1,1,0"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
exam.equal(R2Spline.parse("M -1,0 Q -1,1 0,1 1,1 1,0"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
}
@Test
parseRelativeQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2q-4,7,-8,-9"), R2Spline.open(R2Curve.quadratic(1, -2, -3, 5, -7, -11)));
exam.equal(R2Spline.parse("m 1 -2 q -4 7 -8 -9"), R2Spline.open(R2Curve.quadratic(1, -2, -3, 5, -7, -11)));
}
@Test
parseExplicitRelativeQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0q0,1,1,1q1,0,1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
exam.equal(R2Spline.parse("m -1,0 q 0,1 1,1 q 1,0 1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
}
@Test
parseImplicitRelativeQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0q0,1,1,1,1,0,1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
exam.equal(R2Spline.parse("m -1,0 q 0,1 1,1 1,0 1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
}
@Test
parseAbsoluteSmoothQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2T-3,5"), R2Spline.open(R2Curve.quadratic(1, -2, 1, -2, -3, 5)));
exam.equal(R2Spline.parse("M 1 -2 T -3 5"), R2Spline.open(R2Curve.quadratic(1, -2, 1, -2, -3, 5)));
exam.equal(R2Spline.parse("M-1,0Q-1,1,0,1T1,0"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
exam.equal(R2Spline.parse("M -1,0 Q -1,1 0,1 T 1,0"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
}
@Test
parseExplicitAbsoluteSmoothQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0Q-1,1,0,1T1,0T0,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
exam.equal(R2Spline.parse("M -1,0 Q -1,1 0,1 T 1,0 T 0,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
}
@Test
parseImplicitAbsoluteSmoothQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0Q-1,1,0,1T1,0,0,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
exam.equal(R2Spline.parse("M -1,0 Q -1,1 0,1 T 1,0 0,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
}
@Test
parseRelativeSmoothQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2t-4,7"), R2Spline.open(R2Curve.quadratic(1, -2, 1, -2, -3, 5)));
exam.equal(R2Spline.parse("m 1 -2 t -4 7"), R2Spline.open(R2Curve.quadratic(1, -2, 1, -2, -3, 5)));
exam.equal(R2Spline.parse("m-1,0q0,1,1,1t1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
exam.equal(R2Spline.parse("m -1,0 q 0,1 1,1 t 1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0)));
}
@Test
parseExplicitRelativeSmoothQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0q0,1,1,1t1,-1t-1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
exam.equal(R2Spline.parse("m -1,0 q 0,1 1,1 t 1,-1 t -1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
}
@Test
parseImplicitRelativeSmoothQuadraticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0q0,1,1,1t1,-1,-1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
exam.equal(R2Spline.parse("m -1,0 q 0,1 1,1 t 1,-1 -1,-1"),
R2Spline.open(R2Curve.quadratic(-1, 0, -1, 1, 0, 1), R2Curve.quadratic(0, 1, 1, 1, 1, 0), R2Curve.quadratic(1, 0, 1, -1, 0, -1)));
}
@Test
parseAbsoluteCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2C-3,5,-7,-11,13,17"), R2Spline.open(R2Curve.cubic(1, -2, -3, 5, -7, -11, 13, 17)));
exam.equal(R2Spline.parse("M 1 -2 C -3 5 -7 -11 13 17"), R2Spline.open(R2Curve.cubic(1, -2, -3, 5, -7, -11, 13, 17)));
}
@Test
parseExplicitAbsoluteCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0C-1,0.5,-0.5,1,0,1C0.5,1,1,0.5,1,0"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
exam.equal(R2Spline.parse("M -1,0 C -1,0.5 -0.5,1 0,1 C 0.5,1 1,0.5 1,0"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
}
@Test
parseImplicitAbsoluteCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0C-1,0.5,-0.5,1,0,1,0.5,1,1,0.5,1,0"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
exam.equal(R2Spline.parse("M -1,0 C -1,0.5 -0.5,1 0,1 0.5,1 1,0.5 1,0"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
}
@Test
parseRelativeCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2c-4,7,-8,-9,12,19"), R2Spline.open(R2Curve.cubic(1, -2, -3, 5, -7, -11, 13, 17)));
exam.equal(R2Spline.parse("m 1 -2 c -4 7 -8 -9 12 19"), R2Spline.open(R2Curve.cubic(1, -2, -3, 5, -7, -11, 13, 17)));
}
@Test
parseExplicitRelativeCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0c0,0.5,0.5,1,1,1c0.5,0,1,-0.5,1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
exam.equal(R2Spline.parse("m -1,0 c 0,0.5 0.5,1 1,1 c 0.5,0 1,-0.5 1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
}
@Test
parseImplicitRelativeCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0c0,0.5,0.5,1,1,1,0.5,0,1,-0.5,1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
exam.equal(R2Spline.parse("m -1,0 c 0,0.5 0.5,1 1,1 0.5,0 1,-0.5 1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
}
@Test
parseAbsoluteSmoothCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2S-3,5,-7,-11"), R2Spline.open(R2Curve.cubic(1, -2, 1, -2, -3, 5, -7, -11)));
exam.equal(R2Spline.parse("M 1 -2 S -3 5 -7 -11"), R2Spline.open(R2Curve.cubic(1, -2, 1, -2, -3, 5, -7, -11)));
exam.equal(R2Spline.parse("M-1,0C-1,0.5,-0.5,1,0,1S1,0.5,1,0"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
exam.equal(R2Spline.parse("M -1,0 C -1,0.5 -0.5,1 0,1 S 1,0.5 1,0"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
}
@Test
parseExplicitAbsoluteSmoothCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0C-1,0.5,-0.5,1,0,1S1,0.5,1,0S0.5,-1,0,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
exam.equal(R2Spline.parse("M -1,0 C -1,0.5 -0.5,1 0,1 S 1,0.5 1,0 S 0.5,-1 0,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
}
@Test
parseImplicitAbsoluteSmoothCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0C-1,0.5,-0.5,1,0,1S1,0.5,1,0,0.5,-1,0,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
exam.equal(R2Spline.parse("M -1,0 C -1,0.5 -0.5,1 0,1 S 1,0.5 1,0 0.5,-1 0,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
}
@Test
parseRelativeSmoothCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2s-4,7,-8,-9"), R2Spline.open(R2Curve.cubic(1, -2, 1, -2, -3, 5, -7, -11)));
exam.equal(R2Spline.parse("m 1 -2 s -4 7 -8 -9"), R2Spline.open(R2Curve.cubic(1, -2, 1, -2, -3, 5, -7, -11)));
exam.equal(R2Spline.parse("m-1,0c0,0.5,0.5,1,1,1s1,-0.5,1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
exam.equal(R2Spline.parse("m -1,0 c 0,0.5 0.5,1 1,1 s 1,-0.5 1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0)));
}
@Test
parseExplicitRelativeSmoothCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0c0,0.5,0.5,1,1,1s1,-0.5,1,-1s-0.5,-1,-1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
exam.equal(R2Spline.parse("m -1,0 c 0,0.5 0.5,1 1,1 s 1,-0.5 1,-1 s -0.5,-1 -1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
}
@Test
parseImplicitRelativeSmoothCubicSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0c0,0.5,0.5,1,1,1s1,-0.5,1,-1,-0.5,-1,-1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
exam.equal(R2Spline.parse("m -1,0 c 0,0.5 0.5,1 1,1 s 1,-0.5 1,-1 -0.5,-1 -1,-1"),
R2Spline.open(R2Curve.cubic(-1, 0, -1, 0.5, -0.5, 1, 0, 1), R2Curve.cubic(0, 1, 0.5, 1, 1, 0.5, 1, 0), R2Curve.cubic(1, 0, 1, -0.5, 0.5, -1, 0, -1)));
}
@Test
parseAbsoluteEllipticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M -1,0 A 1,1 0 0,1 0,-1"), R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, Math.PI / 2)));
exam.equal(R2Spline.parse("M -1,0 A 1,1 0 1,0 0,-1"), R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -3 * Math.PI / 2)));
exam.equal(R2Spline.parse("M -1,0 A 1,1 0 0,0 0,-1"), R2Spline.open(R2Curve.elliptic(-1, -1, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
exam.equal(R2Spline.parse("M -1,0 A 1,1 0 1,1 0,-1"), R2Spline.open(R2Curve.elliptic(-1, -1, 1, 1, 0, Math.PI / 2, 3 * Math.PI / 2)));
}
@Test
parseExplicitAbsoluteEllipticSplines(exam: Exam): void {
exam.equivalent(R2Spline.parse("M-1,0A1,1,0,0,0,0,1A1,1,0,0,0,1,0"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
exam.equivalent(R2Spline.parse("M -1,0 A 1,1 0 0,0 0,1 A 1,1 0 0,0 1,0"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
}
@Test
parseImplicitAbsoluteEllipticSplines(exam: Exam): void {
exam.equivalent(R2Spline.parse("M-1,0A1,1,0,0,0,0,1,1,1,0,0,0,1,0"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
exam.equivalent(R2Spline.parse("M -1,0 A 1,1 0 0,0 0,1 1,1 0 0,0 1,0"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
}
@Test
parseRelativeEllipticSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m -1,0 a 1,1 0 0,1 1,-1"), R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, Math.PI / 2)));
exam.equal(R2Spline.parse("m -1,0 a 1,1 0 1,0 1,-1"), R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -3 * Math.PI / 2)));
exam.equal(R2Spline.parse("m -1,0 a 1,1 0 0,0 1,-1"), R2Spline.open(R2Curve.elliptic(-1, -1, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
exam.equal(R2Spline.parse("m -1,0 a 1,1 0 1,1 1,-1"), R2Spline.open(R2Curve.elliptic(-1, -1, 1, 1, 0, Math.PI / 2, 3 * Math.PI / 2)));
}
@Test
parseExplicitRelativeEllipticSplines(exam: Exam): void {
exam.equivalent(R2Spline.parse("m-1,0a1,1,0,0,0,1,1a1,1,0,0,0,1,-1"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
exam.equivalent(R2Spline.parse("m -1,0 a 1,1 0 0,0 1,1 a 1,1 0 0,0 1,-1"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
}
@Test
parseImplicitRelativeEllipticSplines(exam: Exam): void {
exam.equivalent(R2Spline.parse("m-1,0a1,1,0,0,0,1,1,1,1,0,0,0,1,-1"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
exam.equivalent(R2Spline.parse("m -1,0 a 1,1 0 0,0 1,1 1,1 0 0,0 1,-1"),
R2Spline.open(R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI, -Math.PI / 2), R2Curve.elliptic(0, 0, 1, 1, 0, Math.PI / 2, -Math.PI / 2)));
}
@Test
parseAbsoluteDegenerateClosedSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M1,-2Z"), R2Spline.closed(R2Curve.linear(1, -2, 1, -2)));
exam.equal(R2Spline.parse("M 1 -2 Z"), R2Spline.closed(R2Curve.linear(1, -2, 1, -2)));
}
@Test
parseRelativeDegenerateClosedSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m1,-2Z"), R2Spline.closed(R2Curve.linear(1, -2, 1, -2)));
exam.equal(R2Spline.parse("m 1 -2 Z"), R2Spline.closed(R2Curve.linear(1, -2, 1, -2)));
}
@Test
parseAbsoluteClosedSplines(exam: Exam): void {
exam.equal(R2Spline.parse("M-1,0L0,1L1,0Z"),
R2Spline.closed(R2Curve.linear(-1, 0, 0, 1), R2Curve.linear(0, 1, 1, 0), R2Curve.linear(1, 0, -1, 0)));
exam.equal(R2Spline.parse("M -1,0 L 0,1 L 1,0 Z"),
R2Spline.closed(R2Curve.linear(-1, 0, 0, 1), R2Curve.linear(0, 1, 1, 0), R2Curve.linear(1, 0, -1, 0)));
}
@Test
parseRelativeClosedSplines(exam: Exam): void {
exam.equal(R2Spline.parse("m-1,0l1,1l1,-1z"),
R2Spline.closed(R2Curve.linear(-1, 0, 0, 1), R2Curve.linear(0, 1, 1, 0), R2Curve.linear(1, 0, -1, 0)));
exam.equal(R2Spline.parse("m -1,0 l 1,1 l 1,-1 z"),
R2Spline.closed(R2Curve.linear(-1, 0, 0, 1), R2Curve.linear(0, 1, 1, 0), R2Curve.linear(1, 0, -1, 0)));
}
} | the_stack |
const React = require('react');
import EncryptionService from '@joplin/lib/services/e2ee/EncryptionService';
import { themeStyle } from '@joplin/lib/theme';
import { _ } from '@joplin/lib/locale';
import time from '@joplin/lib/time';
import shim from '@joplin/lib/shim';
import dialogs from '../dialogs';
import { decryptedStatText, determineKeyPassword, dontReencryptData, enableEncryptionConfirmationMessages, onSavePasswordClick, onToggleEnabledClick, reencryptData, upgradeMasterKey, useInputPasswords, useNeedMasterPassword, usePasswordChecker, useStats, useToggleShowDisabledMasterKeys } from '@joplin/lib/components/EncryptionConfigScreen/utils';
import { MasterKeyEntity } from '@joplin/lib/services/e2ee/types';
import { getEncryptionEnabled, masterKeyEnabled, SyncInfo } from '@joplin/lib/services/synchronizer/syncInfoUtils';
import { getDefaultMasterKey, getMasterPasswordStatusMessage, masterPasswordIsValid, toggleAndSetupEncryption } from '@joplin/lib/services/e2ee/utils';
import Button, { ButtonLevel } from '../Button/Button';
import { useCallback, useMemo } from 'react';
import { connect } from 'react-redux';
import { AppState } from '../../app.reducer';
import Setting from '@joplin/lib/models/Setting';
import CommandService from '@joplin/lib/services/CommandService';
import { PublicPrivateKeyPair } from '@joplin/lib/services/e2ee/ppk';
interface Props {
themeId: any;
masterKeys: MasterKeyEntity[];
passwords: Record<string, string>;
notLoadedMasterKeys: string[];
encryptionEnabled: boolean;
shouldReencrypt: boolean;
activeMasterKeyId: string;
masterPassword: string;
ppk: PublicPrivateKeyPair;
}
const EncryptionConfigScreen = (props: Props) => {
const { inputPasswords, onInputPasswordChange } = useInputPasswords(props.passwords);
const theme: any = useMemo(() => {
return themeStyle(props.themeId);
}, [props.themeId]);
const stats = useStats();
const { passwordChecks, masterPasswordKeys, masterPasswordStatus } = usePasswordChecker(props.masterKeys, props.activeMasterKeyId, props.masterPassword, props.passwords);
const { showDisabledMasterKeys, toggleShowDisabledMasterKeys } = useToggleShowDisabledMasterKeys();
const needMasterPassword = useNeedMasterPassword(passwordChecks, props.masterKeys);
const onUpgradeMasterKey = useCallback(async (mk: MasterKeyEntity) => {
const password = determineKeyPassword(mk.id, masterPasswordKeys, props.masterPassword, props.passwords);
const result = await upgradeMasterKey(mk, password);
alert(result);
}, [props.passwords, masterPasswordKeys, props.masterPassword]);
const renderNeedUpgradeSection = () => {
if (!shim.isElectron()) return null;
const needUpgradeMasterKeys = EncryptionService.instance().masterKeysThatNeedUpgrading(props.masterKeys);
if (!needUpgradeMasterKeys.length) return null;
const theme = themeStyle(props.themeId);
const rows = [];
for (const mk of needUpgradeMasterKeys) {
rows.push(
<tr key={mk.id}>
<td style={theme.textStyle}>{mk.id}</td>
<td><button onClick={() => onUpgradeMasterKey(mk)} style={theme.buttonStyle}>Upgrade</button></td>
</tr>
);
}
return (
<div>
<h2>{_('Keys that need upgrading')}</h2>
<p>{_('The following keys use an out-dated encryption algorithm and it is recommended to upgrade them. The upgraded key will still be able to decrypt and encrypt your data as usual.')}</p>
<table>
<tbody>
<tr>
<th style={theme.textStyle}>{_('ID')}</th>
<th style={theme.textStyle}>{_('Upgrade')}</th>
</tr>
{rows}
</tbody>
</table>
</div>
);
};
const renderReencryptData = () => {
if (!shim.isElectron()) return null;
if (!props.shouldReencrypt) return null;
const theme = themeStyle(props.themeId);
const buttonLabel = _('Re-encrypt data');
const intro = props.shouldReencrypt ? _('The default encryption method has been changed to a more secure one and it is recommended that you apply it to your data.') : _('You may use the tool below to re-encrypt your data, for example if you know that some of your notes are encrypted with an obsolete encryption method.');
let t = `${intro}\n\n${_('In order to do so, your entire data set will have to be encrypted and synchronised, so it is best to run it overnight.\n\nTo start, please follow these instructions:\n\n1. Synchronise all your devices.\n2. Click "%s".\n3. Let it run to completion. While it runs, avoid changing any note on your other devices, to avoid conflicts.\n4. Once sync is done on this device, sync all your other devices and let it run to completion.\n\nImportant: you only need to run this ONCE on one device.', buttonLabel)}`;
t = t.replace(/\n\n/g, '</p><p>');
t = t.replace(/\n/g, '<br>');
t = `<p>${t}</p>`;
return (
<div>
<h2>{_('Re-encryption')}</h2>
<p style={theme.textStyle} dangerouslySetInnerHTML={{ __html: t }}></p>
<span style={{ marginRight: 10 }}>
<button onClick={() => void reencryptData()} style={theme.buttonStyle}>{buttonLabel}</button>
</span>
{ !props.shouldReencrypt ? null : <button onClick={() => dontReencryptData()} style={theme.buttonStyle}>{_('Ignore')}</button> }
</div>
);
};
const renderMasterKey = (mk: MasterKeyEntity) => {
const theme = themeStyle(props.themeId);
const passwordStyle = {
color: theme.color,
backgroundColor: theme.backgroundColor,
border: '1px solid',
borderColor: theme.dividerColor,
};
const password = inputPasswords[mk.id] ? inputPasswords[mk.id] : '';
const isActive = props.activeMasterKeyId === mk.id;
const activeIcon = isActive ? '✔' : '';
const passwordOk = passwordChecks[mk.id] === true ? '✔' : '❌';
const renderPasswordInput = (masterKeyId: string) => {
if (masterPasswordKeys[masterKeyId] || !passwordChecks['master']) {
return (
<td style={{ ...theme.textStyle, color: theme.colorFaded, fontStyle: 'italic' }}>
({_('Master password')})
</td>
);
} else {
return (
<td style={theme.textStyle}>
<input type="password" style={passwordStyle} value={password} onChange={event => onInputPasswordChange(mk, event.target.value)} />{' '}
<button style={theme.buttonStyle} onClick={() => onSavePasswordClick(mk, props.passwords)}>
{_('Save')}
</button>
</td>
);
}
};
return (
<tr key={mk.id}>
<td style={theme.textStyle}>{activeIcon}</td>
<td style={theme.textStyle}>{mk.id}<br/>{_('Source: ')}{mk.source_application}</td>
<td style={theme.textStyle}>{_('Created: ')}{time.formatMsToLocal(mk.created_time)}<br/>{_('Updated: ')}{time.formatMsToLocal(mk.updated_time)}</td>
{renderPasswordInput(mk.id)}
<td style={theme.textStyle}>{passwordOk}</td>
<td style={theme.textStyle}>
<button style={theme.buttonStyle} onClick={() => onToggleEnabledClick(mk)}>{masterKeyEnabled(mk) ? _('Disable') : _('Enable')}</button>
</td>
</tr>
);
};
const renderMasterKeySection = (masterKeys: MasterKeyEntity[], isEnabledMasterKeys: boolean) => {
const theme = themeStyle(props.themeId);
const mkComps = [];
const showTable = isEnabledMasterKeys || showDisabledMasterKeys;
for (let i = 0; i < masterKeys.length; i++) {
const mk = masterKeys[i];
mkComps.push(renderMasterKey(mk));
}
const headerComp = isEnabledMasterKeys ? <h2>{_('Encryption keys')}</h2> : <a onClick={() => toggleShowDisabledMasterKeys() } style={{ ...theme.urlStyle, display: 'inline-block', marginBottom: 10 }} href="#">{showTable ? _('Hide disabled keys') : _('Show disabled keys')}</a>;
const infoComp: any = null; // isEnabledMasterKeys ? <p>{'Note: Only one key is going to be used for encryption (the one marked as "active"). Any of the keys might be used for decryption, depending on how the notes or notebooks were originally encrypted.'}</p> : null;
const tableComp = !showTable ? null : (
<table>
<tbody>
<tr>
<th style={theme.textStyle}>{_('Active')}</th>
<th style={theme.textStyle}>{_('ID')}</th>
<th style={theme.textStyle}>{_('Date')}</th>
<th style={theme.textStyle}>{_('Password')}</th>
<th style={theme.textStyle}>{_('Valid')}</th>
<th style={theme.textStyle}>{_('Actions')}</th>
</tr>
{mkComps}
</tbody>
</table>
);
if (mkComps.length) {
return (
<div className="section">
{headerComp}
{tableComp}
{infoComp}
</div>
);
}
return null;
};
const onToggleButtonClick = useCallback(async () => {
const isEnabled = getEncryptionEnabled();
const newEnabled = !isEnabled;
const masterKey = getDefaultMasterKey();
const hasMasterPassword = !!props.masterPassword;
let newPassword = '';
if (isEnabled) {
const answer = await dialogs.confirm(_('Disabling encryption means *all* your notes and attachments are going to be re-synchronised and sent unencrypted to the sync target. Do you wish to continue?'));
if (!answer) return;
} else {
const msg = enableEncryptionConfirmationMessages(masterKey, hasMasterPassword);
newPassword = await dialogs.prompt(msg.join('\n\n'), '', '', { type: 'password' });
}
if (hasMasterPassword && newEnabled) {
if (!(await masterPasswordIsValid(newPassword))) {
alert('Invalid password. Please try again. If you have forgotten your password you will need to reset it.');
return;
}
}
try {
await toggleAndSetupEncryption(EncryptionService.instance(), newEnabled, masterKey, newPassword);
} catch (error) {
await dialogs.alert(error.message);
}
}, [props.masterPassword]);
const renderEncryptionSection = () => {
const decryptedItemsInfo = <p>{decryptedStatText(stats)}</p>;
const toggleButton = (
<Button
onClick={onToggleButtonClick}
title={props.encryptionEnabled ? _('Disable encryption') : _('Enable encryption')}
level={ButtonLevel.Secondary}
/>
);
const needUpgradeSection = renderNeedUpgradeSection();
const reencryptDataSection = renderReencryptData();
return (
<div className="section">
<div className="encryption-section">
<h2 className="-no-top-margin">{_('End-to-end encryption')}</h2>
<p>
{_('Encryption:')} <strong>{props.encryptionEnabled ? _('Enabled') : _('Disabled')}</strong>
</p>
<p>
{_('Public-private key pair:')} <strong>{props.ppk ? _('Generated') : _('Not generated')}</strong>
</p>
{decryptedItemsInfo}
{toggleButton}
{needUpgradeSection}
{props.shouldReencrypt ? reencryptDataSection : null}
</div>
</div>
);
};
const renderMasterPasswordSection = () => {
const onManageMasterPassword = async () => {
void CommandService.instance().execute('openMasterPasswordDialog');
};
const buttonTitle = CommandService.instance().label('openMasterPasswordDialog');
const needPasswordMessage = !needMasterPassword ? null : (
<p className="needpassword">{_('Your master password is needed to decrypt some of your data.')}<br/>{_('Please click on "%s" to proceed', buttonTitle)}</p>
);
return (
<div className="section">
<div className="manage-password-section">
<h2>{_('Master password')}</h2>
<p className="status"><span>{_('Master password:')}</span> <span className="bold">{getMasterPasswordStatusMessage(masterPasswordStatus)}</span></p>
{needPasswordMessage}
<Button className="managebutton" level={needMasterPassword ? ButtonLevel.Primary : ButtonLevel.Secondary} onClick={onManageMasterPassword} title={buttonTitle} />
</div>
</div>
);
};
const onClearMasterPassword = useCallback(() => {
Setting.setValue('encryption.masterPassword', '');
}, []);
const renderDebugSection = () => {
if (Setting.value('env') !== 'dev') return null;
return (
<div style={{ paddingBottom: '20px' }}>
<Button level={ButtonLevel.Secondary} onClick={onClearMasterPassword} title="Clear master password" />
</div>
);
};
const renderNonExistingMasterKeysSection = () => {
let nonExistingMasterKeySection = null;
const nonExistingMasterKeyIds = props.notLoadedMasterKeys.slice();
for (let i = 0; i < props.masterKeys.length; i++) {
const mk = props.masterKeys[i];
const idx = nonExistingMasterKeyIds.indexOf(mk.id);
if (idx >= 0) nonExistingMasterKeyIds.splice(idx, 1);
}
if (nonExistingMasterKeyIds.length) {
const rows = [];
for (let i = 0; i < nonExistingMasterKeyIds.length; i++) {
const id = nonExistingMasterKeyIds[i];
rows.push(
<tr key={id}>
<td style={theme.textStyle}>{id}</td>
</tr>
);
}
nonExistingMasterKeySection = (
<div className="section">
<h2>{_('Missing keys')}</h2>
<p>{_('The keys with these IDs are used to encrypt some of your items, however the application does not currently have access to them. It is likely they will eventually be downloaded via synchronisation.')}</p>
<table>
<tbody>
<tr>
<th style={theme.textStyle}>{_('ID')}</th>
</tr>
{rows}
</tbody>
</table>
</div>
);
}
return nonExistingMasterKeySection;
};
return (
<div className="config-screen-content">
{renderDebugSection()}
{renderEncryptionSection()}
{renderMasterPasswordSection()}
{renderMasterKeySection(props.masterKeys.filter(mk => masterKeyEnabled(mk)), true)}
{renderMasterKeySection(props.masterKeys.filter(mk => !masterKeyEnabled(mk)), false)}
{renderNonExistingMasterKeysSection()}
</div>
);
};
const mapStateToProps = (state: AppState) => {
const syncInfo = new SyncInfo(state.settings['syncInfoCache']);
return {
themeId: state.settings.theme,
masterKeys: syncInfo.masterKeys,
passwords: state.settings['encryption.passwordCache'],
encryptionEnabled: syncInfo.e2ee,
activeMasterKeyId: syncInfo.activeMasterKeyId,
shouldReencrypt: state.settings['encryption.shouldReencrypt'] >= Setting.SHOULD_REENCRYPT_YES,
notLoadedMasterKeys: state.notLoadedMasterKeys,
masterPassword: state.settings['encryption.masterPassword'],
ppk: syncInfo.ppk,
};
};
export default connect(mapStateToProps)(EncryptionConfigScreen); | the_stack |
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { Component, ViewChild } from '@angular/core';
import { IgComboComponent } from '../igniteui-angular-wrappers.module';
import { Northwind } from 'src/app/shared/northwind';
import { FormsModule } from '@angular/forms';
describe('Infragistics Angular Combo', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [IgComboComponent,
TestComponent,
TestComponentNoNgModelComponent,
TestComponentMultipleSelectionComponent,
TestComponentAllowCustomValueComponent,
TestComponentEmptyDataComponent,
TestComponentRemoteDataComponent
]
})
.compileComponents();
}));
describe('With ngModel', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should initialize correctly', () => {
expect(component).toBeTruthy();
expect(fixture.debugElement.componentInstance.viewChild instanceof IgComboComponent)
.toBe(true);
});
it('should be updated correctly if the ngModel value is updated', (done) => {
fixture.detectChanges();
fixture.componentInstance.combo.value1 = 1;
fixture.detectChanges();
setTimeout(() => {
expect($('#combo1').igCombo('value')).toBe(1);
expect($('#combo1').igCombo('text')).toBe('Chai');
done();
}, 10);
});
it('should be updated correctly if the ngModel value is cleared.', (done) => {
fixture.detectChanges();
fixture.componentInstance.combo.value1 = 1;
fixture.detectChanges();
setTimeout(() => {
// clear
$('#combo1').parents('ig-combo').find('.ui-igcombo-clearicon').trigger('click');
fixture.detectChanges();
setTimeout(() => {
expect(fixture.componentInstance.combo.value1).toBeNull();
done();
}, 10);
}, 10);
});
it('the ngModel should be updated correctly if the combo selection is updated', (done) => {
fixture.detectChanges();
const elem = $('#combo1').igCombo('itemsFromIndex', 0)['element'];
$('#combo1').igCombo('select', elem, {}, true);
fixture.detectChanges();
setTimeout(() => {
expect(fixture.componentInstance.combo.value1).toEqual(1);
done();
}, 10);
});
it('should reflect changes when a record in the data changes', (done) => {
fixture.detectChanges();
fixture.componentInstance.northwind[19].ProductName = 'Test';
setTimeout(() => {
fixture.detectChanges();
const elem = $('#combo1').igCombo('itemsFromIndex', 19)['element'];
expect(elem.text()).toBe('Test');
expect($('#combo1').igCombo('text')).toBe('Test');
done();
}, 10);
});
});
describe('Without ngModel', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponentNoNgModelComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should initialize ig-combo', () => {
fixture.detectChanges();
expect(fixture.debugElement.componentInstance.viewChild instanceof IgComboComponent)
.toBe(true);
});
it('should select correctly without ngModel', () => {
fixture.detectChanges();
const elem = $('#combo1').igCombo('itemsFromIndex', 0)['element'];
const select = () => {
$('#combo1').igCombo('select', elem, {}, true);
};
// #244 fails with 'Cannot read property 'viewToModelUpdate' of undefined'
expect(select).not.toThrow();
expect(fixture.componentInstance.viewChild.value()).toEqual(1);
});
});
describe('With multiple selection', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponentMultipleSelectionComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be updated correctly if the ngModel value is cleared when multiple selection.', (done) => {
fixture.detectChanges();
fixture.componentInstance.combo.value1 = 1;
fixture.detectChanges();
setTimeout(() => {
// clear
$('#combo1').parents('ig-combo').find('.ui-igcombo-clearicon').trigger('click');
fixture.detectChanges();
setTimeout(() => {
expect(fixture.componentInstance.combo.value1 instanceof Array &&
fixture.componentInstance.combo.value1.length === 0).toBeTruthy();
done();
}, 10);
}, 10);
});
it('should apply ngModel when multiple selection and no valueKey set.', () => {
fixture.componentInstance.viewChild.options = {
multiSelection: { enabled: true, showCheckboxes: true }
};
fixture.componentInstance.viewChild.dataSource = ['foo', 'bar', 'bas'];
fixture.detectChanges();
const elem = $('#combo1').igCombo('itemsFromIndex', 0)['element'];
$('#combo1').igCombo('select', elem, {}, true);
fixture.detectChanges();
expect(fixture.componentInstance.combo.value1.length).toBe(1);
expect(fixture.componentInstance.combo.value1[0]).toBe('foo');
});
it('the ngModel should be updated correctly if the combo selection is updated and multiple items are selected', (done) => {
fixture.detectChanges();
const $firstThreeItems = $('.ui-igcombo-listitem:lt(3)');
$('#combo1').igCombo('select', $firstThreeItems, {}, true);
fixture.detectChanges();
setTimeout(() => {
expect(fixture.componentInstance.combo.value1).toEqual([1, 2, 3]);
done();
}, 10);
});
});
describe('With allowed custom values', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponentAllowCustomValueComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('the ngModel should be updated correctly if the combo is allowing custom values', (done) => {
fixture.detectChanges();
setTimeout(() => {
// var elem = $("#combo1").igCombo("itemsFromIndex", 0)["element"];
// $("#combo1").igCombo("select", elem, {}, true);
$(fixture.debugElement.nativeElement).find('#combo1').val('foo').trigger('input');
fixture.detectChanges();
setTimeout(() => {
expect(fixture.componentInstance.combo.value1).toEqual('foo');
// clear
$('#combo1').parents('ig-combo').find('.ui-igcombo-clearicon').trigger('click');
fixture.detectChanges();
setTimeout(() => {
expect(fixture.componentInstance.combo.value1).toBeNull();
done();
}, 10);
}, 10);
}, 100);
});
});
describe('With empty data', () => {
beforeEach(() => {
fixture = TestBed.createComponent(TestComponentEmptyDataComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should apply the model if there is a new data assigned', (done) => {
fixture.detectChanges();
fixture.componentInstance.data = fixture.componentInstance.northwind;
setTimeout(() => {
fixture.detectChanges();
expect($('#combo1').igCombo('value')).toBe(fixture.componentInstance.combo.value1);
expect($('#combo1').val())
.toBe(fixture.componentInstance.northwind[fixture.componentInstance.combo.value1 - 1].ProductName);
done();
}, 10);
});
});
describe('With remote data', () => {
beforeEach(() => {
$['mockjax']({
url: 'myURL/Northwind',
contentType: 'application/json',
dataType: 'json',
responseText: '[{"ProductID": 1, "ProductName": "Chai"}]'
});
fixture = TestBed.createComponent(TestComponentRemoteDataComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should initialize correctly when datasource is remote', (done) => {
fixture.detectChanges();
expect(fixture.debugElement.componentInstance.viewChild instanceof IgComboComponent)
.toBe(true);
done();
});
});
});
@Component({
selector: 'test-cmp',
template: `<div>
<ig-combo [(widgetId)]="comboID" [(options)]="options" [(ngModel)]="combo.value1" [dataSource]="northwind"></ig-combo>
</div>`
})
class TestComponent {
public options: IgCombo;
public options2: IgCombo;
public optionsMultipleSelection: IgCombo;
public northwind: any;
public combo: any;
private comboID: string;
public data: Array<any> = [];
public val = [];
@ViewChild(IgComboComponent, { static: true })
public viewChild: IgComboComponent;
constructor() {
this.northwind = Northwind.getData();
this.comboID = 'combo1';
this.options = {
valueKey: 'ProductID',
textKey: 'ProductName',
// dataSource: this.northwind,
width: '100%'
};
this.options2 = {
valueKey: 'ProductID',
textKey: 'ProductName',
dataSource: 'myURL/Northwind',
width: '100%'
};
this.optionsMultipleSelection = $.extend({
multiSelection: {
enabled: true,
addWithKeyModifier: false,
showCheckboxes: true,
itemSeparator: ', '
}
}, this.options);
this.combo = {
value1: 20
};
}
}
@Component({
selector: 'test-cmp',
template: '<div><ig-combo [(widgetId)]="comboID" [(options)]="options" [(dataSource)]="northwind"></ig-combo></div>'
})
class TestComponentNoNgModelComponent extends TestComponent { }
@Component({
selector: 'test-cmp',
template: '<div><ig-combo [(widgetId)]="comboID" [(options)]="optionsMultipleSelection" [(ngModel)]="combo.value1" [(dataSource)]="northwind"></ig-combo></div>'
})
class TestComponentMultipleSelectionComponent extends TestComponent { }
@Component({
selector: 'test-cmp',
template: `<div>
<ig-combo [(widgetId)]="comboID"
[(options)]="options"
[(ngModel)]="combo.value1"
[dataSource]="northwind"
[allowCustomValue]="true"></ig-combo>
</div>`
})
class TestComponentAllowCustomValueComponent extends TestComponent { }
@Component({
selector: 'test-cmp',
template: `<div>
<ig-combo [(widgetId)]="comboID"
[valueKey]="\'ProductID\'"
[textKey]="\'ProductName\'"
[dataSource]="data"
[(ngModel)]="combo.value1"></ig-combo>
</div>`
})
class TestComponentEmptyDataComponent extends TestComponent { }
@Component({
selector: 'test-cmp',
template: '<div><ig-combo [(widgetId)]="comboID" [(options)]="options2" [(ngModel)]="combo.value1"></ig-combo></div>'
})
class TestComponentRemoteDataComponent extends TestComponent { } | the_stack |
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { FilteringLogic, IFilteringExpression } from '../../data-operations/filtering-expression.interface';
import { IgxGridComponent } from './grid.component';
import { IgxGridModule } from './public_api';
import { configureTestSuite } from '../../test-utils/configure-suite';
import { IgxChipComponent } from '../../chips/public_api';
import {
IgxStringFilteringOperand,
IgxNumberFilteringOperand,
IgxBooleanFilteringOperand,
IgxDateFilteringOperand,
IgxTimeFilteringOperand,
IgxDateTimeFilteringOperand
} from '../../data-operations/filtering-condition';
import { FilteringExpressionsTree } from '../../data-operations/filtering-expressions-tree';
import { SampleTestData } from '../../test-utils/sample-test-data.spec';
import { GridFunctions, GridSummaryFunctions } from '../../test-utils/grid-functions.spec';
import { IgxGridFilteringComponent, CustomFilter, IgxGridFilteringBindingComponent } from '../../test-utils/grid-samples.spec';
import { ExpressionUI } from '../filtering/grid-filtering.service';
import { NoopFilteringStrategy } from '../../data-operations/filtering-strategy';
describe('IgxGrid - Filtering actions #grid', () => {
configureTestSuite((() => {
TestBed.configureTestingModule({
declarations: [
IgxGridFilteringComponent
],
imports: [
NoopAnimationsModule,
IgxGridModule]
});
}));
let fix; let grid;
beforeEach(fakeAsync(() => {
fix = TestBed.createComponent(IgxGridFilteringComponent);
fix.detectChanges();
grid = fix.componentInstance.grid;
}));
it('should correctly filter by \'string\' filtering conditions', fakeAsync(() => {
// Contains filter
grid.filter('ProductName', 'Ignite', IgxStringFilteringOperand.instance().condition('contains'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
expect(grid.getCellByColumn(0, 'ID').value).toEqual(1);
expect(grid.getCellByColumn(1, 'ID').value).toEqual(3);
// Clear filtering
grid.clearFilter('ProductName');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
// StartsWith filter
grid.filter('ProductName', 'Net', IgxStringFilteringOperand.instance().condition('startsWith'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
expect(grid.getCellByColumn(0, 'ID').value).toEqual(2);
// EndsWith filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', 'Script', IgxStringFilteringOperand.instance().condition('endsWith'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// DoesNotContain filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', 'Ignite', IgxStringFilteringOperand.instance().condition('doesNotContain'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(6);
// Equals filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', 'NetAdvantage', IgxStringFilteringOperand.instance().condition('equals'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// DoesNotEqual filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', 'NetAdvantage', IgxStringFilteringOperand.instance().condition('doesNotEqual'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Null filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', null, IgxStringFilteringOperand.instance().condition('null'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
// NotNull filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', null, IgxStringFilteringOperand.instance().condition('notNull'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(5);
// Empty filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', null, IgxStringFilteringOperand.instance().condition('empty'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// NotEmpty filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', null, IgxStringFilteringOperand.instance().condition('notEmpty'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// Ignorecase filter 'false'
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('ProductName', 'Ignite UI for Angular', IgxStringFilteringOperand.instance().condition('equals'), false);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Custom Filter
grid.clearFilter('ProductName');
fix.detectChanges();
grid.filter('AnotherField', '', CustomFilter.instance().condition('custom'), false);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
}));
it('should correctly filter by \'number\' filtering conditions', fakeAsync(() => {
// DoesNotEqual filter
grid.filter('Downloads', 254, IgxNumberFilteringOperand.instance().condition('doesNotEqual'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Equal filter
grid.clearFilter('Downloads');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('Downloads', 127, IgxNumberFilteringOperand.instance().condition('equals'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// GreaterThan filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', 100, IgxNumberFilteringOperand.instance().condition('greaterThan'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// LessThan filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', 100, IgxNumberFilteringOperand.instance().condition('lessThan'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
// GreaterThanOrEqualTo filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', 100, IgxNumberFilteringOperand.instance().condition('greaterThanOrEqualTo'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(5);
// LessThanOrEqualTo filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', 20, IgxNumberFilteringOperand.instance().condition('lessThanOrEqualTo'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
// Null filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', null, IgxNumberFilteringOperand.instance().condition('null'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// NotNull filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', null, IgxNumberFilteringOperand.instance().condition('notNull'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Empty filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', null, IgxNumberFilteringOperand.instance().condition('empty'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// NotEmpty filter
grid.clearFilter('Downloads');
fix.detectChanges();
grid.filter('Downloads', null, IgxNumberFilteringOperand.instance().condition('notEmpty'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
}));
it('should correctly filter by \'boolean\' filtering conditions', fakeAsync(() => {
// Empty filter
grid.filter('Released', null, IgxBooleanFilteringOperand.instance().condition('empty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
// False filter
grid.clearFilter('Released');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('Released', null, IgxBooleanFilteringOperand.instance().condition('false'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// True filter
grid.clearFilter('Released');
fix.detectChanges();
grid.filter('Released', null, IgxBooleanFilteringOperand.instance().condition('true'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
// NotEmpty filter
grid.clearFilter('Released');
fix.detectChanges();
grid.filter('Released', null, IgxBooleanFilteringOperand.instance().condition('notEmpty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(5);
// NotNull filter
grid.clearFilter('Released');
fix.detectChanges();
grid.filter('Released', null, IgxBooleanFilteringOperand.instance().condition('notNull'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(6);
// Null filter
grid.clearFilter('Released');
fix.detectChanges();
grid.filter('Released', null, IgxBooleanFilteringOperand.instance().condition('null'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
}));
it('should correctly filter by \'date\' filtering conditions', fakeAsync(() => {
const cal = SampleTestData.timeGenerator;
const today = SampleTestData.today;
// Fill expected results based on the current date
const expectedResults = GridFunctions.createDateFilterConditions(grid, today);
// After filter
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 4),
IgxDateFilteringOperand.instance().condition('after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// Before filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 4),
IgxDateFilteringOperand.instance().condition('before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// DoesNotEqual filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 15),
IgxDateFilteringOperand.instance().condition('doesNotEqual'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Equals filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 15),
IgxDateFilteringOperand.instance().condition('equals'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// LastMonth filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('lastMonth'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[0]);
// NextMonth filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('nextMonth'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[1]);
// ThisYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('thisYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[2]);
// LastYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('lastYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[4]);
// NextYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('nextYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[3]);
// Null filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('null'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// NotNull filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('notNull'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Empty filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('empty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// NotEmpty filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('notEmpty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(6);
// Today filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('today'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Yesterday filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('yesterday'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
}));
it('should correctly filter by \'time\' filtering conditions', fakeAsync(() => {
const cal = SampleTestData.timeGenerator;
const today = SampleTestData.todayFullDate;
// At, Not At, Before, After, At or Before
// At or After, Empty, Not Empty, Null, Not Null
// At 11:15:35
grid.filter('ReleaseTime', cal.timedelta(today, 'hour', 1),
IgxTimeFilteringOperand.instance().condition('at'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Not At 09:15:35
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', cal.timedelta(today, 'hour', -1),
IgxTimeFilteringOperand.instance().condition('not_at'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Before 10:25:35
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', cal.timedelta(today, 'minute', +10),
IgxTimeFilteringOperand.instance().condition('before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// After 10:15:55
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', cal.timedelta(today, 'second', +20),
IgxTimeFilteringOperand.instance().condition('after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// At or Before 10:25:35
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', cal.timedelta(today, 'minute', +10),
IgxTimeFilteringOperand.instance().condition('at_before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(5);
// At or After 10:15:55
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', cal.timedelta(today, 'second', +20),
IgxTimeFilteringOperand.instance().condition('at_after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
// Empty filter
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', null, IgxTimeFilteringOperand.instance().condition('empty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// NotEmpty filter
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', null, IgxTimeFilteringOperand.instance().condition('notEmpty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(6);
// Null filter
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', null, IgxTimeFilteringOperand.instance().condition('null'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// NotNull filter
grid.clearFilter('ReleaseTime');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseTime', null, IgxTimeFilteringOperand.instance().condition('notNull'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
}));
it('should correctly filter by \'dateTime\' filtering conditions', fakeAsync(() => {
const cal = SampleTestData.timeGenerator;
const today = SampleTestData.todayFullDate;
// Equals 11:15:35
grid.filter('ReleaseDate', cal.timedelta(today, 'hour', 1),
IgxDateTimeFilteringOperand.instance().condition('equals'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Does not equal 11:15:35
grid.filter('ReleaseDate', cal.timedelta(today, 'hour', 1),
IgxDateTimeFilteringOperand.instance().condition('doesNotEqual'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
}));
it('should correctly filter with earliest/latest \'date\' values', fakeAsync(() => {
const earliest = new Date(SampleTestData.timeGenerator.timedelta(SampleTestData.today, 'month', -1).getTime() + 7200 * 1000);
const latest = new Date(SampleTestData.timeGenerator.timedelta(SampleTestData.today, 'month', 1).getTime() - 7200 * 1000);
// Before filter
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseDate', earliest, IgxDateFilteringOperand.instance().condition('before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// After filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', earliest, IgxDateFilteringOperand.instance().condition('after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(5);
// DoesNotEqual filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', earliest, IgxDateFilteringOperand.instance().condition('doesNotEqual'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Equals filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', earliest, IgxDateFilteringOperand.instance().condition('equals'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Before filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', latest, IgxDateFilteringOperand.instance().condition('before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(5);
// After filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', latest, IgxDateFilteringOperand.instance().condition('after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
}));
it('should correctly filter by \'date\' filtering conditions when dates are ISO 8601 strings', fakeAsync(() => {
const cal = SampleTestData.timeGenerator;
const today = SampleTestData.today;
grid.data = grid.data.map(rec => {
const newRec = Object.assign({}, rec) as any;
newRec.ReleaseDate = rec.ReleaseDate ? rec.ReleaseDate.toISOString() : rec.ReleaseDate;
return newRec;
});
// Fill expected results based on the current date
const expectedResults = GridFunctions.createDateFilterConditions(grid, today);
// After filter
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 4),
IgxDateFilteringOperand.instance().condition('after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// Before filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 4),
IgxDateFilteringOperand.instance().condition('before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// DoesNotEqual filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 15),
IgxDateFilteringOperand.instance().condition('doesNotEqual'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Equals filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 15),
IgxDateFilteringOperand.instance().condition('equals'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// LastMonth filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('lastMonth'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[0]);
// NextMonth filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('nextMonth'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[1]);
// ThisYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('thisYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[2]);
// LastYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('lastYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[4]);
// NextYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('nextYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[3]);
// Null filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('null'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// NotNull filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('notNull'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Empty filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('empty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// NotEmpty filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('notEmpty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(6);
// Today filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('today'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Yesterday filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('yesterday'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
}));
it('should correctly filter by \'date\' filtering conditions when dates are miliseconds numbers', fakeAsync(() => {
const cal = SampleTestData.timeGenerator;
const today = SampleTestData.today;
grid.data = grid.data.map(rec => {
const newRec = Object.assign({}, rec) as any;
newRec.ReleaseDate = rec.ReleaseDate ? rec.ReleaseDate.getTime() : rec.ReleaseDate;
return newRec;
});
// Fill expected results based on the current date
const expectedResults = GridFunctions.createDateFilterConditions(grid, today);
// After filter
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 4),
IgxDateFilteringOperand.instance().condition('after'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// Before filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 4),
IgxDateFilteringOperand.instance().condition('before'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
// DoesNotEqual filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 15),
IgxDateFilteringOperand.instance().condition('doesNotEqual'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Equals filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', cal.timedelta(today, 'day', 15),
IgxDateFilteringOperand.instance().condition('equals'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// LastMonth filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('lastMonth'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[0]);
// NextMonth filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('nextMonth'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[1]);
// ThisYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('thisYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[2]);
// LastYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('lastYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[4]);
// NextYear filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('nextYear'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(expectedResults[3]);
// Null filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('null'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// NotNull filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('notNull'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(7);
// Empty filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('empty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
// NotEmpty filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('notEmpty'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(6);
// Today filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('today'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Yesterday filter
grid.clearFilter('ReleaseDate');
fix.detectChanges();
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('yesterday'));
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
}));
it('should exclude null and undefined values when filter by \'false\'', fakeAsync(() => {
expect(grid.rowList.length).toEqual(8);
grid.filter('Released', false, IgxStringFilteringOperand.instance().condition('equals'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
expect(grid.getCellByColumn(0, 'Released').value).toBe(false);
expect(grid.getCellByColumn(1, 'Released').value).toBe(false);
}));
it('should correctly apply multiple filtering through API', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
const gridExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And);
gridExpressionsTree.filteringOperands = [
{ fieldName: 'Downloads', searchVal: 20, condition: IgxNumberFilteringOperand.instance().condition('greaterThanOrEqualTo') },
{ fieldName: 'ID', searchVal: 4, condition: IgxNumberFilteringOperand.instance().condition('greaterThan') }
];
grid.filteringExpressionsTree = gridExpressionsTree;
tick(30);
fix.detectChanges();
expect(grid.filtering.emit).toHaveBeenCalledTimes(0);
expect(grid.filteringDone.emit).toHaveBeenCalledTimes(0);
expect(grid.rowList.length).toEqual(3);
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(2);
let expression = grid.filteringExpressionsTree.filteringOperands[0] as IFilteringExpression;
expect(expression).toBeDefined();
expression = grid.filteringExpressionsTree.filteringOperands[1] as IFilteringExpression;
expect(expression).toBeDefined();
grid.clearFilter();
tick(30);
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(0);
}));
it('should correctly apply global filtering', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
grid.filteringLogic = FilteringLogic.Or;
grid.filterGlobal('some', IgxStringFilteringOperand.instance().condition('contains'));
tick(30);
fix.detectChanges();
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(grid.columns.length);
expect(grid.rowList.length).toEqual(1);
const filteringExpressions = grid.filteringExpressionsTree;
const args = { owner: grid, cancel: false, filteringExpressions };
expect(grid.filtering.emit).toHaveBeenCalledWith(args);
expect(grid.filteringDone.emit).toHaveBeenCalledWith(filteringExpressions);
}));
it('Should render chip when filtering using the API.', fakeAsync(() => {
const firstHeaderCell = fix.debugElement.query(By.css('.header-release-date'));
let filteringChips = firstHeaderCell.parent.queryAll(By.directive(IgxChipComponent));
expect(filteringChips.length).toEqual(1);
let chipContent = filteringChips[0].query(By.css('.igx-chip__content')).nativeElement.innerText;
expect(chipContent).toEqual('Filter');
grid.filter('ReleaseDate', null, IgxDateFilteringOperand.instance().condition('today'));
fix.detectChanges();
filteringChips = firstHeaderCell.parent.queryAll(By.directive(IgxChipComponent));
expect(filteringChips.length).toEqual(1);
chipContent = filteringChips[0].query(By.css('.igx-chip__content')).nativeElement.innerText;
expect(chipContent).not.toEqual('Filter');
grid.clearFilter('ReleaseDate');
fix.detectChanges();
filteringChips = firstHeaderCell.parent.queryAll(By.directive(IgxChipComponent));
expect(filteringChips.length).toEqual(1);
chipContent = filteringChips[0].query(By.css('.igx-chip__content')).nativeElement.innerText;
expect(chipContent).toEqual('Filter');
}));
it('Should correctly apply two conditions to two columns at once.', fakeAsync(() => {
const colDownloadsExprTree = new FilteringExpressionsTree(FilteringLogic.And, 'Downloads');
colDownloadsExprTree.filteringOperands = [
{ fieldName: 'Downloads', searchVal: 20, condition: IgxNumberFilteringOperand.instance().condition('greaterThanOrEqualTo') },
{ fieldName: 'Downloads', searchVal: 100, condition: IgxNumberFilteringOperand.instance().condition('lessThanOrEqualTo') }
];
const colIdExprTree = new FilteringExpressionsTree(FilteringLogic.And, 'ID');
colIdExprTree.filteringOperands = [
{ fieldName: 'ID', searchVal: 1, condition: IgxNumberFilteringOperand.instance().condition('greaterThan') },
{ fieldName: 'ID', searchVal: 5, condition: IgxNumberFilteringOperand.instance().condition('lessThan') }
];
const gridExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And);
gridExpressionsTree.filteringOperands = [colDownloadsExprTree, colIdExprTree];
grid.filteringExpressionsTree = gridExpressionsTree;
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(2);
grid.clearFilter();
fix.detectChanges();
expect(grid.rowList.length).toEqual(8);
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(0);
}));
it('Should correctly apply two conditions to number column.', fakeAsync(() => {
const filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And, 'Downloads');
const expression = {
fieldName: 'Downloads',
searchVal: 50,
condition: IgxNumberFilteringOperand.instance().condition('greaterThan')
};
const expression1 = {
fieldName: 'Downloads',
searchVal: 500,
condition: IgxNumberFilteringOperand.instance().condition('lessThan')
};
filteringExpressionsTree.filteringOperands.push(expression);
filteringExpressionsTree.filteringOperands.push(expression1);
grid.filter('Downloads', null, filteringExpressionsTree);
fix.detectChanges();
expect(grid.rowList.length).toEqual(3);
expect((grid.filteringExpressionsTree.filteringOperands[0] as FilteringExpressionsTree).filteringOperands.length).toEqual(2);
}));
it('Should correctly apply two conditions to string column.', fakeAsync(() => {
const filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And, 'ProductName');
const expression = {
fieldName: 'ProductName',
searchVal: 'Ignite',
condition: IgxStringFilteringOperand.instance().condition('startsWith')
};
const expression1 = {
fieldName: 'ProductName',
searchVal: 'Angular',
condition: IgxStringFilteringOperand.instance().condition('contains')
};
filteringExpressionsTree.filteringOperands.push(expression);
filteringExpressionsTree.filteringOperands.push(expression1);
grid.filter('ProductName', null, filteringExpressionsTree);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
expect((grid.filteringExpressionsTree.filteringOperands[0] as FilteringExpressionsTree).filteringOperands.length).toEqual(2);
}));
it('Should correctly apply two conditions to date column.', fakeAsync(() => {
const today: Date = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), 0, 0, 0);
const filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.Or, 'ReleaseDate');
const expression = {
fieldName: 'ReleaseDate',
searchVal: null,
condition: IgxDateFilteringOperand.instance().condition('yesterday')
};
const expression1 = {
fieldName: 'ReleaseDate',
searchVal: today,
condition: IgxDateFilteringOperand.instance().condition('after')
};
filteringExpressionsTree.filteringOperands.push(expression);
filteringExpressionsTree.filteringOperands.push(expression1);
grid.filter('ReleaseDate', null, filteringExpressionsTree);
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
expect((grid.filteringExpressionsTree.filteringOperands[0] as FilteringExpressionsTree).filteringOperands.length).toEqual(2);
}));
it('Should correctly update summary.', fakeAsync(() => {
const gridExpressionsTree = new FilteringExpressionsTree(FilteringLogic.Or);
const filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.Or, 'ReleaseDate');
const expression = {
fieldName: 'ReleaseDate',
searchVal: null,
condition: IgxDateFilteringOperand.instance().condition('yesterday')
};
filteringExpressionsTree.filteringOperands.push(expression);
gridExpressionsTree.filteringOperands.push(filteringExpressionsTree);
grid.filteringExpressionsTree = gridExpressionsTree;
fix.detectChanges();
tick(100);
expect(grid.rowList.length).toEqual(1);
const summaryRow = fix.debugElement.query(By.css('igx-grid-summary-row'));
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['1']);
}));
it('should correctly show and hide the "No records found." message.', fakeAsync(() => {
grid.filter('ProductName', 'asdf', IgxStringFilteringOperand.instance().condition('contains'), true);
fix.detectChanges();
let noRecordsSpan = fix.debugElement.query(By.css('.igx-grid__tbody-message'));
expect(grid.rowList.length).toEqual(0);
expect(noRecordsSpan).toBeTruthy();
expect(noRecordsSpan.nativeElement.innerText).toBe('No records found.');
grid.filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.And);
fix.detectChanges();
noRecordsSpan = fix.debugElement.query(By.css('.igx-grid__tbody-message'));
expect(grid.rowList.length).toEqual(8);
expect(noRecordsSpan).toBeFalsy();
}));
it('Should generate the expressions UI list correctly.', fakeAsync(() => {
const filteringExpressionsTree = new FilteringExpressionsTree(FilteringLogic.Or, 'ProductName');
const expression = {
fieldName: 'ProductName',
searchVal: 'Ignite',
condition: IgxStringFilteringOperand.instance().condition('startsWith')
};
const expression1 = new FilteringExpressionsTree(FilteringLogic.And, 'ProductName');
const expression11 = {
fieldName: 'ProductName',
searchVal: 'Angular',
condition: IgxStringFilteringOperand.instance().condition('contains')
};
const expression12 = {
fieldName: 'ProductName',
searchVal: 'jQuery',
condition: IgxStringFilteringOperand.instance().condition('contains')
};
const expression2 = new FilteringExpressionsTree(FilteringLogic.And, 'ProductName');
const expression21 = {
fieldName: 'ProductName',
searchVal: 'Angular',
condition: IgxStringFilteringOperand.instance().condition('contains')
};
const expression22 = {
fieldName: 'ProductName',
searchVal: 'jQuery',
condition: IgxStringFilteringOperand.instance().condition('contains')
};
expression1.filteringOperands.push(expression11);
expression1.filteringOperands.push(expression12);
expression2.filteringOperands.push(expression21);
expression2.filteringOperands.push(expression22);
filteringExpressionsTree.filteringOperands.push(expression);
filteringExpressionsTree.filteringOperands.push(expression1);
filteringExpressionsTree.filteringOperands.push(expression2);
grid.filter('ProductName', null, filteringExpressionsTree);
const expressionUIs: ExpressionUI[] = [];
grid.filteringService.generateExpressionsList(grid.filteringExpressionsTree, grid.filteringLogic, expressionUIs);
verifyExpressionUI(expressionUIs[0], expression, FilteringLogic.Or, undefined);
verifyExpressionUI(expressionUIs[1], expression11, FilteringLogic.And, FilteringLogic.Or);
verifyExpressionUI(expressionUIs[2], expression12, FilteringLogic.Or, FilteringLogic.And);
verifyExpressionUI(expressionUIs[3], expression21, FilteringLogic.And, FilteringLogic.Or);
verifyExpressionUI(expressionUIs[4], expression22, null, FilteringLogic.And);
}));
it('Should do nothing when clearing filter of non-existing column.', fakeAsync(() => {
grid.filter('ProductName', 'ignite', IgxStringFilteringOperand.instance().condition('contains'), true);
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
grid.clearFilter('NonExistingColumnName');
fix.detectChanges();
expect(grid.rowList.length).toEqual(2);
}));
it('Should always emit filteringDone with proper eventArgs, even when column does not exist', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
grid.filteringLogic = FilteringLogic.Or;
grid.filter('Nonexisting', 'ignite', IgxStringFilteringOperand.instance().condition('contains'), true);
tick(100);
fix.detectChanges();
expect(grid.rowList.length).toEqual(0);
const args = grid.filteringExpressionsTree.find('Nonexisting') as FilteringExpressionsTree;
expect(grid.filtering.emit).toHaveBeenCalledWith({ owner: grid, cancel: false, filteringExpressions: args });
expect(grid.filteringDone.emit).toHaveBeenCalledWith(args);
}));
it('Should emit filteringDone when filtering globally', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
grid.filteringLogic = FilteringLogic.Or;
grid.filterGlobal('some', IgxStringFilteringOperand.instance().condition('contains'));
tick(100);
fix.detectChanges();
const args = { owner: grid, cancel: false, filteringExpressions: grid.filteringExpressionsTree };
expect(grid.filtering.emit).toHaveBeenCalledWith(args);
expect(grid.filteringDone.emit).toHaveBeenCalledWith(grid.filteringExpressionsTree);
}));
it('Should keep existing expressionTree when filtering with a null expressionTree.', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
const expression1 = new FilteringExpressionsTree(FilteringLogic.Or, 'ProductName');
const expression11 = {
fieldName: 'ProductName',
searchVal: 'Angular',
condition: IgxStringFilteringOperand.instance().condition('contains')
};
// Verify results after filtering.
expression1.filteringOperands.push(expression11);
grid.filter('ProductName', null, expression1);
tick(30);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
expect(GridFunctions.getCurrentCellFromGrid(grid, 0, 1).value).toBe('Ignite UI for Angular');
const args = { owner: grid, cancel: false, filteringExpressions: expression1 };
expect(grid.filtering.emit).toHaveBeenCalledWith(args);
expect(grid.filteringDone.emit).toHaveBeenCalledWith(expression1);
// Verify that passing null for expressionTree with a new searchVal will keep the existing expressionTree.
grid.filter('ProductName', 'ignite', null);
tick(30);
fix.detectChanges();
expect(grid.rowList.length).toEqual(1);
expect(GridFunctions.getCurrentCellFromGrid(grid, 0, 1).value).toBe('Ignite UI for Angular');
expect(grid.filtering.emit).toHaveBeenCalledWith(args);
expect(grid.filteringDone.emit).toHaveBeenCalledWith(expression1);
}));
it('Should throw descriptive error when filter() is called without condition', fakeAsync(() => {
expect(() => {
grid.filter('Downloads', 100);
fix.detectChanges();
}).toThrowError('Invalid condition or Expression Tree!');
}));
it('Should not clear previous filtering when filterGlobal() is called with invalid condition', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
grid.filter('Downloads', 100, IgxNumberFilteringOperand.instance().condition('greaterThan'), true);
tick(30);
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
expect(grid.getCellByColumn(0, 'Downloads').value).toEqual(254);
const args = { owner: grid, cancel: false, filteringExpressions: grid.filteringExpressionsTree.find('Downloads') };
expect(grid.filtering.emit).toHaveBeenCalledWith(args);
expect(grid.filteringDone.emit).toHaveBeenCalledWith(grid.filteringExpressionsTree.find('Downloads'));
// Execute global filtering with invalid condition.
grid.filterGlobal(1000, null);
fix.detectChanges();
expect(grid.rowList.length).toEqual(4);
expect(grid.getCellByColumn(0, 'Downloads').value).toEqual(254);
expect(grid.filtering.emit).toHaveBeenCalledTimes(1);
expect(grid.filteringDone.emit).toHaveBeenCalledTimes(1);
}));
it('Should disable filtering feature when using NoopFilteringStrategy.', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
// Use the NoopFilteringStrategy.
grid.filterStrategy = NoopFilteringStrategy.instance();
fix.detectChanges();
grid.filter('ProductName', 'some value', IgxStringFilteringOperand.instance().condition('contains'));
tick(30);
fix.detectChanges();
// Verify the grid is not filtered, because of the noop filter strategy.
expect(grid.rowList.length).toBe(8);
expect(GridFunctions.getCurrentCellFromGrid(grid, 0, 1).value).toBe('Ignite UI for JavaScript');
expect(GridFunctions.getCurrentCellFromGrid(grid, 1, 1).value).toBe('NetAdvantage');
const filteringExpressions = grid.filteringExpressionsTree.find('ProductName');
const args = { owner: grid, cancel: false, filteringExpressions };
expect(grid.filtering.emit).toHaveBeenCalledWith(args);
expect(grid.filteringDone.emit).toHaveBeenCalledWith(filteringExpressions);
}));
});
describe('IgxGrid - Filtering expression tree bindings #grid', () => {
configureTestSuite((() => {
TestBed.configureTestingModule({
declarations: [
IgxGridFilteringBindingComponent
],
imports: [
NoopAnimationsModule,
IgxGridModule]
});
}));
let fix; let grid: IgxGridComponent;
beforeEach(fakeAsync(() => {
fix = TestBed.createComponent(IgxGridFilteringBindingComponent);
fix.detectChanges();
grid = fix.componentInstance.grid;
}));
it('should correctly filter with \'filteringExpressionsTree\' binding', fakeAsync(() => {
spyOn(grid.filtering, 'emit');
spyOn(grid.filteringDone, 'emit');
// Verify initially filtered 'Downloads > 200'
expect(grid.rowList.length).toEqual(3);
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(1);
// Verify filtering expressions tree binding state
expect(grid.filteringExpressionsTree).toBe(fix.componentInstance.filterTree);
// Clear filter
grid.clearFilter('Downloads');
tick(30);
fix.detectChanges();
// Verify filtering expressions tree binding state
expect(grid.filteringExpressionsTree).toBe(fix.componentInstance.filterTree);
// Verify no filtered data
expect(grid.rowList.length).toEqual(8);
expect(grid.filteringExpressionsTree.filteringOperands.length).toEqual(0);
}));
});
const verifyExpressionUI = (expressionUI: ExpressionUI, expression: IFilteringExpression,
afterOperator: FilteringLogic, beforeOperator: FilteringLogic) => {
expect(expressionUI.expression).toBe(expression);
expect(expressionUI.afterOperator).toBe(afterOperator);
expect(expressionUI.beforeOperator).toBe(beforeOperator);
}; | the_stack |
import * as actionTypes from "../../src/constants/ActionTypes";
import { expect, should } from "chai";
import actions from "../../src/actionCreators/actions";
import map from "../../src/mappers/hostMessageToAction";
import sampleThemes from "../sampleThemes";
import { cloneWorkspace } from "../../src/workspaces";
import { emptyWorkspace, defaultGistProject } from "../testResources";
import { IWorkspace } from "../../src/IState";
import getStore from "../observableAppStore";
import { CREATE_REGIONS_FROM_SOURCEFILES_REQUEST, CREATE_PROJECT_FROM_GIST_REQUEST, CREATE_OPERATION_ID_REQUEST, SET_ACTIVE_BUFFER_REQUEST } from "../../src/constants/ApiMessageTypes";
describe("hostMessageToAction mapper", () => {
it("returns undefined for messages it is not configured to map", () => {
should().not.exist(map({ type: "some type" }));
});
it("maps setRunResult to RUN_CODE_RESULT_SPECIFIED", () => {
const expectedPayload = {
output: ["a", "b"],
succeeded: true
};
map({
type: "setRunResult",
...expectedPayload
}).should.deep.equal({
type: actionTypes.RUN_CODE_RESULT_SPECIFIED,
...expectedPayload
});
});
it("maps setSourceCode to UPDATE_WORKSPACE_BUFFER", () => {
var store = getStore();
var sourceCode = "Console.WriteLine(\"Hello, World\");";
const expectedActions = [actions.updateWorkspaceBuffer("some source code;", "currentBufferId")];
var ws = cloneWorkspace(emptyWorkspace);
ws.buffers = [{ id: "currentBufferId", position: 0, content: sourceCode }];
store.withDefaultClient();
store.configure([actions.setActiveBuffer("currentBufferId"), actions.setWorkspace(ws)]);
var mapped = map({
type: "setSourceCode",
sourceCode: "some source code;"
});
store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps setAdditionalUsings to SET_ADDITIONAL_USINGS", () => {
const expectedPayload = {
additionalUsings: ["a_using;"]
};
map({
type: "setAdditionalUsings",
...expectedPayload
}).should.deep.equal({
type: actionTypes.SET_ADDITIONAL_USINGS,
...expectedPayload
});
});
it("maps setWorkspaceFromGist to LOAD_SOURCE", async () => {
var store = getStore();
const info = {
originType: "gist",
htmlUrl: "https://gist.github.com/df44833326fcc575e8169fccb9d41fc7",
rawFileUrls:
[{
fileName: "Program.cs",
url: "https://gist.githubusercontent.com/colombod/df44833326fcc575e8169fccb9d41fc7/raw/35765c05ddb54bc827419211a6b645473cdda7f9/FibonacciGenerator.cs"
},
{
fileName: "FibonacciGenerator.cs",
url: "https://gist.githubusercontent.com/colombod/df44833326fcc575e8169fccb9d41fc7/raw/700a834733fa650d2a663ccd829f8a9d09b44642/Program.cs"
}],
workspace:
{
workspaceType: "console",
buffers:
[
{ id: "Program.cs", content: "console code", position: 0 },
{ id: "FibonacciGenerator.cs", content: "generator code", position: 0 }
],
}
};
const expectedActions = [
actions.setWorkspaceInfo(info),
actions.canShowGitHubPanel(false),
actions.setWorkspace(info.workspace),
actions.setWorkspaceLanguage("csharp"),
actions.setActiveBuffer("FibonacciGenerator.cs"),
actions.setCodeSource("workspace"),
actions.loadCodeRequest("workspace"),
actions.loadCodeSuccess(info.workspace.buffers[1].content, info.workspace.buffers[1].id)
];
var mapped = map({
type: "setWorkspaceFromGist",
gistId: "df44833326fcc575e8169fccb9d41fc7",
bufferId: "FibonacciGenerator.cs",
workspaceType: "console"
});
store.withDefaultClient();
await store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps setWorkspace to LOAD_SOURCE", async () => {
var store = getStore();
let workspace: IWorkspace = {
workspaceType: "console",
files: [{
name: "Program.cs",
text: "using System;\nusing System.Linq;\n\nnamespace FibonacciTest\n{\n public class Program\n {\n public static void Main()\n {\n #region codeRegion\n #endregion\n }\n }\n}"
}],
buffers: [{
id: "Program.cs@codeRegion",
content: "Console.WriteLine(\"something new here\")",
position: 0
}],
};
const expectedActions = [
actions.setWorkspace(workspace),
actions.setWorkspaceLanguage("csharp"),
actions.setActiveBuffer("Program.cs@codeRegion"),
actions.setCodeSource("workspace"),
actions.loadCodeRequest("workspace"),
actions.loadCodeSuccess(workspace.buffers[0].content, workspace.buffers[0].id)
];
var mapped = map({
type: "setWorkspace",
workspace: workspace,
bufferId: "Program.cs@codeRegion",
});
store.withDefaultClient();
await store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps run to RUN_CODE_REQUEST", async () => {
var store = getStore();
const expectedActions = [
actions.runRequest("Test_Run"),
actions.runSuccess({
output: ["Hello, World"],
succeeded: true
})
];
var sourceCode = "Console.WriteLine(\"Hello, World\");";
var ws = cloneWorkspace(emptyWorkspace);
ws.buffers = [{ id: "Program.cs", position: 0, content: sourceCode }];
store.withDefaultClient();
store.configure([actions.setWorkspace(ws)]);
var mapped = map({
type: "run",
requestId: "Test_Run"
});
await store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps setEditorOptions to CONFIGURE_MONACO_EDITOR", () => {
const expectedPayload = {
editorOptions: { some: "option" },
theme: "some string"
};
map({
type: "configureMonacoEditor",
...expectedPayload
}).should.deep.equal({
type: actionTypes.CONFIGURE_MONACO_EDITOR,
...expectedPayload
});
});
it("maps showEditor to SHOW_EDITOR", () => {
map({
type: "showEditor"
}).should.deep.equal({
type: actionTypes.SHOW_EDITOR
});
});
it("maps focus to focusMonacoEditor", () => {
var store = getStore();
var focusInvoked = false;
store.configure([actions.notifyMonacoReady({ focus: () => { focusInvoked = true; }, layout: () => { } })]);
var mapped = map({
type: "focusEditor"
});
store.dispatch(mapped);
expect(focusInvoked).to.be.true;
});
it("maps defineMonacoEditorThemes to DEFINE_MONACO_EDITOR_THEMES", () => {
const expectedPayload = {
themes: [sampleThemes.myCustomTheme]
};
map({
type: "defineMonacoEditorThemes",
themes: [sampleThemes.myCustomTheme]
}).should.deep.equal({
type: actionTypes.DEFINE_MONACO_EDITOR_THEMES,
...expectedPayload
});
});
it("maps setInstrumentation to SET_INSTRUMENTATION", () => {
map({
type: "setInstrumentation",
enabled: true
}).should.deep.equal({
type: actionTypes.SET_INSTRUMENTATION,
enabled: true
});
});
it("maps checkPrevEnabled", () => {
const store = getStore();
store.withDefaultClient();
store.configure([actions.runSuccess({
output: ["before after"],
instrumentation: [
{
output: {
start: 0,
end: 6
}
}]
})]);
store.dispatch(
map({
type: "checkPrevEnabled"
})
);
store.getActions().should.deep.equal([{
type: actionTypes.CANNOT_MOVE_PREV
}]);
});
it("maps checkNextEnabled", () => {
const store = getStore();
store.configure([actions.runSuccess({
output: ["before after"],
instrumentation: [
{
output: {
start: 0,
end: 6
}
}]
})]);
store.dispatch(
map({
type: "checkNextEnabled"
})
);
store.getActions().should.deep.equal([{
type: actionTypes.CANNOT_MOVE_NEXT
}]);
});
it("maps prevInstrumentationStep", async () => {
const store = getStore();
store.configure([actions.runSuccess({
output: ["before after"],
instrumentation: [
{
output: {
start: 0,
end: 6
}
}, {
output: {
start: 6,
end: 12
}
}]
})]);
const next = map({ type: "nextInstrumentationStep" });
const back = map({ type: "prevInstrumentationStep" });
store.dispatch(next);
store.dispatch(back);
store.getActions().should.deep.include.members([{
type: actionTypes.PREV_INSTRUMENT_STEP
}, {
type: actionTypes.OUTPUT_UPDATED,
output: ["before"]
}, {
type: actionTypes.CANNOT_MOVE_PREV
}]);
});
it("maps nextInstrumentationStep", async () => {
const store = getStore();
store.configure([actions.runSuccess({
output: ["before after"],
instrumentation: [
{},
{
output: {
start: 0,
end: 6
}
}]
})]);
const mapped = map({ type: "nextInstrumentationStep" });
store.dispatch(mapped);
store.getActions().should.deep.equal([{
type: actionTypes.NEXT_INSTRUMENT_STEP
}, {
type: actionTypes.OUTPUT_UPDATED,
output: ["before"]
}, {
type: actionTypes.CANNOT_MOVE_NEXT
}]);
});
it("maps applyScaffolding", async () => {
var store = getStore();
const expectedActions = [
actions.setWorkspace({
activeBufferId: "foo.cs@scaffold",
buffers: [{
content: "",
id: "foo.cs@scaffold",
position: 0
}],
files: [{
name: "foo.cs",
text: `using System;
class C
{
#region scaffold
#endregion
}`
}],
workspaceType: "script",
}),
actions.setActiveBuffer("foo.cs@scaffold"),
actions.setCodeSource("workspace"),
actions.loadCodeRequest("workspace"),
actions.loadCodeSuccess("", "foo.cs@scaffold")
];
var mapped = map({
type: "applyScaffolding",
fileName: "foo.cs",
scaffoldingType: "Class",
additionalUsings: ["System"]
});
store.withDefaultClient();
await store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps generateOperationId to OPERATION_ID_GENERATED", () => {
let action = map({
type: CREATE_OPERATION_ID_REQUEST,
requestId: "Test_Run"
});
action.type.should.equal(actionTypes.OPERATION_ID_GENERATED);
action.requestId.should.equal("Test_Run");
action.operationId.should.not.equal(null);
});
it("maps createprojectfromgist to CREATE_PROJECT_SUCCESS", async () => {
var store = getStore();
const expectedActions = [
{
type: actionTypes.CREATE_PROJECT_SUCCESS,
requestId: "Test_Run",
project: { ...defaultGistProject }
}
];
store.withDefaultClient();
var mapped = map({
type: CREATE_PROJECT_FROM_GIST_REQUEST,
requestId: "Test_Run",
gistId: "any",
projectTemplate: defaultGistProject.projectTemplate
});
await store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps generateregionfromfiles to GENERATE_REGIONS_FROM_FILES_SUCCESS", async () => {
var store = getStore();
const expectedActions = [
{
type: actionTypes.CREATE_REGIONS_FROM_SOURCEFILES_SUCCESS,
requestId: "Test_Run",
regions: [{ id: "code.cs@left", content: "right" }]
}
];
store.withDefaultClient();
var mapped = map({
type: CREATE_REGIONS_FROM_SOURCEFILES_REQUEST,
requestId: "Test_Run",
files: [{ name: "code.cs", content: "left$$right" }]
});
await store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
it("maps SET_ACTIVE_BUFFER_REQUEST to SET_ACTIVE_BUFFER", () => {
var store = getStore();
var sourceCode = "Console.WriteLine(\"Hello, World\");";
const expectedActions = [actions.setActiveBuffer("new bufferId")];
var ws = cloneWorkspace(emptyWorkspace);
ws.buffers = [{ id: "currentBufferId", position: 0, content: sourceCode },{ id: "new bufferId", position: 0, content: sourceCode }];
store.withDefaultClient();
store.configure([actions.setActiveBuffer("currentBufferId"), actions.setWorkspace(ws)]);
var mapped = map({
type: SET_ACTIVE_BUFFER_REQUEST,
bufferId: "new bufferId"
});
store.dispatch(mapped);
store.getActions().should.deep.equal(expectedActions);
});
}); | the_stack |
import { SessionContext } from '@jupyterlab/apputils';
import {
IOutputAreaModel,
OutputArea,
OutputAreaModel
} from '@jupyterlab/outputarea';
import { KernelManager } from '@jupyterlab/services';
import {
createSessionContext,
defaultRenderMime,
flakyIt as it,
JupyterServer,
NBTestUtils
} from '@jupyterlab/testutils';
import { Message } from '@lumino/messaging';
import { Widget } from '@lumino/widgets';
/**
* The default rendermime instance to use for testing.
*/
const rendermime = defaultRenderMime();
const CODE = 'print("hello")';
class LogOutputArea extends OutputArea {
methods: string[] = [];
protected onUpdateRequest(msg: Message): void {
super.onUpdateRequest(msg);
this.methods.push('onUpdateRequest');
}
protected onModelChanged(
sender: IOutputAreaModel,
args: IOutputAreaModel.ChangedArgs
) {
super.onModelChanged(sender, args);
this.methods.push('onModelChanged');
}
}
const server = new JupyterServer();
beforeAll(async () => {
jest.setTimeout(20000);
await server.start();
});
afterAll(async () => {
await server.shutdown();
});
describe('outputarea/widget', () => {
let widget: LogOutputArea;
let model: OutputAreaModel;
beforeEach(() => {
model = new OutputAreaModel({
values: NBTestUtils.DEFAULT_OUTPUTS,
trusted: true
});
widget = new LogOutputArea({ rendermime, model });
});
afterEach(() => {
model.dispose();
widget.dispose();
});
describe('OutputArea', () => {
describe('#constructor()', () => {
it('should create an output area widget', () => {
expect(widget).toBeInstanceOf(OutputArea);
expect(widget.hasClass('jp-OutputArea')).toBe(true);
});
it('should take an optional contentFactory', () => {
const contentFactory = Object.create(OutputArea.defaultContentFactory);
const widget = new OutputArea({ rendermime, contentFactory, model });
expect(widget.contentFactory).toBe(contentFactory);
});
});
describe('#model', () => {
it('should be the model used by the widget', () => {
expect(widget.model).toBe(model);
});
});
describe('#rendermime', () => {
it('should be the rendermime instance used by the widget', () => {
expect(widget.rendermime).toBe(rendermime);
});
});
describe('#contentFactory', () => {
it('should be the contentFactory used by the widget', () => {
expect(widget.contentFactory).toBe(OutputArea.defaultContentFactory);
});
});
describe('#widgets', () => {
it('should get the child widget at the specified index', () => {
expect(widget.widgets[0]).toBeInstanceOf(Widget);
});
it('should get the number of child widgets', () => {
expect(widget.widgets.length).toBe(
NBTestUtils.DEFAULT_OUTPUTS.length - 1
);
widget.model.clear();
expect(widget.widgets.length).toBe(0);
});
});
describe('#future', () => {
let sessionContext: SessionContext;
beforeEach(async () => {
sessionContext = await createSessionContext();
await sessionContext.initialize();
await sessionContext.session?.kernel?.info;
});
afterEach(async () => {
await sessionContext.shutdown();
sessionContext.dispose();
});
it('should execute code on a kernel and send outputs to the model', async () => {
const future = sessionContext.session!.kernel!.requestExecute({
code: CODE
});
widget.future = future;
const reply = await future.done;
expect(reply!.content.execution_count).toBeTruthy();
expect(reply!.content.status).toBe('ok');
expect(model.length).toBe(1);
});
it('should clear existing outputs', async () => {
widget.model.fromJSON(NBTestUtils.DEFAULT_OUTPUTS);
const future = sessionContext.session!.kernel!.requestExecute({
code: CODE
});
widget.future = future;
const reply = await future.done;
expect(reply!.content.execution_count).toBeTruthy();
expect(model.length).toBe(1);
});
});
describe('#onModelChanged()', () => {
it('should handle an added output', () => {
widget.model.clear();
widget.methods = [];
widget.model.add(NBTestUtils.DEFAULT_OUTPUTS[0]);
expect(widget.methods).toEqual(
expect.arrayContaining(['onModelChanged'])
);
expect(widget.widgets.length).toBe(1);
});
it('should handle a clear', () => {
widget.model.fromJSON(NBTestUtils.DEFAULT_OUTPUTS);
widget.methods = [];
widget.model.clear();
expect(widget.methods).toEqual(
expect.arrayContaining(['onModelChanged'])
);
expect(widget.widgets.length).toBe(0);
});
it('should handle a set', () => {
widget.model.clear();
widget.model.add(NBTestUtils.DEFAULT_OUTPUTS[0]);
widget.methods = [];
widget.model.add(NBTestUtils.DEFAULT_OUTPUTS[0]);
expect(widget.methods).toEqual(
expect.arrayContaining(['onModelChanged'])
);
expect(widget.widgets.length).toBe(1);
});
it('should rerender when preferred mimetype changes', () => {
// Add output with both safe and unsafe types
widget.model.clear();
widget.model.add({
output_type: 'display_data',
data: {
'image/svg+xml':
'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"></svg>',
'text/plain': 'hello, world'
},
metadata: {}
});
expect(widget.node.innerHTML).toContain('<img src="data:image/svg+xml');
widget.model.trusted = !widget.model.trusted;
expect(widget.node.innerHTML).toEqual(
expect.not.arrayContaining(['<img src="data:image/svg+xml'])
);
widget.model.trusted = !widget.model.trusted;
expect(widget.node.innerHTML).toContain('<img src="data:image/svg+xml');
});
it('should rerender when isolation changes', () => {
// Add output with both safe and unsafe types
widget.model.clear();
widget.model.add({
output_type: 'display_data',
data: {
'text/plain': 'hello, world'
}
});
expect(widget.node.innerHTML).toEqual(
expect.not.arrayContaining(['<iframe'])
);
widget.model.set(0, {
output_type: 'display_data',
data: {
'text/plain': 'hello, world'
},
metadata: {
isolated: true
}
});
expect(widget.node.innerHTML).toContain('<iframe');
widget.model.set(0, {
output_type: 'display_data',
data: {
'text/plain': 'hello, world'
}
});
expect(widget.node.innerHTML).not.toContain('<iframe');
});
});
describe('.execute()', () => {
let sessionContext: SessionContext;
beforeEach(async () => {
sessionContext = await createSessionContext();
await sessionContext.initialize();
await sessionContext.session?.kernel?.info;
});
afterEach(async () => {
await sessionContext.shutdown();
sessionContext.dispose();
});
it('should execute code on a kernel and send outputs to the model', async () => {
const reply = await OutputArea.execute(CODE, widget, sessionContext);
expect(reply!.content.execution_count).toBeTruthy();
expect(reply!.content.status).toBe('ok');
expect(model.length).toBe(1);
});
it('should clear existing outputs', async () => {
widget.model.fromJSON(NBTestUtils.DEFAULT_OUTPUTS);
const reply = await OutputArea.execute(CODE, widget, sessionContext);
expect(reply!.content.execution_count).toBeTruthy();
expect(model.length).toBe(1);
});
it('should handle routing of display messages', async () => {
const model0 = new OutputAreaModel({ trusted: true });
const widget0 = new LogOutputArea({ rendermime, model: model0 });
const model1 = new OutputAreaModel({ trusted: true });
const widget1 = new LogOutputArea({ rendermime, model: model1 });
const model2 = new OutputAreaModel({ trusted: true });
const widget2 = new LogOutputArea({ rendermime, model: model2 });
const code0 = [
'ip = get_ipython()',
'from IPython.display import display',
'def display_with_id(obj, display_id, update=False):',
' iopub = ip.kernel.iopub_socket',
' session = get_ipython().kernel.session',
' data, md = ip.display_formatter.format(obj)',
' transient = {"display_id": display_id}',
' content = {"data": data, "metadata": md, "transient": transient}',
' msg_type = "update_display_data" if update else "display_data"',
' session.send(iopub, msg_type, content, parent=ip.parent_header)'
].join('\n');
const code1 = [
'display("above")',
'display_with_id(1, "here")',
'display("below")'
].join('\n');
const code2 = [
'display_with_id(2, "here")',
'display_with_id(3, "there")',
'display_with_id(4, "here")'
].join('\n');
let ipySessionContext: SessionContext;
ipySessionContext = await createSessionContext({
kernelPreference: { name: 'ipython' }
});
await ipySessionContext.initialize();
const promise0 = OutputArea.execute(code0, widget0, ipySessionContext);
const promise1 = OutputArea.execute(code1, widget1, ipySessionContext);
await Promise.all([promise0, promise1]);
expect(model1.length).toBe(3);
expect(model1.toJSON()[1].data).toEqual({ 'text/plain': '1' });
await OutputArea.execute(code2, widget2, ipySessionContext);
expect(model1.length).toBe(3);
expect(model1.toJSON()[1].data).toEqual({ 'text/plain': '4' });
expect(model2.length).toBe(3);
const outputs = model2.toJSON();
expect(outputs[0].data).toEqual({ 'text/plain': '4' });
expect(outputs[1].data).toEqual({ 'text/plain': '3' });
expect(outputs[2].data).toEqual({ 'text/plain': '4' });
await ipySessionContext.shutdown();
});
it('should stop on an error', async () => {
let ipySessionContext: SessionContext;
ipySessionContext = await createSessionContext({
kernelPreference: { name: 'ipython' }
});
await ipySessionContext.initialize();
const widget1 = new LogOutputArea({ rendermime, model });
const future1 = OutputArea.execute('a++1', widget, ipySessionContext);
const future2 = OutputArea.execute('a=1', widget1, ipySessionContext);
const reply = await future1;
const reply2 = await future2;
expect(reply!.content.status).toBe('error');
expect(reply2!.content.status).toBe('aborted');
expect(model.length).toBe(1);
widget1.dispose();
await ipySessionContext.shutdown();
});
it('should allow an error given "raises-exception" metadata tag', async () => {
let ipySessionContext: SessionContext;
ipySessionContext = await createSessionContext({
kernelPreference: { name: 'ipython' }
});
await ipySessionContext.initialize();
const widget1 = new LogOutputArea({ rendermime, model });
const metadata = { tags: ['raises-exception'] };
const future1 = OutputArea.execute(
'a++1',
widget,
ipySessionContext,
metadata
);
const future2 = OutputArea.execute('a=1', widget1, ipySessionContext);
const reply = await future1;
const reply2 = await future2;
expect(reply!.content.status).toBe('error');
expect(reply2!.content.status).toBe('ok');
widget1.dispose();
await ipySessionContext.shutdown();
});
});
describe('.ContentFactory', () => {
describe('#createOutputPrompt()', () => {
it('should create an output prompt', () => {
const factory = new OutputArea.ContentFactory();
expect(factory.createOutputPrompt().executionCount).toBeNull();
});
});
describe('#createStdin()', () => {
it('should create a stdin widget', async () => {
const manager = new KernelManager();
const kernel = await manager.startNew();
const factory = new OutputArea.ContentFactory();
const future = kernel.requestExecute({ code: CODE });
const options = {
prompt: 'hello',
password: false,
future
};
expect(factory.createStdin(options)).toBeInstanceOf(Widget);
await kernel.shutdown();
kernel.dispose();
});
});
});
describe('.defaultContentFactory', () => {
it('should be a `contentFactory` instance', () => {
expect(OutputArea.defaultContentFactory).toBeInstanceOf(
OutputArea.ContentFactory
);
});
});
});
}); | the_stack |
import * as nbformat from '@jupyterlab/nbformat';
import { ISignal, Signal } from '@lumino/signaling';
import { Awareness } from 'y-protocols/awareness';
import * as Y from 'yjs';
import * as models from './api';
/**
* Abstract interface to define Shared Models that can be bound to a text editor using any existing
* Yjs-based editor binding.
*/
export interface IYText extends models.ISharedText {
readonly ysource: Y.Text;
readonly awareness: Awareness | null;
readonly undoManager: Y.UndoManager | null;
}
export declare type YCellType = YRawCell | YCodeCell | YMarkdownCell;
export declare class YDocument<T> implements models.ISharedDocument {
/**
* Perform a transaction. While the function f is called, all changes to the shared
* document are bundled into a single event.
*/
transact(f: () => void, undoable?: boolean): void;
/**
* Dispose of the resources.
*/
dispose(): void;
/**
* Whether the object can undo changes.
*/
canUndo(): boolean;
/**
* Whether the object can redo changes.
*/
canRedo(): boolean;
/**
* Undo an operation.
*/
undo(): void;
/**
* Redo an operation.
*/
redo(): void;
/**
* Clear the change stack.
*/
clearUndoHistory(): void;
/**
* The changed signal.
*/
get changed(): ISignal<this, T>;
isDisposed: boolean;
ydoc: Y.Doc;
source: Y.Text;
undoManager: Y.UndoManager;
awareness: Awareness;
protected _changed: Signal<this, T>;
}
export declare class YFile extends YDocument<models.FileChange> implements models.ISharedFile, models.ISharedText, IYText {
constructor();
/**
* Handle a change to the ymodel.
*/
private _modelObserver;
static create(): YFile;
/**
* Gets cell's source.
*
* @returns Cell's source.
*/
getSource(): string;
/**
* Sets cell's source.
*
* @param value: New source.
*/
setSource(value: string): void;
/**
* Replace content from `start' to `end` with `value`.
*
* @param start: The start index of the range to replace (inclusive).
*
* @param end: The end index of the range to replace (exclusive).
*
* @param value: New source (optional).
*/
updateSource(start: number, end: number, value?: string): void;
ysource: Y.Text;
}
/**
* Shared implementation of the Shared Document types.
*
* Shared cells can be inserted into a SharedNotebook.
* Shared cells only start emitting events when they are connected to a SharedNotebook.
*
* "Standalone" cells must not be inserted into a (Shared)Notebook.
* Standalone cells emit events immediately after they have been created, but they must not
* be included into a (Shared)Notebook.
*/
export declare class YNotebook extends YDocument<models.NotebookChange> implements models.ISharedNotebook {
constructor();
/**
* Get a shared cell by index.
*
* @param index: Cell's position.
*
* @returns The requested shared cell.
*/
getCell(index: number): YCellType;
/**
* Insert a shared cell into a specific position.
*
* @param index: Cell's position.
*
* @param cell: Cell to insert.
*/
insertCell(index: number, cell: YCellType): void;
/**
* Insert a list of shared cells into a specific position.
*
* @param index: Position to insert the cells.
*
* @param cells: Array of shared cells to insert.
*/
insertCells(index: number, cells: YCellType[]): void;
/**
* Move a cell.
*
* @param fromIndex: Index of the cell to move.
*
* @param toIndex: New position of the cell.
*/
moveCell(fromIndex: number, toIndex: number): void;
/**
* Remove a cell.
*
* @param index: Index of the cell to remove.
*/
deleteCell(index: number): void;
/**
* Remove a range of cells.
*
* @param from: The start index of the range to remove (inclusive).
*
* @param to: The end index of the range to remove (exclusive).
*/
deleteCellRange(from: number, to: number): void;
/**
* Returns the metadata associated with the notebook.
*
* @returns Notebook's metadata.
*/
getMetadata(): nbformat.INotebookMetadata;
/**
* Sets the metadata associated with the notebook.
*
* @param metadata: Notebook's metadata.
*/
setMetadata(value: nbformat.INotebookMetadata): void;
/**
* Updates the metadata associated with the notebook.
*
* @param value: Metadata's attribute to update.
*/
updateMetadata(value: Partial<nbformat.INotebookMetadata>): void;
/**
* Create a new YNotebook.
*/
static create(): models.ISharedNotebook;
/**
* Dispose of the resources.
*/
dispose(): void;
/**
* Handle a change to the list of cells.
*/
private _onYCellsChanged;
ycells: Y.Array<Y.Map<any>>;
ymeta: Y.Map<any>;
ymodel: Y.Map<any>;
undoManager: Y.UndoManager;
private _ycellMapping;
nbformat_minor: number;
nbformat: number;
cells: YCellType[];
}
/**
* Create a new shared cell given the type.
*/
export declare const createCellFromType: (type: Y.Map<any>) => YCellType;
/**
* Create a new standalone cell given the type.
*/
export declare const createStandaloneCell: (cellType: 'raw' | 'code' | 'markdown', id?: string | undefined) => YCellType;
export declare class YBaseCell<Metadata extends models.ISharedBaseCellMetadata> implements models.ISharedBaseCell<Metadata>, IYText {
constructor(ymodel: Y.Map<any>);
get ysource(): Y.Text;
get awareness(): Awareness | null;
/**
* Perform a transaction. While the function f is called, all changes to the shared
* document are bundled into a single event.
*/
transact(f: () => void, undoable?: boolean): void;
/**
* The notebook that this cell belongs to.
*/
get undoManager(): Y.UndoManager | null;
/**
* Undo an operation.
*/
undo(): void;
/**
* Redo an operation.
*/
redo(): void;
/**
* Whether the object can undo changes.
*/
canUndo(): boolean;
/**
* Whether the object can redo changes.
*/
canRedo(): boolean;
/**
* Clear the change stack.
*/
clearUndoHistory(): void;
/**
* The notebook that this cell belongs to.
*/
get notebook(): YNotebook | null;
/**
* The notebook that this cell belongs to.
*/
protected _notebook: YNotebook | null;
/**
* Whether the cell is standalone or not.
*
* If the cell is standalone. It cannot be
* inserted into a YNotebook because the Yjs model is already
* attached to an anonymous Y.Doc instance.
*/
isStandalone: boolean;
/**
* Create a new YRawCell that can be inserted into a YNotebook
*/
static create(id?: string): YBaseCell<any>;
/**
* Create a new YRawCell that works standalone. It cannot be
* inserted into a YNotebook because the Yjs model is already
* attached to an anonymous Y.Doc instance.
*/
static createStandalone(id?: string): YBaseCell<any>;
/**
* Clone the cell.
*
* @todo clone should only be available in the specific implementations i.e. ISharedCodeCell
*/
clone(): YBaseCell<any>;
/**
* Handle a change to the ymodel.
*/
private _modelObserver;
/**
* The changed signal.
*/
get changed(): ISignal<this, models.CellChange<Metadata>>;
/**
* Dispose of the resources.
*/
dispose(): void;
/**
* Gets the cell attachments.
*
* @returns The cell attachments.
*/
getAttachments(): nbformat.IAttachments | undefined;
/**
* Sets the cell attachments
*
* @param attachments: The cell attachments.
*/
setAttachments(attachments: nbformat.IAttachments | undefined): void;
/**
* Get cell id.
*
* @returns Cell id
*/
getId(): string;
/**
* Gets cell's source.
*
* @returns Cell's source.
*/
getSource(): string;
/**
* Sets cell's source.
*
* @param value: New source.
*/
setSource(value: string): void;
/**
* Replace content from `start' to `end` with `value`.
*
* @param start: The start index of the range to replace (inclusive).
*
* @param end: The end index of the range to replace (exclusive).
*
* @param value: New source (optional).
*/
updateSource(start: number, end: number, value?: string): void;
/**
* The type of the cell.
*/
get cell_type(): any;
/**
* Returns the metadata associated with the notebook.
*
* @returns Notebook's metadata.
*/
getMetadata(): Partial<Metadata>;
/**
* Sets the metadata associated with the notebook.
*
* @param metadata: Notebook's metadata.
*/
setMetadata(value: Partial<Metadata>): void;
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IBaseCell;
isDisposed: boolean;
ymodel: Y.Map<any>;
private _undoManager;
private _changed;
private _prevSourceLength;
}
export declare class YCodeCell extends YBaseCell<models.ISharedBaseCellMetadata> implements models.ISharedCodeCell {
/**
* The type of the cell.
*/
get cell_type(): 'code';
/**
* The code cell's prompt number. Will be null if the cell has not been run.
*/
get execution_count(): number | null;
/**
* The code cell's prompt number. Will be null if the cell has not been run.
*/
set execution_count(count: number | null);
/**
* Execution, display, or stream outputs.
*/
getOutputs(): Array<nbformat.IOutput>;
/**
* Replace all outputs.
*/
setOutputs(outputs: Array<nbformat.IOutput>): void;
/**
* Replace content from `start' to `end` with `outputs`.
*
* @param start: The start index of the range to replace (inclusive).
*
* @param end: The end index of the range to replace (exclusive).
*
* @param outputs: New outputs (optional).
*/
updateOutputs(start: number, end: number, outputs?: Array<nbformat.IOutput>): void;
/**
* Create a new YCodeCell that can be inserted into a YNotebook
*/
static create(id?: string): YCodeCell;
/**
* Create a new YCodeCell that works standalone. It cannot be
* inserted into a YNotebook because the Yjs model is already
* attached to an anonymous Y.Doc instance.
*/
static createStandalone(id?: string): YCodeCell;
/**
* Create a new YCodeCell that can be inserted into a YNotebook
*
* @todo clone should only be available in the specific implementations i.e. ISharedCodeCell
*/
clone(): YCodeCell;
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.ICodeCell;
}
export declare class YRawCell extends YBaseCell<models.ISharedBaseCellMetadata> implements models.ISharedRawCell {
/**
* Create a new YRawCell that can be inserted into a YNotebook
*/
static create(id?: string): YRawCell;
/**
* Create a new YRawCell that works standalone. It cannot be
* inserted into a YNotebook because the Yjs model is already
* attached to an anonymous Y.Doc instance.
*/
static createStandalone(id?: string): YRawCell;
/**
* String identifying the type of cell.
*/
get cell_type(): 'raw';
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IRawCell;
}
export declare class YMarkdownCell extends YBaseCell<models.ISharedBaseCellMetadata> implements models.ISharedMarkdownCell {
/**
* Create a new YMarkdownCell that can be inserted into a YNotebook
*/
static create(id?: string): YMarkdownCell;
/**
* Create a new YMarkdownCell that works standalone. It cannot be
* inserted into a YNotebook because the Yjs model is already
* attached to an anonymous Y.Doc instance.
*/
static createStandalone(id?: string): YMarkdownCell;
/**
* String identifying the type of cell.
*/
get cell_type(): 'markdown';
/**
* Serialize the model to JSON.
*/
toJSON(): nbformat.IMarkdownCell;
}
export default YNotebook; | the_stack |
import * as fs from "fs";
import * as stream from "stream";
import * as readline from "readline";
import * as path from "path";
import * as child_process from "child_process";
import { transports } from "electron-log";
import { app } from "electron";
import { sync } from "read-chunk";
import { Server } from "@server/index";
import { escapeDoubleQuote, concatUint8Arrays, parseMetadataString } from "@server/helpers/utils";
import { Attachment } from "@server/databases/imessage/entity/Attachment";
import { startMessages } from "./scripts";
import {
AudioMetadata,
AudioMetadataKeys,
MetadataDataTypes,
MetadataKeyMap,
VideoMetadataKeys,
VideoMetadata,
ImageMetadata,
ImageMetadataKeys
} from "./types";
// Directory modifiers based on the environment
let subdir = "";
let moddir = "app.asar.unpacked";
let appPath = __dirname.replace("/app.asar/dist", "");
if (process.env.NODE_ENV !== "production") {
appPath = __dirname.replace("/dist", "");
subdir = "bluebubbles-server";
moddir = "";
}
/**
* The class used to handle all communications to the App's "filesystem".
* The filesystem is the directory dedicated to the app-specific files
*/
export class FileSystem {
public static baseDir = path.join(app.getPath("userData"), subdir);
public static attachmentsDir = path.join(FileSystem.baseDir, "Attachments");
public static attachmentCacheDir = path.join(FileSystem.baseDir, "Attachments", "Cached");
public static certsDir = path.join(FileSystem.baseDir, "Certs");
public static themesDir = path.join(FileSystem.baseDir, "Themes");
public static settingsDir = path.join(FileSystem.baseDir, "Settings");
public static contactsDir = path.join(FileSystem.baseDir, "Contacts");
public static convertDir = path.join(FileSystem.baseDir, "Convert");
public static fcmDir = path.join(FileSystem.baseDir, "FCM");
public static modules = path.join(appPath, moddir, "node_modules");
public static resources = path.join(appPath, "appResources");
public static addressBookFile = `${FileSystem.contactsDir}/AddressBook.vcf`;
public static contactsFile = `${FileSystem.contactsDir}/contacts.vcf`;
/**
* Sets up all required directories and then, writes the scripts
* to the scripts directory
*/
static async setup(): Promise<void> {
FileSystem.setupDirectories();
}
/**
* Creates required directories
*/
static setupDirectories(): void {
if (!fs.existsSync(FileSystem.baseDir)) fs.mkdirSync(FileSystem.baseDir);
if (!fs.existsSync(FileSystem.attachmentsDir)) fs.mkdirSync(FileSystem.attachmentsDir);
if (!fs.existsSync(FileSystem.attachmentCacheDir)) fs.mkdirSync(FileSystem.attachmentCacheDir);
if (!fs.existsSync(FileSystem.convertDir)) fs.mkdirSync(FileSystem.convertDir);
if (!fs.existsSync(FileSystem.contactsDir)) fs.mkdirSync(FileSystem.contactsDir);
if (!fs.existsSync(FileSystem.fcmDir)) fs.mkdirSync(FileSystem.fcmDir);
if (!fs.existsSync(FileSystem.certsDir)) fs.mkdirSync(FileSystem.certsDir);
if (!fs.existsSync(FileSystem.themesDir)) fs.mkdirSync(FileSystem.themesDir);
if (!fs.existsSync(FileSystem.settingsDir)) fs.mkdirSync(FileSystem.settingsDir);
}
static cachedAttachmentPath(attachment: Attachment, name: string) {
return path.join(FileSystem.attachmentCacheDir, attachment.guid, name);
}
static cachedAttachmentExists(attachment: Attachment, name: string) {
const basePath = this.cachedAttachmentPath(attachment, name);
return fs.existsSync(basePath);
}
static saveCachedAttachment(attachment: Attachment, name: string, data: Buffer) {
const basePath = path.join(FileSystem.attachmentCacheDir, attachment.guid);
if (!fs.existsSync(basePath)) {
fs.mkdirSync(basePath, { recursive: true });
}
fs.writeFileSync(path.join(basePath, name), data);
}
/**
* Saves an attachment
*
* @param name Name for the attachment
* @param buffer The attachment bytes (buffer)
*/
static saveAttachment(name: string, buffer: Uint8Array): void {
fs.writeFileSync(path.join(FileSystem.attachmentsDir, name), buffer);
}
/**
* Saves an attachment by chunk
*
* @param guid Unique identifier for the attachment
* @param chunkNumber The index of the chunk (for ordering/reassembling)
* @param buffer The attachment chunk bytes (buffer)
*/
static saveAttachmentChunk(guid: string, chunkNumber: number, buffer: Uint8Array): void {
const parent = path.join(FileSystem.attachmentsDir, guid);
if (!fs.existsSync(parent)) fs.mkdirSync(parent);
fs.writeFileSync(path.join(parent, `${chunkNumber}.chunk`), buffer);
}
static getLogs({ count = 100 }): Promise<string> {
const fPath = transports.file.getFile().path;
return FileSystem.readLastLines({
filePath: fPath,
count
});
}
private static readLastLines({ filePath, count = 100 }: { filePath: string; count?: number }): Promise<string> {
return FileSystem.execShellCommand(`tail -n ${count} ${filePath}`);
}
/**
* Removes a chunk directory
*
* @param guid Unique identifier for the attachment
*/
static deleteChunks(guid: string): void {
const dir = path.join(FileSystem.attachmentsDir, guid);
if (fs.existsSync(dir)) fs.rmdirSync(dir, { recursive: true });
}
/**
* Builds an attachment by combining all chunks
*
* @param guid Unique identifier for the attachment
*/
static buildAttachmentChunks(guid: string): Uint8Array {
let chunks = new Uint8Array(0);
// Get the files in ascending order
const files = fs.readdirSync(path.join(FileSystem.attachmentsDir, guid));
files.sort((a, b) => Number(a.split(".")[0]) - Number(b.split(".")[0]));
// Read the files and append to chunks
for (const file of files) {
const fileData = fs.readFileSync(path.join(FileSystem.attachmentsDir, guid, file));
chunks = concatUint8Arrays(chunks, Uint8Array.from(fileData));
}
return chunks;
}
/**
* Saves a VCF file
*
* @param vcf The VCF data to save
*/
static saveVCF(vcf: string): void {
// Delete the file if it exists
if (fs.existsSync(FileSystem.contactsFile)) {
fs.unlinkSync(FileSystem.contactsFile);
}
// Writes the file to disk
fs.writeFileSync(FileSystem.contactsFile, vcf);
}
/**
* Gets a VCF file
*/
static getVCF(): string | null {
// Delete the file if it exists
if (!fs.existsSync(FileSystem.contactsFile)) {
return null;
}
// Reads the VCF file
return fs.readFileSync(FileSystem.contactsFile).toString();
}
/**
* Saves the Client FCM JSON file
*
* @param contents The object data for the FCM client
*/
static saveFCMClient(contents: any): void {
fs.writeFileSync(path.join(FileSystem.fcmDir, "client.json"), JSON.stringify(contents));
}
/**
* Saves the Server FCM JSON file
*
* @param contents The object data for the FCM server
*/
static saveFCMServer(contents: any): void {
fs.writeFileSync(path.join(FileSystem.fcmDir, "server.json"), JSON.stringify(contents));
}
/**
* Gets the FCM client data
*
* @returns The parsed FCM client data
*/
static getFCMClient(): any {
const filePath = path.join(FileSystem.fcmDir, "client.json");
if (!fs.existsSync(filePath)) return null;
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
/**
* Gets the FCM server data
*
* @returns The parsed FCM server data
*/
static getFCMServer(): any {
const filePath = path.join(FileSystem.fcmDir, "server.json");
if (!fs.existsSync(filePath)) return null;
return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
/**
* Deletes an attachment from the app's image cache
*
* @param name The name of the attachment to delete
*/
static removeAttachment(name: string): void {
try {
fs.unlinkSync(path.join(FileSystem.attachmentsDir, name));
} catch (ex: any) {
Server().log(`Could not remove attachment: ${ex.message}`, "error");
}
}
static readFileChunk(filePath: string, start: number, chunkSize = 1024): Uint8Array {
// Get the file size
const stats = fs.statSync(filePath);
let fStart = start;
// Make sure the start are not bigger than the size
if (fStart > stats.size) fStart = stats.size;
return Uint8Array.from(sync(filePath, fStart, chunkSize));
}
/**
* Loops over all the files in the attachments directory,
* then call the delete method
*/
static purgeAttachments(): void {
const files = fs.readdirSync(FileSystem.attachmentsDir);
files.forEach(file => {
FileSystem.removeAttachment(file);
});
}
/**
* Asynchronously executes a shell command
*/
static async execShellCommand(cmd: string): Promise<string> {
const { exec } = child_process;
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout, stderr) => {
if (error) {
reject(error);
}
resolve(stdout || stderr);
});
});
}
static async executeAppleScript(cmd: string) {
if (!cmd || cmd.length === 0) return null;
let parts = cmd.split("\n");
parts = parts
.map(i => escapeDoubleQuote(i).trim())
.filter(i => i && i.length > 0)
.map(i => `"${i}"`);
return FileSystem.execShellCommand(`osascript -e ${parts.join(" -e ")}`);
}
/**
* Makes sure that Messages is running
*/
static async startMessages() {
await FileSystem.executeAppleScript(startMessages());
}
static deleteAddressBook() {
try {
fs.unlinkSync(FileSystem.addressBookFile);
} catch (ex: any) {
// Do nothing
}
}
static getRealPath(filePath: string) {
let output = filePath;
if (output[0] === "~") {
output = path.join(process.env.HOME, output.slice(1));
}
return output;
}
static async convertCafToMp3(attachment: Attachment, outputPath: string): Promise<void> {
const oldPath = FileSystem.getRealPath(attachment.filePath);
await FileSystem.execShellCommand(`/usr/bin/afconvert -f m4af -d aac "${oldPath}" "${outputPath}"`);
}
static async getFileMetadata(filePath: string): Promise<{ [key: string]: string }> {
try {
return parseMetadataString(await FileSystem.execShellCommand(`mdls "${FileSystem.getRealPath(filePath)}"`));
} catch (ex: any) {
return null;
}
}
private static async parseMetadata(filePath: string, parserKeyDefinition: MetadataKeyMap): Promise<any> {
const metadata: { [key: string]: string } = await FileSystem.getFileMetadata(filePath);
if (!metadata) return null;
const getNumber = (num: string) => {
if (!num) return null;
try {
return Number.parseFloat(num);
} catch (ex: any) {
return null;
}
};
const meta: { [key: string]: any } = {};
for (const [key, value] of Object.entries(metadata)) {
if (!(key in parserKeyDefinition)) continue;
// Get the types info for the field
const { dataType, metaKey } = parserKeyDefinition[key];
// Parse the item by type
let itemValue: any;
switch (dataType) {
case MetadataDataTypes.Bool:
itemValue = value === "1";
break;
case MetadataDataTypes.Float:
itemValue = getNumber(value);
break;
case MetadataDataTypes.Int:
itemValue = Math.trunc(getNumber(value));
break;
default:
itemValue = value;
break;
}
meta[metaKey] = itemValue;
}
return meta;
}
static async getAudioMetadata(audioPath: string): Promise<AudioMetadata> {
const meta = await FileSystem.parseMetadata(audioPath, AudioMetadataKeys);
return meta as AudioMetadata;
}
static async getVideoMetadata(videoPath: string): Promise<VideoMetadata> {
const meta = await FileSystem.parseMetadata(videoPath, VideoMetadataKeys);
return meta as VideoMetadata;
}
static async getImageMetadata(imagePath: string): Promise<ImageMetadata> {
const meta = await FileSystem.parseMetadata(imagePath, ImageMetadataKeys);
return meta as ImageMetadata;
}
} | the_stack |
import {zip} from 'fp-ts/es6/Array'
import {Container} from './container'
const PICO_CLONE_ID_KEY = 'picocloneid'
const id = () =>
Math.random()
.toString(32)
.substring(2)
function isHTMLElement(
element: Element
): element is HTMLElement {
return element instanceof HTMLElement
}
function isHTMLOrSVGElement(
element: Element
): element is HTMLElement | SVGElement {
return (
element instanceof HTMLElement ||
element instanceof SVGElement
)
}
const defaultNaN = (defaultTo: number) => (value: number) =>
isNaN(value) ? defaultTo : value
// Even though this function uses `querySelectorAll('*')` it's relatively
// fast - on a page with 25k nodes (youtube) it executes in 10-15ms
const getScrolledElements = (
$target: HTMLElement
): HTMLElement[] =>
Array.from($target.querySelectorAll('*'))
.filter(
$el => $el.scrollTop !== 0 || $el.scrollLeft !== 0
)
.filter(isHTMLElement)
const attachCloneID = ($target: HTMLElement) => {
for (const $element of [
...$target.querySelectorAll('input'),
...$target.querySelectorAll('textarea'),
...$target.querySelectorAll('canvas'),
...getScrolledElements($target)
]) {
$element.dataset[PICO_CLONE_ID_KEY] = id()
}
}
const removeCloneID = ($target: HTMLElement) => {
for (const $element of $target.querySelectorAll(
`[data-${PICO_CLONE_ID_KEY}]`
)) {
if (!($element instanceof HTMLElement)) {
console.warn(
'Element that had a pico clone id attached was not an HTMLElement during cleanup',
$element
)
continue
}
$element.removeAttribute(`data-${PICO_CLONE_ID_KEY}`)
}
}
const cloneCanvases = (container: Container) => {
for (const $clonedCanvas of container.tree.html.querySelectorAll(
'canvas'
)) {
const cloneId = $clonedCanvas.dataset[PICO_CLONE_ID_KEY]
if (cloneId === undefined) {
console.warn(
'Failed to get clone id from cloned canvas',
$clonedCanvas
)
continue
}
const $originalCanvas = Array.from(
container.parentWindow.document.querySelectorAll(
'canvas'
)
).find(
$original =>
$original.dataset[PICO_CLONE_ID_KEY] === cloneId
)
if ($originalCanvas === undefined) {
console.warn(
'Failed to find original canvas for cloned canvas',
$clonedCanvas
)
continue
}
const $replacementImg = container.parentWindow.document.createElement(
'img'
)
// Since we're changing the element's name the "canvas"
// will be untargetable by css, therefore we need to
// clone all the style properties over manually in this
// particular case.
$replacementImg.style.cssText = container.parentWindow.window.getComputedStyle(
$originalCanvas
).cssText
$replacementImg.src = $originalCanvas.toDataURL()
const parent = $clonedCanvas.parentNode
if (!parent) {
console.warn(
'Failed to get parent of node',
$clonedCanvas
)
continue
}
parent.replaceChild($replacementImg, $clonedCanvas)
}
return container
}
// Input values set by JS don't get copied when performing a recursive
// `Node.cloneNode`, we need to set the attributes ourselves.
const cloneInputs = (container: Container) => {
for (const $clonedInputOrTextarea of [
...container.tree.html.querySelectorAll('input'),
...container.tree.html.querySelectorAll('textarea')
]) {
const cloneId =
$clonedInputOrTextarea.dataset[PICO_CLONE_ID_KEY]
if (cloneId === undefined) {
console.warn(
'Failed to get clone id from cloned input or textarea',
$clonedInputOrTextarea
)
continue
}
const $originalInputOrTextarea = [
...container.parentWindow.document.querySelectorAll(
'input'
),
...container.parentWindow.document.querySelectorAll(
'textarea'
)
].find(
$original =>
$original.dataset[PICO_CLONE_ID_KEY] === cloneId
)
if ($originalInputOrTextarea === undefined) {
console.warn(
'Failed to find original input or textarea for cloned input or textarea',
$clonedInputOrTextarea
)
continue
}
if (
$originalInputOrTextarea instanceof
HTMLInputElement &&
$clonedInputOrTextarea instanceof HTMLInputElement
) {
if (
($clonedInputOrTextarea.type === 'checkbox' ||
$clonedInputOrTextarea.type === 'radio') &&
$originalInputOrTextarea.checked
) {
// <input type="checkbox | radio" />
$clonedInputOrTextarea.setAttribute(
'checked',
'checked'
)
} else if (
// <input type="number | text | range" />
['number', 'text', 'range'].indexOf(
$clonedInputOrTextarea.type
) !== -1
) {
$clonedInputOrTextarea.setAttribute(
'value',
$originalInputOrTextarea.value
)
}
} else if (
$originalInputOrTextarea instanceof
HTMLTextAreaElement &&
$clonedInputOrTextarea instanceof HTMLTextAreaElement
) {
// <textarea>
const contents = container.parentWindow.document.createTextNode(
$originalInputOrTextarea.value
)
$clonedInputOrTextarea.innerHTML = ''
$clonedInputOrTextarea.appendChild(contents)
}
}
return container
}
const cloneElementScroll = (
container: Container,
$clone: HTMLElement
) => {
const cloneId = $clone.dataset[PICO_CLONE_ID_KEY]
if (cloneId === undefined) {
console.warn(
'Failed to get clone id from cloned scrolled element',
$clone
)
return
}
const $original = container.parentWindow.document.querySelector(
`[data-${PICO_CLONE_ID_KEY} = "${cloneId}"]`
)
if (!($original instanceof HTMLElement)) {
console.warn(
'Failed to find original element for scrolled element',
$clone
)
return
}
$clone.style.position =
$clone.style.position === 'absolute'
? 'absolute'
: 'relative'
$clone.style.overflow = 'hidden'
$clone.style.width = $original.offsetWidth + 'px'
$clone.style.height = $original.offsetHeight + 'px'
const $clonedChildren = Array.from($clone.children).filter(
isHTMLOrSVGElement
)
const $originalChildren = Array.from(
$original.children
).filter(isHTMLOrSVGElement)
if ($clonedChildren.length !== $originalChildren.length) {
console.warn(
'Scrolled element has a different amount of children ' +
'than its clone, skipping scroll emulation',
$original
)
return
}
const $$zippedChildren = zip(
$originalChildren,
$clonedChildren
)
let scrollTopRemaining = $original.scrollTop
let scrollLeftRemaining = $original.scrollLeft
let lastChild
for (const [
$originalChild,
$clonedChild
] of $$zippedChildren) {
const originalChildStyles = container.parentWindow.window.getComputedStyle(
$originalChild
)
// Handle absolutely positioned children
if (
container.parentWindow.window.getComputedStyle(
$original
).position === 'relative' &&
originalChildStyles.position === 'absolute'
) {
$clonedChild.style.top =
defaultNaN(0)(
parseInt(originalChildStyles.top)
) -
$original.scrollTop +
'px'
$clonedChild.style.left =
defaultNaN(0)(
parseInt(originalChildStyles.left)
) -
$original.scrollLeft +
'px'
// Since all relative children are now absolute, increment z-index
// of all previously absolute children by 1 so that they're
// still visible over
$clonedChild.style.zIndex = (
defaultNaN(0)(
parseInt(originalChildStyles.zIndex)
) + 1
).toString()
continue
}
$clonedChild.style.position = 'absolute'
$clonedChild.style.width = originalChildStyles.width
$clonedChild.style.height = originalChildStyles.height
if (typeof lastChild !== 'undefined') {
const lastChildBoundingRect = lastChild.getBoundingClientRect()
scrollTopRemaining -=
$originalChild.getBoundingClientRect().top -
lastChildBoundingRect.top
scrollLeftRemaining -=
$originalChild.getBoundingClientRect().left -
lastChildBoundingRect.left
}
$clonedChild.style.top = -scrollTopRemaining + 'px'
$clonedChild.style.left = -scrollLeftRemaining + 'px'
lastChild = $originalChild
// const cloneChildBoundingRect = $originalChild.getBoundingClientRect()
}
}
const cloneScrolls = (container: Container) => {
for (const $original of getScrolledElements(
container.parentWindow.html
)) {
const cloneId = $original.dataset[PICO_CLONE_ID_KEY]
if (cloneId === undefined) {
console.warn(
'Failed to get clone id from scrolled element',
$original
)
continue
}
const $cloned = container.tree.html.querySelector(
`[data-${PICO_CLONE_ID_KEY} = "${cloneId}"]`
)
if (!($cloned instanceof HTMLElement)) {
console.warn(
'Failed to find cloned element for original scrolled element',
$original
)
continue
}
cloneElementScroll(container, $cloned)
}
// The above code doesn't process <html> scroll since it usually gets
// special treatment in browsers, a simple `translate` will do
container.tree.html.style.transform += ` translate(-${container.parentWindow.html.scrollLeft}px, -${container.parentWindow.html.scrollTop}px)`
return container
}
const removeNodesMatchingSelectors = (selectors: string[]) => (
$node: Node
) => {
if ($node instanceof Element) {
selectors.forEach(selector => {
for (const $child of $node.querySelectorAll(
selector
)) {
$child.remove()
}
})
}
}
// (ugly)
export const cloneBody = (ignoredSelectors: string[]) => (
container: Container
): Container => {
attachCloneID(container.parentWindow.html)
container.tree.html.className =
container.parentWindow.html.className
container.tree.html.style.cssText =
container.parentWindow.html.style.cssText
// Fix for `rem` units
container.tree.svg.style.fontSize = container.parentWindow.window.getComputedStyle(
container.parentWindow.html
).fontSize
const $clonedBody = container.parentWindow.body.cloneNode(
true
)
removeNodesMatchingSelectors(ignoredSelectors)($clonedBody)
container.tree.html.appendChild($clonedBody)
cloneInputs(container)
cloneCanvases(container)
cloneScrolls(container)
if ($clonedBody instanceof HTMLBodyElement) {
container.tree.html.style.margin = '0'
}
removeCloneID(container.parentWindow.html)
return container
} | the_stack |
import { BFT } from '@liskhq/lisk-bft';
import { codec } from '@liskhq/lisk-codec';
import { KVStore } from '@liskhq/lisk-db';
import { TransactionPool } from '@liskhq/lisk-transaction-pool';
import { when } from 'jest-when';
import { InMemoryChannel } from '../../../src/controller/channels';
import { BaseModule, DPoSModule, TokenModule } from '../../../src/modules';
import { Forger, HighFeeForgingStrategy } from '../../../src/node/forger';
import { Network } from '../../../src/node/network';
import { Node } from '../../../src/node/node';
import { Processor } from '../../../src/node/processor';
import { Synchronizer } from '../../../src/node/synchronizer/synchronizer';
import { cacheConfig, nodeOptions } from '../../fixtures/node';
import { createMockBus } from '../../utils/channel';
import { createGenesisBlock } from '../../../src/testing/create_genesis_block';
jest.mock('@liskhq/lisk-db');
jest.mock('fs-extra');
describe('Node', () => {
let node: Node;
let subscribedEvents: any;
const stubs: any = {};
let blockchainDB: KVStore;
let forgerDB: KVStore;
let nodeDB: KVStore;
let tokenModule: BaseModule;
let dposModule: BaseModule;
const { genesisBlock, genesisBlockJSON } = createGenesisBlock({
modules: [TokenModule, DPoSModule],
});
const lastBlock = genesisBlock;
beforeEach(() => {
// Arrange
subscribedEvents = {};
jest.spyOn(Processor.prototype, 'init').mockResolvedValue(undefined);
jest.spyOn(Synchronizer.prototype, 'init').mockResolvedValue(undefined);
blockchainDB = new KVStore('blockchain.db');
forgerDB = new KVStore('forger.db');
nodeDB = new KVStore('node.db');
tokenModule = new TokenModule(nodeOptions.genesisConfig);
dposModule = new DPoSModule(nodeOptions.genesisConfig);
/* Arranging Stubs start */
stubs.logger = {
trace: jest.fn(),
error: jest.fn(),
debug: jest.fn(),
fatal: jest.fn(),
info: jest.fn(),
cleanup: jest.fn(),
};
stubs.forgerDB = {
get: jest.fn(),
put: jest.fn(),
close: jest.fn(),
};
stubs.channel = {
invoke: jest.fn(),
subscribe: jest.fn((event, cb) => {
subscribedEvents[event] = cb;
}),
once: jest.fn(),
registerToBus: jest.fn(),
};
when(stubs.channel.invoke)
.calledWith('app:getComponentConfig', 'cache')
.mockResolvedValue(cacheConfig as never);
node = new Node({
options: nodeOptions,
});
codec.clearCache();
node.registerModule(tokenModule);
// Because the genesis block contains a delegate, so we must register dpos module to process it
node.registerModule(dposModule);
});
describe('constructor', () => {
it('should throw error when waitThreshold is greater than blockTime', () => {
const invalidChainOptions = {
...nodeOptions,
forging: {
waitThreshold: 5,
},
genesisConfig: {
...nodeOptions.genesisConfig,
blockTime: 4,
},
};
expect(
() =>
new Node({
options: invalidChainOptions as any,
}),
).toThrow('forging.waitThreshold=5 is greater or equal to genesisConfig.blockTime=4');
});
it('should throw error when waitThreshold is same as blockTime', () => {
const invalidChainOptions = {
...nodeOptions,
forging: {
waitThreshold: 5,
},
genesisConfig: {
...nodeOptions.genesisConfig,
blockTime: 5,
},
};
expect(
() =>
new Node({
options: invalidChainOptions as any,
}),
).toThrow('forging.waitThreshold=5 is greater or equal to genesisConfig.blockTime=5');
});
});
describe('init', () => {
beforeEach(async () => {
jest.spyOn(Network.prototype, 'applyNodeInfo');
jest.spyOn(TransactionPool.prototype, 'start');
jest.spyOn(node as any, '_startForging');
jest.spyOn(Processor.prototype, 'register');
jest.spyOn(InMemoryChannel.prototype, 'registerToBus');
jest.spyOn(tokenModule, 'init');
// Act
await node.init({
genesisBlockJSON,
dataPath: `/tmp/.lisk/${Date.now()}`,
bus: createMockBus() as any,
channel: stubs.channel,
blockchainDB,
forgerDB,
nodeDB,
logger: stubs.logger,
});
});
it('should initialize scope object with valid structure', () => {
expect(node).toHaveProperty('_options');
expect(node).toHaveProperty('_channel');
expect(node).toHaveProperty('_networkIdentifier');
});
describe('_initModules', () => {
it('should initialize bft module', () => {
expect(node['_bft']).toBeInstanceOf(BFT);
});
it('should initialize forger module', () => {
expect(node['_forger']).toBeInstanceOf(Forger);
});
it('should initialize forger module with high fee strategy', () => {
expect(node['_forger']['_forgingStrategy']).toBeInstanceOf(HighFeeForgingStrategy);
});
});
describe('on-chain modules', () => {
it('should register custom module with processor', () => {
expect(node['_processor'].register).toHaveBeenCalledTimes(2);
expect(node['_processor'].register).toHaveBeenCalledWith(tokenModule);
expect(node['_processor'].register).toHaveBeenCalledWith(dposModule);
});
it('should register in-memory channel to bus', () => {
// one time for each module
expect(InMemoryChannel.prototype.registerToBus).toHaveBeenCalledTimes(2);
expect(InMemoryChannel.prototype.registerToBus).toHaveBeenCalledWith(node['_bus']);
});
it('should init custom module', () => {
expect(tokenModule.init).toHaveBeenCalledTimes(1);
expect(tokenModule.init).toHaveBeenCalledWith(
expect.objectContaining({
channel: { publish: expect.any(Function) },
dataAccess: {
getChainState: expect.any(Function),
getAccountByAddress: expect.any(Function),
getLastBlockHeader: expect.any(Function),
},
logger: stubs.logger,
}),
);
});
});
it('should invoke Processor.init', () => {
expect(node['_processor'].init).toHaveBeenCalledTimes(1);
});
it('should call "applyNodeInfo" with correct params', () => {
// Assert
return expect(node['_networkModule'].applyNodeInfo).toHaveBeenCalledWith({
height: lastBlock.header.height,
blockVersion: lastBlock.header.version,
maxHeightPrevoted: 0,
lastBlockID: lastBlock.header.id,
});
});
it('should start transaction pool', () => {
return expect(node['_transactionPool'].start).toHaveBeenCalled();
});
it('should start forging', () => {
return expect(node['_startForging']).toHaveBeenCalled();
});
});
describe('getSchema', () => {
it('should return all schema with currently registered modules', () => {
const schema = node.getSchema();
expect(Object.keys(schema.account.properties)).toInclude('token');
expect(Object.keys(schema.blockHeadersAssets).length).toBeGreaterThanOrEqual(2);
expect(schema.block).not.toBeUndefined();
expect(schema.blockHeader).not.toBeUndefined();
expect(schema.transaction).not.toBeUndefined();
});
});
describe('getRegisteredModules', () => {
it('should return currently registered modules information', () => {
const registeredModules = node.getRegisteredModules();
expect(registeredModules).toHaveLength(2);
expect(registeredModules[0].name).toEqual('token');
expect(registeredModules[1].name).toEqual('dpos');
});
});
describe('cleanup', () => {
beforeEach(async () => {
// Arrange
await node.init({
genesisBlockJSON,
dataPath: `/tmp/.lisk/${Date.now()}`,
bus: createMockBus() as any,
channel: stubs.channel,
blockchainDB,
forgerDB,
nodeDB,
logger: stubs.logger,
});
jest.spyOn(node['_transactionPool'], 'stop');
jest.spyOn(node['_processor'], 'stop');
jest.spyOn(node['_synchronizer'], 'stop');
jest.spyOn(node['_networkModule'], 'cleanup');
});
it('should be an async function', () => {
// Assert
return expect(node.cleanup.constructor.name).toEqual('AsyncFunction');
});
it('should call stop for running tasks', async () => {
await node.cleanup();
// Assert
expect(node['_transactionPool'].stop).toHaveBeenCalled();
expect(node['_synchronizer'].stop).toHaveBeenCalled();
expect(node['_processor'].stop).toHaveBeenCalled();
expect(node['_networkModule'].cleanup).toHaveBeenCalled();
});
});
describe('#_forgingTask', () => {
beforeEach(async () => {
await node.init({
genesisBlockJSON,
dataPath: `/tmp/.lisk/${Date.now()}`,
bus: createMockBus() as any,
channel: stubs.channel,
blockchainDB,
forgerDB,
nodeDB,
logger: stubs.logger,
});
jest.spyOn(node['_forger'], 'delegatesEnabled').mockReturnValue(true);
jest.spyOn(node['_forger'], 'forge');
jest.spyOn(node['_synchronizer'], 'isActive', 'get').mockReturnValue(false);
});
it('should halt if no delegates are enabled', async () => {
// Arrange
(node['_forger'].delegatesEnabled as jest.Mock).mockReturnValue(false);
// Act
await node['_forgingTask']();
// Assert
expect(stubs.logger.trace).toHaveBeenNthCalledWith(1, 'No delegates are enabled');
expect(node['_forger'].forge).not.toHaveBeenCalled();
});
it('should halt if the client is not ready to forge (is syncing)', async () => {
// Arrange
jest.spyOn(node['_synchronizer'], 'isActive', 'get').mockReturnValue(true);
// Act
await node['_forgingTask']();
// Assert
expect(stubs.logger.debug).toHaveBeenNthCalledWith(1, 'Client not ready to forge');
expect(node['_forger'].forge).not.toHaveBeenCalled();
});
it('should execute forger.forge otherwise', async () => {
await node['_forgingTask']();
expect(node['_forger'].forge).toHaveBeenCalled();
});
});
describe('#_startForging', () => {
beforeEach(async () => {
await node.init({
genesisBlockJSON,
dataPath: `/tmp/.lisk/${Date.now()}`,
bus: createMockBus() as any,
channel: stubs.channel,
blockchainDB,
forgerDB,
nodeDB,
logger: stubs.logger,
});
jest.spyOn(node['_forger'], 'loadDelegates');
});
it('should load the delegates', async () => {
await node['_startForging']();
expect(node['_forger'].loadDelegates).toHaveBeenCalled();
});
it('should register a task in Jobs Queue named "nextForge" with a designated interval', async () => {
await node['_startForging']();
expect(node['_forgingJob']).not.toBeUndefined();
});
});
}); | the_stack |
import {fontStyles} from '../../styles/gr-font-styles';
import {customElement, property} from 'lit/decorators';
import './gr-checks-action';
import {CheckRun} from '../../services/checks/checks-model';
import {
AttemptDetail,
iconFor,
runActions,
worstCategory,
} from '../../services/checks/checks-util';
import {durationString, fromNow} from '../../utils/date-util';
import {RunStatus} from '../../api/checks';
import {ordinal} from '../../utils/string-util';
import {HovercardMixin} from '../../mixins/hovercard-mixin/hovercard-mixin';
import {css, html, LitElement} from 'lit';
import {checksStyles} from './gr-checks-styles';
// This avoids JSC_DYNAMIC_EXTENDS_WITHOUT_JSDOC closure compiler error.
const base = HovercardMixin(LitElement);
@customElement('gr-hovercard-run')
export class GrHovercardRun extends base {
@property({type: Object})
run?: CheckRun;
static override get styles() {
return [
fontStyles,
checksStyles,
base.styles || [],
css`
#container {
min-width: 356px;
max-width: 356px;
padding: var(--spacing-xl) 0 var(--spacing-m) 0;
}
.row {
display: flex;
margin-top: var(--spacing-s);
}
.attempts.row {
flex-wrap: wrap;
}
.chipRow {
display: flex;
margin-top: var(--spacing-s);
}
.chip {
background: var(--gray-background);
color: var(--gray-foreground);
border-radius: 20px;
padding: var(--spacing-xs) var(--spacing-m) var(--spacing-xs)
var(--spacing-s);
}
.title {
color: var(--deemphasized-text-color);
margin-right: var(--spacing-m);
}
div.section {
margin: 0 var(--spacing-xl) var(--spacing-m) var(--spacing-xl);
display: flex;
}
div.sectionIcon {
flex: 0 0 30px;
}
div.chip iron-icon {
width: 16px;
height: 16px;
/* Positioning of a 16px icon in the middle of a 20px line. */
position: relative;
top: 2px;
}
div.sectionIcon iron-icon {
position: relative;
top: 2px;
width: 20px;
height: 20px;
}
div.sectionIcon iron-icon.small {
position: relative;
top: 6px;
width: 16px;
height: 16px;
}
div.sectionContent iron-icon.link {
color: var(--link-color);
}
div.sectionContent .attemptIcon iron-icon,
div.sectionContent iron-icon.small {
width: 16px;
height: 16px;
margin-right: var(--spacing-s);
/* Positioning of a 16px icon in the middle of a 20px line. */
position: relative;
top: 2px;
}
div.sectionContent .attemptIcon iron-icon {
margin-right: 0;
}
.attemptIcon,
.attemptNumber {
margin-right: var(--spacing-s);
color: var(--deemphasized-text-color);
text-align: center;
width: 24px;
font-size: var(--font-size-small);
}
div.action {
border-top: 1px solid var(--border-color);
margin-top: var(--spacing-m);
padding: var(--spacing-m) var(--spacing-xl) 0;
}
`,
];
}
override render() {
if (!this.run) return '';
const icon = this.computeIcon();
return html`
<div id="container" role="tooltip" tabindex="-1">
<div class="section">
<div
?hidden="${!this.run || this.run.status === RunStatus.RUNNABLE}"
class="chipRow"
>
<div class="chip">
<iron-icon icon="gr-icons:${this.computeChipIcon()}"></iron-icon>
<span>${this.run.status}</span>
</div>
</div>
</div>
<div class="section">
<div class="sectionIcon" ?hidden="${icon.length === 0}">
<iron-icon class="${icon}" icon="gr-icons:${icon}"></iron-icon>
</div>
<div class="sectionContent">
<h3 class="name heading-3">
<span>${this.run.checkName}</span>
</h3>
</div>
</div>
${this.renderStatusSection()} ${this.renderAttemptSection()}
${this.renderTimestampSection()} ${this.renderDescriptionSection()}
${this.renderActions()}
</div>
`;
}
private renderStatusSection() {
if (!this.run || (!this.run.statusLink && !this.run.statusDescription))
return;
return html`
<div class="section">
<div class="sectionIcon">
<iron-icon class="small" icon="gr-icons:info-outline"></iron-icon>
</div>
<div class="sectionContent">
${this.run.statusLink
? html` <div class="row">
<div class="title">Status</div>
<div>
<a href="${this.run.statusLink}" target="_blank"
><iron-icon
aria-label="external link to check status"
class="small link"
icon="gr-icons:launch"
></iron-icon
>${this.computeHostName(this.run.statusLink)}
</a>
</div>
</div>`
: ''}
${this.run.statusDescription
? html` <div class="row">
<div class="title">Message</div>
<div>${this.run.statusDescription}</div>
</div>`
: ''}
</div>
</div>
`;
}
private renderAttemptSection() {
if (this.hideAttempts()) return;
const attempts = this.computeAttempts();
return html`
<div class="section">
<div class="sectionIcon">
<iron-icon class="small" icon="gr-icons:arrow-forward"></iron-icon>
</div>
<div class="sectionContent">
<div class="attempts row">
<div class="title">Attempt</div>
${attempts.map(a => this.renderAttempt(a))}
</div>
</div>
</div>
`;
}
private renderAttempt(attempt: AttemptDetail) {
return html`
<div>
<div class="attemptIcon">
<iron-icon
class="${attempt.icon}"
icon="gr-icons:${attempt.icon}"
></iron-icon>
</div>
<div class="attemptNumber">${ordinal(attempt.attempt)}</div>
</div>
`;
}
private renderTimestampSection() {
if (
!this.run ||
(!this.run.startedTimestamp &&
!this.run.scheduledTimestamp &&
!this.run.finishedTimestamp)
)
return;
return html`
<div class="section">
<div class="sectionIcon">
<iron-icon class="small" icon="gr-icons:schedule"></iron-icon>
</div>
<div class="sectionContent">
<div ?hidden="${this.hideScheduled()}" class="row">
<div class="title">Scheduled</div>
<div>${this.computeDuration(this.run.scheduledTimestamp)}</div>
</div>
<div ?hidden="${!this.run.startedTimestamp}" class="row">
<div class="title">Started</div>
<div>${this.computeDuration(this.run.startedTimestamp)}</div>
</div>
<div ?hidden="${!this.run.finishedTimestamp}" class="row">
<div class="title">Ended</div>
<div>${this.computeDuration(this.run.finishedTimestamp)}</div>
</div>
<div ?hidden="${this.hideCompletion()}" class="row">
<div class="title">Completion</div>
<div>${this.computeCompletionDuration()}</div>
</div>
</div>
</div>
`;
}
private renderDescriptionSection() {
if (!this.run || (!this.run.checkLink && !this.run.checkDescription))
return;
return html`
<div class="section">
<div class="sectionIcon">
<iron-icon class="small" icon="gr-icons:link"></iron-icon>
</div>
<div class="sectionContent">
${this.run.checkDescription
? html` <div class="row">
<div class="title">Description</div>
<div>${this.run.checkDescription}</div>
</div>`
: ''}
${this.run.checkLink
? html` <div class="row">
<div class="title">Documentation</div>
<div>
<a href="${this.run.checkLink}" target="_blank"
><iron-icon
aria-label="external link to check documentation"
class="small link"
icon="gr-icons:launch"
></iron-icon
>${this.computeHostName(this.run.checkLink)}
</a>
</div>
</div>`
: ''}
</div>
</div>
`;
}
private renderActions() {
const actions = runActions(this.run);
return actions.map(
action =>
html`
<div class="action">
<gr-checks-action
.eventTarget="${this._target}"
.action="${action}"
></gr-checks-action>
</div>
`
);
}
computeIcon() {
if (!this.run) return '';
const category = worstCategory(this.run);
if (category) return iconFor(category);
return this.run.status === RunStatus.COMPLETED
? iconFor(RunStatus.COMPLETED)
: '';
}
computeAttempts(): AttemptDetail[] {
const details = this.run?.attemptDetails ?? [];
const more =
details.length > 7 ? [{icon: 'more-horiz', attempt: undefined}] : [];
return [...more, ...details.slice(-7)];
}
private computeChipIcon() {
if (this.run?.status === RunStatus.COMPLETED) {
return 'check';
}
if (this.run?.status === RunStatus.RUNNING) {
return iconFor(RunStatus.RUNNING);
}
if (this.run?.status === RunStatus.SCHEDULED) {
return iconFor(RunStatus.SCHEDULED);
}
return '';
}
private computeCompletionDuration() {
if (!this.run?.finishedTimestamp || !this.run?.startedTimestamp) return '';
return durationString(
this.run.startedTimestamp,
this.run.finishedTimestamp,
true
);
}
private computeDuration(date?: Date) {
return date ? fromNow(date) : '';
}
private computeHostName(link?: string) {
return link ? new URL(link).hostname : '';
}
private hideAttempts() {
const attemptCount = this.run?.attemptDetails?.length;
return attemptCount === undefined || attemptCount < 2;
}
private hideScheduled() {
return !this.run?.scheduledTimestamp || !!this.run?.startedTimestamp;
}
private hideCompletion() {
return !this.run?.startedTimestamp || !this.run?.finishedTimestamp;
}
}
declare global {
interface HTMLElementTagNameMap {
'gr-hovercard-run': GrHovercardRun;
}
} | the_stack |
import { TasksRunner } from './tasks-runner';
import defaultTaskRunner from './default-tasks-runner';
import { createTasksForProjectToRun, getRunner } from './run-command';
import type { NxJsonConfiguration, ProjectGraph } from '@nrwl/devkit';
import { DependencyType } from '@nrwl/devkit';
describe('createTasksForProjectToRun', () => {
let projectGraph: ProjectGraph;
beforeEach(() => {
projectGraph = {
nodes: {
app1: {
name: 'app1',
type: 'app',
data: {
root: 'app1-root',
files: [],
targets: {
prebuild: {},
build: {},
serve: {},
},
},
},
lib1: {
name: 'lib1',
type: 'lib',
data: {
root: 'lib1-root',
files: [],
targets: {
build: {},
},
},
},
},
dependencies: {
app1: [],
lib1: [],
},
};
});
it('should create the task for the project and target passed', () => {
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'serve',
configuration: undefined,
overrides: {},
},
projectGraph,
null
);
expect(tasks).toEqual([
{
id: 'app1:serve',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'serve',
},
},
]);
});
it('should create the task for multiple projects passed', () => {
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1, projectGraph.nodes.lib1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
null
);
expect(tasks).toEqual([
{
id: 'app1:build',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'build',
},
},
{
id: 'lib1:build',
overrides: {},
projectRoot: 'lib1-root',
target: {
configuration: undefined,
project: 'lib1',
target: 'build',
},
},
]);
});
it('should create the tasks for multiple projects passed with configuration', () => {
projectGraph.nodes.app1.data.targets.build.configurations =
projectGraph.nodes.lib1.data.targets.build.configurations = {
production: {},
};
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1, projectGraph.nodes.lib1],
{
target: 'build',
configuration: 'production',
overrides: {},
},
projectGraph,
null
);
expect(tasks).toEqual([
{
id: 'app1:build:production',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: 'production',
project: 'app1',
target: 'build',
},
},
{
id: 'lib1:build:production',
overrides: {},
projectRoot: 'lib1-root',
target: {
configuration: 'production',
project: 'lib1',
target: 'build',
},
},
]);
});
it('should create the tasks for multiple projects passed with configuration and fallback to default configuration', () => {
projectGraph.nodes.app1.data.targets.build.configurations = {
production: {},
};
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1, projectGraph.nodes.lib1],
{
target: 'build',
configuration: 'production',
overrides: {},
},
projectGraph,
null
);
expect(tasks).toEqual([
{
id: 'app1:build:production',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: 'production',
project: 'app1',
target: 'build',
},
},
{
id: 'lib1:build',
overrides: {},
projectRoot: 'lib1-root',
target: {
project: 'lib1',
target: 'build',
},
},
]);
});
it('should create tasks for self dependencies', () => {
projectGraph.nodes.app1.data.targets.serve.dependsOn = [
{
target: 'build',
projects: 'self',
},
];
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'serve',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toEqual([
{
id: 'app1:build',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'build',
},
},
{
id: 'app1:serve',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'serve',
},
},
]);
});
it('should create tasks for target dependencies', () => {
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'build',
projects: 'dependencies',
},
];
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toEqual([
{
id: 'lib1:build',
overrides: {},
projectRoot: 'lib1-root',
target: {
configuration: undefined,
project: 'lib1',
target: 'build',
},
},
{
id: 'app1:build',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'build',
},
},
]);
});
it('should create tasks for multiple sets of dependencies', () => {
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'prebuild',
projects: 'self',
},
{
target: 'build',
projects: 'dependencies',
},
];
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toEqual([
{
id: 'app1:prebuild',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'prebuild',
},
},
{
id: 'lib1:build',
overrides: {},
projectRoot: 'lib1-root',
target: {
configuration: undefined,
project: 'lib1',
target: 'build',
},
},
{
id: 'app1:build',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'build',
},
},
]);
});
it('should create tasks for multiple sets of dependencies for multiple targets', () => {
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'prebuild',
projects: 'dependencies',
},
{
target: 'build',
projects: 'dependencies',
},
];
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
projectGraph.nodes.lib1.data.targets.prebuild = {};
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toEqual([
{
id: 'lib1:prebuild',
overrides: {},
projectRoot: 'lib1-root',
target: {
configuration: undefined,
project: 'lib1',
target: 'prebuild',
},
},
{
id: 'lib1:build',
overrides: {},
projectRoot: 'lib1-root',
target: {
configuration: undefined,
project: 'lib1',
target: 'build',
},
},
{
id: 'app1:build',
overrides: {},
projectRoot: 'app1-root',
target: {
configuration: undefined,
project: 'app1',
target: 'build',
},
},
]);
});
it('should include dependencies of projects without the same target', () => {
// App 1 depends on builds of its dependencies
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'build',
projects: 'dependencies',
},
];
// App 1 depends on Lib 1
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
// Lib 1 does not have build but depends on Lib 2
delete projectGraph.nodes.lib1.data.targets.build;
projectGraph.dependencies.lib1.push({
type: DependencyType.static,
source: 'lib1',
target: 'lib2',
});
// Lib 2 has a build
projectGraph.nodes.lib2 = {
name: 'lib2',
type: 'lib',
data: {
root: 'lib2-root',
files: [],
targets: {
build: {},
},
},
};
projectGraph.dependencies.lib2 = [];
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toContainEqual({
id: 'app1:build',
target: { project: 'app1', target: 'build' },
projectRoot: 'app1-root',
overrides: {},
});
expect(tasks).toContainEqual({
id: 'lib2:build',
target: { project: 'lib2', target: 'build' },
projectRoot: 'lib2-root',
overrides: {},
});
});
it('should handle circular dependencies between projects', () => {
// App 1 depends on builds of its dependencies
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'build',
projects: 'dependencies',
},
];
// App 1 depends on Lib 1
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
// Lib 1 does not have build but depends on Lib 2
delete projectGraph.nodes.lib1.data.targets.build;
projectGraph.dependencies.lib1.push(
{
type: DependencyType.static,
source: 'lib1',
target: 'app1',
},
{
type: DependencyType.static,
source: 'lib1',
target: 'lib2',
}
);
// Lib 2 has a build
projectGraph.nodes.lib2 = {
name: 'lib2',
type: 'lib',
data: {
root: 'lib2-root',
files: [],
targets: {
build: {},
},
},
};
projectGraph.dependencies.lib2 = [
{
type: DependencyType.static,
source: 'lib2',
target: 'lib1',
},
];
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toContainEqual({
id: 'app1:build',
target: { project: 'app1', target: 'build' },
projectRoot: 'app1-root',
overrides: {},
});
expect(tasks).toContainEqual({
id: 'lib2:build',
target: { project: 'lib2', target: 'build' },
projectRoot: 'lib2-root',
overrides: {},
});
});
it('should handle circular dependencies between projects with no tasks', () => {
// App 1 depends on builds of its dependencies
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'build',
projects: 'dependencies',
},
];
// App 1 depends on Lib 1
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
// Lib 1 does not have build but depends on Lib 2
delete projectGraph.nodes.lib1.data.targets.build;
projectGraph.dependencies.lib1.push(
{
type: DependencyType.static,
source: 'lib1',
target: 'app1',
},
{
type: DependencyType.static,
source: 'lib1',
target: 'lib2',
}
);
// Lib 2 has a build
projectGraph.nodes.lib2 = {
name: 'lib2',
type: 'lib',
data: {
root: 'lib2-root',
files: [],
targets: {
build: {},
},
},
};
projectGraph.dependencies.lib2 = [];
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
expect(tasks).toContainEqual({
id: 'app1:build',
target: { project: 'app1', target: 'build' },
projectRoot: 'app1-root',
overrides: {},
});
expect(tasks).toContainEqual({
id: 'lib2:build',
target: { project: 'lib2', target: 'build' },
projectRoot: 'lib2-root',
overrides: {},
});
});
it('should throw an error for an invalid target', () => {
jest.spyOn(process, 'exit').mockImplementation(() => {
throw new Error();
});
try {
createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'invalid',
configuration: undefined,
overrides: {},
},
projectGraph,
null
);
fail();
} catch (e) {
expect(process.exit).toHaveBeenCalledWith(1);
}
});
it('should throw an error for an invalid configuration for the initiating project', () => {
jest.spyOn(process, 'exit').mockImplementation(() => {
throw new Error();
});
try {
createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'serve',
configuration: 'invalid',
overrides: {},
},
projectGraph,
'app1'
);
fail();
} catch (e) {
expect(process.exit).toHaveBeenCalledWith(1);
}
});
it('should throw an error for circular dependencies', () => {
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'build',
projects: 'dependencies',
},
];
projectGraph.nodes.lib1.data.targets.build.dependsOn = [
{
target: 'build',
projects: 'dependencies',
},
];
projectGraph.dependencies.app1.push({
type: DependencyType.static,
source: 'app1',
target: 'lib1',
});
projectGraph.dependencies.lib1.push({
type: DependencyType.static,
source: 'lib1',
target: 'app1',
});
jest.spyOn(process, 'exit').mockImplementation(() => {
throw new Error();
});
try {
createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
fail();
} catch (e) {
expect(process.exit).toHaveBeenCalledWith(1);
}
});
it('should throw an error for depending on a non-existent target of itself', () => {
projectGraph.nodes.app1.data.targets.serve.dependsOn = [
{
target: 'non-existent',
projects: 'self',
},
];
jest.spyOn(process, 'exit').mockImplementation(() => {
throw new Error();
});
try {
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'serve',
configuration: undefined,
overrides: {},
},
projectGraph,
projectGraph.nodes.app1.name
);
fail();
} catch (e) {
expect(process.exit).toHaveBeenCalledWith(1);
}
});
it('should throw an error for circular dependencies in tasks', () => {
projectGraph.nodes.app1.data.targets.build.dependsOn = [
{
target: 'serve',
projects: 'self',
},
];
projectGraph.nodes.app1.data.targets.serve.dependsOn = [
{
target: 'build',
projects: 'self',
},
];
jest.spyOn(process, 'exit').mockImplementation(() => {
throw new Error();
});
try {
const tasks = createTasksForProjectToRun(
[projectGraph.nodes.app1],
{
target: 'build',
configuration: undefined,
overrides: {},
},
projectGraph,
null
);
fail();
} catch (e) {
expect(process.exit).toHaveBeenCalledWith(1);
}
});
});
describe('getRunner', () => {
let nxJson: NxJsonConfiguration;
let mockRunner: TasksRunner;
let overrides: any;
beforeEach(() => {
nxJson = {
npmScope: 'proj',
};
mockRunner = jest.fn();
});
it('gets a default runner when runner is not defined in the nx json', () => {
const { tasksRunner, runnerOptions } = getRunner({}, nxJson);
expect(tasksRunner).toEqual(defaultTaskRunner);
});
it('gets a default runner when default options are not configured', () => {
const { tasksRunner, runnerOptions } = getRunner({}, nxJson);
expect(tasksRunner).toEqual(defaultTaskRunner);
});
it('gets a custom task runner', () => {
jest.mock('custom-runner', () => mockRunner, {
virtual: true,
});
nxJson.tasksRunnerOptions = {
custom: {
runner: 'custom-runner',
},
};
const { tasksRunner, runnerOptions } = getRunner(
{ runner: 'custom' },
nxJson
);
expect(tasksRunner).toEqual(mockRunner);
});
it('gets a custom task runner with options', () => {
jest.mock('custom-runner2', () => mockRunner, {
virtual: true,
});
nxJson.tasksRunnerOptions = {
custom: {
runner: 'custom-runner2',
options: {
runnerOption: 'runner-option',
},
},
};
const { tasksRunner, runnerOptions } = getRunner(
{ runner: 'custom' },
nxJson
);
expect(tasksRunner).toBe(mockRunner);
expect(runnerOptions).toEqual({
runner: 'custom',
runnerOption: 'runner-option',
});
});
it('gets a custom defined default task runner', () => {
jest.mock('custom-default-runner', () => mockRunner, {
virtual: true,
});
nxJson.tasksRunnerOptions = {
default: {
runner: 'custom-default-runner',
},
};
const { tasksRunner } = getRunner({}, nxJson);
expect(tasksRunner).toEqual(mockRunner);
});
}); | the_stack |
import { Controller, createController } from './controller/controller';
import { Operation } from './operation';
import { swallowHalt } from './halt-error';
import { EventEmitter } from 'events';
import { StateMachine, State } from './state-machine';
import { Labels } from './labels';
import { addTrace } from './error';
import { createFutureOnRunLoop, Future, FutureLike, Value } from './future';
import { createRunLoop } from './run-loop';
let COUNTER = 0;
/**
* @hidden
*/
export interface TaskInfo {
id: number;
type: string;
labels: Labels;
state: State;
}
/**
* @hidden
*/
export interface TaskTree extends TaskInfo {
yieldingTo?: TaskTree;
children: TaskTree[];
}
/**
* Task options can be used to configure the behaviour of a task. Options can
* be passed to {@link run}, `main`, {@link spawn} and when creating a
* task manually through {@link createTask}.
*/
export interface TaskOptions {
/**
* Normally a task's type is inferred from its operation, but it can also be
* explicitly set via this option.
*/
readonly type?: string;
/**
* The scope of a task describes the scope in which this task creates resource
* tasks.
*
* Usually this is the parent task, but in some instances it can be useful to
* change the scope of a task. This is for example often the case with
* "higher-order operations", that is operations which take another operation
* as an argument, such as the {@link all} operation.
*
* This is a very advanced feature and great care should be taken when using
* it as it can lead to possibly breaking some of the guarantees that
* Effection makes.
*/
readonly scope?: Task;
/**
* @internal
*
* The yieldScope of a task describes the scope in which this task's yield
* points create resources. This is normally the task itself. It is currently
* only changed for resource's `init` tasks.
*
* This is an internal API and you should not set this option yourself.
*/
readonly yieldScope?: Task;
/**
* Normally when a task finishes its operation, it halts all of its children.
* When setting this option to `true` on a child, it will cause the parent
* task to wait for the child to complete after it finishes its operation.
* Essentially it allows a child to block the completion of its parent.
*/
readonly blockParent?: boolean;
/**
* When a child task becomes errored it normally causes its parent task to
* become errored as well. When setting this option to `true` on a parent
* task, an error in its children will be ignored. This is useful for some
* tasks which want to have finer grained control over their children, such
* as supervisors or root tasks.
*/
readonly ignoreChildErrors?: boolean;
/**
* When a child task becomes errored it normally causes its parent task to
* become errored as well. When setting this option to `true` on a child
* task, then an error in the child will not cause the parent to become
* errored. This is useful for some tasks which want finer grained control
* over error conditions.
*/
readonly ignoreError?: boolean;
/**
* Set the given labels on the task.
*/
readonly labels?: Labels;
}
/**
* A `Task` in Effection has many responsibilities. Fundamentally it represents
* a computation which at some point will result in either a value or an error,
* or become halted. It can also have children, which are also tasks.
*
* See [the Task and Operations guide](https://frontside.com/effection/docs/guides/tasks) for more information.
*
*/
export interface Task<TOut = unknown> extends Promise<TOut>, FutureLike<TOut> {
/**
* Each `Task` has a unique id
*/
readonly id: number;
/**
* The type of a `Task` is usually determined by the operation that the task
* is running, but it can also be adjusted via the `type` option.
*/
readonly type: string;
/**
* Returns the {@link State} that the task is currently in.
*/
readonly state: State;
/**
* Returns the options that the task was created with
*/
readonly options: TaskOptions;
/**
* Returns a map of {@link Labels} which provide additional information about
* the task, such as its name, or any other metadata that the task wants to
* provide.
*/
readonly labels: Labels;
/**
* Returns a list of the task's children
*/
readonly children: Task[];
/**
* Returns a {@link Future} for this task. The task itself can act as a
* Future, so usually you do not need to access this property explicitly.
*/
readonly future: Future<TOut>;
/**
* Returns the task that this task is currently yielding to. When using a
* generator with a task, a task ends up processing one operation at a time,
* each such operation runs in its own task, and can be accessed via this
* property.
*
* ### Example
*
* ``` typescript
* import { run, sleep } from 'effection'
*
* let task = run(function*() {
* yield sleep(2000);
* });
*
* console.log(task.yieldingTo); // => logs the sleep task
* ```
*/
readonly yieldingTo: Task | undefined;
/**
* Tasks which construct a resource create a special task in the background called
* a resource task, which groups everything running inside the resource. This property
* provides access to such a task.
*
* ### Example
*
* ``` typescript
* import { main, spawn, fetch } from 'effection'
*
* main(function*() {
* let fetchTask = yield spawn(fetch('http://www.example.com'));
* console.log(fetchTask.resourceTask); // => logs the resource task of the fetch
* });
* ```
*/
readonly resourceTask: Task | undefined;
/**
* When using a task as a `Promise`, it would usually be rejected when the task
* is halted. Using `catchHalt()` we can treat a `halt` as the promise
* resolving to `undefined`, rather than being rejected.
*
* ### Example
*
* ``` typescript
* import { run, sleep } from 'effection'
*
* let task = run(function*() {
* yield sleep(2000);
* return "done!";
* });
*
* task.halt();
*
* task.then((value) => console.log(value)); // => log "undefined"
*/
catchHalt(): Promise<TOut | undefined>;
/**
* Sets the given {@link Labels} on the task. This only adds new labels or
* overwrites labels with the same key, but does not remove other labels.
*
* See also the {@link label} operation for setting labels dynamically.
*
* ### Example
*
* ``` typescript
* import { run } from 'effection'
*
* let task = run();
* task.setLabels({ name: 'myTask', florb: 123 });
* ```
*/
setLabels(labels: Labels): void;
/**
* Run the given operation as a child of this task.
*
* This is similar to {@link spawn}, but it is *not* an operation and
* therefore should *not* be used with `yield`. If you are inside Effection
* code, you should generally prefer {@link spawn}. `run` is useful when you
* are creating children from outside of Effection.
*
* ### Example
*
* ``` typescript
* import { run } from 'effection'
*
* let task = run();
* task.run(function*() { ... }) // run a child of this task
* ```
*
* @typeParam TOutChild the type that the child resolves to
*/
run<TOutChild>(operation?: Operation<TOutChild>, options?: TaskOptions): Task<TOutChild>;
/**
* An operation to run the given operation as child of this task.
*
* This is similar to {@link run}, but it is an operation and therefore must
* be used with `yield` or `run`. If you are inside Effection code, you
* should generally prefer `spawn`. {@link run} is useful when you are
* creating children from outside of Effection.
*
* ### Example
*
* ``` typescript
* import { main, spawn } from 'effection'
*
* main(function*(mainTask) {
* yield function*() {
* yield mainTask.spawn(function*() { ... }); // => run as child of `main`.
* }
* });
* ```
*
* @param operation the operation that the child runs
* @typeParam TOutChild the type that the child resolves to
*/
spawn<TOutChild>(operation?: Operation<TOutChild>, options?: TaskOptions): Operation<Task<TOutChild>>;
/**
* Cause this task to halt. This will halt the task itself, as well as any task
* it is currently {@link yieldingTo} and its {@link children}.
*/
halt(): Promise<void>;
/**
* Starts running the task if it has not yet started, does nothing otherwise.
* You will only need to call this if you created your task manually through
* {@link createTask}.
*
* ### Example
*
* ``` typescript
* import { createTask } from 'effection'
*
* let task = createTask(someOperation);
* console.log(task.state) // => 'pending';
*
* task.start();
* console.log(task.state) // => 'running';
* ```
*/
start(): void;
/**
* Serializes information about the task into an object. This will include
* the task's {@link id}, {@link state}, {@link type}, {@link labels} as well
* as the task it is {@link yieldingTo} and its {@link children}.
*/
toJSON(): TaskTree;
/**
* Returns a readable description of the task and its children. This is
* useful for debugging. The output can be improved by applying {@link labels}.
* For more advanced debugging you can also use the
* [inspector](https://frontside.com/effection/docs/guides/inspector).
*/
toString(): string;
/**
* @hidden
*/
on: EventEmitter['on'];
/**
* @hidden
*/
off: EventEmitter['off'];
}
/**
* Low level interface to create a task which does not have a parent. Normally all
* tasks are spawned as children of {@link Effection}.root, but on rare occasions it is necessary
* to create a task outside the normal task hierarchy.
*
* @param operation the operation that the task runs
* @param options the options that the task is configured with
* @returns the new task
*/
export function createTask<TOut = unknown>(operation: Operation<TOut>, options: TaskOptions = {}): Task<TOut> {
let id = ++COUNTER;
let children = new Set<Task>();
let emitter = new EventEmitter();
emitter.setMaxListeners(100000);
let stateMachine = new StateMachine(emitter);
let result: Value<TOut>;
let runLoop = createRunLoop(`task ${id}`);
let { produce, future } = createFutureOnRunLoop<TOut>(runLoop);
let controller: Controller<TOut>;
let labels: Labels = { ...operation?.labels, ...options.labels };
let yieldingTo: Task | undefined;
if (!labels.name) {
if (operation?.name) {
labels.name = operation?.name;
} else if (!operation) {
labels.name = 'suspend';
}
}
let task: Task<TOut> = {
id,
options,
future,
get labels() { return labels },
get state() { return stateMachine.current },
get type() { return options.type || controller.type },
get children() { return Array.from(children) },
get yieldingTo() { return yieldingTo },
get resourceTask() { return controller.resourceTask },
catchHalt() {
return future.catch(swallowHalt);
},
setLabels(newLabels) {
labels = { ...labels, ...newLabels };
emitter.emit('labels', labels);
},
run(operation?, options = {}) {
if(stateMachine.current !== 'running') {
throw new Error('cannot spawn a child on a task which is not running');
}
let child = createTask(operation, { scope: task, ...options });
link(child as Task);
child.start();
return child;
},
spawn(operation?, options = {}) {
return {
name: 'spawn',
*init() {
return task.run(operation, options);
}
};
},
start() {
runLoop.run(() => {
if(stateMachine.current === 'pending') {
stateMachine.start();
controller.start();
}
});
},
async halt() {
controller.halt();
if(stateMachine.current === 'running') {
stateMachine.halting();
result = { state: 'halted' };
}
shutdown(true);
await future.catch(() => {
// TODO: should this catch all errors, or only halt errors?
// see https://github.com/jnicklas/mini-effection/issues/23
});
},
toJSON() {
return {
id: id,
type: task.type,
labels: labels,
state: stateMachine.current,
yieldingTo: yieldingTo?.toJSON(),
children: Array.from(children).map((c) => c.toJSON()),
};
},
toString() {
let formattedLabels = Object.entries(labels).filter(([key]) => key !== 'name' && key !== 'expand').map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(' ');
return [
[labels.name || 'task', formattedLabels, `[${task.type} ${id}]`].filter(Boolean).join(' '),
yieldingTo && yieldingTo.toString().split('\n').map(l => '┃ ' + l).join('\n').replace(/^┃ /, `┣ yield `),
...Array.from(children).map((c) => c.toString().split('\n').map(l => '┃ ' + l).join('\n').replace(/^┃/, '┣'),)
].filter(Boolean).join('\n');
},
on: (...args) => emitter.on(...args),
off: (...args) => emitter.off(...args),
then: (...args) => future.then(...args),
catch: (...args) => future.catch(...args),
finally: (...args) => future.finally(...args),
consume: (...args) => future.consume(...args),
[Symbol.toStringTag]: `[Task ${id}]`,
};
controller = createController(task, operation, {
runLoop,
onYieldingToChange(value) {
yieldingTo = value;
emitter.emit('yieldingTo', value);
}
});
controller.future.consume((value) => {
if(stateMachine.isFinalized) return;
if(value.state === 'completed') {
stateMachine.completing();
if(!result) {
result = { state: 'completed', value: value.value };
}
shutdown(false);
} else if(value.state === 'errored') {
stateMachine.erroring();
result = { state: 'errored', error: addTrace(value.error, task) };
shutdown(true);
} else if(value.state === 'halted' && stateMachine.current !== 'erroring') {
stateMachine.halting();
result = { state: 'halted' };
shutdown(true);
}
finalize();
});
function link(child: Task) {
if(!children.has(child)) {
child.consume((value) => {
runLoop.run(() => {
if(stateMachine.isFinalized) return;
if(value.state === 'errored' && !child.options.ignoreError && !options.ignoreChildErrors) {
stateMachine.erroring();
result = { state: 'errored', error: addTrace(value.error, task) };
controller.halt();
shutdown(true);
}
if(children.has(child)) {
children.delete(child);
emitter.emit('unlink', child);
}
finalize();
});
});
children.add(child);
emitter.emit('link', child);
}
}
function shutdown(force: boolean) {
controller.future.consume(() => {
let nextChild: Task | undefined;
function haltNextChild() {
runLoop.run(() => {
nextChild = Array.from(children)
.reverse()
.find((c) => (c !== nextChild) && (force || !c.options.blockParent));
if(nextChild) {
nextChild.consume(haltNextChild);
nextChild.halt();
}
});
}
haltNextChild();
});
}
function finalize() {
if(Array.from(children).length !== 0) return;
if(controller.future.state === 'pending') return;
if(future.state !== 'pending') return;
stateMachine.finish();
produce(result);
}
return task;
} | the_stack |
import * as vscode from "vscode";
import {
glo,
IEditorInfo,
TyInLineInDepthInQueueInfo,
TyDepthDecInfo,
} from "./extension";
import { renderSingleLineBoxV1 } from "./renderLineToolV1";
import { renderSingleLineBoxV2 } from "./renderLineToolV2";
import { renderSingleLineBoxV3 } from "./renderLineToolV3";
import { renderSingleLineBoxV4 } from "./renderLineToolV4";
import { renderSingleLineBoxV5 } from "./renderLineToolV5";
import {
AdvancedColoringFields,
editorBackgroundFormula,
makeInnerKitchenNotation,
} from "./settingsManager";
import { IBlockRender } from "./utils";
import { notYetDisposedDecsObject } from "./utils2";
const neu = "neutral";
const advNeu = makeInnerKitchenNotation("basic");
export interface ISingleLineBox {
editorInfo: IEditorInfo;
depth: number; // 0 means entire file. 1 means first level block....
inDepthBlockIndex: number;
lineBlockType: "opening" | "middle" | "closing" | "onlyLine";
isfirstFromTopToDown: boolean;
isFirstFromBottomToUp: boolean;
lineZero: number;
boxHeight: number; // px
boxLeftEdge: number; // px
boxRightEdge: number; // px
optimalLeftOfRangePx: number;
optimalRightOfRangePx: number;
legitFirstLineZero: number;
legitLastLineZero: number;
isFocusedBlock: boolean;
firstLineHasVisibleChar: boolean;
lastLineHasVisibleChar: boolean;
firstVisibleChar: {
lineZero: number;
inLineIndexZero: number;
};
lastVisibleChar: {
lineZero: number;
inLineIndexZero: number;
};
inputBorderColor: string;
inputBackgroundColor: string;
borderSize: number;
}
export const renderSingleBlock = ({
firstLineHasVisibleChar,
lastLineHasVisibleChar,
firstVisibleChar,
lastVisibleChar,
optimalLeftOfRange,
optimalRightOfRange,
depth,
inDepthBlockIndex,
firstLineZeroOfRender,
lastLineZeroOfRender,
editorInfo,
lang,
isFocusedBlock,
absRangeEndPos,
}: IBlockRender) => {
if (!firstVisibleChar || firstVisibleChar.lineZero < 0) {
return;
}
// -----11111111111
let inputBorderColor: string = `linear-gradient(to right, ${"transparent"}, ${"transparent"})`; // in final state it always must be linear gradient
let inputBackgroundColor: string = `linear-gradient(to right, ${editorBackgroundFormula}, ${editorBackgroundFormula})`; // in final state it always must be linear gradient
inputBorderColor = glo.coloring.border;
switch (depth) {
case 0:
inputBackgroundColor = glo.coloring.onEachDepth[0];
inputBorderColor = glo.coloring.borderOfDepth0;
break;
case 1:
inputBackgroundColor = glo.coloring.onEachDepth[1];
break;
case 2:
inputBackgroundColor = glo.coloring.onEachDepth[2];
break;
case 3:
inputBackgroundColor = glo.coloring.onEachDepth[3];
break;
case 4:
inputBackgroundColor = glo.coloring.onEachDepth[4];
break;
case 5:
inputBackgroundColor = glo.coloring.onEachDepth[5];
break;
case 6:
inputBackgroundColor = glo.coloring.onEachDepth[6];
break;
case 7:
inputBackgroundColor = glo.coloring.onEachDepth[7];
break;
case 8:
inputBackgroundColor = glo.coloring.onEachDepth[8];
break;
case 9:
inputBackgroundColor = glo.coloring.onEachDepth[9];
break;
case 10:
inputBackgroundColor = glo.coloring.onEachDepth[10];
break;
default:
inputBackgroundColor = glo.coloring.onEachDepth[10];
}
let borderSize = glo.borderSize;
if (glo.enableFocus && isFocusedBlock) {
if (!glo.coloring.focusedBlock.includes("same")) {
inputBackgroundColor = glo.coloring.focusedBlock;
}
if (!glo.coloring.borderOfFocusedBlock.includes("same")) {
inputBorderColor = glo.coloring.borderOfFocusedBlock;
}
borderSize = 2;
}
// kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
let borderOfAC: undefined | string = undefined;
let backgroundOfAC: undefined | string = undefined;
const aCSettingsForBorders = glo.coloring.advanced.forBorders;
const aCSettingsForBackgrounds = glo.coloring.advanced.forBackgrounds;
const focPath = editorInfo.focusTreePath;
// if (focPath) {
// if (focPath[depth] === inDepthBlockIndex) {
// // borderOfAC =
// // "linear-gradient(to right, red, rgba(250, 10, 100, 0.3))";
// }
// }
const focInners = editorInfo.innersFromFocus;
// if (focInners) {
// const indexes = focInners[depth];
// if (indexes && indexes.includes(inDepthBlockIndex)) {
// // borderOfAC = "linear-gradient(to right, blue, blue)";
// }
// }
const focusedBlockInfo = editorInfo.focusDuo.curr;
const focDepth = focusedBlockInfo?.depth;
// const focIndITD = focusedBlockInfo.indexInTheDepth;
const inOnFocTree =
focDepth &&
depth <= focDepth &&
focPath &&
focPath[depth] === inDepthBlockIndex;
const isInsideFoc =
focDepth &&
depth >= focDepth &&
focInners &&
focInners[depth]?.includes(inDepthBlockIndex);
const decideColor = (
aCSettings: {
priority: number;
sequence: string[];
kind: AdvancedColoringFields;
}[],
): string | undefined => {
for (let i = 0; i < aCSettings.length; i += 1) {
const seqInfo = aCSettings[i];
const kind = seqInfo.kind;
if (kind === AdvancedColoringFields.fromD0ToInward_All) {
const myColor = seqInfo.sequence[depth];
if (myColor && myColor !== neu) {
// borderOfAC = myColor;
// break;
if (myColor === advNeu) {
return undefined;
}
return myColor;
}
} else if (
kind === AdvancedColoringFields.fromD0ToInward_FocusTree
) {
let myColor = neu;
if (inOnFocTree) {
myColor = seqInfo.sequence[depth];
}
if (myColor && myColor !== neu) {
// borderOfAC = myColor;
// break;
if (myColor === advNeu) {
return undefined;
}
return myColor;
}
} else if (kind === AdvancedColoringFields.fromFocusToInward_All) {
let myColor = neu;
if (focDepth && isInsideFoc) {
const myInd = depth - focDepth;
myColor = seqInfo.sequence[myInd];
}
if (myColor && myColor !== neu) {
// borderOfAC = myColor;
// break;
if (myColor === advNeu) {
return undefined;
}
return myColor;
}
} else if (kind === AdvancedColoringFields.fromFocusToOutward_All) {
let myColor = neu;
if (focDepth && depth <= focDepth) {
const myInd = focDepth - depth;
myColor = seqInfo.sequence[myInd];
}
if (myColor && myColor !== neu) {
// borderOfAC = myColor;
// break;
if (myColor === advNeu) {
return undefined;
}
return myColor;
}
} else if (
kind === AdvancedColoringFields.fromFocusToOutward_FocusTree
) {
let myColor = neu;
if (focDepth && inOnFocTree) {
const myInd = focDepth - depth;
myColor = seqInfo.sequence[myInd];
}
if (myColor && myColor !== neu) {
// borderOfAC = myColor;
// break;
if (myColor === advNeu) {
return undefined;
}
return myColor;
}
}
}
return undefined;
};
borderOfAC = decideColor(aCSettingsForBorders);
backgroundOfAC = decideColor(aCSettingsForBackgrounds);
// ------222222222
if (borderOfAC) {
inputBorderColor = borderOfAC;
}
if (backgroundOfAC) {
inputBackgroundColor = backgroundOfAC;
}
// ------- 333333
for (
let currLineZero = firstVisibleChar.lineZero;
currLineZero <= lastVisibleChar.lineZero;
currLineZero += 1
) {
if (currLineZero < firstLineZeroOfRender) {
continue;
}
if (currLineZero > lastLineZeroOfRender) {
break;
}
let lChar = optimalLeftOfRange;
let rChar = optimalRightOfRange;
let currType: "opening" | "middle" | "closing" | "onlyLine";
let isfirstFromTopToDown = false;
let isFirstFromBottomToUp = false;
// console.log("firstLineHasVisibleChar:", firstLineHasVisibleChar);
// console.log("currLineZero:", currLineZero);
// console.log(
// "firstVisibleChar.lineZero + 1:",
// firstVisibleChar.lineZero + 1,
// );
if (
firstLineHasVisibleChar &&
currLineZero === firstVisibleChar.lineZero + 1
) {
isfirstFromTopToDown = true;
}
if (
lastLineHasVisibleChar &&
currLineZero === lastVisibleChar.lineZero - 1
) {
isFirstFromBottomToUp = true;
}
if (firstVisibleChar.lineZero === lastVisibleChar.lineZero) {
currType = "onlyLine";
} else if (currLineZero === firstVisibleChar.lineZero) {
currType = "opening";
if (firstLineHasVisibleChar) {
// if (!["python"].includes(lang)) {
// for language which is not based on indentation
lChar = firstVisibleChar.inLineIndexZero;
// }
}
} else if (currLineZero === lastVisibleChar.lineZero) {
currType = "closing";
if (lastLineHasVisibleChar) {
// if (!["python"].includes(lang)) {
// for language which is not based on indentation
// }
if (
!(
absRangeEndPos &&
editorInfo.monoText[absRangeEndPos.globalIndexZero] ===
"\n"
)
) {
rChar = lastVisibleChar.inLineIndexZero;
}
}
} else {
currType = "middle";
}
// if (depth === 2) {
// console.log("rendering depth");
const singleRangeRendArg = {
editorInfo,
depth,
inDepthBlockIndex,
lineBlockType: currType,
isfirstFromTopToDown,
isFirstFromBottomToUp,
lineZero: currLineZero,
boxHeight: glo.eachCharFrameHeight, // px
boxLeftEdge: glo.eachCharFrameWidth * lChar, // px
boxRightEdge: glo.eachCharFrameWidth * (rChar + 1), // px
optimalLeftOfRangePx: optimalLeftOfRange * glo.eachCharFrameWidth,
optimalRightOfRangePx:
(optimalRightOfRange + 1) * glo.eachCharFrameWidth,
legitFirstLineZero: firstLineZeroOfRender,
legitLastLineZero: lastLineZeroOfRender,
isFocusedBlock,
firstLineHasVisibleChar,
lastLineHasVisibleChar,
firstVisibleChar,
lastVisibleChar,
inputBorderColor,
inputBackgroundColor,
borderSize,
};
// renderSingleLineBoxV1(singleRangeRendArg); // old renderer function
// renderSingleLineBoxV2(singleRangeRendArg); // new renderer function
// for V3
const firstLineOfMiddles = firstVisibleChar.lineZero + 2;
const lastLineOfMiddles = lastVisibleChar.lineZero - 2;
const isMid =
currLineZero >= firstLineOfMiddles &&
currLineZero <= lastLineOfMiddles;
// renderSingleLineBoxV4(singleRangeRendArg);
renderSingleLineBoxV5(singleRangeRendArg);
if (isMid) {
currLineZero = lastLineOfMiddles;
}
// }
}
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/policyAssignmentsMappers";
import * as Parameters from "../models/parameters";
import { PolicyClientContext } from "../policyClientContext";
/** Class representing a PolicyAssignments. */
export class PolicyAssignments {
private readonly client: PolicyClientContext;
/**
* Create a PolicyAssignments.
* @param {PolicyClientContext} client Reference to the service client.
*/
constructor(client: PolicyClientContext) {
this.client = client;
}
/**
* Deletes a policy assignment.
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment to delete.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsDeleteMethodResponse>
*/
deleteMethod(scope: string, policyAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsDeleteMethodResponse>;
/**
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment to delete.
* @param callback The callback
*/
deleteMethod(scope: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
/**
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment to delete.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(scope: string, policyAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
deleteMethod(scope: string, policyAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignment>, callback?: msRest.ServiceCallback<Models.PolicyAssignment>): Promise<Models.PolicyAssignmentsDeleteMethodResponse> {
return this.client.sendOperationRequest(
{
scope,
policyAssignmentName,
options
},
deleteMethodOperationSpec,
callback) as Promise<Models.PolicyAssignmentsDeleteMethodResponse>;
}
/**
* Policy assignments are inherited by child resources. For example, when you apply a policy to a
* resource group that policy is assigned to all resources in the group.
* @summary Creates a policy assignment.
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment.
* @param parameters Parameters for the policy assignment.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsCreateResponse>
*/
create(scope: string, policyAssignmentName: string, parameters: Models.PolicyAssignment, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsCreateResponse>;
/**
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment.
* @param parameters Parameters for the policy assignment.
* @param callback The callback
*/
create(scope: string, policyAssignmentName: string, parameters: Models.PolicyAssignment, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
/**
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment.
* @param parameters Parameters for the policy assignment.
* @param options The optional parameters
* @param callback The callback
*/
create(scope: string, policyAssignmentName: string, parameters: Models.PolicyAssignment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
create(scope: string, policyAssignmentName: string, parameters: Models.PolicyAssignment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignment>, callback?: msRest.ServiceCallback<Models.PolicyAssignment>): Promise<Models.PolicyAssignmentsCreateResponse> {
return this.client.sendOperationRequest(
{
scope,
policyAssignmentName,
parameters,
options
},
createOperationSpec,
callback) as Promise<Models.PolicyAssignmentsCreateResponse>;
}
/**
* Gets a policy assignment.
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment to get.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsGetResponse>
*/
get(scope: string, policyAssignmentName: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsGetResponse>;
/**
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment to get.
* @param callback The callback
*/
get(scope: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
/**
* @param scope The scope of the policy assignment.
* @param policyAssignmentName The name of the policy assignment to get.
* @param options The optional parameters
* @param callback The callback
*/
get(scope: string, policyAssignmentName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
get(scope: string, policyAssignmentName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignment>, callback?: msRest.ServiceCallback<Models.PolicyAssignment>): Promise<Models.PolicyAssignmentsGetResponse> {
return this.client.sendOperationRequest(
{
scope,
policyAssignmentName,
options
},
getOperationSpec,
callback) as Promise<Models.PolicyAssignmentsGetResponse>;
}
/**
* Gets policy assignments for the resource group.
* @param resourceGroupName The name of the resource group that contains policy assignments.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsListForResourceGroupResponse>
*/
listForResourceGroup(resourceGroupName: string, options?: Models.PolicyAssignmentsListForResourceGroupOptionalParams): Promise<Models.PolicyAssignmentsListForResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group that contains policy assignments.
* @param callback The callback
*/
listForResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
/**
* @param resourceGroupName The name of the resource group that contains policy assignments.
* @param options The optional parameters
* @param callback The callback
*/
listForResourceGroup(resourceGroupName: string, options: Models.PolicyAssignmentsListForResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
listForResourceGroup(resourceGroupName: string, options?: Models.PolicyAssignmentsListForResourceGroupOptionalParams | msRest.ServiceCallback<Models.PolicyAssignmentListResult>, callback?: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): Promise<Models.PolicyAssignmentsListForResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listForResourceGroupOperationSpec,
callback) as Promise<Models.PolicyAssignmentsListForResourceGroupResponse>;
}
/**
* Gets policy assignments for a resource.
* @param resourceGroupName The name of the resource group containing the resource. The name is
* case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath The parent resource path.
* @param resourceType The resource type.
* @param resourceName The name of the resource with policy assignments.
* @param [options] The optional parameters
* @deprecated This operation is deprecated. Please do not use it any longer.
* @returns Promise<Models.PolicyAssignmentsListForResourceResponse>
*/
listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: Models.PolicyAssignmentsListForResourceOptionalParams): Promise<Models.PolicyAssignmentsListForResourceResponse>;
/**
* @param resourceGroupName The name of the resource group containing the resource. The name is
* case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath The parent resource path.
* @param resourceType The resource type.
* @param resourceName The name of the resource with policy assignments.
* @param callback The callback
* @deprecated This operation is deprecated. Please do not use it any longer.
*/
listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
/**
* @param resourceGroupName The name of the resource group containing the resource. The name is
* case insensitive.
* @param resourceProviderNamespace The namespace of the resource provider.
* @param parentResourcePath The parent resource path.
* @param resourceType The resource type.
* @param resourceName The name of the resource with policy assignments.
* @param options The optional parameters
* @param callback The callback
* @deprecated This operation is deprecated. Please do not use it any longer.
*/
listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options: Models.PolicyAssignmentsListForResourceOptionalParams, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
listForResource(resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, options?: Models.PolicyAssignmentsListForResourceOptionalParams | msRest.ServiceCallback<Models.PolicyAssignmentListResult>, callback?: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): Promise<Models.PolicyAssignmentsListForResourceResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
resourceProviderNamespace,
parentResourcePath,
resourceType,
resourceName,
options
},
listForResourceOperationSpec,
callback) as Promise<Models.PolicyAssignmentsListForResourceResponse>;
}
/**
* Gets all the policy assignments for a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsListResponse>
*/
list(options?: Models.PolicyAssignmentsListOptionalParams): Promise<Models.PolicyAssignmentsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: Models.PolicyAssignmentsListOptionalParams, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
list(options?: Models.PolicyAssignmentsListOptionalParams | msRest.ServiceCallback<Models.PolicyAssignmentListResult>, callback?: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): Promise<Models.PolicyAssignmentsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.PolicyAssignmentsListResponse>;
}
/**
* When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for
* subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for
* resource groups, and
* '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
* for resources.
* @summary Deletes a policy assignment by ID.
* @param policyAssignmentId The ID of the policy assignment to delete. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsDeleteByIdResponse>
*/
deleteById(policyAssignmentId: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsDeleteByIdResponse>;
/**
* @param policyAssignmentId The ID of the policy assignment to delete. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param callback The callback
*/
deleteById(policyAssignmentId: string, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
/**
* @param policyAssignmentId The ID of the policy assignment to delete. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param options The optional parameters
* @param callback The callback
*/
deleteById(policyAssignmentId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
deleteById(policyAssignmentId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignment>, callback?: msRest.ServiceCallback<Models.PolicyAssignment>): Promise<Models.PolicyAssignmentsDeleteByIdResponse> {
return this.client.sendOperationRequest(
{
policyAssignmentId,
options
},
deleteByIdOperationSpec,
callback) as Promise<Models.PolicyAssignmentsDeleteByIdResponse>;
}
/**
* Policy assignments are inherited by child resources. For example, when you apply a policy to a
* resource group that policy is assigned to all resources in the group. When providing a scope for
* the assignment, use '/subscriptions/{subscription-id}/' for subscriptions,
* '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, and
* '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
* for resources.
* @summary Creates a policy assignment by ID.
* @param policyAssignmentId The ID of the policy assignment to create. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param parameters Parameters for policy assignment.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsCreateByIdResponse>
*/
createById(policyAssignmentId: string, parameters: Models.PolicyAssignment, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsCreateByIdResponse>;
/**
* @param policyAssignmentId The ID of the policy assignment to create. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param parameters Parameters for policy assignment.
* @param callback The callback
*/
createById(policyAssignmentId: string, parameters: Models.PolicyAssignment, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
/**
* @param policyAssignmentId The ID of the policy assignment to create. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param parameters Parameters for policy assignment.
* @param options The optional parameters
* @param callback The callback
*/
createById(policyAssignmentId: string, parameters: Models.PolicyAssignment, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
createById(policyAssignmentId: string, parameters: Models.PolicyAssignment, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignment>, callback?: msRest.ServiceCallback<Models.PolicyAssignment>): Promise<Models.PolicyAssignmentsCreateByIdResponse> {
return this.client.sendOperationRequest(
{
policyAssignmentId,
parameters,
options
},
createByIdOperationSpec,
callback) as Promise<Models.PolicyAssignmentsCreateByIdResponse>;
}
/**
* When providing a scope for the assignment, use '/subscriptions/{subscription-id}/' for
* subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for
* resource groups, and
* '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
* for resources.
* @summary Gets a policy assignment by ID.
* @param policyAssignmentId The ID of the policy assignment to get. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsGetByIdResponse>
*/
getById(policyAssignmentId: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsGetByIdResponse>;
/**
* @param policyAssignmentId The ID of the policy assignment to get. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param callback The callback
*/
getById(policyAssignmentId: string, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
/**
* @param policyAssignmentId The ID of the policy assignment to get. Use the format
* '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
* @param options The optional parameters
* @param callback The callback
*/
getById(policyAssignmentId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignment>): void;
getById(policyAssignmentId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignment>, callback?: msRest.ServiceCallback<Models.PolicyAssignment>): Promise<Models.PolicyAssignmentsGetByIdResponse> {
return this.client.sendOperationRequest(
{
policyAssignmentId,
options
},
getByIdOperationSpec,
callback) as Promise<Models.PolicyAssignmentsGetByIdResponse>;
}
/**
* Gets policy assignments for the resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsListForResourceGroupNextResponse>
*/
listForResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsListForResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listForResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listForResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
listForResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignmentListResult>, callback?: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): Promise<Models.PolicyAssignmentsListForResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listForResourceGroupNextOperationSpec,
callback) as Promise<Models.PolicyAssignmentsListForResourceGroupNextResponse>;
}
/**
* Gets policy assignments for a resource.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @deprecated This operation is deprecated. Please do not use it any longer.
* @returns Promise<Models.PolicyAssignmentsListForResourceNextResponse>
*/
listForResourceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsListForResourceNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
* @deprecated This operation is deprecated. Please do not use it any longer.
*/
listForResourceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
* @deprecated This operation is deprecated. Please do not use it any longer.
*/
listForResourceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
listForResourceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignmentListResult>, callback?: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): Promise<Models.PolicyAssignmentsListForResourceNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listForResourceNextOperationSpec,
callback) as Promise<Models.PolicyAssignmentsListForResourceNextResponse>;
}
/**
* Gets all the policy assignments for a subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyAssignmentsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyAssignmentsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyAssignmentListResult>, callback?: msRest.ServiceCallback<Models.PolicyAssignmentListResult>): Promise<Models.PolicyAssignmentsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.PolicyAssignmentsListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}",
urlParameters: [
Parameters.scope,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignment
},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}",
urlParameters: [
Parameters.scope,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.PolicyAssignment,
required: true
}
},
responses: {
201: {
bodyMapper: Mappers.PolicyAssignment
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{scope}/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}",
urlParameters: [
Parameters.scope,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignment
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listForResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.filter0,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignmentListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listForResourceOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}/providers/Microsoft.Authorization/policyAssignments",
urlParameters: [
Parameters.resourceGroupName,
Parameters.resourceProviderNamespace,
Parameters.parentResourcePath,
Parameters.resourceType,
Parameters.resourceName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.filter1,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignmentListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyAssignments",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.filter1,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignmentListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteByIdOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{policyAssignmentId}",
urlParameters: [
Parameters.policyAssignmentId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignment
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createByIdOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{policyAssignmentId}",
urlParameters: [
Parameters.policyAssignmentId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.PolicyAssignment,
required: true
}
},
responses: {
201: {
bodyMapper: Mappers.PolicyAssignment
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getByIdOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "{policyAssignmentId}",
urlParameters: [
Parameters.policyAssignmentId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignment
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listForResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignmentListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listForResourceNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignmentListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyAssignmentListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import * as ko from "knockout";
import React from "react";
import * as _ from "underscore";
import { AuthType } from "../../AuthType";
import * as Constants from "../../Common/Constants";
import { readCollections } from "../../Common/dataAccess/readCollections";
import { readDatabaseOffer } from "../../Common/dataAccess/readDatabaseOffer";
import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils";
import * as Logger from "../../Common/Logger";
import { fetchPortalNotifications } from "../../Common/PortalNotifications";
import * as DataModels from "../../Contracts/DataModels";
import * as ViewModels from "../../Contracts/ViewModels";
import { useSidePanel } from "../../hooks/useSidePanel";
import { useTabs } from "../../hooks/useTabs";
import { IJunoResponse, JunoClient } from "../../Juno/JunoClient";
import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants";
import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor";
import { userContext } from "../../UserContext";
import { getCollectionName } from "../../Utils/APITypeUtils";
import { isServerlessAccount } from "../../Utils/CapabilityUtils";
import { logConsoleError } from "../../Utils/NotificationConsoleUtils";
import Explorer from "../Explorer";
import { AddCollectionPanel } from "../Panes/AddCollectionPanel";
import { DatabaseSettingsTabV2 } from "../Tabs/SettingsTabV2";
import { useDatabases } from "../useDatabases";
import { useSelectedNode } from "../useSelectedNode";
import Collection from "./Collection";
export default class Database implements ViewModels.Database {
public nodeKind: string;
public container: Explorer;
public self: string;
public rid: string;
public id: ko.Observable<string>;
public offer: ko.Observable<DataModels.Offer>;
public collections: ko.ObservableArray<Collection>;
public isDatabaseExpanded: ko.Observable<boolean>;
public isDatabaseShared: ko.Computed<boolean>;
public selectedSubnodeKind: ko.Observable<ViewModels.CollectionTabKind>;
public junoClient: JunoClient;
private isOfferRead: boolean;
constructor(container: Explorer, data: DataModels.Database) {
this.nodeKind = "Database";
this.container = container;
this.self = data._self;
this.rid = data._rid;
this.id = ko.observable(data.id);
this.offer = ko.observable();
this.collections = ko.observableArray<Collection>();
this.collections.subscribe(() => useDatabases.getState().updateDatabase(this));
this.isDatabaseExpanded = ko.observable<boolean>(false);
this.selectedSubnodeKind = ko.observable<ViewModels.CollectionTabKind>();
this.isDatabaseShared = ko.pureComputed(() => {
return this.offer && !!this.offer();
});
this.junoClient = new JunoClient();
this.isOfferRead = false;
}
public onSettingsClick = (): void => {
useSelectedNode.getState().setSelectedNode(this);
this.selectedSubnodeKind(ViewModels.CollectionTabKind.DatabaseSettings);
TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, {
description: "Settings node",
dataExplorerArea: Constants.Areas.ResourceTree,
});
const pendingNotificationsPromise: Promise<DataModels.Notification> = this.getPendingThroughputSplitNotification();
const tabKind = ViewModels.CollectionTabKind.DatabaseSettingsV2;
const matchingTabs = useTabs.getState().getTabs(tabKind, (tab) => tab.node?.id() === this.id());
let settingsTab = matchingTabs?.[0] as DatabaseSettingsTabV2;
if (!settingsTab) {
const startKey: number = TelemetryProcessor.traceStart(Action.Tab, {
databaseName: this.id(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: "Scale",
});
pendingNotificationsPromise.then(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(data: any) => {
const pendingNotification: DataModels.Notification = data?.[0];
const tabOptions: ViewModels.TabOptions = {
tabKind,
title: "Scale",
tabPath: "",
node: this,
rid: this.rid,
database: this,
onLoadStartKey: startKey,
};
settingsTab = new DatabaseSettingsTabV2(tabOptions);
settingsTab.pendingNotification(pendingNotification);
useTabs.getState().activateNewTab(settingsTab);
},
(error) => {
const errorMessage = getErrorMessage(error);
TelemetryProcessor.traceFailure(
Action.Tab,
{
databaseName: this.id(),
collectionName: this.id(),
dataExplorerArea: Constants.Areas.Tab,
tabTitle: "Scale",
error: errorMessage,
errorStack: getErrorStack(error),
},
startKey
);
logConsoleError(`Error while fetching database settings for database ${this.id()}: ${errorMessage}`);
throw error;
}
);
} else {
pendingNotificationsPromise.then(
(pendingNotification: DataModels.Notification) => {
settingsTab.pendingNotification(pendingNotification);
useTabs.getState().activateTab(settingsTab);
},
() => {
settingsTab.pendingNotification(undefined);
useTabs.getState().activateTab(settingsTab);
}
);
}
};
public async expandDatabase() {
if (this.isDatabaseExpanded()) {
return;
}
await this.loadOffer();
await this.loadCollections();
this.isDatabaseExpanded(true);
TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, {
description: "Database node",
dataExplorerArea: Constants.Areas.ResourceTree,
});
}
public collapseDatabase() {
if (!this.isDatabaseExpanded()) {
return;
}
this.isDatabaseExpanded(false);
TelemetryProcessor.trace(Action.CollapseTreeNode, ActionModifiers.Mark, {
description: "Database node",
dataExplorerArea: Constants.Areas.ResourceTree,
});
}
public async loadCollections(): Promise<void> {
const collectionVMs: Collection[] = [];
const collections: DataModels.Collection[] = await readCollections(this.id());
// TODO Remove
// This is a hack to make Mongo collections read via ARM have a SQL-ish partitionKey property
if (userContext.apiType === "Mongo" && userContext.authType === AuthType.AAD) {
collections.map((collection) => {
if (collection.shardKey) {
const shardKey = Object.keys(collection.shardKey)[0];
collection.partitionKey = {
version: undefined,
kind: "Hash",
paths: [`/"$v"/"${shardKey.split(".").join(`"/"$v"/"`)}"/"$v"`],
};
} else {
collection.partitionKey = {
paths: ["/'$v'/'_partitionKey'/'$v'"],
kind: "Hash",
version: 2,
systemKey: true,
};
}
});
}
const deltaCollections = this.getDeltaCollections(collections);
collections.forEach((collection: DataModels.Collection) => {
this.addSchema(collection);
});
deltaCollections.toAdd.forEach((collection: DataModels.Collection) => {
const collectionVM: Collection = new Collection(this.container, this.id(), collection);
collectionVMs.push(collectionVM);
});
//merge collections
this.addCollectionsToList(collectionVMs);
this.deleteCollectionsFromList(deltaCollections.toDelete);
useDatabases.getState().updateDatabase(this);
}
public async openAddCollection(database: Database): Promise<void> {
await useDatabases.getState().loadDatabaseOffers();
useSidePanel
.getState()
.openSidePanel(
"New " + getCollectionName(),
<AddCollectionPanel explorer={database.container} databaseId={database.id()} />
);
}
public findCollectionWithId(collectionId: string): ViewModels.Collection {
return _.find(this.collections(), (collection: ViewModels.Collection) => collection.id() === collectionId);
}
public async loadOffer(): Promise<void> {
if (!this.isOfferRead && !isServerlessAccount() && !this.offer()) {
const params: DataModels.ReadDatabaseOfferParams = {
databaseId: this.id(),
databaseResourceId: this.self,
};
this.offer(await readDatabaseOffer(params));
this.isOfferRead = true;
}
}
public async getPendingThroughputSplitNotification(): Promise<DataModels.Notification> {
if (!this.container) {
return undefined;
}
try {
const notifications: DataModels.Notification[] = await fetchPortalNotifications();
if (!notifications || notifications.length === 0) {
return undefined;
}
return _.find(notifications, (notification: DataModels.Notification) => {
const throughputUpdateRegExp = new RegExp("Throughput update (.*) in progress");
return (
notification.kind === "message" &&
!notification.collectionName &&
notification.databaseName === this.id() &&
notification.description &&
throughputUpdateRegExp.test(notification.description)
);
});
} catch (error) {
Logger.logError(
JSON.stringify({
error: getErrorMessage(error),
accountName: userContext?.databaseAccount,
databaseName: this.id(),
collectionName: this.id(),
}),
"Settings tree node"
);
return undefined;
}
}
private getDeltaCollections(
updatedCollectionsList: DataModels.Collection[]
): { toAdd: DataModels.Collection[]; toDelete: Collection[] } {
const collectionsToAdd: DataModels.Collection[] = _.filter(
updatedCollectionsList,
(collection: DataModels.Collection) => {
const collectionExists = _.some(
this.collections(),
(existingCollection: Collection) => existingCollection.id() === collection.id
);
return !collectionExists;
}
);
const collectionsToDelete: Collection[] = [];
ko.utils.arrayForEach(this.collections(), (collection: Collection) => {
const collectionPresentInUpdatedList = _.some(
updatedCollectionsList,
(coll: DataModels.Collection) => coll.id === collection.id()
);
if (!collectionPresentInUpdatedList) {
collectionsToDelete.push(collection);
}
});
return { toAdd: collectionsToAdd, toDelete: collectionsToDelete };
}
private addCollectionsToList(collections: Collection[]): void {
this.collections(
this.collections()
.concat(collections)
.sort((collection1, collection2) => collection1.id().localeCompare(collection2.id()))
);
}
private deleteCollectionsFromList(collectionsToRemove: Collection[]): void {
if (collectionsToRemove.length === 0) {
return;
}
const collectionsToKeep: Collection[] = [];
ko.utils.arrayForEach(this.collections(), (collection: Collection) => {
const shouldRemoveCollection = _.some(collectionsToRemove, (coll: Collection) => coll.id() === collection.id());
if (!shouldRemoveCollection) {
collectionsToKeep.push(collection);
}
});
this.collections(collectionsToKeep);
}
public addSchema(collection: DataModels.Collection, interval?: number): NodeJS.Timeout {
let checkForSchema: NodeJS.Timeout;
interval = interval || 5000;
if (collection.analyticalStorageTtl !== undefined && userContext.features.enableSchema) {
collection.requestSchema = () => {
this.junoClient.requestSchema({
id: undefined,
subscriptionId: userContext.subscriptionId,
resourceGroup: userContext.resourceGroup,
accountName: userContext.databaseAccount.name,
resource: `dbs/${this.id()}/colls/${collection.id}`,
status: "new",
});
checkForSchema = setInterval(async () => {
const response: IJunoResponse<DataModels.ISchema> = await this.junoClient.getSchema(
userContext.subscriptionId,
userContext.resourceGroup,
userContext.databaseAccount.name,
this.id(),
collection.id
);
if (response.status >= 404) {
clearInterval(checkForSchema);
}
if (response.data !== undefined) {
clearInterval(checkForSchema);
collection.schema = response.data;
}
}, interval);
};
collection.requestSchema();
}
return checkForSchema;
}
} | the_stack |
import { expect } from "chai";
import { shallow } from "enzyme";
import * as React from "react";
import * as sinon from "sinon";
import { MockRender } from "@itwin/core-frontend";
import { ContentLayoutProps, StandardContentLayouts } from "@itwin/appui-abstract";
import {
ConfigurableCreateInfo, ContentControl, ContentGroup, ContentLayout, ContentLayoutDef, ContentLayoutManager,
ContentViewManager, CoreTools, FloatingContentControl, Frontstage, FrontstageManager, FrontstageProps, FrontstageProvider, SplitPane,
} from "../../appui-react";
import TestUtils, { mount } from "../TestUtils";
describe("ContentLayout", () => {
class TestContentControl extends ContentControl {
constructor(info: ConfigurableCreateInfo, options: any) {
super(info, options);
this.reactNode = <div>Test</div>;
}
}
const myContentGroup: ContentGroup = new ContentGroup({
id: "testGroup",
layout: StandardContentLayouts.singleView,
contents: [{ id: "myContent", classId: TestContentControl, applicationData: { name: "Test" } }],
});
const myContentLayout: ContentLayoutDef = new ContentLayoutDef({
id: "SingleContent",
description: "UiFramework:tests.singleContent",
});
const contentGroup2: ContentGroup = new ContentGroup({
id: "contentGroup2",
layout: StandardContentLayouts.fourQuadrants,
contents: [
{ id: "one", classId: TestContentControl, applicationData: "data1" },
{ id: "two", classId: TestContentControl, applicationData: "data2" },
{ id: "three", classId: TestContentControl, applicationData: "data3" },
{ id: "four", classId: TestContentControl, applicationData: "data4" },
],
});
const contentLayout2: ContentLayoutDef = new ContentLayoutDef({
id: "TwoHalvesVertical",
description: "SampleApp:ContentLayoutDef.TwoHalvesVertical",
verticalSplit: { id: "TwoHalvesVertical.VerticalSplit", percentage: 0.50, left: 0, right: 1 },
});
const standardContentLayout1: ContentLayoutDef = new ContentLayoutDef(StandardContentLayouts.fourQuadrants);
class TestFrontstage2 extends FrontstageProvider {
public static stageId = "TestFrontstage2";
public get id(): string {
return TestFrontstage2.stageId;
}
public get frontstage(): React.ReactElement<FrontstageProps> {
return (
<Frontstage id={this.id} defaultTool={CoreTools.selectElementCommand}
contentGroup={contentGroup2} />
);
}
}
before(async () => {
await TestUtils.initializeUiFramework();
await MockRender.App.startup();
FrontstageManager.clearFrontstageProviders();
const frontstageProvider = new TestFrontstage2();
FrontstageManager.addFrontstageProvider(frontstageProvider);
const frontstageDef = await FrontstageManager.getFrontstageDef(TestFrontstage2.stageId);
await FrontstageManager.setActiveFrontstageDef(frontstageDef);
});
after(async () => {
await MockRender.App.shutdown();
TestUtils.terminateUiFramework();
});
it("SingleContent should render", () => {
mount(<ContentLayout contentGroup={myContentGroup} contentLayout={myContentLayout} isInFooterMode={true} />);
});
it("SingleContent renders correctly", () => {
shallow(<ContentLayout contentGroup={myContentGroup} contentLayout={myContentLayout} isInFooterMode={true} />).should.matchSnapshot();
});
it("TwoHalvesVertical should render", () => {
mount(<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout2} isInFooterMode={true} />);
});
it("TwoHalvesVertical renders correctly", () => {
shallow(<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout2} isInFooterMode={true} />).should.matchSnapshot();
});
const contentLayout3: ContentLayoutDef = new ContentLayoutDef({
id: "TwoHalvesHorizontal",
description: "SampleApp:ContentLayoutDef.TwoHalvesHorizontal",
horizontalSplit: { id: "TwoHalvesHorizontal.HorizontalSplit", percentage: 0.50, top: 0, bottom: 1 },
});
it("TwoHalvesHorizontal should render", () => {
mount(<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout3} isInFooterMode={false} />);
});
it("TwoHalvesHorizontal renders correctly", () => {
shallow(<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout3} isInFooterMode={false} />).should.matchSnapshot();
});
const fourQuadrantsVerticalLayoutDef: ContentLayoutDef = new ContentLayoutDef(
{ // Four Views, two stacked on the left, two stacked on the right.
id: "fourQuadrantsVertical",
verticalSplit: {
id: "fourQuadrantsVertical",
percentage: 0.50,
lock: true,
minSizeLeft: 100,
minSizeRight: 100,
left: { horizontalSplit: { id: "fourQuadrantsRightHorizontal", percentage: 0.50, top: 0, bottom: 1, lock: true, minSizeTop: 50, minSizeBottom: 50 } },
right: { horizontalSplit: { id: "fourQuadrantsLeftHorizontal", percentage: 0.50, top: 2, bottom: 3, lock: true, minSizeTop: 50, minSizeBottom: 50 } },
},
},
);
it("FourQuadrantsVertical should render", () => {
mount(<ContentLayout contentGroup={contentGroup2} contentLayout={fourQuadrantsVerticalLayoutDef} isInFooterMode={false} />);
});
it("FourQuadrantsVertical renders correctly", () => {
shallow(<ContentLayout contentGroup={contentGroup2} contentLayout={fourQuadrantsVerticalLayoutDef} isInFooterMode={false} />).should.matchSnapshot();
});
const fourQuadrantsHorizontalLayoutDef: ContentLayoutDef = new ContentLayoutDef(
{ // Four Views, two stacked on the left, two stacked on the right.
id: "fourQuadrantsHorizontal",
horizontalSplit: {
id: "fourQuadrantsHorizontal",
percentage: 0.50,
lock: true,
minSizeTop: 100,
minSizeBottom: 100,
top: { verticalSplit: { id: "fourQuadrantsTopVertical", percentage: 0.50, left: 0, right: 1, lock: true, minSizeLeft: 100, minSizeRight: 100 } },
bottom: { verticalSplit: { id: "fourQuadrantsBottomVertical", percentage: 0.50, left: 2, right: 3, lock: true, minSizeLeft: 100, minSizeRight: 100 } },
},
},
);
it("FourQuadrantsHorizontal should render", () => {
mount(<ContentLayout contentGroup={contentGroup2} contentLayout={fourQuadrantsHorizontalLayoutDef} isInFooterMode={false} />);
});
it("FourQuadrantsVertical renders correctly", () => {
shallow(<ContentLayout contentGroup={contentGroup2} contentLayout={fourQuadrantsHorizontalLayoutDef} isInFooterMode={false} />).should.matchSnapshot();
});
it("ContentLayoutDiv mouse down and up", () => {
const wrapper = mount(<ContentLayout contentGroup={myContentGroup} contentLayout={myContentLayout} isInFooterMode={true} />);
const layoutDiv = wrapper.find("#uifw-contentlayout-div");
layoutDiv.simulate("mouseDown");
expect(ContentViewManager.isMouseDown).to.be.true;
layoutDiv.simulate("mouseUp");
expect(ContentViewManager.isMouseDown).to.be.false;
});
it("ContentWrapper mouse down", () => {
const wrapper = mount(<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout2} isInFooterMode={true} />);
const layoutWrappers = wrapper.find("div.uifw-contentlayout-wrapper");
expect(layoutWrappers.length).to.eq(2);
expect(wrapper.find("div.uifw-contentlayout-overlay-active").length).to.eq(1);
layoutWrappers.at(1).simulate("mouseDown");
wrapper.update();
expect(wrapper.find("div.uifw-contentlayout-overlay-active").length).to.eq(1);
});
it("Vertical SplitPane onChanged", () => {
const wrapper = mount(
<div>
<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout2} isInFooterMode={true} />
</div>);
const splitPanel = wrapper.find(SplitPane);
expect(splitPanel.length).to.eq(1);
splitPanel.prop("onChange")!(50);
wrapper.update();
});
it("Horizontal SplitPane onChanged", () => {
const wrapper = mount(
<div>
<ContentLayout contentGroup={contentGroup2} contentLayout={contentLayout3} isInFooterMode={true} />
</div>);
const splitPanel = wrapper.find(SplitPane);
expect(splitPanel.length).to.eq(1);
splitPanel.prop("onChange")!(50);
wrapper.update();
});
it("ContentLayoutManager.setActiveLayout & refreshActiveLayout should emit onContentLayoutActivatedEvent", async () => {
const spyMethod = sinon.spy();
const layoutProps: ContentLayoutProps = {
id: "UiFramework:tests.singleContent",
description: "UiFramework:tests.singleContent",
};
const contentLayout = new ContentLayoutDef(layoutProps);
const remove = FrontstageManager.onContentLayoutActivatedEvent.addListener(spyMethod);
await ContentLayoutManager.setActiveLayout(contentLayout, myContentGroup);
spyMethod.calledOnce.should.true;
ContentLayoutManager.refreshActiveLayout();
spyMethod.calledTwice.should.true;
remove();
});
const threeRightStackedLayoutDef: ContentLayoutDef = new ContentLayoutDef(
{ // Three Views, one on the left, two stacked on the right.
id: "ThreeRightStacked",
description: "SampleApp:ContentLayoutDef.ThreeRightStacked",
verticalSplit: {
id: "ThreeRightStacked.MainVertical",
percentage: 0.50,
left: 0,
right: { horizontalSplit: { id: "ThreeRightStacked.Right", percentage: 0.50, top: 1, bottom: 3 } },
},
},
);
it("ContentLayoutDef.getUsedContentIndexes should return correct indexes", () => {
expect(myContentLayout.getUsedContentIndexes()).to.have.members([0]);
expect(contentLayout2.getUsedContentIndexes()).to.have.members([0, 1]);
expect(contentLayout3.getUsedContentIndexes()).to.have.members([0, 1]);
expect(fourQuadrantsVerticalLayoutDef.getUsedContentIndexes()).to.have.members([0, 1, 2, 3]);
expect(fourQuadrantsHorizontalLayoutDef.getUsedContentIndexes()).to.have.members([0, 1, 2, 3]);
expect(threeRightStackedLayoutDef.getUsedContentIndexes()).to.have.members([0, 1, 3]);
expect(standardContentLayout1.getUsedContentIndexes()).to.have.members([0, 1, 2, 3]);
});
});
describe("SingleContentLayout", () => {
class TestContentControl extends ContentControl {
constructor(info: ConfigurableCreateInfo, options: any) {
super(info, options);
this.reactNode = <div>Test</div>;
}
}
const myContentGroup: ContentGroup = new ContentGroup({
id: "testGroup",
layout: StandardContentLayouts.singleView,
contents: [{ id: "myContent", classId: TestContentControl, applicationData: { name: "Test" } }],
});
const myContentLayout: ContentLayoutDef = new ContentLayoutDef({
id: "SingleContent",
description: "UiFramework:tests.singleContent",
});
class TestFrontstage1 extends FrontstageProvider {
public static stageId = "TestFrontstage1";
public get id(): string {
return TestFrontstage1.stageId;
}
public get frontstage(): React.ReactElement<FrontstageProps> {
return (
<Frontstage id={this.id} defaultTool={CoreTools.selectElementCommand}
contentGroup={myContentGroup} />
);
}
}
before(async () => {
await TestUtils.initializeUiFramework();
await MockRender.App.startup();
FrontstageManager.clearFrontstageProviders();
const frontstageProvider = new TestFrontstage1();
FrontstageManager.addFrontstageProvider(frontstageProvider);
const frontstageDef = await FrontstageManager.getFrontstageDef(TestFrontstage1.stageId);
await FrontstageManager.setActiveFrontstageDef(frontstageDef);
});
after(async () => {
await MockRender.App.shutdown();
TestUtils.terminateUiFramework();
});
it("Should set active if floating content exists", () => {
const floatingNode = <div key="floating" />;
class TestFloatingContentControl extends FloatingContentControl {
constructor() {
super("ContentTestFloatingContentControl", "ContentTestFloatingContentControl", floatingNode);
}
}
const floatingControl = new TestFloatingContentControl();
ContentViewManager.addFloatingContentControl(floatingControl);
const wrapper = mount(<ContentLayout contentGroup={myContentGroup} contentLayout={myContentLayout} isInFooterMode={true} />);
const layoutWrappers = wrapper.find("div.uifw-contentlayout-wrapper");
expect(layoutWrappers.length).to.eq(1);
layoutWrappers.at(0).simulate("mouseDown");
wrapper.update();
// eslint-disable-next-line no-console
// console.log(wrapper.debug());
expect(wrapper.find("div.uifw-contentlayout-overlay-active").length).to.eq(1);
ContentViewManager.setActiveContent(floatingControl.reactNode);
wrapper.update();
// eslint-disable-next-line no-console
// console.log(wrapper.debug());
expect(wrapper.find("div.uifw-contentlayout-overlay-active").length).to.eq(0);
ContentViewManager.dropFloatingContentControl(floatingControl);
});
}); | the_stack |
import * as path from 'path'
import { validator } from '@salto-io/workspace'
import { collections } from '@salto-io/lowerdash'
import { EditorWorkspace } from '../src/workspace'
import { mockWorkspace } from './workspace'
const { awu } = collections.asynciterable
describe('workspace', () => {
const workspaceBaseDir = path.resolve(`${__dirname}/../../test/test-nacls`)
const naclFileName = path.join(workspaceBaseDir, 'all.nacl')
const validation1FileName = path.join(workspaceBaseDir, 'validation1.nacl')
const validation2FileName = path.join(workspaceBaseDir, 'validation2.nacl')
const validation3FileName = path.join(workspaceBaseDir, 'validation3.nacl')
const splitted1FileName = path.join(workspaceBaseDir, 'splitted1.nacl')
const splitted2FileName = path.join(workspaceBaseDir, 'splitted2.nacl')
const inactiveFileName = path.join(workspaceBaseDir, 'inactive', 'test.nacl')
const validate = async (workspace: EditorWorkspace, elements: number):
Promise<void> => {
const wsElements = await workspace.elements
expect(wsElements && (await awu(await wsElements.getAll()).toArray()).length).toBe(elements)
}
it('should initiate a workspace', async () => {
const workspace = new EditorWorkspace(workspaceBaseDir, await mockWorkspace([naclFileName]))
await validate(workspace, 18)
})
it('should collect errors', async () => {
const baseWs = await mockWorkspace([naclFileName])
baseWs.hasErrors = jest.fn().mockResolvedValue(true)
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
expect(workspace.hasErrors()).toBeTruthy()
})
it('should update a single file', async () => {
const baseWs = await mockWorkspace([naclFileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const filename = 'new'
const buffer = 'test'
await workspace.setNaclFiles({ filename, buffer })
await workspace.awaitAllUpdates()
expect((await workspace.getNaclFile(filename))?.buffer).toEqual(buffer)
})
it('should maintain status on error', async () => {
const baseWs = await mockWorkspace([naclFileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
baseWs.hasErrors = jest.fn().mockResolvedValue(true)
await workspace.setNaclFiles({ filename: 'error', buffer: 'error content' })
await workspace.awaitAllUpdates()
expect(await workspace.elements).toBeDefined()
expect(await workspace.hasErrors()).toBeTruthy()
await validate(workspace, 18)
})
it('should support file removal', async () => {
const baseWs = await mockWorkspace([naclFileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
await workspace.removeNaclFiles(naclFileName)
await workspace.awaitAllUpdates()
expect(await workspace.getNaclFile(naclFileName)).toEqual(undefined)
})
describe('error iterative calculation', () => {
it('should fix old validation errors', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
expect((await workspace.errors()).validation).toHaveLength(1)
const buffer = `
type vs.type {
number field {}
}
vs.type withReference {
_parent = vs.type.instance.referenced
}
`
await workspace.setNaclFiles({ filename: validation1FileName, buffer })
await workspace.awaitAllUpdates()
expect((await workspace.errors()).validation).toHaveLength(0)
})
it('should create a validation error for unresolved reference', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const currentValidationErrors = (await workspace.errors()).validation
expect(currentValidationErrors).toHaveLength(1)
expect(currentValidationErrors[0]).toBeInstanceOf(validator.InvalidValueTypeValidationError)
const buffer = `
vs.type inst {
field = "4"
}
vs.type oldReferenced {
}
`
await workspace.setNaclFiles({ filename: validation2FileName, buffer })
await workspace.awaitAllUpdates()
const newValidationErrors = (await workspace.errors()).validation
expect(newValidationErrors).toHaveLength(3)
newValidationErrors.forEach(ve => {
expect(ve).toBeInstanceOf(validator.UnresolvedReferenceValidationError)
})
})
it('should create a validation error for unresolved reference field', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const currentValidationErrors = (await workspace.errors()).validation
expect(currentValidationErrors).toHaveLength(1)
expect(currentValidationErrors[0]).toBeInstanceOf(validator.InvalidValueTypeValidationError)
const buffer = `
vs.type inst {
field = "4"
}
vs.type referenced {
}
vs.type referencedField {
}
`
await workspace.setNaclFiles({ filename: validation2FileName, buffer })
await workspace.awaitAllUpdates()
const newValidationErrors = (await workspace.errors()).validation
expect(newValidationErrors).toHaveLength(2)
newValidationErrors.forEach(ve => {
expect(ve).toBeInstanceOf(validator.UnresolvedReferenceValidationError)
})
})
it('should have a validation error for unresolved reference even if errors was never called', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const buffer = `
vs.type inst {
field = "4"
}
vs.type oldReferenced {
}
`
await workspace.setNaclFiles({ filename: validation2FileName, buffer })
await workspace.awaitAllUpdates()
const newValidationErrors = (await workspace.errors()).validation
expect(newValidationErrors).toHaveLength(3)
newValidationErrors.forEach(ve => {
expect(ve).toBeInstanceOf(validator.UnresolvedReferenceValidationError)
})
})
it('should create new unresolved reference errors when there are already errors', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const currentValidationErrors = (await workspace.errors()).validation
expect(currentValidationErrors).toHaveLength(1)
expect(currentValidationErrors[0]).toBeInstanceOf(validator.InvalidValueTypeValidationError)
const buffer = `
vs.type inst {
field = "4"
}
vs.type referenced {
}
`
await workspace.setNaclFiles({ filename: validation2FileName, buffer })
await workspace.awaitAllUpdates()
const firstUpdateValidationErrors = (await workspace.errors()).validation
expect(firstUpdateValidationErrors).toHaveLength(2)
firstUpdateValidationErrors.forEach(ve => {
expect(ve).toBeInstanceOf(validator.UnresolvedReferenceValidationError)
})
const newBuffer = `
vs.type inst {
field = "4"
}
`
await workspace.setNaclFiles({ filename: validation2FileName, buffer: newBuffer })
await workspace.awaitAllUpdates()
const newValidationErrors = (await workspace.errors()).validation
expect(newValidationErrors).toHaveLength(3)
newValidationErrors.forEach(ve => {
expect(ve).toBeInstanceOf(validator.UnresolvedReferenceValidationError)
})
})
})
describe('validate files', () => {
let workspace: EditorWorkspace
beforeEach(async () => {
const baseWs = await mockWorkspace([validation3FileName, validation2FileName])
workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
await workspace.errors()
const buffer = `
type vs.type {
string field {}
}
`
await workspace.setNaclFiles({ filename: validation3FileName, buffer })
await workspace.awaitAllUpdates()
})
it('should validate specific files correctly', async () => {
expect((await workspace.errors()).validation).toHaveLength(0)
const newErrors = await workspace.validateFiles([validation2FileName])
expect(newErrors.validation).toHaveLength(1)
expect(await workspace.errors()).toEqual(newErrors)
})
it('should validate file with element with error correctly', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const newWorkspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const currentErrors = (await newWorkspace.errors()).validation
expect(currentErrors).toHaveLength(1)
const buffer = `
type vs.type {
boolean field {}
}
`
await newWorkspace.setNaclFiles({ filename: validation1FileName, buffer })
await newWorkspace.awaitAllUpdates()
const newErrors = await newWorkspace.validateFiles([validation2FileName])
expect(newErrors.validation).toHaveLength(2)
expect(await newWorkspace.errors()).toEqual(newErrors)
})
it('should calc all errors if wsErrors is undefiend', async () => {
const baseWs = await mockWorkspace([validation1FileName, validation2FileName])
const newWorkspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const errors = await newWorkspace.validateFiles([validation1FileName])
expect(errors.validation).toHaveLength(1)
expect(errors.validation[0].elemID.getFullName()).toEqual('vs.type.instance.inst.field')
})
it('should validate all touched elements', async () => {
const baseWs = await mockWorkspace([splitted1FileName, splitted2FileName])
const newWorkspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const errors = await newWorkspace.errors()
expect(errors.validation).toHaveLength(0)
const buffer = ''
await newWorkspace.setNaclFiles({ filename: splitted2FileName, buffer })
await newWorkspace.awaitAllUpdates()
const newErrors = await newWorkspace.errors()
expect(newErrors.validation).toHaveLength(1)
})
it('should not validate elements that are not already in the workspace', async () => {
const baseWs = await mockWorkspace([splitted1FileName, splitted2FileName])
const newWorkspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const errors = await newWorkspace.errors()
expect(errors.validation).toHaveLength(0)
const newErrors = await workspace.validateFiles([inactiveFileName])
expect(newErrors.validation).toHaveLength(0)
})
})
it('should call workspace opearation', async () => {
const baseWs = await mockWorkspace([naclFileName])
const workspace = new EditorWorkspace(workspaceBaseDir, baseWs)
const mockFunc = jest.fn().mockReturnValue(Promise.resolve('value'))
expect(await workspace.runOperationWithWorkspace(mockFunc)).toBe('value')
expect(mockFunc).toHaveBeenCalledWith(baseWs)
})
it('should not run two workspace opearations in parallel', async () => {
const arr: string[] = []
const firstOperation = async (): Promise<void> => {
arr.push('first')
await new Promise(resolve => setTimeout(resolve, 0))
arr.push('first')
}
const secondOperation = async (): Promise<void> => {
arr.push('second')
await new Promise(resolve => setTimeout(resolve, 0))
arr.push('second')
}
const workspace = new EditorWorkspace(workspaceBaseDir, await mockWorkspace([naclFileName]))
const firstPromise = workspace.runOperationWithWorkspace(firstOperation)
const secondPromise = workspace.runOperationWithWorkspace(secondOperation)
await firstPromise
await secondPromise
expect(arr).toEqual(['first', 'first', 'second', 'second'])
})
}) | the_stack |
import {Store, bindActionCreators} from "redux";
import ReactDOM from "react-dom";
import React, {useContext, useState, useEffect, useRef, useMemo} from "react";
import {shallowEqual, is} from "./shallow-equal";
declare const process: any;
/**
* Tuple constraint
* https://github.com/Microsoft/TypeScript/issues/29780
*/
type Tuple<T = any> = [T] | T[];
/**
* Pick only functions from an object and remove their return values
*/
type RemoveReturnTypes<T> = {
[K in keyof T]: T[K] extends (...args: any) => any
? (...args: Parameters<T[K]>) => void
: never
};
/**
* Flatten functions to their return types
*/
type FlattenToReturnTypes<T> = {
[K in keyof T]: T[K] extends (...args: any) => any
? ReturnType<T[K]>
: never
};
/** id sequence */
let SEQ = 0;
// Custom "null" because mapState can return the js null we must be able to
// differentiate from it
const nil = {} as "nil"; // cross browser Symbol hack :)
type Nil = "nil";
/**
* Subset of Map we use
*/
interface UpdatersMap {
set(id: number, updater: Function): unknown;
delete(id: number): unknown;
forEach(cb: (updater: Function) => void): unknown;
}
/**
* Require only parts of the store we need
*/
interface LooseStore {
dispatch(action: any): any;
getState(): any;
subscribe(cb: Function): void;
}
interface ContextType {
store?: LooseStore;
updaters: UpdatersMap;
}
interface MapState<S, Result> {
(state: S): Result;
}
class NoProviderError extends Error {
constructor() {
super("<HooksProvider> wrapping missing for useRedux*()?");
}
}
/**
* Create ponyfill Map if native is not available
*/
function createMap(): UpdatersMap {
if (typeof Map !== "undefined") {
return new Map<number, Function>();
}
const poorMap: Record<number, Function> = {};
// ponyfill for Map
return {
set(id: number, updater: Function) {
poorMap[id] = updater;
},
delete(id: number) {
delete poorMap[id];
},
forEach(cb: (updater: Function) => void) {
for (const id in poorMap) {
cb(poorMap[id]);
}
},
};
}
const StoreContext = React.createContext<ContextType>({
updaters: createMap(),
});
export function HooksProvider(props: {
store: LooseStore;
children: React.ReactNode;
}) {
// Mutable updaters list of all useReduxState() users
const updaters = useRef<UpdatersMap>(createMap());
/**
* Notify subscribers
*/
const notify = () => {
ReactDOM.unstable_batchedUpdates(() => {
updaters.current.forEach(updater => updater());
});
};
const preEffectState = useMemo(() => props.store.getState(), [props.store]);
useEffect(() => {
// Children might dispatch during effect exection. Check for that and
// notify them
if (preEffectState !== props.store.getState()) {
notify();
}
// Setup only one listener for the provider so we can batch update all
// hook users without causing tearing
return props.store.subscribe(notify);
}, [props.store]);
// Context values never update. We put the store directly and the updates
// list into it
return (
<StoreContext.Provider
value={{store: props.store, updaters: updaters.current}}
>
{props.children}
</StoreContext.Provider>
);
}
/**
* Use Redux dispatch
*/
export function useDispatch() {
const {store} = useContext(StoreContext);
if (!store) {
throw new NoProviderError();
}
return store.dispatch;
}
export function createUseSelect<State>() {
function useSelect<Selection, Result>(
select: (state: State) => Selection,
produce: (selection: Selection) => Result,
deps?: any[],
): Result;
function useSelect<Selection>(
select: (state: State) => Selection,
): Selection;
function useSelect<Selection, Result>(
select: (state: State) => Selection,
produce?: (selection: Selection) => Result,
deps?: any[],
): Selection | Result {
const ref = useRef<{
result: Result | Nil;
prevSelection: Selection | Nil;
}>({
result: nil,
prevSelection: nil,
});
function defaultProduce(state: Selection): Selection {
return state as any;
}
return useMapState(
(state: State) => {
const selection = select(state);
const selectionChanged = !shallowEqual(
selection,
ref.current.prevSelection,
);
if (selectionChanged) {
ref.current.prevSelection = selection;
}
if (!selectionChanged && ref.current.result !== nil) {
return ref.current.result;
}
const res = produce
? produce(selection)
: defaultProduce(selection);
ref.current.result = res as any;
return res as any;
},
deps as any,
);
}
return useSelect;
}
/**
* Bound actions creators object to Redux dispatch. Memoized.
*/
export function useActionCreators<T>(actionCreators: T): RemoveReturnTypes<T> {
const dispatch = useDispatch();
return useMemo(() => bindActionCreators(actionCreators as any, dispatch), [
actionCreators,
]);
}
function useForceRender() {
const [_, setUpdateCount] = useState(0);
return function triggerRender() {
setUpdateCount(count => count + 1);
};
}
function useDidDepsChange(deps: any[] | undefined) {
if (!deps) {
return false;
}
const memoDeps = useMemo(() => deps, deps);
// changed when useMemo returns the same deps reference
return memoDeps == deps;
}
export function createUseMapState<State>() {
return function useMapState<Deps extends Tuple, Result = any>(
mapState?: MapState<State, Result>,
deps?: Deps,
): Result {
const {store, updaters} = useContext(StoreContext);
if (!store) {
throw new NoProviderError();
}
/**
* Hold inital store state when the component mounts
*/
const initialState = useMemo(() => store.getState(), [store]);
/**
* Reference to the previously mapped state
*/
const prevRef = useRef<Result | Nil>(nil);
/**
* When this is set can bailout state mapping and just return this
*/
const bailoutRef = useRef<Result | Nil>(nil);
/**
* Trigger render from store updates
*/
const triggerRender = useForceRender();
/**
* Detect deps change when using the deps array
*/
const depsChanged = useDidDepsChange(deps);
/**
* Reference to the mapState function
*/
const mapStateRef = useRef<MapState<State, Result>>();
mapStateRef.current = mapState;
/**
* Get mapped value from the state
*/
const getMappedValue = (): Result => {
const state = store.getState();
if (!mapStateRef.current) {
return state;
}
const res = mapStateRef.current(state);
if (process.env.NODE_ENV !== "production") {
const check = mapStateRef.current(state);
if (!is(check, res)) {
console.warn(
"useMapState returns new identity on every run. This causes the component to render on every Redux state change. Consider use using useSelect().",
res,
);
}
}
return res;
};
// Set initial mapped states for the first render
if (prevRef.current === nil) {
prevRef.current = bailoutRef.current = getMappedValue();
}
useEffect(() => {
// handle updates from the store
const update = () => {
const next = getMappedValue();
if (!is(prevRef.current, next)) {
bailoutRef.current = next;
prevRef.current = next;
triggerRender();
}
};
// Mutate the updaters map so the subscription in the provider can
// update this hook
const id = ++SEQ;
updaters.set(id, update);
// Self update if the store did update between first render and this effect
if (initialState !== store.getState()) {
update();
}
return () => {
// Remove the updater on unmount or store change
updaters.delete(id);
// clear cached on store change
prevRef.current = nil;
bailoutRef.current = nil;
};
}, [store]);
// Bailout with the previously mapped state if we have deps and they did not
// change
if (deps && !depsChanged && bailoutRef.current === nil) {
bailoutRef.current = prevRef.current;
}
// Use the bailout if we have one
if (bailoutRef.current !== nil) {
const ret = bailoutRef.current;
bailoutRef.current = nil;
return ret;
}
// Normal render. Must map the state because the mapping function might
// have changed
return (prevRef.current = getMappedValue());
};
}
export function createUsePassiveMapState<State>() {
return function usePassiveMapState<Deps extends Tuple<any>, Result = any>(
mapState: MapState<State, Result>,
deps: Deps,
): Result {
const {store} = useContext(StoreContext);
if (!store) {
throw new NoProviderError();
}
if (deps) {
return useMemo(() => {
return mapState(store.getState());
}, deps);
}
return mapState(store.getState());
};
}
export const useMapState = createUseMapState<any>();
export const usePassiveMapState = createUsePassiveMapState<any>();
export const useSelect = createUseSelect<any>();
interface UseDispatch<Action> {
(): (action: Action) => void;
}
/**
* Create custom typed versions of the hooks
*/
export function createHooks<State, Action = any>() {
return {
useMapState: createUseMapState<State>(),
usePassiveMapState: createUsePassiveMapState<State>(),
useSelect: createUseSelect<State>(),
useDispatch: useDispatch as UseDispatch<Action>,
useActionCreators: useActionCreators,
};
} | the_stack |
import { TestBed } from '@angular/core/testing';
import {
TripPinConfig,
Person,
NAMESPACE,
PersonGender,
Trip,
Photo,
} from '../trippin.spec';
import { ODataClient } from '../client';
import { ODataModule } from '../module';
import { ODataEnumTypeParser } from './enum-type';
import {
ODataStructuredTypeParser,
ODataStructuredTypeFieldParser,
} from './structured-type';
import { ODataApi } from '../api';
import { ODataStructuredType } from '../schema';
import { Parser } from '../types';
import { HttpClientModule } from '@angular/common/http';
describe('ODataClient', () => {
let client: ODataClient;
let api: ODataApi;
enum Color {
Red = 1,
Yellow,
Orange,
Green,
Black,
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule, ODataModule.forRoot(TripPinConfig)],
});
client = TestBed.inject<ODataClient>(ODataClient);
api = new ODataApi({
serviceRootUrl: 'http://parser.testing.foo',
options: {
stringAsEnum: true,
},
schemas: [
{
namespace: 'ParserTesting',
enums: [{ name: 'Color', members: Color, fields: {} }],
entities: [
{
name: 'Entity',
fields: {
// Null values are represented as the JSON literal null.
null: { type: 'Edm.String', nullable: true },
// Values of type Edm.Boolean are represented as the JSON literals true and false
true: { type: 'Edm.Boolean' }, //The binary-valued logic
false: { type: 'Edm.Boolean' },
// Values of types Edm.Byte, Edm.SByte, Edm.Int16, Edm.Int32, Edm.Int64, Edm.Single, Edm.Double, and Edm.Decimal are represented as JSON numbers, except for NaN, INF, and –INF which are represented as strings.
byte: { type: 'Edm.Byte' }, //The unsigned 8-bit integer
sbyte: { type: 'Edm.SByte' }, //The signed 8-bit integer
int16: { type: 'Edm.Int16' },
int32: { type: 'Edm.Int32' },
int64: { type: 'Edm.Int64' },
single: { type: 'Edm.Single' },
double: { type: 'Edm.Double' }, //The IEEE 754 binary64 floating-point number with 15 - 17 decimal digits
decimal: { type: 'Edm.Decimal' }, //The numeric values with fixed precision and scale
// Values of type Edm.String are represented as JSON strings, using the JSON string escaping rules.
string: { type: 'Edm.String' },
// Values of type Edm.Binary, Edm.Date, Edm.DateTimeOffset, Edm.Duration, Edm.Guid, and Edm.TimeOfDay as well as enumeration values are represented as JSON strings whose content satisfies the rules binaryValue, dateValue, dateTimeOffsetValue, durationValue, guidValue, timeOfDayValue, and enumValue
binary: { type: 'Edm.Binary' },
date: { type: 'Edm.Date' }, //The date without a time-zone offset
dates: { type: 'Edm.Date', collection: true }, //The date without a time-zone offset
dateTimeOffset: { type: 'Edm.DateTimeOffset' },
dateTimeOffsets: {
type: 'Edm.DateTimeOffset',
collection: true,
},
duration: { type: 'Edm.Duration' },
timeOfDay: { type: 'Edm.TimeOfDay' }, //The clock time 00:00 - 23:59:59.999999999999
guid: { type: 'Edm.Guid' },
enumeration: { type: 'ParserTesting.Color' },
},
},
{
name: 'Complex',
fields: {
Number: { type: 'Edm.Int32', nullable: false },
String: { type: 'Edm.String' },
Color: { type: 'ParserTesting.Color' },
},
},
{
name: 'Testing',
fields: {
ID: {
type: 'Edm.Int32',
key: true,
referenced: 'ID',
nullable: false,
},
Value: { type: 'Edm.String' },
},
},
],
callables: [
{
name: 'TestingAction',
bound: true,
composable: false,
parameters: {
Notes: { type: 'Edm.String' },
Complexes: { type: 'ParserTesting.Complex', collection: true },
},
return: { type: 'ParserTesting.Testing' },
},
],
},
],
});
api.configure();
});
it('should return parser for type', () => {
const parser = client.parserForType(`${NAMESPACE}.Person`);
expect(parser instanceof ODataStructuredTypeParser).toBeTruthy();
});
it('should return parser from config', () => {
const schema = client.structuredTypeForType<Person>(`${NAMESPACE}.Person`);
expect(schema !== null).toBeTruthy();
const parser = (schema as ODataStructuredType<Person>).parser;
expect(parser instanceof ODataStructuredTypeParser).toBeTruthy();
});
it('should serialize enum', () => {
const schema = client.structuredTypeForType<Person>(`${NAMESPACE}.Person`);
expect(schema !== null).toBeTruthy();
const field = (schema as ODataStructuredType<Person>).findFieldByName(
'Gender'
);
expect(field !== undefined).toBeTruthy();
expect(
(field as ODataStructuredTypeFieldParser<any>).serialize(
PersonGender.Female,
(schema as ODataStructuredType<Person>).api.options
)
).toEqual('Female');
});
it('should deserialize enum', () => {
const schema = client.structuredTypeForType<Person>(`${NAMESPACE}.Person`);
const field = schema.findFieldByName(
'Gender'
) as ODataStructuredTypeFieldParser<PersonGender>;
expect(field !== undefined).toBeTruthy();
expect(field.deserialize('Female', schema.api.options)).toEqual(
PersonGender.Female
);
});
it('should serialize flags', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const parser = client.parserForType(
`${NAMESPACE}.PersonGender`
) as ODataEnumTypeParser<PersonGender>;
parser.flags = true;
const options = schema.api.options;
options.stringAsEnum = true;
const field = (schema as ODataStructuredType<Person>).findFieldByName(
'Gender'
) as Parser<PersonGender>;
expect(field !== undefined).toBeTruthy();
expect(field.serialize(3, options)).toEqual('Male, Female, Unknown');
expect(
field.serialize(
PersonGender.Male | PersonGender.Female | PersonGender.Unknown,
options
)
).toEqual('Male, Female, Unknown');
});
it('should deserialize flags', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const parser = client.parserForType(
`${NAMESPACE}.PersonGender`
) as ODataEnumTypeParser<PersonGender>;
parser.flags = true;
const field = (schema as ODataStructuredType<Person>).findFieldByName(
'Gender'
) as Parser<PersonGender>;
expect(field !== undefined).toBeTruthy();
expect(
field.deserialize('Male, Female, Unknown', schema.api.options)
).toEqual(3);
});
it('should validate entity', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.validate({
Gender: 4,
} as any)
).toEqual({
UserName: ['required'],
FirstName: ['required'],
LastName: ['required'],
Gender: ['mismatch'],
Concurrency: ['required'],
});
});
it('should validate entity with collection', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.validate(
{
FirstName: 'FirstName',
LastName: 'LastName',
Emails: ['some@email.com', 'other@email.com'],
Friends: [
{ FirstName: 'FirstName' } as Person,
{ FirstName: 'FirstName', LastName: 'LastName' },
],
Trips: [],
Gender: PersonGender.Male,
},
{ method: 'create', navigation: true }
)
).toEqual({
UserName: ['required'],
Friends: [
{ UserName: ['required'], LastName: ['required'] },
{ UserName: ['required'] },
],
});
});
it('should validate valid entity on create', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.validate(
<Person>{
FirstName: 'FirstName',
LastName: 'LastName',
UserName: 'UserName',
Emails: [],
Gender: PersonGender.Male,
},
{ method: 'create' }
)
).toBeUndefined();
});
it('should validate invalid entity on create', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.validate(
{
FirstName: 'FirstName',
LastName: 'LastName',
},
{ method: 'create' }
)
).toEqual({ UserName: ['required'] });
});
it('should validate entity on update', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.validate({
FirstName: 'FirstName',
LastName: 'LastName',
UserName: 'UserName',
Gender: PersonGender.Male,
})
).toEqual({ Concurrency: ['required'] });
});
it('should validate entity on patch', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.validate(
<Person>{
FirstName: 'FirstName',
Gender: PersonGender.Male,
},
{ method: 'modify' }
)
).toBeUndefined();
});
it('should serialize entity', () => {
const schema = client.structuredTypeForType<Person>(
`${NAMESPACE}.Person`
) as ODataStructuredType<Person>;
const options = schema.api.options;
options.stringAsEnum = false;
expect(
schema.parser.serialize(
<Person>{
FirstName: 'Name',
LastName: 'Name',
UserName: 'name',
Emails: [],
Gender: PersonGender.Male,
},
options
)
).toEqual({
FirstName: 'Name',
LastName: 'Name',
UserName: 'name',
Emails: [],
Gender: `${NAMESPACE}.PersonGender'Male'`,
});
});
it('should deserialize/serialize primitive values', () => {
const primitives = {
null: null,
true: true,
false: false,
byte: -128,
sbyte: -128,
int16: -128,
int32: -128,
int64: -128,
single: 'INF',
double: 3.1415926535897931,
decimal: 34.95,
string: 'Say "Hello",\nthen go',
binary: 'T0RhdGE=',
date: '2012-12-03',
dates: ['2012-12-03'],
timeOfDay: '07:59:59.999',
dateTimeOffset: '2012-12-03T07:16:23.000Z',
dateTimeOffsets: ['2012-12-03T07:16:23.000Z'],
duration: 'P2Y1M1W12DT23H59M59.999999999999S',
guid: '01234567-89ab-cdef-0123-456789abcdef',
enumeration: 'Yellow',
point: { type: 'point', coordinates: [142.1, 64.1] },
};
const parser = api.parserForType<any>(
'ParserTesting.Entity'
) as Parser<any>;
const result = parser.deserialize(primitives, api.options);
expect(parser.serialize(result, api.options)).toEqual(primitives);
});
it('should serialize callable parameters', () => {
const parameters = {
Notes: 'asdf',
Complexes: [
{
Number: 1,
String: 'asdf1',
Color: Color.Red,
},
],
};
const parser = api.findCallableForType<any>(
'ParserTesting.TestingAction'
) as Parser<any>;
const result = parser.serialize(parameters, api.options);
expect(result).toEqual({
Notes: 'asdf',
Complexes: [
{
Number: 1,
String: 'asdf1',
Color: 'Red',
},
],
});
});
}); | the_stack |
import { XStore, XType, XString } from '../pastore';
// TODO: 把测试对象的属性名改为 “数据结构名”, 使含义更明确
// it 的描述同意改成三部曲:has correct root xpath, has correct prop xpath, has correct prop value
// 用标准值 number: 1 , 2 ; string: string1, string2
interface SimpleState {
name: string,
age: number,
isMale: boolean,
isFemale: boolean,
homeInfo: {
city: string,
NO: number,
isRent: boolean,
applianceInfo: {
count: number,
brand: string,
isRent: boolean
}
},
numberStringProp: {
[key: string]: any
},
creditCardInfo: {
isValids: Array<boolean>,
limits: Array<number>,
name: Array<string>,
},
pets: Array<{
name: string,
age: number,
isCat: boolean
}>,
twoDimensionalArray: Array<Array<string>>
}
const initState: SimpleState = {
name: 'Peter',
age: 24,
isMale: true,
isFemale: false,
homeInfo: {
city: 'Guangzhou',
NO: 12,
isRent: false,
applianceInfo: {
count: 12,
brand: 'Gree',
isRent: false
}
},
numberStringProp: {
'0001': 'test'
},
creditCardInfo: {
isValids: [true, false],
limits: [10000, 20000],
name: ['Card1', 'Card2'],
},
pets: [{
name: 'Kitty',
age: 1,
isCat: true
}, {
name: 'Puppy',
age: 2,
isCat: false
}],
twoDimensionalArray: [
['a00', 'a01'],
['a10', 'a11']
]
}
class SimpleStore extends XStore<SimpleState>{
}
describe('toXType function test suit', function () {
let myStore = new SimpleStore(initState);
describe('can transform basic type at root', function () {
it('can transform initState into state', function () {
expect((myStore.imState as XType).__xpath__).toBe('');
expect((myStore.imState as XType).__store__).toBe(myStore);
})
it('can be get by path', function(){
expect(myStore.getByPath('')).toBe(myStore.imState)
expect(myStore.getByPath('name')).toBe(myStore.imState.name)
})
describe('can transform boolean correctly', function () {
describe('can transform boolean->true correctly', function () {
it('transform boolean: has the same primitive value', function () {
expect(myStore.imState.isMale).toEqual(true)
})
it('transform boolean: has the correct __xpath__ value', function () {
expect((myStore.imState.isMale as XType).__xpath__).toEqual('.isMale')
})
it('transform boolean: has the correct __store__ value', function () {
expect((myStore.imState.isMale as XType).__store__).toBe(myStore)
})
})
describe('can transform boolean->false correctly', function () {
it('transform boolean: has the same primitive value', function () {
expect(myStore.imState.isFemale).toEqual(false)
})
it('transform boolean: has the correct __xpath__ value', function () {
expect((myStore.imState.isFemale as XType).__xpath__).toEqual('.isFemale')
})
it('transform boolean: has the correct __store__ value', function () {
expect((myStore.imState.isFemale as XType).__store__).toBe(myStore)
})
})
})
describe('can transform number correctly', function () {
it('transform number: has the same primitive value', function () {
expect(myStore.imState.age).toEqual(24)
})
it('transform number: has the correct __xpath__ value', function () {
expect((myStore.imState.age as XType).__xpath__).toEqual('.age')
})
it('transform number: has the correct __store__ value', function () {
expect((myStore.imState.age as XType).__store__).toBe(myStore)
})
})
describe('can transform string correctly', function () {
it('transform string: has the same primitive value', function () {
expect(myStore.imState.name).toEqual('Peter')
})
it('transform string: has the correct __xpath__ value', function () {
expect((myStore.imState.name as XType).__xpath__).toEqual('.name')
})
it('transform string: has the correct __store__ value', function () {
expect((myStore.imState.name as XType).__store__).toBe(myStore)
})
})
})
describe('can transform object', function () {
it('can be get by path', function(){
expect(myStore.getByPath('homeInfo')).toBe(myStore.imState.homeInfo)
expect(myStore.getByPath('homeInfo.city')).toBe(myStore.imState.homeInfo.city)
})
describe('can transform object at root', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.homeInfo as XType).__xpath__).toEqual('.homeInfo')
})
it('has correct __store__', function () {
expect((myStore.imState.homeInfo as XType).__store__).toBe(myStore)
})
it('object props have correct primitive value', function () {
expect(myStore.imState.homeInfo.city).toEqual('Guangzhou')
expect(myStore.imState.homeInfo.isRent).toEqual(false)
expect(myStore.imState.homeInfo.NO).toEqual(12)
})
it('object props have correct __xpath__ value', function () {
expect((myStore.imState.homeInfo.city as XType).__xpath__).toEqual('.homeInfo.city')
expect((myStore.imState.homeInfo.isRent as XType).__xpath__).toEqual('.homeInfo.isRent')
expect((myStore.imState.homeInfo.NO as XType).__xpath__).toEqual('.homeInfo.NO')
})
it('object props have correct __store__ value', function () {
expect((myStore.imState.homeInfo.city as XType).__store__).toBe(myStore)
expect((myStore.imState.homeInfo.isRent as XType).__store__).toBe(myStore)
expect((myStore.imState.homeInfo.NO as XType).__store__).toBe(myStore)
})
})
describe('can transform nested object', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.homeInfo.applianceInfo as XType).__xpath__).toEqual('.homeInfo.applianceInfo')
})
it('has correct __store__', function () {
expect((myStore.imState.homeInfo.applianceInfo as XType).__store__).toBe(myStore)
})
it('object props have correct primitive value', function () {
expect(myStore.imState.homeInfo.applianceInfo.isRent).toEqual(false)
expect(myStore.imState.homeInfo.applianceInfo.count).toEqual(12)
expect(myStore.imState.homeInfo.applianceInfo.brand).toEqual('Gree')
})
it('object props have correct __xpath__ value', function () {
expect((myStore.imState.homeInfo.applianceInfo.isRent as XType).__xpath__)
.toEqual('.homeInfo.applianceInfo.isRent')
expect((myStore.imState.homeInfo.applianceInfo.count as XType).__xpath__)
.toEqual('.homeInfo.applianceInfo.count')
expect((myStore.imState.homeInfo.applianceInfo.brand as XType).__xpath__)
.toEqual('.homeInfo.applianceInfo.brand')
})
it('object props have correct __store__ value', function () {
expect((myStore.imState.homeInfo.applianceInfo.isRent as XType).__store__)
.toBe(myStore)
expect((myStore.imState.homeInfo.applianceInfo.count as XType).__store__)
.toBe(myStore)
expect((myStore.imState.homeInfo.applianceInfo.brand as XType).__store__)
.toBe(myStore)
})
})
describe('can transform numberStringProp', function () {
// Note: support but not suggest to use this kind of data structure,
// please use Array in place of it
it('has correct root __xpath__', function () {
expect((myStore.imState.numberStringProp as XType).__xpath__)
.toEqual('.numberStringProp')
})
it('has correct root __store__', function () {
expect((myStore.imState.numberStringProp as XType).__store__)
.toBe(myStore)
})
it('has correct value __xpath__', function () {
expect((myStore.imState.numberStringProp['0001'] as XType).__xpath__)
.toEqual('.numberStringProp.0001')
})
it('has correct value __store__', function () {
expect((myStore.imState.numberStringProp['0001'] as XType).__store__)
.toBe(myStore)
})
it('has correct primetive value', function () {
expect(myStore.imState.numberStringProp['0001'])
.toEqual('test')
})
})
})
describe('can transform root array', function () {
it('can be get by path', function(){
expect(myStore.getByPath('creditCardInfo.name')).toBe(myStore.imState.creditCardInfo.name)
expect(myStore.getByPath('creditCardInfo.name.0')).toBe(myStore.imState.creditCardInfo.name[0])
})
describe('can transform array with basic type elements', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.creditCardInfo as XType).__xpath__)
.toEqual('.creditCardInfo')
})
it('has correct __store__', function () {
expect((myStore.imState.creditCardInfo as XType).__store__)
.toBe(myStore)
})
describe('boolean elements', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.creditCardInfo.isValids as XType).__xpath__)
.toEqual('.creditCardInfo.isValids')
})
it('has correct __store__', function () {
expect((myStore.imState.creditCardInfo.isValids as XType).__store__)
.toBe(myStore)
})
it('array elements have correct __xpath__ value', function () {
expect((myStore.imState.creditCardInfo.isValids[0] as XType).__xpath__)
.toEqual('.creditCardInfo.isValids.0')
expect((myStore.imState.creditCardInfo.isValids[1] as XType).__xpath__)
.toEqual('.creditCardInfo.isValids.1')
})
it('array elements have correct __store__ value', function () {
expect((myStore.imState.creditCardInfo.isValids[0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.creditCardInfo.isValids[1] as XType).__store__)
.toBe(myStore)
})
it('array elements have correct primitive value', function () {
expect(myStore.imState.creditCardInfo.isValids[0])
.toEqual(true)
expect(myStore.imState.creditCardInfo.isValids[1])
.toEqual(false)
})
})
describe('number elements', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.creditCardInfo.limits as XType).__xpath__)
.toEqual('.creditCardInfo.limits')
})
it('has correct __store__', function () {
expect((myStore.imState.creditCardInfo.limits as XType).__store__)
.toBe(myStore)
})
it('array elements have correct __xpath__ value', function () {
expect((myStore.imState.creditCardInfo.limits[0] as XType).__xpath__)
.toEqual('.creditCardInfo.limits.0')
expect((myStore.imState.creditCardInfo.limits[1] as XType).__xpath__)
.toEqual('.creditCardInfo.limits.1')
})
it('array elements have correct __store__ value', function () {
expect((myStore.imState.creditCardInfo.limits[0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.creditCardInfo.limits[1] as XType).__store__)
.toBe(myStore)
})
it('array elements have correct primitive value', function () {
expect(myStore.imState.creditCardInfo.limits[0])
.toEqual(10000)
expect(myStore.imState.creditCardInfo.limits[1])
.toEqual(20000)
})
})
describe('string elements', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.creditCardInfo.name as XType).__xpath__)
.toEqual('.creditCardInfo.name')
})
it('has correct __store__', function () {
expect((myStore.imState.creditCardInfo.name as XType).__store__)
.toBe(myStore)
})
it('array elements have correct __xpath__ value', function () {
expect((myStore.imState.creditCardInfo.name[0] as XType).__xpath__)
.toEqual('.creditCardInfo.name.0')
expect((myStore.imState.creditCardInfo.name[1] as XType).__xpath__)
.toEqual('.creditCardInfo.name.1')
})
it('array elements have correct __store__ value', function () {
expect((myStore.imState.creditCardInfo.name[0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.creditCardInfo.name[1] as XType).__store__)
.toBe(myStore)
})
it('array elements have correct primitive value', function () {
expect(myStore.imState.creditCardInfo.name[0])
.toEqual('Card1')
expect(myStore.imState.creditCardInfo.name[1])
.toEqual('Card2')
})
})
})
describe('can transform array with object elements', function () {
it('has correct __xpath__', function () {
expect((myStore.imState.pets as XType).__xpath__)
.toEqual('.pets')
})
it('has correct __store__', function () {
expect((myStore.imState.pets as XType).__store__)
.toBe(myStore)
})
it('obejct has correct __xpath__ value', function () {
expect((myStore.imState.pets[0] as XType).__xpath__)
.toEqual('.pets.0')
expect((myStore.imState.pets[1] as XType).__xpath__)
.toEqual('.pets.1')
})
it('obejct has correct __store__ value', function () {
expect((myStore.imState.pets[0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.pets[1] as XType).__store__)
.toBe(myStore)
})
describe('object`s boolean prop', function () {
it('object` props has correct __xpath__ value', function () {
expect((myStore.imState.pets[0].isCat as XType).__xpath__)
.toEqual('.pets.0.isCat')
expect((myStore.imState.pets[1].isCat as XType).__xpath__)
.toEqual('.pets.1.isCat')
})
it('object` props has correct __store__ value', function () {
expect((myStore.imState.pets[0].isCat as XType).__store__)
.toBe(myStore)
expect((myStore.imState.pets[1].isCat as XType).__store__)
.toBe(myStore)
})
it('object` props has correct primetive value', function () {
expect(myStore.imState.pets[0].isCat)
.toEqual(true)
expect(myStore.imState.pets[1].isCat)
.toEqual(false)
})
})
describe('object`s number prop', function () {
it('object` props has correct __xpath__ value', function () {
expect((myStore.imState.pets[0].age as XType).__xpath__)
.toEqual('.pets.0.age')
expect((myStore.imState.pets[1].age as XType).__xpath__)
.toEqual('.pets.1.age')
})
it('object` props has correct __store__ value', function () {
expect((myStore.imState.pets[0].age as XType).__store__)
.toBe(myStore)
expect((myStore.imState.pets[1].age as XType).__store__)
.toBe(myStore)
})
it('object` props has correct primetive value', function () {
expect(myStore.imState.pets[0].age)
.toEqual(1)
expect(myStore.imState.pets[1].age)
.toEqual(2)
})
})
describe('object`s string prop', function () {
it('object` props has correct __xpath__ value', function () {
expect((myStore.imState.pets[0].name as XType).__xpath__)
.toEqual('.pets.0.name')
expect((myStore.imState.pets[1].name as XType).__xpath__)
.toEqual('.pets.1.name')
})
it('object` props has correct __store__ value', function () {
expect((myStore.imState.pets[0].name as XType).__store__)
.toBe(myStore)
expect((myStore.imState.pets[1].name as XType).__store__)
.toBe(myStore)
})
it('object` props has correct primetive value', function () {
expect(myStore.imState.pets[0].name)
.toEqual('Kitty')
expect(myStore.imState.pets[1].name)
.toEqual('Puppy')
})
})
})
describe('can transform array with array elements (multidimensional array)', function () {
it('has correct root __xpath__', function () {
expect((myStore.imState.twoDimensionalArray as XType).__xpath__)
.toEqual('.twoDimensionalArray')
})
it('has correct root __store__', function () {
expect((myStore.imState.twoDimensionalArray as XType).__store__)
.toBe(myStore)
})
it('has correct prop __xpath__, 1st dime', function () {
expect((myStore.imState.twoDimensionalArray[0] as XType).__xpath__)
.toEqual('.twoDimensionalArray.0')
expect((myStore.imState.twoDimensionalArray[1] as XType).__xpath__)
.toEqual('.twoDimensionalArray.1')
})
it('has correct prop __store__, 1st dime', function () {
expect((myStore.imState.twoDimensionalArray[0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.twoDimensionalArray[1] as XType).__store__)
.toBe(myStore)
})
it('has correct prop __xpath__, 2nd dime', function () {
expect((myStore.imState.twoDimensionalArray[0][0] as XType).__xpath__)
.toEqual('.twoDimensionalArray.0.0')
expect((myStore.imState.twoDimensionalArray[0][1] as XType).__xpath__)
.toEqual('.twoDimensionalArray.0.1')
expect((myStore.imState.twoDimensionalArray[1][0] as XType).__xpath__)
.toEqual('.twoDimensionalArray.1.0')
expect((myStore.imState.twoDimensionalArray[1][1] as XType).__xpath__)
.toEqual('.twoDimensionalArray.1.1')
})
it('has correct prop __store__, 2nd dime', function () {
expect((myStore.imState.twoDimensionalArray[0][0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.twoDimensionalArray[0][1] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.twoDimensionalArray[1][0] as XType).__store__)
.toBe(myStore)
expect((myStore.imState.twoDimensionalArray[1][1] as XType).__store__)
.toBe(myStore)
})
it('has correct prop value', function () {
expect(myStore.imState.twoDimensionalArray[0][0]).toEqual('a00')
expect(myStore.imState.twoDimensionalArray[0][1]).toEqual('a01')
expect(myStore.imState.twoDimensionalArray[1][0]).toEqual('a10')
expect(myStore.imState.twoDimensionalArray[1][1]).toEqual('a11')
})
})
})
describe('make different reference from the same raw type', function(){
let objectElement = {name: 'name'}
let arrayElement = ['name']
let initState1 = {
objectList: [objectElement, objectElement],
arrayList: [arrayElement, arrayElement]
}
let store1 = new XStore<typeof initState1>(initState1)
it('object', function(){
expect((store1.imState.objectList[0] as XType).__xpath__).toBe('.objectList.0')
expect((store1.imState.objectList[0].name as XType).__xpath__).toBe('.objectList.0.name')
expect((store1.imState.objectList[1] as XType).__xpath__).toBe('.objectList.1')
expect((store1.imState.objectList[1].name as XType).__xpath__).toBe('.objectList.1.name')
})
it('array', function(){
expect((store1.imState.arrayList[0] as XType).__xpath__).toBe('.arrayList.0')
expect((store1.imState.arrayList[0][0] as XType).__xpath__).toBe('.arrayList.0.0')
expect((store1.imState.arrayList[1] as XType).__xpath__).toBe('.arrayList.1')
expect((store1.imState.arrayList[1][0] as XType).__xpath__).toBe('.arrayList.1.0')
})
})
}) | the_stack |
import * as $ from 'jquery';
import * as guiStateController from 'guiState.controller';
const MODE = 'x3d';
const BROADCAST = false;
class StreamingViewer {
private readonly element: HTMLElement;
protected view;
private webots;
private disconnectCallback: Function;
private readyCallback: Function;
constructor(element: HTMLElement, webots) {
this.element = element;
this.webots = webots;
}
connect(url, mobileDevice: boolean, readyCallback: Function, disconnectCallback: Function) {
if (!this.view) {
this.view = new this.webots.View(this.element, mobileDevice);
}
this.view.broadcast = BROADCAST;
this.view.setTimeout(-1); // Disable timeout
this.disconnectCallback = disconnectCallback;
this.readyCallback = readyCallback;
this.view.open(url, MODE);
this.view.onquit = () => this.disconnect();
this.view.onready = () => {
window.onresize = this.view.onresize;
this.readyCallback();
};
}
disconnect() {
window.onresize = undefined;
this.view.close();
this.element.innerHTML = null;
if (this.view.mode === 'mjpeg') {
this.view.multimediaClient = undefined;
}
this.disconnectCallback();
}
hideToolbar() {
let toolbar = this.getToolbar();
if (toolbar) {
if (toolbar.style.display !== 'none') {
toolbar.style.display = 'none';
$('#view3d').height('100%');
window.dispatchEvent(new Event('resize'));
}
}
}
showToolbar() {
let toolbar = this.getToolbar();
if (toolbar) {
if (toolbar.style.display !== 'block') toolbar.style.display = 'block';
$('#view3d').height('calc(100% - 48px)');
window.dispatchEvent(new Event('resize'));
}
}
showQuit(enable) {
this.webots.showQuit = enable;
}
showRevert(enable) {
this.webots.showRevert = enable;
}
showRun(enable) {
this.webots.showRun = enable;
}
sendMessage(message: string) {
if (typeof this.view !== 'undefined' && this.view.stream.socket.readyState === 1) this.view.stream.socket.send(message);
}
private getToolbar() {
return this.element.querySelector<HTMLElement>('#toolBar');
}
}
class WebotsSimulation extends StreamingViewer {
private connected = false;
private sourceCode: string;
private context: any;
private volume: number = 0.5;
private lang: string;
private SpeechSynthesis: any;
private recognition: any;
private final_transcript: string;
constructor(element: HTMLElement, webots) {
super(element, webots);
}
uploadController(sourceCode: string) {
let message = {
name: 'supervisor',
message: 'upload:' + sourceCode,
};
super.sendMessage('robot:' + JSON.stringify(message));
}
start(url: string, sourceCode: string) {
this.sourceCode = sourceCode;
if (this.connected) {
return;
}
super.connect(
url,
false,
() => {
this.connected = true;
},
() => {
this.connected = false;
}
);
super.hideToolbar();
this.initSpeechSynthesis();
this.initSpeechRecognition();
$('#webotsProgress').height('120px');
let that = this;
this.view.onstdout = function (text: string) {
if (text.indexOf('finish') === 0) {
$('#simControl').trigger('click');
} else if (text.indexOf('say') === 0) {
let data = text.split(':');
that.sayText(data);
} else if (text.indexOf('setLanguage') === 0) {
let data = text.split(':');
that.lang = data[1];
} else if (text.indexOf('setVolume') === 0) {
let data = text.split(':');
that.volume = parseInt(data[1]) / 100;
} else if (text.indexOf('getVolume') === 0) {
let message = {
name: 'NAO',
message: 'volume:' + that.volume * 100,
};
that.sendMessage('robot:' + JSON.stringify(message));
} else if (text.indexOf('recognizeSpeech')) {
that.recognizeSpeech();
} else {
// console.log(text); // enable this maybe for debugging
}
};
}
reset() {
super.sendMessage('reset');
}
pause() {
this.view.runOnLoad = false;
super.sendMessage('pause');
}
run(sourceCode: string) {
this.sourceCode = sourceCode;
this.view.runOnLoad = true;
super.sendMessage('pause');
this.uploadController(sourceCode);
super.sendMessage('real-time:-1');
}
initSpeechSynthesis() {
this.SpeechSynthesis = window.speechSynthesis;
//cancel needed so speak works in chrome because it's created already speaking
this.SpeechSynthesis.cancel();
if (!this.SpeechSynthesis) {
this.context = null;
console.log(
'Sorry, but the Speech Synthesis API is not supported by your browser. Please, consider upgrading to the latest version or downloading Google Chrome or Mozilla Firefox'
);
}
}
sayText(data) {
let text = data[1];
let speed = data[2];
let pitch = data[3];
let lang = this.lang || guiStateController.getLanguage();
// Prevents an empty string from crashing the simulation
if (text === '') text = ' ';
// IE apparently doesnt support default parameters, this prevents it from crashing the whole simulation
speed = speed === undefined ? 30 : speed;
pitch = pitch === undefined ? 50 : pitch;
// Clamp values
speed = Math.max(0, Math.min(100, speed));
pitch = Math.max(0, Math.min(100, pitch));
// Convert to SpeechSynthesis values
speed = speed * 0.015 + 0.5; // use range 0.5 - 2; range should be 0.1 - 10, but some voices dont accept values beyond 2
pitch = pitch * 0.02 + 0.001; // use range 0.0 - 2.0; + 0.001 as some voices dont accept 0
var utterThis = new SpeechSynthesisUtterance(text);
// https://bugs.chromium.org/p/chromium/issues/detail?id=509488#c11
// Workaround to keep utterance object from being garbage collected by the browser
(window as any).utterances = [];
(window as any).utterances.push(utterThis);
if (lang === '') {
console.log('Language is not supported!');
} else {
var voices = (this.SpeechSynthesis as any).getVoices();
for (var i = 0; i < voices.length; i++) {
if (voices[i].lang.indexOf(this.lang) !== -1 || voices[i].lang.indexOf(lang.substr(0, 2)) !== -1) {
utterThis.voice = voices[i];
break;
}
}
if (utterThis.voice === null) {
console.log(
'Language "' +
lang +
'" could not be found. Try a different browser or for chromium add the command line flag "--enable-speech-dispatcher".'
);
}
}
utterThis.pitch = pitch;
utterThis.rate = speed;
utterThis.volume = this.volume;
let that = this;
let message = {
name: 'NAO',
message: 'finish',
};
utterThis.onend = function (event) {
that.sendMessage('robot:' + JSON.stringify(message));
};
//does not work for volume = 0 thus workaround with if statement
if (this.volume != 0) {
(this.SpeechSynthesis as any).speak(utterThis);
} else {
this.sendMessage('robot:' + JSON.stringify(message));
}
}
initSpeechRecognition() {
var SpeechRecognition = SpeechRecognition || (window as any).webkitSpeechRecognition;
let that = this;
if (SpeechRecognition) {
this.recognition = new SpeechRecognition();
this.recognition.continuous = false;
this.recognition.interimResults = true;
this.recognition.onresult = function (event) {
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
that.final_transcript += event.results[i][0].transcript;
}
}
};
this.recognition.onend = function () {
let message = {
name: 'NAO',
message: 'transcript:' + that.final_transcript,
};
that.sendMessage('robot:' + JSON.stringify(message));
this.stop();
};
}
}
recognizeSpeech() {
if (this.recognition) {
this.final_transcript = '';
this.recognition.lang = this.lang || guiStateController.getLanguage();
this.recognition.start();
} else {
alert('Sorry, your browser does not support speech recognition. Please use the latest version of Chrome, Edge, Safari or Opera');
let message = {
name: 'NAO',
message: 'transcript:' + '',
};
this.sendMessage('robot:' + JSON.stringify(message));
}
}
}
async function waitFor(predicate: () => boolean, interval: number, timeout: number): Promise<void> {
const start = Date.now();
return new Promise((resolve, reject) => {
function check() {
return setTimeout(() => {
if (predicate()) {
resolve();
} else if (Date.now() - start > timeout) {
reject();
} else {
check();
}
}, interval);
}
check();
});
}
class WebotsSimulationController {
private isPrepared = false;
private webotsSimulation: WebotsSimulation;
async init(sourceCode) {
$('#simEditButtons, #canvasDiv, #simRobot, #simValues').hide();
$('#webotsDiv, #simButtons').show();
if (!this.webotsSimulation) {
this.prepareWebots();
// Lazy load webots and all other dependencies only if the webots simulation is actually used
// @ts-ignore
const { webots } = await import('webots');
try {
await this.wasmLoaded();
} catch (e) {
console.error('Could not load webots simulation', e);
return;
}
this.webotsSimulation = new WebotsSimulation(WebotsSimulationController.createWebotsDiv(), webots);
}
this.webotsSimulation.start(guiStateController.getWebotsUrl(), sourceCode);
}
run(sourceCode) {
this.webotsSimulation.run(sourceCode);
}
resetPose() {
this.webotsSimulation.reset();
}
stopProgram() {
this.webotsSimulation.pause();
}
disconnect() {
this.webotsSimulation.disconnect();
}
private async wasmLoaded() {
await waitFor(() => window['Module']['asm'], 10, 1000);
}
private prepareWebots() {
if (!this.isPrepared) {
WebotsSimulationController.loadCss();
WebotsSimulationController.prepareModuleForWebots();
this.isPrepared = true;
}
}
private static createWebotsDiv(): HTMLElement {
let webotsDiv: HTMLElement = document.querySelector('#webotsDiv');
if (webotsDiv) {
return;
}
webotsDiv = document.createElement('webots-streaming');
webotsDiv.id = 'webotsDiv';
document.getElementById('simDiv').prepend(webotsDiv);
return webotsDiv;
}
private static loadCss() {
let link = document.createElement('link');
link.href = 'https://cyberbotics.com/wwi/R2021c/css/wwi.css';
link.type = 'text/css';
link.rel = 'stylesheet';
document.head.appendChild(link);
}
private static prepareModuleForWebots() {
if (!window.hasOwnProperty('Module')) {
window['Module'] = [];
}
window['Module']['locateFile'] = function (path, prefix) {
// if it's a data file, use a custom dir
if (path.endsWith('.data')) return window.location.origin + '/js/libs/webots/' + path;
// otherwise, use the default, the prefix (JS file's dir) + the path
return prefix + path;
};
}
}
export = new WebotsSimulationController(); | the_stack |
* @module Tools
*/
import { BeEvent, GuidString, Id64String } from "@itwin/core-bentley";
import { FeatureAppearance, GeometricElementProps } from "@itwin/core-common";
import { EmphasizeElements, FeatureOverrideProvider, FeatureSymbology, IModelApp, IModelConnection, ScreenViewport, Viewport } from "@itwin/core-frontend";
import { Presentation } from "@itwin/presentation-frontend";
import { SyncUiEventDispatcher } from "../syncui/SyncUiEventDispatcher";
import { UiFramework } from "../UiFramework";
/** Supported Hide, Isolate, and Emphasize Actions. These also serve as FeatureTracking Ids.
* @public
*/
export enum HideIsolateEmphasizeAction {
EmphasizeSelectedElements = "EmphasizeSelectedElements",
IsolateSelectedElements = "IsolateSelectedElements",
IsolateSelectedCategories = "IsolateSelectedCategories",
IsolateSelectedModels = "IsolateSelectedModels",
HideSelectedElements = "HideSelectedElements",
HideSelectedModels = "HideSelectedModels",
HideSelectedCategories = "HideSelectedCategories",
ClearHiddenIsolatedEmphasized = "ClearHiddenIsolatedEmphasized",
ClearOverrideModels = "ClearOverrideModels",
ClearOverrideCategories = "ClearOverrideCategories",
}
const featureIdMap = new Map<HideIsolateEmphasizeAction, GuidString>([
[HideIsolateEmphasizeAction.EmphasizeSelectedElements, "d74eb93f-deae-4700-8da6-1013a8a7aa26"],
[HideIsolateEmphasizeAction.IsolateSelectedElements, "24327638-1611-45fa-a379-fa73329098ec"],
[HideIsolateEmphasizeAction.IsolateSelectedCategories, "e58081ab-2c33-4a15-924f-71082b58ca3b"],
[HideIsolateEmphasizeAction.IsolateSelectedModels, "3475921e-7dd1-4547-993e-a3e284ef8b62"],
[HideIsolateEmphasizeAction.HideSelectedElements, "2ca673ec-001a-4890-bc25-18bc88358fe0"],
[HideIsolateEmphasizeAction.HideSelectedModels, "8b41e859-ae17-4e19-b220-87a5cf9f8242"],
[HideIsolateEmphasizeAction.HideSelectedCategories, "c5d6916b-e8d7-4796-bae9-a5303712d46b"],
[HideIsolateEmphasizeAction.ClearHiddenIsolatedEmphasized, "7b135c8a-3f3c-4297-b36c-b0ac51f1d8de"],
[HideIsolateEmphasizeAction.ClearOverrideModels, "6e519b94-edab-4b13-9ce7-0bcdfa27ccfe"],
[HideIsolateEmphasizeAction.ClearOverrideCategories, "9d2be3c6-6992-4c30-84eb-10f6b9379d06"],
]);
/** Selection Context Action Event Argument
* @public
*/
export interface EmphasizeElementsChangedArgs {
/** viewport where action was performed */
readonly viewport: ScreenViewport;
/** action being performed */
readonly action: HideIsolateEmphasizeAction;
}
/** Overrides given models to provide emphasize functionality
* @public
*/
// istanbul ignore next
class ModelOverrideProvider implements FeatureOverrideProvider {
constructor(public modelIds: string[], public defaultAppearance: FeatureAppearance) { }
public addFeatureOverrides(overrides: FeatureSymbology.Overrides, _viewport: Viewport): void {
overrides.setDefaultOverrides(this.defaultAppearance, true);
// Override with nothing so that we keep the model looking normal and override the default appearance of everything else
const emptyAppearance = FeatureAppearance.fromJSON({});
this.modelIds.forEach((modelId: string) => {
overrides.overrideModel(modelId, emptyAppearance, true);
});
}
}
/** Overrides given categories to provide emphasize functionality
* @public
*/
// istanbul ignore next
class SubCategoryOverrideProvider implements FeatureOverrideProvider {
constructor(public subCategoryIds: string[], public defaultAppearance: FeatureAppearance) { }
public addFeatureOverrides(overrides: FeatureSymbology.Overrides, _viewport: Viewport): void {
overrides.setDefaultOverrides(this.defaultAppearance, true);
// Override with nothing so that we keep the category looking normal and override the default appearance of everything else
const emptyAppearance = FeatureAppearance.fromJSON({});
this.subCategoryIds.forEach((id: string) => {
overrides.overrideSubCategory(id, emptyAppearance, true);
});
}
}
/** Cache of Models that are inside of subjects */
// istanbul ignore next
class SubjectModelIdsCache {
private _imodel: IModelConnection;
private _subjectsHierarchy: Map<Id64String, Id64String[]> | undefined;
private _subjectModels: Map<Id64String, Id64String[]> | undefined;
private _init: Promise<void> | undefined;
constructor(imodel: IModelConnection) {
this._imodel = imodel;
}
private async initSubjectsHierarchy() {
this._subjectsHierarchy = new Map();
const ecsql = `SELECT ECInstanceId id, Parent.Id parentId FROM bis.Subject WHERE Parent IS NOT NULL`;
const result = this._imodel.query(ecsql, undefined, 1000);
for await (const row of result) {
let list = this._subjectsHierarchy.get(row.parentId);
if (!list) {
list = [];
this._subjectsHierarchy.set(row.parentId, list);
}
list.push(row.id);
}
}
private async initSubjectModels() {
this._subjectModels = new Map();
const ecsql = `SELECT p.ECInstanceId id, p.Parent.Id subjectId FROM bis.InformationPartitionElement p JOIN bis.Model m ON m.ModeledElement.Id = p.ECInstanceId`;
const result = this._imodel.query(ecsql, undefined, 1000);
for await (const row of result) {
let list = this._subjectModels.get(row.subjectId);
if (!list) {
list = [];
this._subjectModels.set(row.subjectId, list);
}
list.push(row.id);
}
}
private async initCache() {
if (!this._init) {
this._init = Promise.all([this.initSubjectModels(), this.initSubjectsHierarchy()]).then(() => { });
}
return this._init;
}
private appendSubjectModelsRecursively(modelIds: Id64String[], subjectId: Id64String) {
const subjectModelIds = this._subjectModels!.get(subjectId);
if (subjectModelIds)
modelIds.push(...subjectModelIds);
const childSubjectIds = this._subjectsHierarchy!.get(subjectId);
if (childSubjectIds)
childSubjectIds.forEach((cs) => this.appendSubjectModelsRecursively(modelIds, cs));
}
public async getSubjectModelIds(subjectId: Id64String): Promise<Id64String[]> {
await this.initCache();
const modelIds = new Array<Id64String>();
this.appendSubjectModelsRecursively(modelIds, subjectId);
return modelIds;
}
}
/**
* Interface for class that handles Hide, Isolate, and Emphasize Actions
* @public
*/
export abstract class HideIsolateEmphasizeActionHandler {
public static emphasizeElementsChanged = new BeEvent<(args: EmphasizeElementsChangedArgs) => void>();
/** String Id sent to allow UI to refresh its display state. */
public static get hideIsolateEmphasizeUiSyncId() {
return "selection-context-emphasize-elements-changed";
}
/**
* Function run when `IsolateSelectedElementsModel` tool button is pressed
*/
public abstract processIsolateSelectedElementsModel(): Promise<void>;
/**
* Function run when `IsolateSelectedElementsModel` tool button is pressed
*/
public abstract processIsolateSelectedElementsCategory(): Promise<void>;
/**
* Function run when `HideSelectedElementsModel` tool button is pressed
*/
public abstract processIsolateSelected(): Promise<void>;
/**
* Function run when `HideSelectedElementsModel` tool button is pressed
*/
public abstract processHideSelectedElementsModel(): Promise<void>;
/**
* Function that is run when `HideSelectedElementsCategory` tool button is pressed
*/
public abstract processHideSelectedElementsCategory(): Promise<void>;
/**
* Function that is run when `HideSelected` tool button is pressed
*/
public abstract processHideSelected(): Promise<void>;
/**
* Function that is run when `EmphasizeSelected` tool button is pressed
*/
public abstract processEmphasizeSelected(): Promise<void>;
/**
* Function that is run when `ClearEmphasize` tool button is pressed
*/
public abstract processClearEmphasize(): Promise<void>;
/**
* Function that informs called if Hide, Isolate, or Emphasize of elements is active.
*/
public abstract areFeatureOverridesActive(vp: Viewport): boolean;
/**
* Function run when `ClearOverrideCategories` tool button is pressed
*/
public abstract processClearOverrideCategories(): Promise<void>;
/**
* Function run when `ClearOverrideModels` tool button is pressed
*/
public abstract processClearOverrideModels(): Promise<void>;
}
/** Provides helper functions for doing commands on logical selection like categories and subjects.
* @public
*/
// istanbul ignore next
export class HideIsolateEmphasizeManager extends HideIsolateEmphasizeActionHandler {
// TODO: We need to check the type by going to backend, not by using classnames
private static _categoryClassName = "BisCore:SpatialCategory";
private static _subjectClassName = "BisCore:Subject";
private static _modelClassName = "BisCore:PhysicalModel";
private static _subjectModelIdsCache: SubjectModelIdsCache | undefined = undefined;
private static _overrideCategoryIds = new Map<Viewport, Set<string>>();
private static _overrideModelIds = new Map<Viewport, Set<string>>();
/**
* Initialize the subject model cache
* @param iModelConnection iModel to use for querying subject's models
*/
public static initializeSubjectModelCache(iModelConnection: IModelConnection) {
HideIsolateEmphasizeManager._subjectModelIdsCache = new SubjectModelIdsCache(iModelConnection);
}
/**
* Returns true if the selection in presentation layer only has a single selection class and it is the given one
* @param className ECClass name to check for
*/
private static _checkClassSelected(className: string) {
if (!UiFramework.getIModelConnection())
throw new Error("Undefined iModelConnection");
const selection = Presentation.selection.getSelection(UiFramework.getIModelConnection()!);
return selection.size === 1 && selection.instanceKeys.has(className);
}
/**
* Gets the Ids of all elements selected that have the given class name
* @param className ECClass name to check for
*/
private static _getIdsOfClassName(className: string) {
if (!UiFramework.getIModelConnection())
throw new Error("Undefined iModelConnection");
const selection = Presentation.selection.getSelection(UiFramework.getIModelConnection()!);
const ids: string[] = [];
selection.instanceKeys.forEach((currentIds: Set<string>, key: string) => {
if (key === className)
ids.push(...currentIds);
});
return ids;
}
/** Returns true if there are only categories selected in presentation's logical selection */
private static categorySelected() {
return HideIsolateEmphasizeManager._checkClassSelected(HideIsolateEmphasizeManager._categoryClassName);
}
/** Returns true if there are only subjects selected in presentation's logical selection */
private static subjectSelected() {
return HideIsolateEmphasizeManager._checkClassSelected(HideIsolateEmphasizeManager._subjectClassName);
}
/** Returns true if a model is selected in presentation's logical selection */
private static modelSelected() {
return HideIsolateEmphasizeManager._checkClassSelected(HideIsolateEmphasizeManager._modelClassName);
}
/**
* Hide the selected category found in presentation layer's logical selection
* @param vp Viewport to affect
*/
private static hideSelectedCategory(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._categoryClassName);
vp.changeCategoryDisplay(ids, false);
}
/** Get sub categories that relate to the category Id */
private static async _getSubCategories(iModelConnection: IModelConnection, categoryIds: string[]) {
const allSubcats: string[] = [];
const request = iModelConnection.subcategories.load(categoryIds);
if (request)
await request.promise;
for (const categoryId of categoryIds) {
const subcats = iModelConnection.subcategories.getSubCategories(categoryId);
if (subcats)
allSubcats.push(...subcats);
}
return allSubcats;
}
/**
* Emphasize the selected category found in presentation layer's logical selection
* @param vp Viewport to affect
*/
public static async emphasizeSelectedCategory(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._categoryClassName);
if (ids.length === 0)
return;
const defaultAppearance = EmphasizeElements.getOrCreate(vp).createDefaultAppearance();
EmphasizeElements.clear(vp);
const subcats = await HideIsolateEmphasizeManager._getSubCategories(vp.iModel, ids);
vp.addFeatureOverrideProvider(new SubCategoryOverrideProvider(subcats, defaultAppearance));
}
/**
* Query the model Id that models a subject
* @param subjectId Subject Id to use in query
*/
private static async _getModelIds(subjectId: string): Promise<string[]> {
return HideIsolateEmphasizeManager._subjectModelIdsCache!.getSubjectModelIds(subjectId);
}
/**
* Hide the selected subject's model found in the presentation layer's logical selection
* @param vp Viewport to affect
*/
private static async hideSelectedSubject(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._subjectClassName);
if (ids.length === 0)
return;
const modelIds = await HideIsolateEmphasizeManager._getModelIds(ids[0]);
vp.changeModelDisplay(modelIds, false);
}
/**
* Isolate the selected subject's model found in the presentation layer's logical selection
* @param vp Viewport to affect
*/
private static async emphasizeSelectedSubject(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._subjectClassName);
if (ids.length === 0)
return;
const modelIds = await HideIsolateEmphasizeManager._getModelIds(ids[0]);
const defaultAppearance = EmphasizeElements.getOrCreate(vp).createDefaultAppearance();
EmphasizeElements.clear(vp);
vp.addFeatureOverrideProvider(new ModelOverrideProvider(modelIds, defaultAppearance));
}
/**
* Hide the selected model
* @param vp Viewport to affect
*/
private static hideSelectedModel(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._modelClassName);
if (ids.length === 0)
return;
vp.changeModelDisplay(ids, false);
}
/**
* Isolate the selected model
* @param vp Viewport to affect
*/
private static emphasizeSelectedModel(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._modelClassName);
if (ids.length === 0)
return;
const defaultAppearance = EmphasizeElements.getOrCreate(vp).createDefaultAppearance();
EmphasizeElements.clear(vp);
vp.addFeatureOverrideProvider(new ModelOverrideProvider(ids, defaultAppearance));
}
/**
* Isolate the selected elements
* @param vp Viewport to affect
*/
public static isolateSelected(vp: Viewport) {
EmphasizeElements.getOrCreate(vp).isolateSelectedElements(vp, true, false); // Isolate selected elements
}
/**
* Hide the selected elements
* @param vp Viewport to affect
*/
public static hideSelected(vp: Viewport) {
EmphasizeElements.getOrCreate(vp).hideSelectedElements(vp, false, false); // Hide all selected elements
}
/**
* Clear Hidden,Isolated, or Emphasized elements in specified view
* @param vp Viewport to affect
*
*/
public static clearEmphasize(vp: Viewport | undefined) {
if (vp) {
EmphasizeElements.clear(vp);
}
}
/**
* Emphasize the selected elements from either presentation layer's logical selection or selected graphics
* @param vp Viewport to affect
* @param emphasisSilhouette defaults to true
*/
public static async emphasizeSelected(vp: Viewport, emphasisSilhouette = true) {
if (HideIsolateEmphasizeManager.categorySelected()) {
await HideIsolateEmphasizeManager.emphasizeSelectedCategory(vp);
return;
} else if (HideIsolateEmphasizeManager.modelSelected()) {
HideIsolateEmphasizeManager.emphasizeSelectedModel(vp);
return;
} else if (HideIsolateEmphasizeManager.subjectSelected()) {
await HideIsolateEmphasizeManager.emphasizeSelectedSubject(vp);
return;
}
const ee = EmphasizeElements.getOrCreate(vp);
ee.wantEmphasis = emphasisSilhouette;
ee.emphasizeSelectedElements(vp, undefined, true, false); // Emphasize elements by making all others grey/transparent
vp.isFadeOutActive = true; // Enable flat alpha for greyed out elements…
}
/**
* Isolate the selected subject's model found in the presentation layer's logical selection
* @param vp Viewport to affect
*/
public static async isolateSelectedSubject(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._subjectClassName);
if (ids.length === 0)
return;
const modelIds = await HideIsolateEmphasizeManager._getModelIds(ids[0]);
await vp.replaceViewedModels(modelIds);
}
/**
* Isolate the selected model
* @param vp Viewport to affect
*/
public static async isolateSelectedModel(vp: Viewport) {
const ids = HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._modelClassName);
if (ids.length === 0)
return;
await vp.replaceViewedModels(ids);
}
/**
* Isolate the selected category found in presentation layer's logical selection
* @param vp Viewport to affect
*/
private static isolateSelectedCategory(vp: Viewport) {
const ids = new Set(HideIsolateEmphasizeManager._getIdsOfClassName(HideIsolateEmphasizeManager._categoryClassName));
const categoriesToDrop: string[] = [];
vp.view.categorySelector.categories.forEach((categoryId: string) => {
if (!ids.has(categoryId))
categoriesToDrop.push(categoryId);
});
vp.changeCategoryDisplay(categoriesToDrop, false);
vp.changeCategoryDisplay(ids, true);
}
private static async getSelectionSetElementModels(iModel: IModelConnection) {
const props = await iModel.elements.getProps(iModel.selectionSet.elements);
const modelIds = new Set<string>();
for (const prop of props)
if (prop.model)
modelIds.add(prop.model);
return modelIds;
}
private static async getSelectionSetElementCategories(iModel: IModelConnection) {
const props = (await iModel.elements.getProps(iModel.selectionSet.elements)) as GeometricElementProps[];
const categoryIds = new Set<string>();
for (const prop of props)
if (prop.category)
categoryIds.add(prop.category);
return categoryIds;
}
/**
* Isolate either based on Presentation selection, if defined, else the selected graphic elements
* @param vp Viewport to affect
*/
public static async isolateCommand(vp: Viewport) {
if (HideIsolateEmphasizeManager.categorySelected()) {
HideIsolateEmphasizeManager.isolateSelectedCategory(vp);
return;
} else if (HideIsolateEmphasizeManager.modelSelected()) {
await HideIsolateEmphasizeManager.isolateSelectedModel(vp);
return;
} else if (HideIsolateEmphasizeManager.subjectSelected()) {
await HideIsolateEmphasizeManager.isolateSelectedSubject(vp);
return;
}
}
/**
* Isolate model from selected elements
* @param vp Viewport to affect
*/
public static async isolateSelectedElementsModel(vp: Viewport) {
const modelsToKeep = new Set(await HideIsolateEmphasizeManager.getSelectionSetElementModels(vp.iModel));
if (vp.view.isSpatialView()) {
const modelsToTurnOff = [...vp.view.modelSelector.models].filter((modelId: string) => !modelsToKeep.has(modelId));
this.updateModelOverride(vp, modelsToTurnOff);
}
await vp.replaceViewedModels(modelsToKeep);
}
/**
* Isolate the selected category found in SelectionSet elements
* @param vp Viewport to affect
*/
public static async isolateSelectedElementsCategory(vp: Viewport) {
const categoriesToKeep = new Set(await HideIsolateEmphasizeManager.getSelectionSetElementCategories(vp.iModel));
const categoriesToTurnOff = [...vp.view.categorySelector.categories].filter((categoryId: string) => !categoriesToKeep.has(categoryId));
vp.changeCategoryDisplay(categoriesToTurnOff, false);
vp.changeCategoryDisplay(categoriesToKeep, true);
this.updateCategoryOverride(vp, categoriesToTurnOff);
}
/**
* Hide either based on Presentation selection, if defined, else the selected graphic elements
* @param vp Viewport to affect
*/
public static async hideCommand(vp: Viewport) {
if (HideIsolateEmphasizeManager.categorySelected()) {
HideIsolateEmphasizeManager.hideSelectedCategory(vp);
return;
} else if (HideIsolateEmphasizeManager.modelSelected()) {
HideIsolateEmphasizeManager.hideSelectedModel(vp);
return;
} else if (HideIsolateEmphasizeManager.subjectSelected()) {
await HideIsolateEmphasizeManager.hideSelectedSubject(vp);
return;
}
EmphasizeElements.getOrCreate(vp).hideSelectedElements(vp, false, false); // Hide selected elements
}
/**
* Hide the models defined by the elements in the current SelectionSet
* @param vp Viewport to affect
*/
public static async hideSelectedElementsModel(vp: Viewport) {
const modelIds = await HideIsolateEmphasizeManager.getSelectionSetElementModels(vp.iModel);
vp.changeModelDisplay(modelIds, false);
this.updateModelOverride(vp, [...modelIds]);
}
/**
* Clear (restore) the previously hidden/isolated models hidden by hideSelectedElementsModel
* @param vp Viewport to affect
*/
public static clearOverrideModels(vp: Viewport) {
const ids = this._overrideModelIds.get(vp);
if (ids) {
vp.changeModelDisplay([...ids], true);
this.clearModelOverride(vp);
}
}
/**
* Determine if models are hidden by hideSelectedElementsModel or isolateSelectedElementsModel
* @param vp Viewport to affect
*/
public static isOverrideModels(vp: Viewport): boolean {
const ids = this._overrideModelIds.get(vp);
return (ids) ? [...ids].length > 0 : false;
}
/**
* Determine if categories are hidden by hideSelectedElementsCategory or isolateSelectedElementsCategory
* @param vp Viewport to affect
*/
public static isOverrideCategories(vp: Viewport): boolean {
const ids = this._overrideCategoryIds.get(vp);
return (ids) ? [...ids].length > 0 : false;
}
/**
* Hide the categories defined by the elements in the current SelectionSet
* @param vp Viewport to affect
*/
public static async hideSelectedElementsCategory(vp: Viewport) {
const categoryIds = await HideIsolateEmphasizeManager.getSelectionSetElementCategories(vp.iModel);
vp.changeCategoryDisplay(categoryIds, false);
this.updateCategoryOverride(vp, [...categoryIds]);
}
/**
* Clear (restore) the previously hidden categories hidden by hideSelectedElementsCategory
* @param vp Viewport to affect
*/
public static clearOverrideCategories(vp: Viewport) {
const ids = this._overrideCategoryIds.get(vp);
if (ids) {
vp.changeCategoryDisplay([...ids], true);
this.clearCategoryOverride(vp);
}
}
/** Checks to see if any featureOverrideProviders are active */
public areFeatureOverridesActive(vp: Viewport): boolean {
// Check all the emphasize possibilities
const emphasizeElementsProvider = vp.findFeatureOverrideProviderOfType<EmphasizeElements>(EmphasizeElements);
if (undefined !== emphasizeElementsProvider && emphasizeElementsProvider.isActive)
return true;
const modelOverrideProvider = vp.findFeatureOverrideProviderOfType<ModelOverrideProvider>(ModelOverrideProvider);
if (undefined !== modelOverrideProvider && modelOverrideProvider.modelIds.length > 0)
return true;
const subCategoryOverrideProvider = vp.findFeatureOverrideProviderOfType<SubCategoryOverrideProvider>(SubCategoryOverrideProvider);
if (undefined !== subCategoryOverrideProvider && subCategoryOverrideProvider.subCategoryIds.length > 0)
return true;
// Check hide/isolate possibilities
if (HideIsolateEmphasizeManager.isOverrideCategories(vp))
return true;
if (HideIsolateEmphasizeManager.isOverrideModels(vp))
return true;
return false;
}
/**
* Function that is run when `IsolateSelectedElementsModel` tool button is pressed
*/
public async processIsolateSelectedElementsModel(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
await HideIsolateEmphasizeManager.isolateSelectedElementsModel(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.IsolateSelectedModels });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.IsolateSelectedModels, featureIdMap.get(HideIsolateEmphasizeAction.IsolateSelectedModels)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Function that is run when `IsolateSelectedElementsCategory` tool button is pressed
*/
public async processIsolateSelectedElementsCategory(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
await HideIsolateEmphasizeManager.isolateSelectedElementsCategory(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.IsolateSelectedCategories });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.IsolateSelectedCategories, featureIdMap.get(HideIsolateEmphasizeAction.IsolateSelectedCategories)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Function that is run when `IsolateSelected` tool button is pressed
*/
public async processIsolateSelected(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
HideIsolateEmphasizeManager.isolateSelected(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.IsolateSelectedElements });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.IsolateSelectedElements, featureIdMap.get(HideIsolateEmphasizeAction.IsolateSelectedElements)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
// clear out selection now that any callbacks have processed
const selection = vp.view.iModel.selectionSet;
if (selection.isActive)
selection.emptyAll();
}
/**
* Function that is run when `HideSelectedElementsModel` tool button is pressed
*/
public async processHideSelectedElementsModel(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
await HideIsolateEmphasizeManager.hideSelectedElementsModel(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.HideSelectedModels });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.HideSelectedModels, featureIdMap.get(HideIsolateEmphasizeAction.HideSelectedModels)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Function that is run when `HideSelectedElementsCategory` tool button is pressed
*/
public async processHideSelectedElementsCategory(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
await HideIsolateEmphasizeManager.hideSelectedElementsCategory(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.HideSelectedCategories });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.HideSelectedCategories, featureIdMap.get(HideIsolateEmphasizeAction.HideSelectedCategories)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Function that is run when `HideSelected` tool button is pressed
*/
public async processHideSelected(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
HideIsolateEmphasizeManager.hideSelected(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.HideSelectedElements });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.HideSelectedCategories, featureIdMap.get(HideIsolateEmphasizeAction.HideSelectedElements)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
// clear out selection now that any callbacks have processed
const selection = vp.view.iModel.selectionSet;
if (selection.isActive)
selection.emptyAll();
}
/**
* Function that is run when `EmphasizeSelected` tool button is pressed
*/
public async processEmphasizeSelected(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
await HideIsolateEmphasizeManager.emphasizeSelected(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.EmphasizeSelectedElements });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.EmphasizeSelectedElements, featureIdMap.get(HideIsolateEmphasizeAction.EmphasizeSelectedElements)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
// clear out selection now that any callbacks have processed
const selection = vp.view.iModel.selectionSet;
if (selection.isActive)
selection.emptyAll();
}
/**
* Function that is run when `ClearEmphasize` tool button is pressed
*/
public async processClearEmphasize(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
HideIsolateEmphasizeManager.clearEmphasize(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.ClearHiddenIsolatedEmphasized });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.ClearHiddenIsolatedEmphasized, featureIdMap.get(HideIsolateEmphasizeAction.ClearHiddenIsolatedEmphasized)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Function that is run when `ClearOverrideModels` tool button is pressed
*/
public async processClearOverrideModels(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
HideIsolateEmphasizeManager.clearOverrideModels(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.ClearOverrideModels });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.ClearOverrideModels, featureIdMap.get(HideIsolateEmphasizeAction.ClearOverrideModels)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Function that is run when `ClearOverrideCategories` tool button is pressed
*/
public async processClearOverrideCategories(): Promise<void> {
const vp = IModelApp.viewManager.selectedView;
if (!vp)
return;
HideIsolateEmphasizeManager.clearOverrideCategories(vp);
HideIsolateEmphasizeActionHandler.emphasizeElementsChanged.raiseEvent({ viewport: vp, action: HideIsolateEmphasizeAction.ClearOverrideCategories });
UiFramework.postTelemetry(HideIsolateEmphasizeAction.ClearOverrideCategories, featureIdMap.get(HideIsolateEmphasizeAction.ClearOverrideCategories)); // eslint-disable-line @typescript-eslint/no-floating-promises
SyncUiEventDispatcher.dispatchSyncUiEvent(HideIsolateEmphasizeActionHandler.hideIsolateEmphasizeUiSyncId);
}
/**
* Add category ids to the category override cache (hidden or isolated categories)
*/
public static updateCategoryOverride(vp: Viewport, ids: string[]) {
const prevIds = this._overrideCategoryIds.get(vp);
const newIds = [...(prevIds || []), ...ids];
this._overrideCategoryIds.set(vp, new Set(newIds));
}
/**
* Add model ids to the model override cache (hidden or isolated models)
*/
public static updateModelOverride(vp: Viewport, ids: string[]) {
const prevIds = this._overrideModelIds.get(vp);
const newIds = [...(prevIds || []), ...ids];
this._overrideModelIds.set(vp, new Set(newIds));
}
/**
* Return the list of category overrides (hidden or isolated categories)
*/
public static getCategoryOverrides(vp: Viewport) {
return this._overrideCategoryIds.get(vp);
}
/**
* Return the list of model overrides (hidden or isolated models)
*/
public static getModelOverrides(vp: Viewport) {
return this._overrideModelIds.get(vp);
}
/**
* Clear the category override cache (hidden or isolated categories)
*/
private static clearCategoryOverride(vp: Viewport) {
this._overrideCategoryIds.delete(vp);
}
/**
* Clear the model override cache (hidden or isolated models)
*/
private static clearModelOverride(vp: Viewport) {
this._overrideModelIds.delete(vp);
}
} | the_stack |
import * as PIXI from 'pixi.js';
import { Texture } from 'pixi.js';
import { Texture as Texture_2 } from '@pixi/core';
/**
* Alignments supported by layout managers in PuxiJS core.
*
* @memberof PUXI
* @enum
*/
export declare enum ALIGN {
LEFT = 0,
TOP = 0,
MIDDLE = 4081,
CENTER = 4081,
RIGHT = 1048561,
BOTTOM = 1048561,
NONE = 4294967295
}
/**
* `AnchorLayout` is used in conjunction with `AnchorLayoutOptions`.
*
* @memberof PUXI
* @class
* @example
* ```
* parent.useLayout(new PUXI.AnchorLayout());
* ```
*/
export declare class AnchorLayout implements ILayoutManager {
private measuredWidth;
private measuredHeight;
private host;
onAttach(host: WidgetGroup): void;
onDetach(): void;
onLayout(): void;
onMeasure(widthLimit: number, heightLimit: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
getMeasuredWidth(): number;
getMeasuredHeight(): number;
/**
* Calculates the actual value of the anchor, given the parent's dimension.
*
* @param {number} anchor - anchor as given in layout options
* @param {number} limit - parent's dimension
* @param {boolean} limitSubtract - true for right/bottom anchors, false for left/top
*/
protected calculateAnchor(anchor: number, limit: number, limitSubtract: boolean): number;
/**
* Calculates the "reach" of a child widget, which is the minimum dimension of
* the parent required to fully fit the child.
*
* @param {number} startAnchor - left or top anchor as given in layout options
* @param {number} endAnchor - right or bottom anchor as given in layout options
* @param {number} dimen - measured dimension of the widget (width or height)
*/
protected calculateReach(startAnchor: number, endAnchor: number, dimen: number): number;
}
/**
* @memberof PUXI
* @interface IAnchorLayoutParams
* @property {number} anchorLeft - distance from parent's left inset to child's left edge
* @property {number} anchorTop - distance from parent's top inset to child's top edge
* @property {number} anchorRight - distance from parent's right inset to child's right edge
* @property {number} anchorBottom - distance from parent's bottom insets to child's bottom edge
* @property {PUXI.ALIGN} horizontalAlign - horizontal alignment of child in anchor region
* @property {PUXI.ALIGN} verticalAlign - vertical alignment of child in anchor region
* @property {number | string} width - requested width of widget (default is `WRAP_CONTENT`)
* @property {number | string} height - requested height of widget (default is `WRAP_CONTENT`)
*/
/**
* Anchors the edge of a widget to defined offsets from the parent's insets.
*
* The following example will render a widget at (10px, 15%) with a width extending
* to the parent's center and a height extending till 40px above the parent's bottom
* inset.
* ```js
* new PUXI.AnchoredLayoutOptions({
* anchorLeft: 10,
* anchorTop: .15,
* anchorRight: .5,
* anchorBottom: 40
* });
* ```
*
* ### Intra-anchor region alignment
*
* You can specify how the widget should be aligned in the intra-anchor region using the
* `horizontalAlign` and `verticalAlign` properties.
*
* ### Support for FILL_PARENT and percentage-of-parent dimensions
*
* Anchor layout does not support a width/height that is `LayoutOptions.FILL_PARENT`
* or a percentage of the parent's width/height. Instead, you can define anchors that
* result in the equivalent behaviour.
*
* @memberof PUXI
* @extends PUXI.LayoutOptions
* @class
*/
export declare class AnchorLayoutOptions extends LayoutOptions {
anchorLeft: number;
anchorTop: number;
anchorRight: number;
anchorBottom: number;
horizontalAlign: ALIGN;
verticalAlign: ALIGN;
constructor(options: IAnchorLayoutParams);
}
/**
* `PUXI.BorderLayout` is used in conjunction with `PUXI.BorderLayoutOptions`.
*
* This layout guarantees that the "center" region will always be in the center of
* the widget-group.
*
* WARNING: This layout may have some bugs in edge cases that haven't been reported.
*
* @memberof PUXI
* @class
* @implements PUXI.ILayoutManager
*/
export declare class BorderLayout implements ILayoutManager {
protected host: WidgetGroup;
protected leftWidgets: Widget[];
protected topWidgets: Widget[];
protected rightWidgets: Widget[];
protected bottomWidgets: Widget[];
protected centerWidgets: Widget[];
protected measuredLeftWidth: number;
protected measuredRightWidth: number;
protected measuredCenterWidth: number;
protected measuredWidth: number;
protected measuredTopHeight: number;
protected measuredBottomHeight: number;
protected measuredCenterHeight: number;
protected measuredHeight: number;
constructor();
onAttach(host: WidgetGroup): void;
onDetach(): void;
onLayout(): void;
layoutChildren(widgets: Widget[], regionX: number, regionY: number, regionWidth: number, regionHeight: number): void;
/**
* @param {number} maxWidth
* @param {number} maxHeight
* @param {PUXI.MeasureMode} widthMode
* @param {PUXI.MeasureMode} heightMode
* @override
*/
onMeasure(maxWidth: number, maxHeight: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
/**
* This measures the list of widgets given the constraints. The max width and
* height amongst the children is returned.
*
* @param {PUXI.Widget[]} list
* @param {number} maxWidth
* @param {number} maxHeight
* @param {PUXI.MeasureMode} widthMode
* @param {PUXI.MeasureMode} heightMode
* @returns {number[]} - [width, height, widthFixedLowerBound, heightFixedLowerBound] -
* the max. width and height amongst children. Also, the minimum required width/height
* for the region (as defined in layout-options).
*/
protected measureChildren(list: Widget[], maxWidth: number, maxHeight: number, widthMode: MeasureMode, heightMode: MeasureMode): number[];
/**
* Ensures all widgets in the list measured their dimensions below the region
* width & height. Widgets that are too large are remeasured in the those
* limits (using `MeasureMode.AT_MOST`).
*
* This will handle widgets that have "FILL_PARENT" width or height.
*
* @param {PUXI.Widget[]} list
* @param {number} measuredRegionWidth
* @param {number} measuredRegionHeight
*/
protected fitChildren(list: Widget[], measuredRegionWidth: number, measuredRegionHeight: number): void;
/**
* Indexes the list of left, top, right, bottom, and center widget lists.
*/
protected indexRegions(): void;
/**
* Clears the left, top, right, bottom, and center widget lists.
*/
protected clearRegions(): void;
/**
* Zeros the measured dimensions.
*/
protected clearMeasureCache(): void;
getMeasuredWidth(): number;
getMeasuredHeight(): number;
}
/**
* @memberof PUXI
* @interface IBorderLayoutParams
* @property {number} width
* @property {number} height
* @property {number} region
* @property {number} horizontalAlign
* @property {number} verticalAlign
*/
/**
* `PUXI.BorderLayoutOptions` defines a simple layout with five regions - the center and
* four regions along each border. The top and bottom regions span the full width of
* the parent widget-group. The left and right regions span the height of the layout
* minus the top and bottom region heights.
*
* ```
* ------------------------------------------------
* | TOP REGION |
* ------------------------------------------------
* | | | |
* | LEFT | CENTER | RIGHT |
* | REGION | REGION | REGION |
* | | | |
* ------------------------------------------------
* | BOTTOM REGION |
* ------------------------------------------------
* ```
*
* The height of the layout is measured as the sum of the heights of the top, center, and bottom
* regions. Similarly, the width of the layout is measured as the width of the left, center, and
* right regions.
*
* As of now, border layout doesn't support percent widths and heights.
*
* @memberof PUXI
* @class
* @extends PUXI.LayoutOptions
*/
export declare class BorderLayoutOptions extends LayoutOptions {
/**
* Positions a widget inside the left border of the layout.
* @static
* @member {number}
*/
static REGION_LEFT: number;
/**
* Positions a widget below the top border of the layout.
* @static
* @member {number}
*/
static REGION_TOP: number;
/**
* Positions a widget below the right border of the layout.
* @static
* @member {number}
*/
static REGION_RIGHT: number;
/**
* Positions a widget below the top border of the layout.
* @static
* @member {number}
*/
static REGION_BOTTOM: number;
/**
* Positions a widget in the center of the layout. The main content of the layout
* should be in the center.
* @static
* @member {number}
*/
static REGION_CENTER: number;
region: number;
horizontalAlign: number;
verticalAlign: number;
constructor(options: IBorderLayoutParams);
}
/**
* Button that can be clicked.
*
* @memberof PUXI
* @class
* @extends PUXI.FocusableWidget
*/
export declare class Button extends FocusableWidget {
isHover: boolean;
protected textWidget: TextWidget;
click: () => void;
/**
* @param [options.background}] {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as background for Button
* @param [options.text=null] {PIXI.UI.Text} optional text
* @param [options.tabIndex=0] {Number} input tab index
* @param [options.tabGroup=0] {Number|String} input tab group
* @param [options.width=options.background.width] {Number|String} width
* @param [options.height=options.background.height] {Number|String} height
*/
constructor(options: IButtonOptions);
onClick(e: PIXI.InteractionEvent): void;
onDoubleClick(e: PIXI.InteractionEvent): void;
update(): void;
initialize(): void;
/**
* Label for this button.
* @member {string}
*/
get value(): string;
set value(val: string);
get text(): any;
set text(val: any);
}
/**
* @memberof PUXI
* @typedef {string} CheckGroup
*/
declare interface CBGroup {
checks: Array<CheckBox>;
selected: CheckBox;
}
/**
* @memberof PUXI
* @extends PUXI.IFocusableOptions
* @member {boolean} checked
* @member {PIXI.Container}[checkmark]
* @member {PUXI.CheckGroup}[checkGroup]
* @member {string}[value]
*/
/**
* A checkbox is a button can be selected (checked). It has a on/off state that
* can be controlled by the user.
*
* When used in a checkbox group, the group will control whether the checkbox can
* be selected or not.
*
* @memberof PUXI
* @class
* @extends PUXI.FocusableWidget
*/
export declare class CheckBox extends FocusableWidget {
private _checked;
private _value;
private label;
private checkmark;
checkGroup: CheckGroup;
/**
* @param {PUXI.ICheckBoxOptions} options
* @param [options.checked=false] {bool} is checked
* @param options.background {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as background for CheckBox
* @param options.checkmark {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as checkmark for CheckBox
* @param {PUXI.CheckGroup}[options.checkGroup=null] CheckGroup name
* @param options.value {String} mostly used along with checkgroup
* @param [options.tabIndex=0] {Number} input tab index
* @param [options.tabGroup=0] {Number|String} input tab group
*/
constructor(options: ICheckBoxOptions);
update(): void;
get checked(): boolean;
set checked(val: boolean);
get value(): string;
set value(val: string);
get selectedValue(): string;
initialize(): void;
protected change: (val: boolean) => void;
protected click: () => void;
}
/**
* Check boxes use this controller to deselect other checkboxes in the group when
* they are selected.
*
* @memberof PUXI
* @class
* @extends PUXI.Controller
*/
declare class CheckBoxGroupController extends Controller<CheckBox> {
protected checkGroups: Map<CheckGroup, CBGroup>;
constructor(stage: Stage);
/**
* @param {PUXI.CheckBox} widget
* @param {PUXI.CheckGroup} checkGroup
* @override
*/
in(widget: CheckBox, checkGroup?: CheckGroup): void;
/**
* @override
*/
out(widget: CheckBox): void;
/**
* Called when a checkbox is selected. Do not call from outside.
*
* @param {CheckBox} widget
*/
notifyCheck(widget: CheckBox): void;
/**
* @param {PUXI.CheckGroup} group
* @returns {CheckBox} the selected checkbox in the group
*/
getSelected(group: CheckGroup): CheckBox;
/**
* Ensures that the check group exists in `this.checkGroups`.
*
* @param {PUXI.CheckGroup} id
* @protected
*/
protected initGroup(id: CheckGroup): CBGroup;
}
declare type CheckGroup = string;
/**
* `ClickManager` handles hover and click events. It registers listeners
* for `mousedown`, `mouseup`, `mousemove`, `mouseout`, `mouseover`, `touchstart`,
* `touchend`, `touchendoutside`, `touchmove`, `rightup`, `rightdown`, `rightupoutside`
* events.
*
* @memberof PUXI
* @class
* @extends PUXI.EventManager
*/
export declare class ClickManager extends EventManager {
onHover: (event: PIXI.InteractionEvent, over: boolean) => void;
onPress: (event: PIXI.InteractionEvent, isPressed: boolean) => void;
onClick: (event: PIXI.InteractionMouseEvents) => void;
onMove: (event: PIXI.InteractionEvent) => void;
protected _rightMouseButton: boolean;
protected _includeHover: boolean;
protected _doubleClick: boolean;
private bound;
private id;
private ishover;
protected target: Widget;
private movementX;
private movementY;
mouse: PIXI.Point;
offset: PIXI.Point;
private evMouseDown;
private evMouseUp;
private evMouseUpOutside;
time: number;
/**
* @param {PUXI.Widget | PUXI.Button} target
* @param {boolean}[includeHover=false] - enable hover (`mouseover`, `mouseout`) listeners
* @param {boolean}[rightMouseButton=false] - use right mouse clicks
* @param {boolean}[doubleClick=false] - fire double clicks
*/
constructor(target: Widget, includeHover?: boolean, rightMouseButton?: any, doubleClick?: boolean);
/**
* Whether right mice are used for clicks rather than left mice.
* @member boolean
*/
get rightMouseButton(): boolean;
set rightMouseButton(val: boolean);
/**
* @param {boolean}[includeHover]
* @param {boolean}[rightMouseButton]
* @param {boolean}[doubleClick]
* @override
*/
startEvent: (includeHover?: boolean, rightMouseButton?: boolean, doubleClick?: boolean) => void;
/**
* @override
*/
stopEvent: () => void;
protected onMouseDownImpl: (event: any) => void;
protected onMouseUpCommonImpl: (event: any) => void;
protected onMouseUpImpl: (event: any) => void;
protected onMouseUpOutsideImpl: (event: any) => void;
protected onMouseOverImpl: (event: any) => void;
protected onMouseOutImpl: (event: any) => void;
protected onMouseMoveImpl: (event: any) => void;
}
declare abstract class Controller<T> extends PIXI.utils.EventEmitter {
stage: Stage;
constructor(stage: Stage);
abstract in(widget: T): any;
abstract out(widget: T): any;
}
export declare function create(fn: any): any;
/**
* `DragManager` handles drag & drop events. It registers listeners for `mousedown`,
* `touchstart` on the target and `mousemove`, `touchmove`, `mouseup`, `mouseupoutside`,
* `touchend`, `touchendoutside` on the stage.
*
* By default, `draggable` widgets will internally handle drag-n-drop and reassigning
* the callbacks on their `DragManager` will break their behaviour. You can prevent
* this by using `eventBroker.dnd` directly without setting `widget.draggable` to
* `true` (or using `widget.makeDraggable()`).
*
* @memberof PUXI
* @class
* @extends PUXI.EventManager
*/
declare class DragManager extends EventManager {
protected isBound: boolean;
protected isDragging: boolean;
protected id: number;
protected dragStart: PIXI.Point;
protected dragOffset: PIXI.Point;
protected lastCursor: PIXI.Point;
protected movementX: number;
protected movementY: number;
protected cancel: boolean;
onPress: (e: PIXI.interaction.InteractionEvent, isPressed: boolean) => void;
onDragStart: (e: PIXI.interaction.InteractionEvent) => void;
onDragMove: (e: PIXI.interaction.InteractionEvent, dragOffset: PIXI.Point) => void;
onDragEnd: (e: PIXI.interaction.InteractionEvent) => void;
constructor(target: Widget);
startEvent(): void;
stopEvent(): void;
protected onDragStartImpl: (e: any) => void;
private onDragMoveImpl;
private onDragEndImpl;
}
export declare namespace Ease {
{ Linear };
export namespace Power0 {
{ Linear as easeNone };
}
export namespace Power1 {
{ easeInFunction as easeIn };
{ easeOutFunction as easeOut };
{ easeInOutFunction as easeInOut };
}
export namespace Quad { }
export namespace Power2 { }
export namespace Cubic { }
export namespace Power3 { }
export namespace Quart { }
export namespace Power4 { }
export namespace Quint { }
export namespace Bounce {
const BounceIn: any;
const BounceOut: any;
const BounceInOut: any;
}
export namespace Circ {
const CircIn: any;
const CircOut: any;
const CircInOut: any;
}
export namespace Expo {
const ExpoIn: any;
const ExpoOut: any;
const ExpoInOut: any;
}
export namespace Sine {
const SineIn: any;
const SineOut: any;
const SineInOut: any;
}
}
declare class EaseBase {
getPosition(p: any): any;
}
/**
* The event brokers allows you to access event managers without manually assigning
* them to a widget. By default, the click (`PUXI.ClickManager`), dnd (`PUXI.DragManager`)
* are defined. You can add event managers for all (new) widgets by adding an entry to
* `EventBroker.MANAGER_MAP`.
*
* @memberof PUXI
* @class
*/
export declare class EventBroker {
[key: string]: EventManager | Widget;
constructor(target: Widget);
static MANAGER_MAP: {
click: typeof ClickManager;
dnd: typeof DragManager;
};
}
/**
* An event manager handles the states related to certain events and can augment
* widget interaction. For example, the click manager will hide clicks when
* the object is dragging.
*
* Event managers are lifecycle objects - they can start/stop. Their constructor
* will always accept one argument - the widget. Other settings can be applied before
* `startEvent`.
*
* Ideally, you should access event managers _after_ your widget has initialized. This is
* because it may depend on the widget's stage being assigned.
*
* @memberof PUXI
* @class
* @abstract
*/
export declare abstract class EventManager {
protected target: Widget;
protected isEnabled: boolean;
/**
* @param {Widget} target
*/
constructor(target: Widget);
/**
* @returns {Widget}
*/
getTarget(): Widget;
/**
* Registers the interaction event listeners that will emit corresponding events
* on the target widget.
*/
abstract startEvent(): any;
/**
* Unregisters any event listeners and releases any resources held. This should
* revert all changes made by `startEvent`.
*/
abstract stopEvent(): any;
}
/**
* `PUXI.FastLayout` is used in conjunction with `PUXI.FastLayoutOptions`. It is the
* default layout for most widget groups.
*
* @memberof PUXI
* @class
* @extends PUXI.ILayoutManager
* @example
* ```
* parent.useLayout(new PUXI.FastLayout())
* ```
*/
export declare class FastLayout implements ILayoutManager {
private host;
private _measuredWidth;
private _measuredHeight;
onAttach(host: WidgetGroup): void;
onDetach(): void;
onLayout(): void;
onMeasure(maxWidth: number, maxHeight: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
private getChildMeasureMode;
private measureWidthReach;
private measureHeightReach;
private measureChildFillers;
getMeasuredWidth(): number;
getMeasuredHeight(): number;
}
/**
* @memberof PUXI
* @interface
* @property {number} width
* @property {number} height
* @property {number} x
* @property {number} y
* @property {PIXI.Point} anchor
*/
/**
* `PUXI.FastLayoutOptions` is an extension to `PUXI.LayoutOptions` that also
* defines the x & y coordinates. It is accepted by the stage and `PUXI.FastLayout`.
*
* If x or y is between -1 and 1, then that dimension will be interpreted as a
* percentage of the parent's width or height.
*
* @memberof PUXI
* @extends PUXI.LayoutOptions
* @class
*/
export declare class FastLayoutOptions extends LayoutOptions {
static DEFAULT_ANCHOR: PIXI.Point;
static CENTER_ANCHOR: PIXI.Point;
x: number;
y: number;
anchor: PIXI.Point;
constructor(options: IFastLayoutParams);
}
/**
* Represents a view that can gain or loose focus. It is primarily subclassed by
* input/form widgets.
*
* Generally, it is a good idea not use layouts on these types of widgets.
*
* @class
* @extends PUXI.Widget
* @memberof PUXI
*/
declare abstract class FocusableWidget extends InteractiveGroup {
_isFocused: boolean;
_isMousePressed: boolean;
tabIndex: number;
tabGroup: TabGroup;
/**
* @param {PUXI.IInputBaseOptions} options
* @param {PIXI.Container}[options.background]
* @param {number}[options.tabIndex]
* @param {any}[options.tabGroup]
*/
constructor(options?: IFocusableOptions);
/**
* Brings this widget into focus.
*/
focus(): void;
/**
* Brings this widget out of focus.
*/
blur(): void;
/**
* Whether this widget is in focus.
* @member {boolean}
* @readonly
*/
get isFocused(): boolean;
private bindEvents;
private clearEvents;
protected onKeyDownImpl: (e: any) => void;
private onDocumentPointerDownImpl;
initialize(): void;
}
/**
* Pressing tab on a focused widget will make the next widget its tab group
* focused. If no tab group is specified for a focusable widget, then it
* has the `'default'` tab group.
*
* @memberof PUXI
* @typedef {string} TabGroup
*/
/**
* @memberof PUXI
* @class
* @extends PUXI.Controller
*/
declare class FocusController extends Controller<FocusableWidget> {
stage: Stage;
protected tabGroups: Map<TabGroup, FocusableWidget[]>;
protected currentItem: FocusableWidget;
useTab: boolean;
useForward: boolean;
useBack: boolean;
constructor(stage: Stage);
/**
* Adds the (focusable) widget to the tab group so that pressing tab repeatedly
* will eventually bring it into focus.
*
* @param {PUXI.FocusableWidget} widget - the widget to add
* @param {number}[tabIndex=0] - unique index for the widget in tab group used for ordering
* @param {PUXI.TabGroup}[tabGroup='default'] - tab group name
*/
in(widget: FocusableWidget, tabIndex?: number, tabGroup?: string): void;
/**
* @param {PUXI.FocusableWidget} widget
* @override
*/
out(widget: FocusableWidget): void;
/**
* Called when a widget comes into focus. Do not call this yourself.
*
* @param {FocusableWidget} widget
*/
notifyFocus(widget: FocusableWidget): void;
/**
* Clears the currently focused item without blurring it. It is called
* when a widget goes out of focus.
*/
notifyBlur(): void;
/**
* Brings the widget into focus.
*
* @param {FocusableWidget} item
*/
focus(item: FocusableWidget): void;
/**
* Blurs the currently focused widget out of focus.
*/
blur(): void;
/**
* Called when tab is pressed on a focusable widget.
*/
onTab(): void;
/**
* Focuses the next item without wrapping, i.e. it does not go to the first
* item if the current one is the last item. This is called when the user
* presses the forward arrow key.
*/
onForward(): void;
/**
* Focuses the last item without wrapping, i.e. it does not go to the last
* item if the current item is the first one. This is called when the user
* presses the back arrow button.
*/
onBack(): void;
}
declare type Gravity = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom';
export declare const Helpers: {
Lerp(start: number, stop: number, amt: number): number;
Round(number: number, decimals: number): number;
componentToHex(c: any): string;
rgbToHex(r: number, g: number, b: number): string;
rgbToNumber(r: number, g: number, b: number): number;
numberToRgb(c: number): any;
hexToRgb(hex: any): any;
};
declare interface IAnchorLayoutParams {
anchorLeft?: number;
anchorTop?: number;
anchorRight?: number;
anchorBottom?: number;
horizontalAlign?: ALIGN;
verticalAlign?: ALIGN;
width: number | string;
height: number | string;
}
export declare interface IBorderLayoutParams {
width?: number;
height?: number;
region?: number;
horizontalAlign?: ALIGN;
verticalAlign?: ALIGN;
}
/**
* @memberof PUXI
* @interface
* @extends PUXI.IFocusableOptions
* @property {PUXI.TextWidget | string} text
*/
export declare interface IButtonOptions extends IFocusableOptions {
background?: PIXI.Container;
text?: TextWidget | string;
tabIndex?: number;
tabGroup?: any;
}
declare interface ICheckBoxOptions extends IFocusableOptions {
checked?: boolean;
background: PIXI.Container;
checkmark?: PIXI.Container;
checkGroup?: CheckGroup;
value?: string;
tabIndex?: number;
tabGroup?: number;
}
export declare interface IFastLayoutParams {
width?: number | string;
height?: number | string;
x?: number;
y?: number;
anchor?: PIXI.Point;
}
/**
* @namespace PUXI
* @interface
* @property {PIXI.Container}[background]
* @property {number}[tabIndex]
* @property {PUXI.TabGroup}[tabGroup]
*/
declare interface IFocusableOptions {
background?: PIXI.Container;
tabIndex?: number;
tabGroup?: any;
}
export declare interface IImageButtonOptions extends IButtonOptions {
icon: string | Texture_2 | ImageWidget;
}
export declare interface ILayoutManager extends IMeasurable {
onAttach(host: WidgetGroup): void;
onDetach(): void;
onLayout(): void;
}
export declare class ImageButton extends Button {
iconWidget: ImageWidget;
constructor(options: IImageButtonOptions);
}
export declare type ImageWidget = Sprite;
export declare const ImageWidget: typeof Sprite;
export declare interface IMeasurable {
onMeasure(maxWidth: number, maxHeight: number, widthMode: MeasureMode, heightMode: MeasureMode): any;
getMeasuredWidth(): number;
getMeasuredHeight(): number;
}
/**
* @memberof PUXI
* @class
*/
export declare class Insets {
left: number;
top: number;
right: number;
bottom: number;
dirtyId: number;
constructor();
reset(): void;
}
/**
* An interactive container.
*
* @class
* @extends PUXI.WidgetGroup
* @memberof PUXI
*/
export declare class InteractiveGroup extends WidgetGroup {
private hitArea;
constructor();
update(): void;
layout(l: number, t: number, r: number, b: number, dirty: boolean): void;
}
declare interface IScrollBarOptions extends ISliderOptions {
track?: Sprite;
handle?: Sprite;
scrollingContainer: ScrollWidget;
orientation: number;
autohide?: boolean;
}
/**
* @namespace PUXI
* @interface
*/
declare interface IScrollingContainerOptions {
scrollX?: boolean;
scrollY?: boolean;
dragScrolling?: boolean;
softness?: number;
radius?: number;
expandMask?: number;
overflowY?: number;
overflowX?: number;
scrollBars?: boolean;
}
export declare interface ISliderOptions {
track?: PIXI.Container | Widget;
handle?: PIXI.Container | Widget;
fill?: Sprite;
orientation?: number;
value?: number;
minValue?: number;
maxValue?: number;
decimals?: number;
onValueChange?: () => void;
onValueChanging?: () => void;
}
/**
* @memberof PUXI
* @interface
*/
declare interface ITextInputOptions extends IFocusableOptions {
multiLine?: boolean;
style?: PIXI.TextStyle;
background?: PIXI.Container;
selectedColor?: string | number[];
selectedBackgroundColor?: string;
width?: number;
height?: number;
padding?: number;
paddingTop?: number;
paddingBottom?: number;
paddingLeft?: number;
paddingRight?: number;
tabIndex?: number;
tabGroup?: number;
maxLength?: number;
caretWidth?: number;
lineHeight?: number;
value?: string;
}
/**
* This are the base constraints that you can apply on a `PUXI.Widget` under any
* layout manager. It specifies the dimensions of a widget, while the position
* of the widget is left to the parent to decide. If a dimension (width or height)
* is set to a value between -1 and 1, then it is interpreted as a percentage
* of the parent's dimension.
*
* The following example will render a widget at 50% of the parent's width and 10px height:
*
* ```js
* const widget = new PUXI.Widget();
* const parent = new PUXI.Widget();
*
* widget.layoutOptions = new PUXI.LayoutOptions(
* .5,
* 10
* );
* parent.addChild(widget);
* ```
*
* @memberof PUXI
* @class
*/
export declare class LayoutOptions {
static FILL_PARENT: number;
static WRAP_CONTENT: number;
static MAX_DIMEN: number;
static DEFAULT: LayoutOptions;
width: number;
height: number;
cache: any;
private _marginLeft;
private _marginTop;
private _marginRight;
private _marginBottom;
/**
* @param {number}[width = LayoutOptions.WRAP_CONTENT]
* @param {number}[height = LayoutOptions.WRAP_CONTENT]
*/
constructor(width?: number | string, height?: number | string);
/**
* Utility method to store width that converts strings to their number format.
*
* @param {number | string} val
* @example
* ```
* lopt.setWidth('68.7%');// 68.7% of parent's width
* lopt.setWidth('96px');// 96px
* lopt.setWidth(34);// 34px
* lopt.setWidth(.45);// 45% of parent's width
* ```
*/
setWidth(val: number | string): void;
/**
* Utility method to store height that converts strings to their number format.
*
* @param {number | string} val
* @example
* ```
* lopt.setHeight('68.7%');// 68.7% of parent's height
* lopt.setHeight('96px');// 96px
* lopt.setHeight(34);// 34px
* lopt.setHeight(.45);// 45% of parent's height
* ```
*/
setHeight(val: number | string): void;
/**
* @member {boolean} - whether the specified width is a constant
* (not a percentage, `WRAP_CONTENT`, or `FILL_PARENT`)
*/
get isWidthPredefined(): boolean;
/**
* @member {boolean} - whether the specified height is a constant
* (not a percentage, `WRAP_CONTENT`, or `FILL_PARENT`)
*/
get isHeightPredefined(): boolean;
/**
* The left margin in pixels of the widget.
* @member {number}
* @default 0
*/
get marginLeft(): number;
set marginLeft(val: number);
/**
* This top margin in pixels of the widget.
* @member {number}
* @default 0
*/
get marginTop(): number;
set marginTop(val: number);
/**
* The right margin in pixels of the widget.
* @member {number}
* @default 0
*/
get marginRight(): number;
set marginRight(val: number);
/**
* The bottom margin in pixels of the widget.
* @member {number}
* @default 0
*/
get marginBottom(): number;
set marginBottom(val: number);
/**
* @param left
* @param top
* @param right
* @param bottom
*/
setMargin(left: number, top: number, right: number, bottom: number): void;
static parseDimen(val: number | string): number;
}
export declare class LinearLayout implements ILayoutManager {
private host;
private orientation;
private gravity;
private measuredWidth;
private measuredHeight;
constructor(orientation?: 'vertical' | 'horizontal', gravity?: Gravity);
onAttach(host: WidgetGroup): void;
onDetach(): void;
onLayout(): void;
onMeasure(widthLimit: number, heightLimit: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
getMeasuredWidth(): number;
getMeasuredHeight(): number;
}
/**
* These are the modes in which an entity can measures its dimension. They are
* relevant when a layout needs to know the optimal sizes of its children.
*
* @memberof PUXI
* @enum
* @property {number} UNBOUNDED - no upper limit on bounds. This should calculate the optimal dimensions for the entity.
* @property {number} EXACTLY - the entity should set its dimension to the one passed to it.
* @property {number} AT_MOST - the entity should find an optimal dimension below the one passed to it.
*/
export declare enum MeasureMode {
UNBOUNDED = 0,
EXACTLY = 1,
AT_MOST = 2
}
declare class Menu extends PIXI.Runner {
items: MenuItem[];
constructor(items: MenuItem[]);
}
declare class MenuItem {
icon: string | Texture;
label: string;
constructor(data: {
icon?: string | Texture;
label?: string;
});
}
/**
* @memberof PUXI
* @interface IScrollBarOptions
* @property {PUXI.Sprite} track
* @property {PUXI.Sprite} handle
*/
/**
* An UI scrollbar to control a ScrollingContainer
*
* @class
* @extends PUXI.Slider
* @memberof PUXI
* @param options {Object} ScrollBar settings
* @param options.track {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} Any type of UIOBject, will be used for the scrollbar track
* @param options.handle {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as scrollbar handle
* @param options.scrollingContainer {PIXI.UI.ScrollingContainer} The container to control
* @param [options.vertical=false] {boolean} Direction of the scrollbar
* @param [options.autohide=false] {boolean} Hides the scrollbar when not needed
*/
export declare class ScrollBar extends Slider {
scrollingContainer: ScrollWidget;
autohide: boolean;
_hidden: boolean;
constructor(options: IScrollBarOptions);
initialize(): void;
toggleHidden(hidden: boolean): void;
/**
* @static
*/
static DEFAULT_TRACK: PIXI.Graphics;
/**
* @static
*/
static DEFAULT_HANDLE: PIXI.Graphics;
}
/**
* Handles the `wheel` and `scroll` DOM events on widgets. It also registers
* listeners for `mouseout` and `mouseover`.
*
* @memberof PUXI
* @class
* @extends PUXI.EventManager
*/
export declare class ScrollManager extends EventManager {
private bound;
private delta;
private preventDefault;
constructor(target: Widget, preventDefault?: boolean);
/**
* @override
*/
startEvent(): void;
/**
* @override
*/
stopEvent(): void;
private onMouseScrollImpl;
private onHoverImpl;
private onMouseOutImpl;
onMouseScroll: (event: any, delta: PIXI.Point) => void;
}
/**
* `ScrollWidget` masks its contents to its layout bounds and translates
* its children when scrolling. It uses the anchor layout.
*
* @memberof PUXI
* @class
* @extends PUXI.InteractiveGroup
*/
export declare class ScrollWidget extends InteractiveGroup {
private mask;
readonly innerContainer: WidgetGroup;
private innerBounds;
scrollX: boolean;
scrollY: boolean;
dragScrolling: boolean;
softness: number;
radius: number;
expandMask: number;
overflowY: number;
overflowX: number;
animating: boolean;
scrolling: boolean;
protected scrollBars: ScrollBar[];
protected scrollPosition: PIXI.Point;
protected scrollVelocity: PIXI.Point;
protected targetPosition: PIXI.Point;
protected lastPosition: PIXI.Point;
protected stop: boolean;
private boundCached;
private lastWidth;
private lastHeight;
/**
* @param {PUXI.IScrollingContainerOptions} options
* @param [options.scrollX=false] {Boolean} Enable horizontal scrolling
* @param [options.scrollY=false] {Boolean} Enable vertical scrolling
* @param [options.dragScrolling=true] {Boolean} Enable mousedrag scrolling
* @param [options.softness=0.5] {Number} (0-1) softness of scrolling
* @param [options.width=0] {Number|String} container width
* @param [options.height=0] {Number} container height
* @param [options.radius=0] {Number} corner radius of clipping mask
* @param [options.expandMask=0] {Number} mask expand (px)
* @param [options.overflowY=0] {Number} how much can be scrolled past content dimensions
* @param [options.overflowX=0] {Number} how much can be scrolled past content dimensions
*/
constructor(options?: IScrollingContainerOptions);
/**
* Updates the mask and scroll position before rendering.
*
* @override
*/
update(): void;
/**
* Adds this scrollbar. It is expected that the given scrollbar has been
* given proper border-layout options.
*
* @todo This only works for TOP, LEFT scrollbars as BOTTOM, RIGHT are occupied.
* @param {PUXI.ScrollBar} scrollBar
*/
addScrollBar(scrollBar: ScrollBar): ScrollWidget;
/**
* @param {PUXI.Widget[]} newChildren
* @returns {ScrollWidget} this widget
*/
addChild(...newChildren: Widget[]): Widget;
/**
* Updates the scroll bar values, and should be called when scrolled.
*/
updateScrollBars(): void;
getInnerBounds(force?: boolean): PIXI.Rectangle;
/**
* @override
*/
initialize(): void;
private initScrolling;
/**
* @param {string} direction - `'x'` or `'y'`
* @returns {number} a value between 0 and 1 indicating how scrolling
* has occured in that direction (called percent position).
*/
getPercentPosition(direction: 'x' | 'y'): number;
forcePctPosition: (direction: string, pct: number) => void;
focusPosition: (pos: PIXI.Point) => void;
/**
* @param {PIXI.Point}[velocity]
*/
setScrollPosition: (velocity?: PIXI.Point) => void;
/**
* @param {number} delta
* @protected
*/
protected updateScrollPosition: (delta: number) => void;
/**
* @param {'x' | 'y'} direction
* @param {number} delta
* @protected
*/
protected updateDirection: (direction: string, delta: number) => void;
}
/**
* A sliced sprite with dynamic width and height.
*
* @class
* @memberof PUXI
* @param Texture {PIXI.Texture} the texture for this SliceSprite
* @param BorderWidth {Number} Width of the sprite borders
* @param horizontalSlice {Boolean} Slice the sprite horizontically
* @param verticalSlice {Boolean} Slice the sprite vertically
* @param [tile=false] {Boolean} tile or streach
*/
export declare class SliceSprite extends Widget {
ftl: PIXI.Rectangle;
ftr: PIXI.Rectangle;
fbl: PIXI.Rectangle;
fbr: PIXI.Rectangle;
ft: PIXI.Rectangle;
fb: PIXI.Rectangle;
fr: PIXI.Rectangle;
fl: PIXI.Rectangle;
ff: PIXI.Rectangle;
stl: PIXI.Sprite;
str: PIXI.Sprite;
sbl: PIXI.Sprite;
sbr: PIXI.Sprite;
st: PIXI.Sprite;
sb: PIXI.Sprite;
sl: PIXI.Sprite;
sr: PIXI.Sprite;
sf: PIXI.Sprite;
bw: number;
vs: boolean;
hs: boolean;
t: PIXI.BaseTexture;
f: PIXI.Rectangle;
tile: any;
constructor(texture: PIXI.Texture, borderWidth: any, horizontalSlice: any, verticalSlice: any, tile: any);
initialize(): void;
update(): void;
}
/**
* @memberof PUXI
* @interface ISliderOptions
* @property {PIXI.Container}[track]
* @property {PIXI.Container}[handle]
*/
/**
* These options are used to configure a `PUXI.Slider`.
*
* @memberof PUXI
* @interface ISliderOptions
* @property {PIXI.Container}[track]
* @property {PIXI.Container}[fill]
* @property {boolean}[vertical]
* @property {number}[value]
* @property {number}[minValue]
* @property {number}[maxValue]
* @property {number}[decimals]
* @property {Function}[onValueChange]
* @property {Function}[onValueChanging]
*/
/**
* A slider is a form of input to set a variable to a value in a continuous
* range. It cannot have its own children.
*
* @memberof PUXI
* @class
* @extends PUXI.Widget
*/
export declare class Slider extends Widget {
protected _disabled: boolean;
track: Widget;
handle: Widget;
fill: Sprite;
readonly orientation: number;
protected percentValue: number;
protected _minValue: number;
protected _maxValue: number;
private _localCursor;
decimals: number;
vertical: boolean;
_lastChange: number;
_lastChanging: number;
onValueChange: (n: number) => void;
onValueChanging: (n: number) => void;
/**
* @param options {Object} Slider settings
* @param options.track {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} Any type of UIOBject, will be used for the slider track
* @param options.handle {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as slider handle
* @param [options.fill=null] {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used for slider fill
* @param [options.vertical=false] {boolean} Direction of the slider
* @param [options.value=0] {number} value of the slider
* @param [options.minValue=0] {number} minimum value
* @param [options.maxValue=100] {number} max value
* @param [options.decimals=0] {boolean} the decimal precision (use negative to round tens and hundreds)
* @param [options.onValueChange=null] {callback} Callback when the value has changed
* @param [options.onValueChanging=null] {callback} Callback while the value is changing
*/
constructor(options: ISliderOptions);
initialize(): void;
get value(): number;
set value(val: number);
get minValue(): number;
set minValue(val: number);
get maxValue(): number;
set maxValue(val: number);
get disabled(): boolean;
set disabled(val: boolean);
/**
* @protected
* @returns the amount of the freedom that handle has in physical units, i.e. pixels. This
* is the width of the track minus the handle's size.
*/
protected getPhysicalRange(): number;
/**
* @protected
* @param {PIXI.Point} cursor
* @returns the value of the slider if the handle's center were (globally)
* positioned at the given point.
*/
protected getValueAtPhysicalPosition(cursor: PIXI.Point): number;
/**
* Re-positions the handle. This should be called after `_value` has been changed.
*/
protected layoutHandle(): void;
/**
* Slider measures itself using the track's natural dimensions in its non-oriented
* direction. The oriented direction will be the equal the range's size times
* the track's resolution.
*
* @param width
* @param height
* @param widthMode
* @param heightMode
*/
onMeasure(width: number, height: number, widthMode: number, heightMode: number): void;
/**
* `Slider` lays the track to fill all of its width and height. The handle is aligned
* in the middle in the non-oriented direction.
*
* @param l
* @param t
* @param r
* @param b
* @param dirty
* @override
*/
onLayout(l: number, t: number, r: number, b: number, dirty: boolean): void;
/**
* The default track for horizontally oriented sliders.
* @static
*/
static DEFAULT_HORIZONTAL_TRACK: PIXI.Graphics;
/**
* The default track for vertically oriented sliders.
* @static
*/
static DEFAULT_VERTICAL_TRACK: PIXI.Graphics;
/**
* @static
*/
static DEFAULT_HANDLE: PIXI.Graphics;
/**
* Horizontal orientation
* @static
*/
static HORIZONTAL: number;
/**
* Vertical orientation
* @static
*/
static VERTICAL: number;
}
/**
* An UI Container object
*
* @memberof PUXI
* @class
* @extends PUXI.Widget
* @param desc {Boolean} Sort the list descending
* @param tweenTime {Number} if above 0 the sort will be animated
* @param tweenEase {PIXI.UI.Ease} ease method used for animation
*/
export declare class SortableList extends InteractiveGroup {
desc: boolean;
tweenTime: number;
tweenEase: EaseBase;
items: any[];
_sortTimeout: NodeJS.Timeout;
constructor(desc: any, tweenTime: any, tweenEase: any);
addChild(UIObject: any, fnValue?: any, fnThenBy?: any): void;
removeChild(UIObject: any): void;
sort(instant?: boolean): void;
_sort(): void;
}
/**
* An UI sprite object
*
* @memberof PUXI
* @class
* @extends PUXI.Widget
*/
export declare class Sprite extends Widget {
private spriteDisplay;
constructor(texture: PIXI.Texture);
update(): void;
static fromImage(imageUrl: any): Sprite;
}
/**
* The stage is the root node in the PUXI scene graph. It does not provide a
* sophisticated layout model; however, it will accept constraints defined by
* `PUXI.FastLayoutOptions` or `PUXI.LayoutOptions` in its children.
*
* The stage is not a `PUXI.Widget` and its dimensions are always fixed.
*
* @memberof PUXI
* @class
* @extends PIXI.Container
*/
export declare class Stage extends PIXI.Container {
__width: number;
__height: number;
minWidth: number;
minHeight: number;
initialized: boolean;
widgetChildren: Widget[];
stage: any;
private _checkBoxGroupCtl;
private _focusCtl;
protected background: PIXI.Container;
/**
* @param {number} width - width of the stage
* @param {number} height - height of the stage
*/
constructor(width: number, height: number);
measureAndLayout(): void;
getBackground(): PIXI.Container;
setBackground(bg: PIXI.Container): void;
private update;
render(renderer: PIXI.Renderer): void;
addChild(UIObject: Widget): void;
removeChild(UIObject: Widget): void;
resize(width?: number, height?: number): void;
get width(): number;
set width(val: number);
get height(): number;
set height(val: number);
/**
* The check box group controller for check boxes in this stage.
*
* @member {PUXI.CheckBoxGroupController}
*/
get checkBoxGroupController(): CheckBoxGroupController;
/**
* The focus controller for widgets in this stage. You can use this to bring a
* widget into focus.
*
* @member {PUXI.FocusController}
*/
get focusController(): FocusController;
/**
* Use this to override which class is used for the check box group controller. It
* should extend from `PUXI.CheckBoxGroupController`.
*
* @static
*/
static CHECK_BOX_GROUP_CONTROLLER: typeof CheckBoxGroupController;
/**
* Use this to override which class is used for the focus controller. It should
* extend from `PUXI.FocusController`.
*
* @static
*/
static FOCUS_CONTROLLER: typeof FocusController;
}
/**
* A StyleSheet provides a mechansim to style widgets in a shared fashion.
*/
export declare class Style extends PIXI.utils.EventEmitter {
dirtyID: number;
private data;
private extends;
private computedData;
private computedDirty;
constructor(data?: StyleData);
/**
* @param prop
*/
getProperty(prop: string): any;
/**
* @param props
* @example
* style.getProperties('paddingLeft', 'paddingRight')
*/
getProperties(...props: string[]): Record<string, any>;
/**
* @param prop
* @param value
*/
setProperty(prop: string, value: any): void;
/**
* Extend the given style so that properties not set on this style are derived from it. If multiple styles
* are extended, the ones extended later have a higher priority.
*
* @param style
*/
extend(style: Style): void;
/**
* Recomputes the style data
*/
private compute;
private onParentSetProperty;
/**
* @param data
* @example
* Style.create({
* backgroundColor: 0xabcdef,
* padding: 8
* })
*/
static create(data: StyleData): Style;
}
export declare type StyleData = {
[id: string]: any;
backgroundColor?: string | number;
background?: PIXI.Container;
fontFamily?: string;
fontSize?: number;
paddingLeft?: number;
paddingTop?: number;
paddingRight?: number;
paddingBottom?: number;
padding?: number;
};
export declare class StyleSheet {
[id: string]: Style;
static create(sheetData: {
[id: string]: StyleData;
}): StyleSheet;
}
declare type TabGroup = string;
export declare const TEXT_STYLE_PROPERTIES: string[];
/**
* An UI text object
*
* @class
* @extends PIXI.UI.InputBase
* @memberof PIXI.UI
*/
export declare class TextInput extends FocusableWidget {
private options;
private _dirtyText;
private _value;
private _lastValue;
private _lastWidth;
private _lastHeight;
private selection;
private textContainer;
maxLength: number;
private chars;
private multiLine;
private color;
private selectedColor;
private selectedBackgroundColor;
private tempText;
private textHeight;
private lineHeight;
private caret;
private caretInterval;
private si;
private sie;
private ei;
private eie;
private sp;
private ds;
private de;
private rdd;
private vrdd;
private selectionStart;
private selectionEnd;
private hasSelection;
private t;
private cc;
private textLengthPX;
private textHeightPX;
private lineIndexMax;
private ctrlDown;
private shiftDown;
private shiftKey;
private ctrlKey;
private cmdKey;
private _sp;
/**
* @param {PUXI.ITextInputOptions} options
* @param {string} options.value Text content
* @param {boolean} [options.multiLine=false] Multiline input
* @param options.style {PIXI.TextStyle} Style used for the Text
* @param options.background {(PIXI.UI.SliceSprite|PIXI.UI.Sprite)} will be used as background for input
* @param [options.selectedColor='#ffffff'] {String|Array} Fill color of selected text
* @param [options.selectedBackgroundColor='#318cfa'] {String} BackgroundColor of selected text
* @param [options.width=150] {Number} width of input
* @param [options.height=20] {Number} height of input
* @param [options.padding=3] {Number} input padding
* @param [options.paddingTop=0] {Number} input padding
* @param [options.paddingBottom=0] {Number} input padding
* @param [options.paddingLeft=0] {Number} input padding
* @param [options.paddingRight=0] {Number} input padding
* @param [options.tabIndex=0] {Number} input tab index
* @param [options.tabGroup=0] {Number|String} input tab group
* @param [options.maxLength=0] {Number} 0 = unlimited
* @param [options.caretWidth=1] {Number} width of the caret
* @param [options.lineHeight=0] {Number} 0 = inherit from text
*/
constructor(options: ITextInputOptions);
setupDrag(): void;
private get innerContainer();
update(): void;
updateText(): void;
updateClosestIndex(point: PIXI.Point, start: boolean): void;
deleteSelection(): boolean;
updateSelectionColors(): void;
scrollToPosition(pos: PIXI.Point): void;
resetScrollPosition(): void;
hideCaret(): void;
showCaret(): void;
insertTextAtCaret(c: string): void;
onKeyDown: (e: any) => void;
keyUpEvent: (e: any) => void;
copyEvent: (e: any) => void;
cutEvent: (e: any) => void;
pasteEvent: (e: any) => void;
inputEvent: (e: any) => void;
inputBlurEvent: (e: any) => void;
focus: () => void;
blur: () => void;
setCaretIndex: (index: number) => void;
select: () => void;
selectWord: (wordIndex: number) => void;
selectRange: (startIndex: number, endIndex: number) => void;
clearSelection: () => void;
updateSelectionGraphics: () => void;
drawSelectionRect: (x: number, y: number, w: number, h: number) => void;
get valueEvent(): string;
set valueEvent(val: string);
get value(): string;
set value(val: string);
get text(): string;
set text(value: string);
}
/**
* A static text widget. It cannot retain children.
*
* @memberof PUXI
* @public
*/
export declare class TextWidget extends Widget {
private textDisplay;
/**
* @param {string} text - text content
* @param {PIXI.TextStyle} textStyle - styled used for text
*/
constructor(text: string, textStyle?: PIXI.TextStyle);
update(): void;
/**
* @deprecated
*/
get value(): string;
set value(val: string);
get text(): string;
set text(val: string);
/**
* Get the text style. You can set properties directly on the style.
*/
getTextStyle(): PIXI.TextStyle;
/**
* Set the text style directly
*
* @param textStyle
* @example
* textWidget.setTextStyle({
* fontFamily: 'Roboto',
* fontSize: 14
* })
*/
setTextStyle(textStyle: PIXI.TextStyle): this;
protected onStyleChange(style: Style): void;
}
/**
* This ticker is an event-emitter that can be used for running periodic tasks
* in the rendering loop. It emits the `update` event every animation frame.
*
* @memberof PUXI
* @class
* @extends PIXI.utils.EventEmitter
*/
export declare class Ticker extends PIXI.utils.EventEmitter {
private _disabled;
private _now;
DeltaTime: number;
Time: number;
Ms: number;
constructor(autoStart: boolean);
get disabled(): boolean;
set disabled(val: boolean);
/**
* Updates the text
*
* @private
*/
update(time: number): void;
/**
* The update event is fired periodically and it can be used to for a rendering
* loop.
* @event update
* @param {DOMHighResTimeStamp} deltaTime - milliseconds since last update
*/
static shared: Ticker;
static on(event: any, fn: Function, context: any): void;
static once(event: any, fn: Function, context: any): void;
static removeListener(event: any, fn: Function): void;
}
/**
* An UI sprite object
*
* @class
* @extends PIXI.UI.UIBase
* @memberof PIXI.UI
* @param Texture {PIXI.Texture} The texture for the sprite
* @param [Width=Texture.width] {number} Width of tilingsprite
* @param [Height=Texture.height] {number} Height of tiling sprite
*/
export declare class TilingSprite extends Widget {
protected sprite: PIXI.extras.TilingSprite;
constructor(t: any, width: number, height: number);
/**
* Updates the text
*
* @private
*/
update(): void;
get tilePosition(): any;
set tilingPosition(val: any);
get tileScale(): number;
set tileScale(val: number);
}
/**
* A widget is a user interface control that renders content inside its prescribed
* rectangle on the screen.
*
* @memberof PUXI
* @class
* @extends PIXI.utils.EventEmitter
* @implements PUXI.IMeasurable
*/
export declare class Widget extends PIXI.utils.EventEmitter implements IMeasurable {
/**
* The minimum delay between two clicks to not consider them as a double-click.
*/
static CLICK_DELAY: number;
readonly insetContainer: PIXI.Container;
readonly contentContainer: PIXI.Container;
readonly widgetChildren: Widget[];
readonly stage: Stage;
initialized: boolean;
protected dragInitialized: boolean;
protected dropInitialized: boolean;
protected isDragging: boolean;
private draggable;
private droppable;
dirty: boolean;
_oldWidth: number;
_oldHeight: number;
pixelPerfect: boolean;
parent: Widget;
layoutMeasure: Insets;
layoutOptions: LayoutOptions;
protected tint: number;
protected blendMode: PIXI.BLEND_MODES;
protected background: PIXI.Container;
protected _measuredWidth: number;
protected _measuredHeight: number;
private _eventBroker;
private _paddingLeft;
private _paddingTop;
private _paddingRight;
private _paddingBottom;
private _width;
private _height;
private _elevation;
private _dropShadow;
private _layoutDirty;
private singleClickTimeout;
private style;
private styleID;
private contextMenu;
private contextPopup;
constructor();
/**
* Update method that is to be overriden. This is called before a `render()`
* pass on widgets that are dirty.
*
* @private
*/
update(): any;
/**
* The measured width that is used by the parent's layout manager to place this
* widget.
* @member {number}
*/
get measuredWidth(): number;
/**
* The measured height that is used by the parent's layout manager to place this
* widget.
* @member {number}
*/
get measuredHeight(): number;
/**
* Alias for `Widget.measuredWidth`.
*
* @returns {number} the measured width
*/
getMeasuredWidth(): number;
/**
* Alias for `Widget.measuredHeight`.
*
* @returns {number} the measured height
*/
getMeasuredHeight(): number;
/**
* Override this method to measure the dimensions for your widget. By default, it
* will use the natural width/height of this widget's content (`contentContainer`)
* plus any padding.
*
* @param {number} width - width of region provided by parent
* @param {number} height - height of region provided by parent
* @param {PUXI.MeasureMode} widthMode - mode in which provided width is to be used
* @param {PUXI.MeasureMode} heightMode - mode in which provided height is to be used
*/
onMeasure(width: number, height: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
/**
* This method calls `Widget.onMeasure` and should not be overriden. It does internal
* bookkeeping.
*
* @param {number} width
* @param {number} height
* @param {PUXI.MeasureMode} widthMode
* @param {PUXI.MeasureMode} heightMode
*/
measure(width: number, height: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
/**
* This method should set the frame in which rendering will occur and lay out
* child widgets in that frame.
*
* @param l
* @param t
* @param r
* @param b
* @param dirty
* @protected
*/
onLayout(l: number, t?: number, r?: number, b?: number, dirty?: boolean): void;
layout(l: number, t?: number, r?: number, b?: number, dirty?: boolean): void;
/**
* Use this to specify how you want to layout this widget w.r.t its parent.
* The specific layout options class depends on which layout you are
* using in the parent widget.
*
* @param {PUXI.LayoutOptions} lopt
* @returns {Widget} this
*/
setLayoutOptions(lopt: LayoutOptions): Widget;
/**
* This is invoked when a style is applied on the widget. If you override it, you must pass through the superclass
* implementation.
*
* @param style
*/
protected onStyleChange(style: Style): void;
/**
* Handles the pointer-entered event.
*
* If you override this method, you must call through to the superclass implementation.
*
* @param e - the triggering interaction event
*/
onPointerEnter(e: PIXI.InteractionEvent): void;
/**
* Handles the pointer-exited event.
*
* If you override this method, you must call through to the superclass implementation.
*
* @param e
*/
onPointerExit(e: PIXI.InteractionEvent): void;
/**
* Handles the pointer-down event. If you override this method, you must call through to the superclass
* implementation.
*/
onPointerPress(e: PIXI.InteractionEvent): void;
/**
* Handles the pointer-move event. If you override this method, you must call through to the superclass
* implementation.
*/
onPointerMove(e: PIXI.InteractionEvent): void;
onPointerRelease(e: PIXI.InteractionEvent): void;
/**
* Event handler for change in the hover state.
*
* @param e
* @param hover
*/
onHoverChange(e: PIXI.InteractionEvent, hover: boolean): void;
onClick(e: PIXI.InteractionEvent): void;
onDoubleClick(e: PIXI.InteractionEvent): void;
onRightClick(e: PIXI.InteractionEvent): void;
/**
* The event broker for this widget that holds all the event managers. This can
* be used to start/stop clicks, drags, scrolls and configure how those events
* are handled/interpreted.
* @member PUXI.EventBroker
*/
get eventBroker(): EventBroker;
/**
* Padding on left side.
* @member {number}
*/
get paddingLeft(): number;
set paddingLeft(val: number);
/**
* Padding on top side.
* @member {number}
*/
get paddingTop(): number;
set paddingTop(val: number);
/**
* Padding on right side.
* @member {number}
*/
get paddingRight(): number;
set paddingRight(val: number);
/**
* Padding on bottom side.
* @member {number}
*/
get paddingBottom(): number;
set paddingBottom(val: number);
/**
* Sum of left & right padding.
* @member {number}
* @readonly
*/
get paddingHorizontal(): number;
/**
* Sum of top & bottom padding.
* @member {number}
* @readonly
*/
get paddingVertical(): number;
/**
* Whether this widget is interactive in the PixiJS scene graph.
* @member {boolean}
*/
get interactive(): boolean;
set interactive(val: boolean);
/**
* Layout width of this widget.
* @member {number}
* @readonly
*/
get width(): number;
/**
* Layout height of this widget.
* @member {number}
* @readonly
*/
get height(): number;
/**
* Layout width of this widget's content, which is the width minus horizontal padding.
* @member {number}
* @readonly
*/
get contentWidth(): number;
/**
* Layout height of this widget's content, which is the height minus vertical padding.
* @member {number}
* @readonly
*/
get contentHeight(): number;
/**
* Alpha of this widget & its contents.
* @member {number}
*/
get alpha(): number;
set alpha(val: number);
/**
* Sets the padding values.
*
* To set all paddings to one value:
* ```
* widget.setPadding(8);
* ```
*
* To set horizontal & vertical padding separately:
* ```
* widget.setPadding(4, 12);
* ```
*
* @param {number}[l=0] - left padding
* @param {number}[t=l] - top padding (default is equal to left padding)
* @param {number}[r=l] - right padding (default is equal to right padding)
* @param {number}[b=t] - bottom padding (default is equal to top padding)
*/
setPadding(l: number, t?: number, r?: number, b?: number): Widget;
/**
* @returns {PIXI.Container} - the background display-object
*/
getBackground(): PIXI.Container;
/**
* The background of a widget is a `PIXI.DisplayObject` that is rendered before
* all of its children.
*
* @param {PIXI.Container | number | string} bg - the background display-object or
* a color that will be used to generate a `PIXI.Graphics` as the background.
*/
setBackground(bg: PIXI.Container | number | string): Widget;
/**
* @returns {number} the alpha on the background display-object.
*/
getBackgroundAlpha(): number;
/**
* This can be used to set the alpha on the _background_ of this widget. This
* does not affect the widget's contents nor individual components of the
* background display-object.
*
* @param {number} val - background alpha
*/
setBackgroundAlpha(val: number): Widget;
/**
* Set the context-menu to be shown on right-clicks.
*
* @param menu
* @alpha
*/
setContextMenu(menu: Menu): void;
/**
* @return {number} the elevation set on this widget
*/
getElevation(): number;
/**
* This can be used add a drop-shadow that will appear to raise this widget by
* the given elevation against its parent.
*
* @param {number} val - elevation to use. 2px is good for most widgets.
*/
setElevation(val: number): Widget;
/**
* Set the style applied on this widget. To unset a style, simply pass {@code null}.
*
* @param style
*/
setStyle(style?: Style): this;
/**
* Will trigger a full layout pass next animation frame.
*/
requestLayout(): void;
/**
* Adds the widgets as children of this one.
*
* @param {PUXI.Widget[]} widgets
* @returns {Widget} - this widget
*/
addChild(...widgets: Widget[]): Widget;
/**
* Orphans the widgets that are children of this one.
*
* @param {PUXI.Widget[]} widgets
* @returns {Widget} - this widget
*/
removeChild(...widgets: Widget[]): Widget;
private openPopupMenu;
private closePopupMenu;
/**
* Makes this widget `draggable`.
*/
makeDraggable(): Widget;
/**
* Makes this widget not `draggable`.
*/
clearDraggable(): void;
/**
* Widget initialization related to the stage. This method should always call
* `super.initialize()`.
*
* This method expects `stage` to be set before calling it. This is handled
* by the `Stage` itself.
*
* This will set `initialized` to true. If it was already set to true, it _should
* do nothing_.
*
* @protected
*/
initialize(): void;
private initDraggable;
/**
* Makes this widget `droppable`.
*/
makeDroppable(): Widget;
protected onDrop: (e: PIXI.interaction.InteractionEvent) => void;
/**
* Makes this widget not `droppable`.
*/
clearDroppable(): void;
private initDroppable;
/**
* Creates a widget that holds the display-object as its content. If `content` is
* a `PUXI.Widget`, then it will be returned.
* @param {PIXI.Container | Widget} content
* @static
*/
static fromContent(content: PIXI.Container | Widget): Widget;
/**
* Easy utility to resolve measured dimension.
* @param {number} natural - your widget's natural dimension
* @param {number} limit - width/height limit passed by parent
* @param {PUXI.MeasureMode} mode - measurement mode passed by parent
*/
static resolveMeasuredDimen(natural: number, limit: number, mode: MeasureMode): number;
}
/**
* A widget group is a layout owner that can position its children according
* to the layout given to it.
*
* @memberof PUXI
* @class
* @extends PUXI.Widget
* @example
* ```
* const group = new PUXI.InteractiveGroup();
*
* group.useLayout(new PUXI.AnchorLayout());
*
* group.addChild(new PUXI.Button({ text: "Hey" })
* .setLayoutOptions(
* new PUXI.AnchorLayoutOptions({
* anchorLeft: 100,
* anchorTop: 300,
* anchorRight: .4,
* anchorBottom: 500,
* horizontalAlign: PUXI.ALIGN.CENTER
* })
* )
* )
* ```
*/
export declare class WidgetGroup extends Widget {
layoutMgr: ILayoutManager;
/**
* Will set the given layout-manager to be used for positioning child widgets.
*
* @param {PUXI.ILayoutManager} layoutMgr
*/
useLayout(layoutMgr: ILayoutManager): WidgetGroup;
/**
* Sets the widget-recommended layout manager. By default (if not overriden by widget
* group class), this is a fast-layout.
*/
useDefaultLayout(): void;
onMeasure(width: number, height: number, widthMode: MeasureMode, heightMode: MeasureMode): void;
onLayout(l: number, t: number, r: number, b: number, dirty?: boolean): void;
}
export declare function wrapEase(easeInFunction: any, easeOutFunction: any, easeInOutFunction: any): {
easeIn: any;
easeOut: any;
easeInOut: any;
};
export { } | the_stack |
import "../install-dom-shim.js";
import { child, children, customElement, ExecutionContext, FASTElement, html, item, ref, repeat, slotted, when } from "@microsoft/fast-element";
import { expect, test } from "@playwright/test";
import fastSSR from "../exports.js";
import { consolidate } from "../test-utilities/consolidate.js";
import { TemplateRenderer } from "./template-renderer.js";
@customElement("hello-world")
class HelloWorld extends FASTElement {}
@customElement({name: "with-slot", template: html`<slot></slot>`})
class WithSlot extends FASTElement {}
@customElement({name: "with-host-attributes", template: html`<template static="static" dynamic="${x => "dynamic"}" ?bool-true=${x => true} ?bool-false=${x => false} :property=${x => "value"}>${x => x.property}<slot></slot></template>`})
class WithHostAttributes extends FASTElement {}
test.describe("TemplateRenderer", () => {
test.describe("should have an initial configuration", () => {
test("that emits to shadow DOM", () => {
const instance = new TemplateRenderer();
expect(instance.componentDOMEmissionMode).toBe("shadow")
});
});
test.describe.skip("should allow configuration", () => {
test("that emits to light DOM", () => {
const instance = new TemplateRenderer(/* Re-implement w/ light mode emission is finished {componentDOMEmissionMode: "light"} */);
expect(instance.componentDOMEmissionMode).toBe("light");
});
});
test.describe("rendering <template> elements", () => {
test("should render a template element without attributes", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe("<template></template>");
});
test("should render a template element with static attributes", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template name="foo" id="bar"></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template name="foo" id="bar"></template>`);
});
test("should render a template element with dynamic attributes", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template name=${x => "bar"} id=${x => "bat"}></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template name="bar" id="bat"></template>`);
});
test("should render a template element with a boolean attribute binding", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template ?true=${x => true} ?false=${x => false}></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template true ></template>`);
});
test("should render a template element with a classList property binding", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template :classList=${x => "a b"}></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template class="a b"></template>`);
});
test("should render a template element with both static and dynamic attributes", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template id="bar" name=${x => "foo"}></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template id="bar" name="foo"></template>`);
});
test("should render with static attributes preceding dynamic attributes", () => {
// Attribute order changes are due to attribute categorization during template parsing.
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template name=${x => "foo"} id="bar"></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template id="bar" name="foo"></template>`);
});
test("should render a template with content", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<template name="bar"><p>Hello world</p></template>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<template name="bar"><p>Hello world</p></template>`);
});
test("should render a template as a child element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<p><template name="bar"></template></p>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<p><template name="bar"></template></p>`);
});
});
test.describe("rendering declarative shadow DOM", () => {
test("should emit static shadow DOM template for a defined custom element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<with-slot></with-slot>`, defaultRenderInfo)
expect(consolidate(result)).toBe("<with-slot><template shadowroot=\"open\"><slot></slot></template></with-slot>");
});
test("should emit template element with shadowroot attribute for defined custom element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<hello-world></hello-world>`, defaultRenderInfo)
expect(consolidate(result)).toBe("<hello-world><template shadowroot=\"open\"></template></hello-world>");
});
test("should a custom element with a static attribute", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<hello-world id="test"></hello-world>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<hello-world id="test"><template shadowroot=\"open\"></template></hello-world>`);
});
test("should emit a custom element with attributes and properties reflected from an element's root <template> element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<with-host-attributes id="foo"></with-host-attributes>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<with-host-attributes id="foo" static="static" dynamic="dynamic" bool-true><template shadowroot=\"open\">value<slot></slot></template></with-host-attributes>`);
});
})
test("should emit a single element template", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<p>Hello world</p>`, defaultRenderInfo)
expect(consolidate(result)).toBe("<p>Hello world</p>")
});
test("should emit un-registered custom elements without any shadow DOM", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<unregistered-element>Hello world</unregistered-element>`, defaultRenderInfo)
expect(consolidate(result)).toBe("<unregistered-element>Hello world</unregistered-element>");
});
/**
* Bindings
*/
test("should provide the source object to any bindings", () => {
const source = {};
let calledWith: any;
const { templateRenderer, defaultRenderInfo} = fastSSR();
consolidate(templateRenderer.render(html`${(x) => {calledWith = x}}`, defaultRenderInfo, source));
expect(source).toBe(calledWith);
});
test("should provide the defaultExecutionContext object to a binding", () => {
let calledWith: any;
const { templateRenderer, defaultRenderInfo} = fastSSR();
consolidate(templateRenderer.render(html`${(x, c) => {calledWith = c}}`, defaultRenderInfo));
expect(calledWith).toBe(ExecutionContext.default);
});
test("should not emit string content from a binding that returns a null value", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`${(x) => null}`, defaultRenderInfo));
expect(result).toBe("");
});
test("should not emit string content from a binding that returns an undefined value", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`${(x) => undefined}`, defaultRenderInfo));
expect(result).toBe("");
});
test("should emit a native element with an attribute when the attr binding returns a string", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<p id="${(x) => "test"}"></p>`, defaultRenderInfo));
expect(result).toBe(`<p id="test"></p>`);
});
test("should emit a custom element with an attribute binding when the attr binding returns a string", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`<hello-world my-attr=${x => "foobar"}></hello-world>`, defaultRenderInfo)
expect(consolidate(result)).toBe(`<hello-world my-attr="foobar"><template shadowroot=\"open\"></template></hello-world>`);
});
test("should emit an element with a boolean attribute when the attr binding returns true", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<input type="checkbox" ?checked="${(x) => true}" />`, defaultRenderInfo));
expect(result).toBe(`<input type="checkbox" checked />`);
});
test("should not emit an attribute for a boolean attribute that returns false", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<input type="checkbox" ?checked="${(x) => false}" />`, defaultRenderInfo));
expect(result).toBe(`<input type="checkbox" />`);
});
test("should evaluate bindings for html element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<html attr=${x => "value"}></html>`, defaultRenderInfo));
expect(result).toBe(`<html attr="value"></html>`);
});
test("should evaluate bindings for head element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<head attr=${x => "value"}></head>`, defaultRenderInfo));
expect(result).toBe(`<head attr="value"></head>`);
});
test("should evaluate bindings for body element", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<body attr=${x => "value"}></body>`, defaultRenderInfo));
expect(result).toBe(`<body attr="value"></body>`);
});
test("should emit embedded templates", () =>{
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<p>Hello ${html`<span>world</span>`}</p>`, defaultRenderInfo))
expect(result).toBe(`<p>Hello <span>world</span></p>`);
});
test.describe("binding the the classList", () => {
test("should emit class attribute to native elements", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<p :classList=${ x => "foo bar"}>Hello world</p>`, defaultRenderInfo))
expect(result).toBe(`<p class="foo bar">Hello world</p>`);
});
test("should emit class attribute to custom elements", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = consolidate(templateRenderer.render(html`<hello-world :classList=${x => "foo bar"}></hello-world>`, defaultRenderInfo))
expect(result).toBe(`<hello-world class="foo bar"><template shadowroot="open"></template></hello-world>`);
});
});
/**
* Directive tests
*/
test.describe("with a 'when' directive", () => {
test("should render a 'when' directive's content when the binding evaluates true", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`${when(x => true, html`<p>Hello world</p>`)}`, defaultRenderInfo)
expect(consolidate(result)).toBe("<p>Hello world</p>")
});
test("should emit nothing when a 'when' directive's binding evaluates false ", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const result = templateRenderer.render(html`${when(x => false, html`<p>Hello world</p>`)}`, defaultRenderInfo)
expect(consolidate(result)).toBe("");
});
});
test.describe("with a 'repeat' directive", () => {
test("should provide parent and parentContext to execution context of bindings in child template", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const source = {
data: ["foo", "bar", "bat"]
};
const ctx = ExecutionContext.default;
consolidate(templateRenderer.render(html<typeof source>`${repeat(x => x.data, child<string>`${(x, c) => {
expect(c.parent).toBe(source);
expect(c.parentContext).toBe(ctx)
}}`)}`, defaultRenderInfo, source, ctx))
});
test("should provide positioning information when invoked with the positioning config", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const source = {
data: ["foo", "bar", "bat"]
};
let i = 0;
consolidate(templateRenderer.render(html<typeof source>`${repeat(x => x.data, item<string>`${(x, c) => {
expect(c.index).toBe(i);
i++;
expect(c.length).toBe(c.parent.data.length)
}}`, { positioning: true})}`, defaultRenderInfo, source))
});
test("should render the provided template with the instance as the source data", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const source = {
data: ["foo", "bar", "bat"]
};
const result = templateRenderer.render(html<typeof source>`${repeat(x => x.data, html<string>`${x => x}`)}`, defaultRenderInfo, source)
expect(consolidate( result )).toBe("foobarbat");
});
});
for (let directive of [children, ref, slotted ]) {
test.describe(`with '${directive.name}' directive`, () => {
test("should interpolate empty string", () => {
const { templateRenderer, defaultRenderInfo} = fastSSR();
const source = {}
const result = templateRenderer.render(html`<ul ${directive('items')}><li>Hello</li><li>World</li></ul>`, defaultRenderInfo, source);
expect(consolidate(result)).toBe("<ul ><li>Hello</li><li>World</li></ul>")
});
});
}
}); | the_stack |
import {PlatformLocation} from '@angular/common';
import {AfterViewInit, Component, NgModule, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {FlexLayoutModule} from '@angular/flex-layout';
import {BrowserModule, Title} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AnimationMenuModule} from '../../../../shared/components/animation_menu';
import {FlowState, LoanerFlowSequence, LoanerFlowSequenceButtons, LoanerFlowSequenceModule, NavigationLabels, Step} from '../../../../shared/components/flow_sequence';
import {LoanerTextCardModule} from '../../../../shared/components/info_card';
import {LoanerProgressModule} from '../../../../shared/components/progress';
import {FlowsEnum, LoanerReturnInstructions, LoanerReturnInstructionsModule} from '../../../../shared/components/return_instructions';
import {Survey, SurveyAnswer, SurveyComponent, SurveyModule, SurveyType} from '../../../../shared/components/survey';
import {BACKGROUND_LOGO, BACKGROUND_LOGO_ENABLED, CHROME_MODE, ConfigService, PROGRAM_NAME, RETURN_ANIMATION_ALT_TEXT, RETURN_ANIMATION_ENABLED, RETURN_ANIMATION_URL, TOOLBAR_ICON, TOOLBAR_ICON_ENABLED} from '../../../../shared/config';
import {ApiConfig, apiConfigFactory} from '../../../../shared/services/api_config';
import {NetworkService} from '../../../../shared/services/network_service';
import {AnalyticsModule, AnalyticsService} from '../shared/analytics';
import {Background} from '../shared/background_service';
import {ChromeAppPlatformLocation} from '../shared/chrome_app_platform_location';
import {FailAction, FailType, Failure, FailureModule} from '../shared/failure';
import {HttpModule} from '../shared/http/http_module';
import {Loan} from '../shared/loan';
import {MaterialModule} from './material_module';
/**
* Steps for the flow sequence.
* Important: Insert components in to HTML in same order as seen below.
*/
const STEPS: Step[] = [
{
id: 'return',
title: 'Get ready to return this device',
},
{
id: 'survey',
title: 'One final question before you go',
},
{
id: 'return_instructions',
title: 'Are you sure you want to return this device?',
},
{
id: 'logout',
title: 'Logout and return the loaner',
},
];
@Component({
encapsulation: ViewEncapsulation.None,
preserveWhitespaces: true,
selector: 'app-root',
styleUrls: ['./app.scss'],
templateUrl: './app.ng.html',
})
export class AppRoot implements AfterViewInit, OnInit {
readonly backgroundLogo = BACKGROUND_LOGO;
readonly backgroundLogoEnabled = BACKGROUND_LOGO_ENABLED;
readonly toolbarIcon = TOOLBAR_ICON;
readonly toolbarIconEnabled = TOOLBAR_ICON_ENABLED;
/** Labels to be used on navigation buttons. */
readonly labels: NavigationLabels = {
previous: {aria: 'Previous step', toolTip: 'Previous Step'},
next: {aria: 'Next step', toolTip: 'Next Step'},
done: {
aria: 'All done! Your loaner can now be returned.',
toolTip: 'All done! Your loaner can now be returned.',
}
};
flows = FlowsEnum;
currentStep = 0;
maxStep = 0;
readonly steps = STEPS;
@ViewChild(LoanerFlowSequence, {static: true})
flowSequence!: LoanerFlowSequence;
@ViewChild(LoanerFlowSequenceButtons, {static: true})
flowSequenceButtons!: LoanerFlowSequenceButtons;
surveyAnswer!: SurveyAnswer;
surveySent = false;
returnCompleted = false;
// Flow components to be manipulated.
@ViewChild(SurveyComponent, {static: true}) surveyComponent!: SurveyComponent;
@ViewChild(LoanerReturnInstructions, {static: true})
returnInstructions!: LoanerReturnInstructions;
// Represents the analytics image in the body.
@ViewChild('analytics', {static: true}) analyticsImg!: HTMLImageElement|null;
// Text to be populated on an info card for logout step.
logoutPage = {
title: 'Your loaner is now set to be returned.',
body:
`You may now logout and return this loaner to the nearest shelf. We hope
you enjoyed your ${PROGRAM_NAME} experience!`,
};
// Text to be populated on an info card for return step.
returnPage = {
title: `Are you sure you want to return this ${PROGRAM_NAME} device?`,
body: `By proceeding to the next step, you will mark the loaner as being
returned. Once you proceed to the next step, you will need to return the
device to your nearest shelf as soon as possible.`,
};
constructor(
private readonly analyticsService: AnalyticsService,
private readonly bg: Background,
private readonly config: ConfigService,
private readonly failure: Failure,
private readonly loan: Loan,
private readonly networkService: NetworkService,
private readonly survey: Survey,
readonly title: Title,
) {
title.setTitle(`Return your ${PROGRAM_NAME} loaner`);
this.survey.answer.subscribe(val => {
this.surveyAnswer = val;
});
}
/**
* Updates the analytics view and changes the analytics img src to match.
* @param view represents the current page/view.
*/
private updateAnalytics(view: string) {
if (this.config.analyticsEnabled && this.config.isAnalyticsIdValid()) {
this.analyticsService.sendView('offboarding', view).subscribe(url => {
if (this.analyticsImg) {
this.analyticsImg.src = window.URL.createObjectURL(url);
}
});
}
}
ngAfterViewInit() {
this.updateAnalytics('/return');
}
ngOnInit() {
this.flowSequence.steps = this.steps;
this.maxStep = this.flowSequence.maxStepNumber;
// Setup navigation buttons
this.flowSequence.flowSequenceButtons = this.flowSequenceButtons;
this.flowSequenceButtons.flowState = this.flowSequence.flowState;
this.flowSequence.setupFlowButtonsListener();
// Setup survey component
this.surveySetup();
this.surveyListener();
// Setup return instructions
this.returnInstructions.programName = PROGRAM_NAME;
this.returnInstructions.animationEnabled = RETURN_ANIMATION_ENABLED;
this.returnInstructions.animationAltText = RETURN_ANIMATION_ALT_TEXT;
this.returnInstructions.animationURL = RETURN_ANIMATION_URL;
// Listen for flow finished
this.flowSequenceButtons.finished.subscribe(finished => {
if (finished) this.closeApplication();
});
// If there is no network connection, disable the flow buttons.
this.networkService.internetStatus.subscribe(status => {
this.flowSequenceButtons.allowButtonClick = status;
});
// Subscribe to flow state
this.flowSequence.flowState.subscribe(state => {
this.updateStepNumber(state);
// Actions to be taken when certain active/next step is shown.
switch (state.activeStep.id) {
case 'logout':
this.updateAnalytics('/logout');
this.completeReturn();
break;
case 'return':
this.updateAnalytics('/return');
// Ensure that can proceed isn't disabled because of a previous check.
this.flowSequenceButtons.canProceed = true;
this.returnInstructions.reloadAnimation();
break;
case 'return_instructions':
this.updateAnalytics('/return_instructions');
break;
// Checks if surveys are required and if so that they are filled out.
case 'survey':
this.updateAnalytics('/survey');
if (this.surveyAnswer == null &&
this.surveyComponent.answerRequired) {
this.flowSequenceButtons.canProceed = false;
this.survey.answer.subscribe(val => {
this.surveyAnswer = val;
if (this.surveyAnswer !== null) {
this.flowSequenceButtons.canProceed = true;
} else {
this.flowSequenceButtons.canProceed = false;
}
});
}
break;
default:
break;
}
});
}
/**
* Update the step number based off of information from the current flow
* state.
* @param state FlowState of the application.
*/
updateStepNumber(state: FlowState) {
if (state.optional) {
if (state.optional.activeStepNumber === 0 ||
state.optional.activeStepNumber) {
this.currentStep = state.optional.activeStepNumber;
}
}
}
/** Opens the managment window and closes the offboarding flow. */
backToManage() {
this.bg.openView('manage');
this.bg.closeView('offboarding');
}
/**
* Sends message to background service to close the 'offboarding' chrome
* application window.
*/
closeApplication() {
this.flowSequenceButtons.canProceed = false;
if (this.surveyAnswer) {
this.surveyComponent.waiting();
this.survey.submitSurvey(this.surveyAnswer)
.subscribe(
() => {
this.surveyComponent.ready();
this.bg.closeView('offboarding');
},
error => {
console.error('The survey failed to submit: ', error);
this.bg.closeView('offboarding');
});
} else {
this.bg.closeView('offboarding');
}
}
// Survey related items
/**
* Setup and configure the survey component.
*/
surveySetup() {
this.surveyComponent.surveyDescription =
`Before you go, we have one more question to ask about your loaner
experience. This will help us improve and maintain the loaner program.`;
this.surveyComponent.surveyType = SurveyType.Return;
}
/**
* Handle changes from survey related items including the SurveyComponent.
*/
surveyListener() {
this.survey.answer.subscribe(val => {
this.surveyAnswer = val;
});
this.surveyComponent.surveyError.subscribe(val => {
const message = `We are unable to retrieve the survey at the moment,
continue using the app as normal.`;
this.failure.register(message, FailType.Network, FailAction.Ignore, val);
});
}
completeReturn() {
if (!this.returnCompleted) {
this.loan.return().subscribe(
() => {
this.returnCompleted = true;
},
error => {
const message = `Something went wrong when marking the device
returned. Please return to the nearest shelf and we will take care of the
rest.`;
this.failure.register(
message, FailType.Other, FailAction.Quit, error);
});
}
}
}
@NgModule({
bootstrap: [AppRoot],
declarations: [AppRoot],
imports: [
AnalyticsModule,
AnimationMenuModule,
BrowserAnimationsModule,
BrowserModule,
FlexLayoutModule,
HttpModule,
MaterialModule,
LoanerProgressModule,
FailureModule,
LoanerReturnInstructionsModule,
LoanerTextCardModule,
SurveyModule,
LoanerFlowSequenceModule,
],
providers: [
{provide: PlatformLocation, useClass: ChromeAppPlatformLocation},
ConfigService,
Background,
NetworkService,
Survey,
Loan,
// useValue used in this provide since useFactory with parameters doesn't
// work in AOT land.
{
provide: ApiConfig,
useValue: apiConfigFactory(
new ConfigService().endpointsApiUrl,
new ConfigService().chromeApiUrl),
},
],
})
export class AppModule {
} | the_stack |
import React, { FC, useState, useEffect, Fragment, ReactNode } from 'react'
import cn from 'classnames'
import { useMenuState, Menu, MenuButton, MenuStateReturn } from 'reakit/Menu'
import { theme, Colors } from '@island.is/island-ui/theme'
import { Text } from '../Text/Text'
import { Box } from '../Box/Box'
import { BoxProps } from '../Box/types'
import { FocusableBox } from '../FocusableBox/FocusableBox'
import { Button } from '../Button/Button'
import * as styles from './Navigation.css'
import { Icon } from '../IconRC/Icon'
export type NavigationColorAttributes =
| 'color'
| 'dividerColor'
| 'backgroundColor'
| 'activeColor'
const colorSchemeColors: Record<
keyof typeof styles.colorScheme,
Record<NavigationColorAttributes, Colors>
> = {
blue: {
color: 'blue600' as Colors,
dividerColor: 'blue200' as Colors,
backgroundColor: 'blue100' as Colors,
activeColor: 'blue400' as Colors,
},
darkBlue: {
color: 'white' as Colors,
dividerColor: 'blue600' as Colors,
backgroundColor: 'blue400' as Colors,
activeColor: 'white' as Colors,
},
purple: {
color: 'purple600' as Colors,
dividerColor: 'purple200' as Colors,
backgroundColor: 'purple100' as Colors,
activeColor: 'purple400' as Colors,
},
}
export interface NavigationItem {
title: string
href?: string
active?: boolean
items?: NavigationItem[]
typename?: string
slug?: string[]
}
interface MobileNavigationDialogProps {
Title: ReactNode
colorScheme: keyof typeof styles.colorScheme
items: NavigationItem[]
renderLink: NavigationTreeProps['renderLink']
isVisible: boolean
onClick: () => void
menuState: MenuStateReturn
}
interface NavigationTreeProps {
items: NavigationItem[]
level?: Level
colorScheme?: keyof typeof styles.colorScheme
expand?: boolean
renderLink?: (link: ReactNode, item?: NavigationItem) => ReactNode
menuState: MenuStateReturn
linkOnClick?: () => void
}
export interface NavigationProps {
title: string
label?: string
activeItemTitle?: string
colorScheme?: keyof typeof styles.colorScheme
expand?: boolean
isMenuDialog?: boolean
titleLink?: Pick<NavigationItem, 'href' | 'active'>
items: NavigationItem[]
baseId: string
/**
* Render function for all links, useful for wrapping framework specific routing links
*/
renderLink?: NavigationTreeProps['renderLink']
titleProps?: NavigationItem
}
// The sidebar nav is not designed to show more than 2 levels.
type Level = keyof typeof styles.level
const MAX_LEVELS = 2
const basePadding = {
paddingY: 1,
paddingX: 3,
} as Pick<BoxProps, 'paddingY' | 'paddingX'>
const defaultLinkRender: NavigationTreeProps['renderLink'] = (link) => link
export const Navigation: FC<NavigationProps> = ({
title = 'Efnisyfirlit',
titleLink,
activeItemTitle,
label,
colorScheme = 'blue',
expand,
renderLink = defaultLinkRender,
isMenuDialog = false,
items,
titleProps,
baseId,
}) => {
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
const color = colorSchemeColors[colorScheme]['color']
const activeColor = colorSchemeColors[colorScheme]['activeColor']
const backgroundColor = colorSchemeColors[colorScheme]['backgroundColor']
const dividerColor = colorSchemeColors[colorScheme]['dividerColor']
const someActiveLinks = items.some((x) => x.active)
const menu = useMenuState({ animated: true, baseId, visible: false })
useEffect(() => {
setMobileMenuOpen(menu.visible)
}, [menu.visible])
const titleLinkProps = titleLink
? {
href: titleLink.href,
}
: null
const Title: MobileNavigationDialogProps['Title'] = titleLinkProps ? (
renderLink(
<FocusableBox
component="a"
href={titleLink?.href}
borderRadius="large"
className={styles.link}
{...basePadding}
>
{({
isFocused,
isHovered,
}: {
isFocused: boolean
isHovered: boolean
}) => {
const textColor =
titleLink?.active || isFocused || isHovered ? activeColor : color
return (
<Text as="span" variant="h4" color={textColor}>
{title}
</Text>
)
}}
<Text
as="span"
variant="h4"
color={titleLink?.active ? activeColor : color}
>
{title}
</Text>
</FocusableBox>,
titleProps,
)
) : (
<Box {...basePadding}>
<Text as="span" variant="h4" color={color}>
{title}
</Text>
</Box>
)
return (
<>
{isMenuDialog ? (
<Box
background={backgroundColor}
alignItems="center"
borderRadius="large"
position="relative"
>
<MenuButton
{...menu}
className={styles.menuBtn}
onClick={() => menu.show}
>
<MobileButton
title={activeItemTitle ?? title}
colorScheme={colorScheme}
aria-expanded={!mobileMenuOpen}
aria-controls={'OpenNavigationDialog'}
/>
</MenuButton>
<Menu
{...menu}
style={{
top: '-10px',
transform: 'none',
width: '100%',
borderRadius: '8px',
zIndex: 10,
}}
className={cn(styles.transition, styles.menuShadow[colorScheme])}
>
<MobileNavigationDialog
Title={Title}
colorScheme={colorScheme}
items={items}
renderLink={renderLink}
isVisible={mobileMenuOpen}
menuState={menu}
onClick={() => {
menu.hide()
}}
/>
</Menu>
</Box>
) : (
<Box
component="nav"
borderRadius="large"
paddingY={2}
aria-label={label ?? title}
background={backgroundColor}
className={cn(styles.root, styles.colorScheme[colorScheme])}
>
{Title}
<Box display="flex" alignItems="center" paddingY={2}>
<Box background={dividerColor} className={styles.divider} />
</Box>
<NavigationTree
items={items}
colorScheme={colorScheme}
renderLink={renderLink}
menuState={menu}
expand={expand}
/>
</Box>
)}
</>
)
}
const MobileNavigationDialog = ({
Title,
colorScheme,
items,
renderLink,
onClick,
menuState,
}: MobileNavigationDialogProps) => {
return (
<Box
component="nav"
background={colorSchemeColors[colorScheme]['backgroundColor']}
paddingY={2}
borderRadius={'large'}
>
<Box position="relative">
{Title}
<Box
position="absolute"
right={0}
marginRight={2}
style={{ top: '50%', transform: 'translateY(-50%)' }}
>
<Button
circle
colorScheme="negative"
icon={'chevronUp'}
size="small"
aria-controls={`CloseNavigationDialog`}
onClick={onClick}
/>
</Box>
</Box>
<Box display="flex" alignItems="center" paddingY={2}>
<Box
background={colorSchemeColors[colorScheme]['dividerColor']}
className={styles.divider}
/>
</Box>
<NavigationTree
items={items}
colorScheme={colorScheme}
renderLink={renderLink}
menuState={menuState}
linkOnClick={onClick}
/>
</Box>
)
}
interface MobileButtonProps {
title: string
colorScheme: keyof typeof styles.colorScheme
}
const MobileButton = ({ title, colorScheme }: MobileButtonProps) => {
return (
<Box
component="span"
display="flex"
justifyContent="spaceBetween"
alignItems="center"
paddingX={2}
paddingY={1}
>
<Text
as="span"
variant="h5"
color={colorSchemeColors[colorScheme]['activeColor']}
>
{title}
</Text>
<Box
component="span"
position="absolute"
right={0}
marginRight={2}
style={{ top: '50%', transform: 'translateY(-50%)' }}
>
<span className={styles.dropdownIcon}>
<Icon icon={'chevronDown'} size="small" color="blue400" />
</span>
</Box>
</Box>
)
}
export const NavigationTree: FC<NavigationTreeProps> = ({
items,
level = 1,
colorScheme = 'blue',
expand = false,
renderLink = defaultLinkRender,
menuState,
linkOnClick,
}: NavigationTreeProps) => {
return (
<Box
component="ul"
className={cn(styles.ul, styles.level[level])}
style={{
borderLeftColor:
level > 1
? theme.color[colorSchemeColors[colorScheme]['dividerColor']]
: undefined,
}}
>
{items.map((item, index) => {
const { title, href, items = [], active } = item
const nextLevel: Level = (level + 1) as Level
const isChildren = level > 1
const showNextLevel =
(active || expand) && items.length && nextLevel <= MAX_LEVELS
return (
<li key={index}>
{renderLink(
<FocusableBox
component="a"
href={href}
borderRadius="large"
paddingLeft={isChildren ? 2 : 3}
paddingRight={2}
paddingY={isChildren ? 'smallGutter' : 1}
className={styles.link}
onClick={linkOnClick}
>
{({
isFocused,
isHovered,
}: {
isFocused: boolean
isHovered: boolean
}) => {
const textColor =
active || isFocused || isHovered
? colorSchemeColors[colorScheme]['activeColor']
: colorSchemeColors[colorScheme]['color']
return (
<Text
as="span"
color={textColor}
variant={isChildren ? 'small' : 'default'}
fontWeight={active ? 'semiBold' : 'light'}
>
{title}
</Text>
)
}}
</FocusableBox>,
item,
)}
{showNextLevel ? (
<NavigationTree
items={items}
level={nextLevel}
colorScheme={colorScheme}
expand={expand}
renderLink={renderLink}
menuState={menuState}
linkOnClick={linkOnClick}
/>
) : null}
</li>
)
})}
</Box>
)
} | the_stack |
namespace wordBreakers {
/**
* Word breaker based on Unicode Standard Annex #29, Section 4.1:
* Default Word Boundary Specification.
*
* @see http://unicode.org/reports/tr29/#Word_Boundaries
* @see https://github.com/eddieantonio/unicode-default-word-boundary/tree/v12.0.0
*/
export function default_(text: string): Span[] {
let boundaries = findBoundaries(text);
if (boundaries.length == 0) {
return [];
}
// All non-empty strings have at least TWO boundaries at the start and end of
// the string.
let spans = [];
for (let i = 0; i < boundaries.length - 1; i++) {
let start = boundaries[i];
let end = boundaries[i + 1];
let span = new LazySpan(text, start, end);
if (isNonSpace(span.text)) {
spans.push(span);
// Preserve a sequence-final space if it exists. Needed to signal "end of word".
} else if (i == boundaries.length - 2) { // if "we just checked the final boundary"...
// We don't want to return the whitespace itself; the correct token is simply ''.
span = new LazySpan(text, end, end);
spans.push(span);
}
}
return spans;
}
// Utilities //
import WordBreakProperty = wordBreakers.data.WordBreakProperty;
import WORD_BREAK_PROPERTY = wordBreakers.data.WORD_BREAK_PROPERTY;
import I = wordBreakers.data.I;
/**
* A span that does not cut out the substring until it absolutely has to!
*/
class LazySpan implements Span {
private _source: string;
readonly start: number;
readonly end: number;
constructor(source: string, start: number, end: number) {
this._source = source;
this.start = start;
this.end = end;
}
get text(): string {
return this._source.substring(this.start, this.end);
}
get length(): number {
return this.end - this.start;
}
}
/**
* Returns true when the chunk does not solely consist of whitespace.
*
* @param chunk a chunk of text. Starts and ends at word boundaries.
*/
function isNonSpace(chunk: string): boolean {
return !Array.from(chunk).map(property).every(wb => (
wb === WordBreakProperty.CR ||
wb === WordBreakProperty.LF ||
wb === WordBreakProperty.Newline ||
wb === WordBreakProperty.WSegSpace
));
}
/**
* Yields a series of string indices where a word break should
* occur. That is, there should be a break BEFORE each string
* index yielded by this generator.
*
* @param text Text to find word boundaries in.
*/
function findBoundaries(text: string): number[] {
// WB1 and WB2: no boundaries if given an empty string.
if (text.length === 0) {
// There are no boundaries in an empty string!
return [];
}
// This algorithm works by maintaining a sliding window of four SCALAR VALUES.
//
// - Scalar values? JavaScript strings are NOT actually a string of
// Unicode code points; some characters are made up of TWO
// JavaScript indices. e.g.,
// "💩".length === 2;
// "💩"[0] === '\uD83D';
// "💩"[1] === '\uDCA9';
//
// These characters that are represented by TWO indices are
// called "surrogate pairs". Since we don't want to be in the
// "middle" of a character, make sure we're always advancing
// by scalar values, and NOT indices. That means, we sometimes
// need to advance by TWO indices, not just one.
// - Four values? Some rules look at what's to the left of
// left, and some look at what's to the right of right. So
// keep track of this!
let boundaries = [];
let rightPos: number;
let lookaheadPos = 0; // lookahead, one scalar value to the right of right.
// Before the start of the string is also the start of the string.
let lookbehind: WordBreakProperty;
let left = WordBreakProperty.sot;
let right = WordBreakProperty.sot;
let lookahead = wordbreakPropertyAt(0);
// Count RIs to make sure we're not splitting emoji flags:
let nConsecutiveRegionalIndicators = 0;
do {
// Shift all positions, one scalar value to the right.
rightPos = lookaheadPos;
lookaheadPos = positionAfter(lookaheadPos);
// Shift all properties, one scalar value to the right.
[lookbehind, left, right, lookahead] =
[left, right, lookahead, wordbreakPropertyAt(lookaheadPos)];
// Break at the start and end of text, unless the text is empty.
// WB1: Break at start of text...
if (left === WordBreakProperty.sot) {
boundaries.push(rightPos);
continue;
}
// WB2: Break at the end of text...
if (right === WordBreakProperty.eot) {
boundaries.push(rightPos);
break; // Reached the end of the string. We're done!
}
// WB3: Do not break within CRLF:
if (left === WordBreakProperty.CR && right === WordBreakProperty.LF)
continue;
// WB3b: Otherwise, break after...
if (left === WordBreakProperty.Newline ||
left === WordBreakProperty.CR ||
left === WordBreakProperty.LF) {
boundaries.push(rightPos);
continue;
}
// WB3a: ...and before newlines
if (right === WordBreakProperty.Newline ||
right === WordBreakProperty.CR ||
right === WordBreakProperty.LF) {
boundaries.push(rightPos);
continue;
}
// TODO: WB3c is not implemented, due to its complex, error-prone
// implementation, requiring a ginormous regexp, and the fact that
// the only thing it does is prevent big emoji sequences from being
// split up, like 🧚🏼♂️
// https://www.unicode.org/Public/emoji/12.0/emoji-zwj-sequences.txt
// WB3d: Keep horizontal whitespace together
if (left === WordBreakProperty.WSegSpace && right == WordBreakProperty.WSegSpace)
continue;
// WB4: Ignore format and extend characters
// This is to keep grapheme clusters together!
// See: Section 6.2: https://unicode.org/reports/tr29/#Grapheme_Cluster_and_Format_Rules
// N.B.: The rule about "except after sot, CR, LF, and
// Newline" already been by WB1, WB2, WB3a, and WB3b above.
while (right === WordBreakProperty.Format ||
right === WordBreakProperty.Extend ||
right === WordBreakProperty.ZWJ) {
// Continue advancing in the string, as if these
// characters do not exist. DO NOT update left and
// lookbehind however!
[rightPos, lookaheadPos] = [lookaheadPos, positionAfter(lookaheadPos)];
[right, lookahead] = [lookahead, wordbreakPropertyAt(lookaheadPos)];
}
// In ignoring the characters in the previous loop, we could
// have fallen off the end of the string, so end the loop
// prematurely if that happens!
if (right === WordBreakProperty.eot) {
boundaries.push(rightPos);
break;
}
// WB4 (continued): Lookahead must ALSO ignore these format,
// extend, ZWJ characters!
while (lookahead === WordBreakProperty.Format ||
lookahead === WordBreakProperty.Extend ||
lookahead === WordBreakProperty.ZWJ) {
// Continue advancing in the string, as if these
// characters do not exist. DO NOT update left and right,
// however!
lookaheadPos = positionAfter(lookaheadPos);
lookahead = wordbreakPropertyAt(lookaheadPos);
}
// WB5: Do not break between most letters.
if (isAHLetter(left) && isAHLetter(right))
continue;
// Do not break across certain punctuation
// WB6: (Don't break before apostrophes in contractions)
if (isAHLetter(left) && isAHLetter(lookahead) &&
(right === WordBreakProperty.MidLetter || isMidNumLetQ(right)))
continue;
// WB7: (Don't break after apostrophes in contractions)
if (isAHLetter(lookbehind) && isAHLetter(right) &&
(left === WordBreakProperty.MidLetter || isMidNumLetQ(left)))
continue;
// WB7a
if (left === WordBreakProperty.Hebrew_Letter && right === WordBreakProperty.Single_Quote)
continue;
// WB7b
if (left === WordBreakProperty.Hebrew_Letter && right === WordBreakProperty.Double_Quote &&
lookahead === WordBreakProperty.Hebrew_Letter)
continue;
// WB7c
if (lookbehind === WordBreakProperty.Hebrew_Letter && left === WordBreakProperty.Double_Quote &&
right === WordBreakProperty.Hebrew_Letter)
continue;
// Do not break within sequences of digits, or digits adjacent to letters.
// e.g., "3a" or "A3"
// WB8
if (left === WordBreakProperty.Numeric && right === WordBreakProperty.Numeric)
continue;
// WB9
if (isAHLetter(left) && right === WordBreakProperty.Numeric)
continue;
// WB10
if (left === WordBreakProperty.Numeric && isAHLetter(right))
continue;
// Do not break within sequences, such as 3.2, 3,456.789
// WB11
if (lookbehind === WordBreakProperty.Numeric && right === WordBreakProperty.Numeric &&
(left === WordBreakProperty.MidNum || isMidNumLetQ(left)))
continue;
// WB12
if (left === WordBreakProperty.Numeric && lookahead === WordBreakProperty.Numeric &&
(right === WordBreakProperty.MidNum || isMidNumLetQ(right)))
continue;
// WB13: Do not break between Katakana
if (left === WordBreakProperty.Katakana && right === WordBreakProperty.Katakana)
continue;
// Do not break from extenders (e.g., U+202F NARROW NO-BREAK SPACE)
// WB13a
if ((isAHLetter(left) ||
left === WordBreakProperty.Numeric ||
left === WordBreakProperty.Katakana ||
left === WordBreakProperty.ExtendNumLet) &&
right === WordBreakProperty.ExtendNumLet)
continue;
// WB13b
if ((isAHLetter(right) ||
right === WordBreakProperty.Numeric ||
right === WordBreakProperty.Katakana) && left === WordBreakProperty.ExtendNumLet)
continue;
// WB15 & WB16:
// Do not break within emoji flag sequences. That is, do not break between
// regional indicator (RI) symbols if there is an odd number of RI
// characters before the break point.
if (right === WordBreakProperty.Regional_Indicator) {
// Emoji flags are actually composed of TWO scalar values, each being a
// "regional indicator". These indicators correspond to Latin letters. Put
// two of them together, and they spell out an ISO 3166-1-alpha-2 country
// code. Since these always come in pairs, NEVER split the pairs! So, if
// we happen to be inside the middle of an odd numbered of
// Regional_Indicators, DON'T SPLIT IT!
nConsecutiveRegionalIndicators += 1;
if ((nConsecutiveRegionalIndicators % 2) == 1) {
continue;
}
} else {
nConsecutiveRegionalIndicators = 0;
}
// WB999: Otherwise, break EVERYWHERE (including around ideographs)
boundaries.push(rightPos);
} while (rightPos < text.length);
return boundaries;
///// Internal utility functions /////
/**
* Returns the position of the start of the next scalar value. This jumps
* over surrogate pairs.
*
* If asked for the character AFTER the end of the string, this always
* returns the length of the string.
*/
function positionAfter(pos: number): number {
if (pos >= text.length) {
return text.length;
} else if (isStartOfSurrogatePair(text[pos])) {
return pos + 2;
}
return pos + 1;
}
/**
* Return the value of the Word_Break property at the given string index.
* @param pos position in the text.
*/
function wordbreakPropertyAt(pos: number) {
if (pos < 0) {
return WordBreakProperty.sot; // Always "start of string" before the string starts!
} else if (pos >= text.length) {
return WordBreakProperty.eot; // Always "end of string" after the string ends!
} else if (isStartOfSurrogatePair(text[pos])) {
// Surrogate pairs the next TWO items from the string!
return property(text[pos] + text[pos + 1]);
}
return property(text[pos]);
}
// Word_Break rule macros
// See: https://unicode.org/reports/tr29/#WB_Rule_Macros
function isAHLetter(prop: WordBreakProperty): boolean {
return prop === WordBreakProperty.ALetter ||
prop === WordBreakProperty.Hebrew_Letter;
}
function isMidNumLetQ(prop: WordBreakProperty): boolean {
return prop === WordBreakProperty.MidNumLet ||
prop === WordBreakProperty.Single_Quote;
}
}
function isStartOfSurrogatePair(character: string) {
let codeUnit = character.charCodeAt(0);
return codeUnit >= 0xD800 && codeUnit <= 0xDBFF;
}
/**
* Return the Word_Break property value for a character.
* Note that
* @param character a scalar value
*/
function property(character: string): WordBreakProperty {
// This MUST be a scalar value.
// TODO: remove dependence on character.codepointAt()?
let codepoint = character.codePointAt(0) as number;
return searchForProperty(codepoint, 0, WORD_BREAK_PROPERTY.length - 1);
}
/**
* Binary search for the word break property of a given CODE POINT.
*/
function searchForProperty(codePoint: number, left: number, right: number): WordBreakProperty {
// All items that are not found in the array are assigned the 'Other' property.
if (right < left) {
return WordBreakProperty.Other;
}
let midpoint = left + ~~((right - left) / 2);
let candidate = WORD_BREAK_PROPERTY[midpoint];
let nextRange = WORD_BREAK_PROPERTY[midpoint + 1];
let startOfNextRange = nextRange ? nextRange[I.Start] : Infinity;
if (codePoint < candidate[I.Start]) {
return searchForProperty(codePoint, left, midpoint - 1);
} else if (codePoint >= startOfNextRange) {
return searchForProperty(codePoint, midpoint + 1, right);
}
// We found it!
return candidate[I.Value];
}
}
// We cannot export a member whose name is a reserved word when
// implementing a namespace, BUT we can manually make the
// assignment and **declare** it as part of the namespace.
wordBreakers['default'] = wordBreakers.default_;
declare namespace wordBreakers {
export { default_ as default };
} | the_stack |
import styles from "./index.module.less";
import {
Dropdown,
Button,
Tag,
Dialog,
Form,
Select,
Textarea,
Input,
Loading,
Alert,
MessagePlugin
} from 'tdesign-react';
import {Icon} from 'tdesign-icons-react';
import {useEffect, useMemo, useRef, useState} from "react";
import {truncate} from 'lodash'
import {request} from "../../../utils/axios";
import {
commitCodeRequest,
getDevVersionRequest, getTemplateListRequest,
releaseCodeRequest,
revokeAuditRequest, rollbackReleaseRequest,
speedUpAuditRequest,
} from "../../../utils/apis";
import {useSearchParams} from "react-router-dom";
import moment from "moment";
import {routes} from "../../../config/route";
const {FormItem} = Form;
const {Option} = Select
type IVersionData = {
auditInfo?: {
auditId: number
status: number
reason: string
screenShot: string
userVersion: string
userDesc: string
submitAuditTime: number
}
releaseInfo?: {
releaseTime: number
releaseVersion: string
releaseDesc: string
releaseQrCode: string // base64
}
expInfo?: {
expTime: number
expVersion: string
expDesc: string
expQrCode: string // base64
}
}
type ITemplateList = {
templateId: number
userVersion: string
userDesc: string
}[]
// 线上版选项
const onlineOptions = [{
content: '版本回退',
value: 1,
}]
export default function MiniProgramVersion() {
const [versionData, setVersionData] = useState<IVersionData>({
auditInfo: undefined,
releaseInfo: undefined,
expInfo: undefined
})
const [visibleSubmitModal, setVisibleSubmitModal] = useState(false)
const [loading, setLoading] = useState(true)
const [templateList, setTemplateList] = useState<ITemplateList>([])
const [searchParams] = useSearchParams();
const formRef = useRef() as any
const appId = useMemo(() => {
return searchParams.get('appId')
}, [searchParams])
// 审核版选项
const auditOptions = useMemo(() => {
if (versionData.auditInfo?.status === 0) {
return [{
content: '提交发布',
value: 4,
}]
}
if (versionData.auditInfo?.status === 1 || versionData.auditInfo?.status === 3) {
return [{
content: '提交审核',
value: 1,
}]
}
if (versionData.auditInfo?.status === 2 || versionData.auditInfo?.status === 4) {
return [{
content: '加急审核',
value: 2,
}, {
content: '撤回审核',
value: 3,
}]
}
return []
}, [versionData])
// 体验版选项
const experienceOptions = useMemo(() => {
const arr = [{
content: '重新提交代码',
value: 1,
}]
if (versionData.auditInfo?.status !== 2) {
arr.push( {
content: '提交审核',
value: 2,
})
}
return arr
}, [versionData])
useEffect(() => {
if (!searchParams.get('appId')) {
return
}
getVersion()
getTemplateList()
}, [])
const onClickOnlineOptions = async () => {
const resp = await request({
request: {
url: `${rollbackReleaseRequest.url}?appid=${appId}`,
method: rollbackReleaseRequest.method
}
})
if (resp.code === 0) {
MessagePlugin.success('版本回退成功')
getVersion()
}
}
// 这个组件这里的interface定义的不好
const onClickAuditOptions = async (option: any) => {
const { value } = option
switch (value) {
case 1: {
// 提交审核
window.location.href = `#${routes.submitAudit.path}?appId=${appId}`
break
}
// 加急审核
case 2: {
const resp = await request({
request: {
url: `${speedUpAuditRequest.url}?appid=${appId}`,
method: speedUpAuditRequest.method
},
})
if (resp.code === 0) {
MessagePlugin.success('加急审核成功')
getVersion()
}
break
}
// 撤回审核
case 3: {
const resp = await request({
request: {
url: `${revokeAuditRequest.url}?appid=${appId}`,
method: revokeAuditRequest.method
},
})
if (resp.code === 0) {
MessagePlugin.success('撤回审核成功')
getVersion()
}
break
}
// 提交发布
case 4: {
const resp = await request({
request: {
url: `${releaseCodeRequest.url}?appid=${appId}`,
method: releaseCodeRequest.method
},
})
if (resp.code === 0) {
MessagePlugin.success('提交发布成功')
getVersion()
}
break
}
}
}
// 这个组件这里的interface定义的不好
const onClickExpOptions = (option: any) => {
const { value } = option
switch (value) {
case 1: {
// 重新提交代码
setVisibleSubmitModal(true)
break
}
case 2: {
// 提交审核
window.location.href = `#${routes.submitAudit.path}?appId=${appId}`
break
}
}
}
const getVersion = async () => {
setLoading(true)
const resp = await request({
request: getDevVersionRequest,
data: {
appid: appId,
}
})
if (resp.code === 0) {
setVersionData(resp.data)
}
setLoading(false)
}
const getTemplateList = async () => {
const resp = await request({
request: getTemplateListRequest,
data: {
templateType: 0
}
})
if (resp.code === 0) {
setTemplateList(resp.data.templateList)
}
}
const closeSubmitModal = () => {
formRef.current.reset()
setVisibleSubmitModal(false)
}
const submitCode = async (e: { validateResult: any }) => {
if (e.validateResult !== true) {
return
}
const { templateId, extJson, userVersion, userDesc } = formRef.current.getAllFieldsValue()
const resp = await request({
request: {
url: `${commitCodeRequest.url}?appid=${appId}`,
method: commitCodeRequest.method
},
data: {
templateId: String(templateId),
extJson,
userVersion,
userDesc
}
})
if (resp.code === 0) {
MessagePlugin.success('提交发布成功')
getVersion()
closeSubmitModal()
}
}
return (
<div>
<p className="text">线上版本</p>
<div className={styles.line} />
{
versionData.releaseInfo
?
<div style={{display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between'}}>
<div>
<div style={{display: 'flex'}}>
<div style={{
display: 'flex',
flexDirection: 'column',
width: '60px',
marginRight: '16px'
}}>
<p className="desc">版本号</p>
<p style={{fontSize: '16px'}}>{versionData.releaseInfo.releaseVersion}</p>
</div>
<div style={{display: 'flex', flexDirection: 'column'}}>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>发布时间</p>
<p>{moment(versionData.releaseInfo.releaseTime).format('YYYY-MM-DD HH:mm:ss')}</p>
</div>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>版本描述</p>
<p>{versionData.releaseInfo.releaseDesc}</p>
</div>
</div>
</div>
{
versionData.releaseInfo.releaseQrCode
&&
<div style={{width: '370px', textAlign: 'center'}}>
<img style={{width: '200px', height: '200px'}}
src={`data:image/png;base64,${versionData.releaseInfo.releaseQrCode}`}
alt="" />
</div>
}
</div>
<Dropdown options={onlineOptions} onClick={onClickOnlineOptions}>
<Button style={{marginTop: '20px', paddingRight: '10px', marginRight: '40px'}}
theme="primary">操作<Icon
style={{marginLeft: '3px'}} name="chevron-down" size="16" /></Button>
</Dropdown>
</div>
:
<Loading size="small" loading={loading} showOverlay>
<div className="desc" style={{textAlign: 'center', margin: '100px 0'}}>
尚未提交线上版本
</div>
</Loading>
}
<div className="normal_flex">
<p className="text" style={{marginTop: '30px'}}>审核版本</p>
{
versionData.auditInfo
&&
<div style={{margin: '30px 10px 18px 10px'}}>
{versionData.auditInfo.status === 0 && <Tag theme="success">审核通过</Tag>}
{versionData.auditInfo.status === 1 && <Tag theme="danger">审核不通过</Tag>}
{versionData.auditInfo.status === 2 && <Tag theme="warning">审核中</Tag>}
{versionData.auditInfo.status === 3 && <Tag theme="primary">已撤回</Tag>}
{versionData.auditInfo.status === 4 && <Tag theme="warning">审核延后</Tag>}
</div>
}
</div>
<div className={styles.line} />
{
versionData.auditInfo
?
<div style={{display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between'}}>
<div>
<div style={{display: 'flex'}}>
<div style={{
display: 'flex',
flexDirection: 'column',
width: '60px',
marginRight: '16px'
}}>
<p className="desc">版本号</p>
<p style={{fontSize: '16px'}}>{versionData.auditInfo.userVersion}</p>
</div>
<div style={{display: 'flex', flexDirection: 'column'}}>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>审核ID</p>
<p>{versionData.auditInfo.auditId}</p>
</div>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>提交时间</p>
<p>{moment(versionData.auditInfo.submitAuditTime).format('YYYY-MM-DD HH:mm:ss')}</p>
</div>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>版本描述</p>
<p>{versionData.auditInfo.userDesc}</p>
</div>
{
versionData.auditInfo.status === 1
&&
<Alert theme="error" icon={<span />} maxLine={0} message={`【驳回原因】:${versionData.auditInfo.reason}`} style={{ marginBottom: '10px' }} />
}
</div>
</div>
</div>
<Dropdown options={auditOptions} onClick={onClickAuditOptions}>
<Button style={{marginTop: '20px', paddingRight: '10px', marginRight: '40px'}}
theme="primary">操作<Icon
style={{marginLeft: '3px'}} name="chevron-down" size="16" /></Button>
</Dropdown>
</div>
:
<Loading size="small" loading={loading} showOverlay>
<div className="desc" style={{textAlign: 'center', margin: '100px 0'}}>
暂无提交审核的版本或者版本已发布上线
</div>
</Loading>
}
<p className="text" style={{marginTop: '30px'}}>体验版本</p>
<div className={styles.line} />
{
versionData.expInfo
?
<div style={{display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between'}}>
<div>
<div style={{display: 'flex'}}>
<div style={{
display: 'flex',
flexDirection: 'column',
width: '60px',
marginRight: '16px'
}}>
<p className="desc">版本号</p>
<p style={{fontSize: '16px'}}>{versionData.expInfo.expVersion}</p>
</div>
<div style={{display: 'flex', flexDirection: 'column'}}>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>提交时间</p>
<p>{moment(versionData.expInfo.expTime).format('YYYY-MM-DD HH:mm:ss')}</p>
</div>
<div className="normal_flex">
<p className="desc" style={{width: '74px'}}>版本描述</p>
<p>{versionData.expInfo.expDesc}</p>
</div>
</div>
</div>
<div style={{width: '370px', textAlign: 'center'}}>
<img style={{width: '200px', height: '200px'}}
src={`data:image/png;base64,${versionData.expInfo.expQrCode}`}
alt="" />
</div>
</div>
<Dropdown options={experienceOptions} onClick={onClickExpOptions}>
<Button style={{marginTop: '20px', paddingRight: '10px', marginRight: '40px'}}
theme="primary">操作<Icon
style={{marginLeft: '3px'}} name="chevron-down" size="16" /></Button>
</Dropdown>
</div>
:
<Loading size="small" loading={loading} showOverlay>
<div style={{textAlign: 'center', margin: '100px 0'}}>
<p className="desc">尚未提交体验版</p>
<Button onClick={() => setVisibleSubmitModal(true)}>提交代码</Button>
</div>
</Loading>
}
<Dialog visible={visibleSubmitModal} onClose={closeSubmitModal} confirmBtn={null} width={700}
cancelBtn={null} header="提交代码">
<Form ref={formRef} onSubmit={submitCode} labelWidth={200}>
<FormItem name="templateId" label="模板ID(template_id)"
help="第三方平台小程序模板库的模板id。需从开发者工具上传代码到第三方平台草稿箱,然后从草稿箱添加到模板库。当前仅支持普通模板,尚未支持标准模板" rules={[{
required: true,
message: '模板id必选',
type: 'error'
}]}>
<Select style={{width: '300px'}} popupProps={{overlayStyle: {width: '350px'}}}>
{/*这个组件极其奇怪,不能静态和动态的混用,会直接白屏,必须一起返回*/}
{
[<Option label={'123'} value={0} disabled key={`template_-1`}>
<div className="normal_flex">
<p style={{width: '80px', margin: 0}}>模板ID</p>
<p style={{width: '80px', margin: 0}}>版本号</p>
<p style={{flex: 1, margin: 0}}>模板描述</p>
</div>
</Option>].concat(templateList.map(i => {
return (
<Option key={`template_${i.templateId}`} value={i.templateId} label={`ID:${i.templateId}`}>
<div className="normal_flex">
<p style={{width: '80px', margin: 0}}>{i.templateId}</p>
<p style={{width: '80px', margin: 0}}>{i.userVersion}</p>
<p style={{flex: 1, margin: 0}}>{truncate(i.userDesc, {length: 10})}</p>
</div>
</Option>
)
}))
}
</Select>
</FormItem>
<FormItem name="extJson" style={{marginBottom: 0}} label="ext.json配置(ext_json)" rules={[{
required: true,
message: 'extJson必填',
type: 'error'
}]}>
<Textarea style={{width: '300px'}} />
</FormItem>
<div className="t-form__controls" style={{marginLeft: '200px'}}>
<div className="t-form__help">用于控制ext.json配置文件的内容的参数 <a className="a" href="https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/commit.html" target="_blank">提交代码api说明</a></div>
</div>
<FormItem name="userVersion" label="代码版本号(user_version)" help="代码版本号,开发者可自定义(长度不超过64个字符)" rules={[{
required: true,
message: 'userVersion必填',
type: 'error'
}]}>
<Input style={{width: '300px'}} />
</FormItem>
<FormItem name="userDesc" label="版本描述(user_desc)" help="代码版本描述,开发者可自定义" rules={[{
required: true,
message: 'userDesc必填',
type: 'error'
}]}>
<Input style={{width: '300px'}} />
</FormItem>
<FormItem statusIcon={false}>
<Button theme="primary" type="submit" style={{marginRight: 10}}>
提交
</Button>
<Button onClick={closeSubmitModal}>取消</Button>
</FormItem>
</Form>
</Dialog>
{/*<Drawer visible={visibleDrawer} onClose={() => setVisibleDrawer(false)} confirmBtn={<span />}*/}
{/* cancelBtn={<span />} destroyOnClose={true} size="medium" header={"查看驳回原因"}>*/}
{/* <div className="normal_flex">*/}
{/* <p style={{width: '160px'}}>驳回时间</p>*/}
{/* <p>驳回原因</p>*/}
{/* </div>*/}
{/* <div className={styles.line} />*/}
{/* <div className="normal_flex" style={{flexWrap: 'nowrap'}}>*/}
{/* <p style={{width: '160px'}}>2022-03-10 15:12:56</p>*/}
{/* <p style={{flex: 1}}>驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因驳回原因</p>*/}
{/* </div>*/}
{/*</Drawer>*/}
</div>
)
} | the_stack |
namespace ts.pxtc {
enum TokenKind {
None,
Whitespace,
Identifier,
Keyword,
Operator,
CommentLine,
CommentBlock,
NewLine,
Literal,
Tree, // nested list of tokens; synKind stays what it was
Block, // Trees with synKind == OpenBraceToken get turned into Blocks
EOF
}
let inputForMsg = ""
interface Stmt {
tokens: Token[];
}
interface Token {
kind: TokenKind;
text: string;
pos: number;
lineNo: number;
synKind: ts.SyntaxKind;
blockSpanLength?: number;
blockSpanIsVirtual?: boolean;
isPrefix?: boolean;
isCursor?: boolean;
}
interface TreeToken extends Token {
children: Token[];
endToken: Token; // if it has proper ending token, this is the text of it
}
interface BlockToken extends Token {
stmts: Stmt[]; // for Block
endToken: Token; // if it has proper ending token, this is the text of it
}
function lookupKind(k: ts.SyntaxKind) {
for (let o of Object.keys(ts.SyntaxKind)) {
if ((<any>ts).SyntaxKind[o] === k)
return o;
}
return "?"
}
let SK = ts.SyntaxKind;
function showMsg(t: Token, msg: string) {
let pos = t.pos
let ctx = inputForMsg.slice(pos - 20, pos) + "<*>" + inputForMsg.slice(pos, pos + 20)
console.log(ctx.replace(/\n/g, "<NL>"), ": L ", t.lineNo, msg)
}
function infixOperatorPrecedence(kind: ts.SyntaxKind) {
switch (kind) {
case SK.CommaToken:
return 2;
case SK.EqualsToken:
case SK.PlusEqualsToken:
case SK.MinusEqualsToken:
case SK.AsteriskEqualsToken:
case SK.AsteriskAsteriskEqualsToken:
case SK.SlashEqualsToken:
case SK.PercentEqualsToken:
case SK.LessThanLessThanEqualsToken:
case SK.GreaterThanGreaterThanEqualsToken:
case SK.GreaterThanGreaterThanGreaterThanEqualsToken:
case SK.AmpersandEqualsToken:
case SK.BarEqualsToken:
case SK.CaretEqualsToken:
return 5;
case SK.QuestionToken:
case SK.ColonToken:
return 7; // ternary operator
case SK.BarBarToken:
return 10;
case SK.AmpersandAmpersandToken:
return 20;
case SK.BarToken:
return 30;
case SK.CaretToken:
return 40;
case SK.AmpersandToken:
return 50;
case SK.EqualsEqualsToken:
case SK.ExclamationEqualsToken:
case SK.EqualsEqualsEqualsToken:
case SK.ExclamationEqualsEqualsToken:
return 60;
case SK.LessThanToken:
case SK.GreaterThanToken:
case SK.LessThanEqualsToken:
case SK.GreaterThanEqualsToken:
case SK.InstanceOfKeyword:
case SK.InKeyword:
case SK.AsKeyword:
return 70;
case SK.LessThanLessThanToken:
case SK.GreaterThanGreaterThanToken:
case SK.GreaterThanGreaterThanGreaterThanToken:
return 80;
case SK.PlusToken:
case SK.MinusToken:
return 90;
case SK.AsteriskToken:
case SK.SlashToken:
case SK.PercentToken:
return 100;
case SK.AsteriskAsteriskToken:
return 101;
case SK.DotToken:
return 120;
default:
return 0;
}
}
function getTokKind(kind: ts.SyntaxKind) {
switch (kind) {
case SK.EndOfFileToken:
return TokenKind.EOF;
case SK.SingleLineCommentTrivia:
return TokenKind.CommentLine;
case SK.MultiLineCommentTrivia:
return TokenKind.CommentBlock;
case SK.NewLineTrivia:
return TokenKind.NewLine;
case SK.WhitespaceTrivia:
return TokenKind.Whitespace;
case SK.ShebangTrivia:
case SK.ConflictMarkerTrivia:
return TokenKind.CommentBlock;
case SK.NumericLiteral:
case SK.StringLiteral:
case SK.RegularExpressionLiteral:
case SK.NoSubstitutionTemplateLiteral:
case SK.TemplateHead:
case SK.TemplateMiddle:
case SK.TemplateTail:
return TokenKind.Literal;
case SK.Identifier:
return TokenKind.Identifier;
default:
if (kind < SK.Identifier)
return TokenKind.Operator;
return TokenKind.Keyword;
}
}
let brokenRegExps = false;
function tokenize(input: string) {
inputForMsg = input
let scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, input, msg => {
let pos = scanner.getTextPos()
console.log("scanner error", pos, msg.message)
})
let tokens: Token[] = []
let braceBalance = 0
let templateLevel = -1;
while (true) {
let kind = scanner.scan()
if (kind == SK.CloseBraceToken && braceBalance == templateLevel) {
templateLevel = -1;
kind = scanner.reScanTemplateToken()
}
if (brokenRegExps && kind == SK.SlashToken || kind == SK.SlashEqualsToken) {
let tmp = scanner.reScanSlashToken()
if (tmp == SK.RegularExpressionLiteral)
kind = tmp;
}
if (kind == SK.GreaterThanToken) {
kind = scanner.reScanGreaterToken()
}
let tok: Token = {
kind: getTokKind(kind),
synKind: kind,
lineNo: 0,
pos: scanner.getTokenPos(),
text: scanner.getTokenText(),
}
if (kind == SK.OpenBraceToken)
braceBalance++;
if (kind == SK.CloseBraceToken) {
if (--braceBalance < 0)
braceBalance = -10000000;
}
tokens.push(tok)
if (kind == SK.TemplateHead || kind == SK.TemplateMiddle) {
templateLevel = braceBalance;
}
if (tok.kind == TokenKind.EOF)
break;
}
// Util.assert(tokens.map(t => t.text).join("") == input)
return { tokens, braceBalance }
}
function skipWhitespace(tokens: Token[], i: number) {
while (tokens[i] && tokens[i].kind == TokenKind.Whitespace)
i++;
return i;
}
// We do not want empty lines in the source to get lost - they serve as a sort of comment dividing parts of code
// We turn them into empty comments here
function emptyLinesToComments(tokens: Token[], cursorPos: number) {
let output: Token[] = []
let atLineBeg = true
let lineNo = 1;
for (let i = 0; i < tokens.length; ++i) {
if (atLineBeg) {
let bkp = i
i = skipWhitespace(tokens, i)
if (tokens[i].kind == TokenKind.NewLine) {
let isCursor = false
if (cursorPos >= 0 && tokens[i].pos >= cursorPos) {
cursorPos = -1;
isCursor = true
}
output.push({
text: "",
kind: TokenKind.CommentLine,
pos: tokens[i].pos,
lineNo,
synKind: SK.SingleLineCommentTrivia,
isCursor: isCursor
})
} else {
i = bkp
}
}
output.push(tokens[i])
tokens[i].lineNo = lineNo
if (tokens[i].kind == TokenKind.NewLine) {
atLineBeg = true
lineNo++;
} else {
atLineBeg = false
}
if (cursorPos >= 0 && tokens[i].pos >= cursorPos) {
cursorPos = -1;
}
}
return output
}
// Add Tree tokens where needed
function matchBraces(tokens: Token[]) {
let braceStack: {
synKind: ts.SyntaxKind;
token: TreeToken;
}[] = []
let braceTop = () => braceStack[braceStack.length - 1]
braceStack.push({
synKind: SK.EndOfFileToken,
token: {
children: [],
} as any,
})
let pushClose = (tok: Token, synKind: ts.SyntaxKind) => {
let token = tok as TreeToken
token.children = []
token.kind = TokenKind.Tree
braceStack.push({ synKind, token })
}
for (let i = 0; i < tokens.length; ++i) {
let token = tokens[i]
let top = braceStack[braceStack.length - 1]
top.token.children.push(token)
switch (token.kind) {
case TokenKind.Operator:
switch (token.synKind) {
case SK.OpenBraceToken:
case SK.OpenParenToken:
case SK.OpenBracketToken:
pushClose(token, token.synKind + 1);
break;
case SK.CloseBraceToken:
case SK.CloseParenToken:
case SK.CloseBracketToken:
top.token.children.pop();
while (true) {
top = braceStack.pop()
if (top.synKind == token.synKind) {
top.token.endToken = token;
break;
}
// don't go past brace with other closing parens
if (braceStack.length == 0 || top.synKind == SK.CloseBraceToken) {
braceStack.push(top);
break;
}
}
break;
default:
break;
}
break;
}
}
return braceStack[0].token.children
}
function mkEOF(): Token {
return {
kind: TokenKind.EOF,
synKind: SK.EndOfFileToken,
pos: 0,
lineNo: 0,
text: ""
}
}
function mkSpace(t: Token, s: string): Token {
return {
kind: TokenKind.Whitespace,
synKind: SK.WhitespaceTrivia,
pos: t.pos - s.length,
lineNo: t.lineNo,
text: s
}
}
function mkNewLine(t: Token): Token {
return {
kind: TokenKind.NewLine,
synKind: SK.NewLineTrivia,
pos: t.pos,
lineNo: t.lineNo,
text: "\n"
}
}
function mkBlock(toks: Token[]): BlockToken {
return {
kind: TokenKind.Block,
synKind: SK.OpenBraceToken,
pos: toks[0].pos,
lineNo: toks[0].lineNo,
stmts: [{ tokens: toks }],
text: "{",
endToken: null
}
}
function mkVirtualTree(toks: Token[]): TreeToken {
return {
kind: TokenKind.Tree,
synKind: SK.WhitespaceTrivia,
pos: toks[0].pos,
lineNo: toks[0].lineNo,
children: toks,
endToken: null,
text: ""
}
}
function isExprEnd(t: Token) {
if (!t) return false;
switch (t.synKind) {
case SK.IfKeyword:
case SK.ElseKeyword:
case SK.LetKeyword:
case SK.ConstKeyword:
case SK.VarKeyword:
case SK.DoKeyword:
case SK.WhileKeyword:
case SK.SwitchKeyword:
case SK.CaseKeyword:
case SK.DefaultKeyword:
case SK.ForKeyword:
case SK.ReturnKeyword:
case SK.BreakKeyword:
case SK.ContinueKeyword:
case SK.TryKeyword:
case SK.CatchKeyword:
case SK.FinallyKeyword:
case SK.DeleteKeyword:
case SK.FunctionKeyword:
case SK.ClassKeyword:
case SK.YieldKeyword:
case SK.DebuggerKeyword:
return true;
default:
return false;
}
}
function delimitStmts(tokens: Token[], inStmtCtx: boolean, ctxToken: Token = null): Stmt[] {
let res: Stmt[] = []
let i = 0;
let currCtxToken: Token;
let didBlock = false;
tokens = tokens.concat([mkEOF()])
while (tokens[i].kind != TokenKind.EOF) {
let stmtBeg = i
skipToStmtEnd();
Util.assert(i > stmtBeg, `Error at ${tokens[i].text}`)
addStatement(tokens.slice(stmtBeg, i))
}
return res
function addStatement(tokens: Token[]) {
if (inStmtCtx)
tokens = trimWhitespace(tokens)
if (tokens.length == 0) return
tokens.forEach(delimitIn)
tokens = injectBlocks(tokens)
let merge = false
if (inStmtCtx && res.length > 0) {
let prev = res[res.length - 1]
let prevKind = prev.tokens[0].synKind
let thisKind = tokens[0].synKind
if ((prevKind == SK.IfKeyword && thisKind == SK.ElseKeyword) ||
(prevKind == SK.TryKeyword && thisKind == SK.CatchKeyword) ||
(prevKind == SK.TryKeyword && thisKind == SK.FinallyKeyword) ||
(prevKind == SK.CatchKeyword && thisKind == SK.FinallyKeyword)
) {
tokens.unshift(mkSpace(tokens[0], " "))
Util.pushRange(res[res.length - 1].tokens, tokens)
return;
}
}
res.push({
tokens: tokens
})
}
function injectBlocks(tokens: Token[]) {
let output: Token[] = []
let i = 0;
while (i < tokens.length) {
if (tokens[i].blockSpanLength) {
let inner = tokens.slice(i, i + tokens[i].blockSpanLength)
let isVirtual = !!inner[0].blockSpanIsVirtual
delete inner[0].blockSpanLength
delete inner[0].blockSpanIsVirtual
i += inner.length
inner = injectBlocks(inner)
if (isVirtual) {
output.push(mkVirtualTree(inner))
} else {
output.push(mkSpace(inner[0], " "))
output.push(mkBlock(trimWhitespace(inner)))
}
} else {
output.push(tokens[i++])
}
}
return output
}
function delimitIn(t: Token) {
if (t.kind == TokenKind.Tree) {
let tree = t as TreeToken
tree.children = Util.concat(delimitStmts(tree.children, false, tree).map(s => s.tokens))
}
}
function nextNonWs(stopOnNewLine = false) {
while (true) {
i++;
switch (tokens[i].kind) {
case TokenKind.Whitespace:
case TokenKind.CommentBlock:
case TokenKind.CommentLine:
break;
case TokenKind.NewLine:
if (stopOnNewLine) break;
break;
default:
return;
}
}
}
function skipOptionalNewLine() {
while (tokens[i].kind == TokenKind.Whitespace) { i++; }
if (tokens[i].kind == TokenKind.NewLine) i++;
}
function skipUntilBlock() {
while (true) {
i++;
switch (tokens[i].kind) {
case TokenKind.EOF:
return;
case TokenKind.Tree:
if (tokens[i].synKind == SK.OpenBraceToken) {
i--;
expectBlock();
return;
}
break;
}
}
}
function handleBlock() {
Util.assert(tokens[i].synKind == SK.OpenBraceToken)
let tree = tokens[i] as TreeToken
Util.assert(tree.kind == TokenKind.Tree)
let blk = tokens[i] as BlockToken
blk.stmts = delimitStmts(tree.children, true, currCtxToken)
delete tree.children
blk.kind = TokenKind.Block
i++;
didBlock = true
}
function expectBlock() {
let begIdx = i + 1
nextNonWs()
if (tokens[i].synKind == SK.OpenBraceToken) {
handleBlock()
skipOptionalNewLine();
} else {
skipToStmtEnd();
tokens[begIdx].blockSpanLength = i - begIdx
}
}
function skipToStmtEnd() {
while (true) {
let t = tokens[i]
let bkp = i
currCtxToken = t
didBlock = false
if (t.kind == TokenKind.EOF)
return;
if (inStmtCtx && t.synKind == SK.SemicolonToken) {
i++;
skipOptionalNewLine();
return;
}
if (t.synKind == SK.EqualsGreaterThanToken) {
nextNonWs()
if (tokens[i].synKind == SK.OpenBraceToken) {
handleBlock();
continue;
} else {
let begIdx = i
skipToStmtEnd()
let j = i
while (tokens[j].kind == TokenKind.NewLine)
j--;
tokens[begIdx].blockSpanLength = j - begIdx
tokens[begIdx].blockSpanIsVirtual = true
return
}
}
if (inStmtCtx && infixOperatorPrecedence(t.synKind)) {
let begIdx = i
// an infix operator at the end of the line prevents the newline from ending the statement
nextNonWs()
if (isExprEnd(tokens[i])) {
// unless next line starts with something statement-like
i = begIdx
} else {
continue;
}
}
if (inStmtCtx && t.kind == TokenKind.NewLine) {
nextNonWs();
t = tokens[i]
// if we get a infix operator other than +/- after newline, it's a continuation
if (infixOperatorPrecedence(t.synKind) && t.synKind != SK.PlusToken && t.synKind != SK.MinusToken) {
continue;
} else {
i = bkp + 1
return;
}
}
if (t.synKind == SK.OpenBraceToken && ctxToken && ctxToken.synKind == SK.ClassKeyword) {
let jj = i - 1;
while (jj >= 0 && tokens[jj].kind == TokenKind.Whitespace)
jj--;
if (jj < 0 || tokens[jj].synKind != SK.EqualsToken) {
i--;
expectBlock(); // method body
return;
}
}
Util.assert(bkp == i)
switch (t.synKind) {
case SK.ForKeyword:
case SK.WhileKeyword:
case SK.IfKeyword:
case SK.CatchKeyword:
nextNonWs();
if (tokens[i].synKind == SK.OpenParenToken) {
expectBlock();
} else {
continue; // just continue until new line
}
return;
case SK.DoKeyword:
expectBlock();
i--;
nextNonWs();
if (tokens[i].synKind == SK.WhileKeyword) {
i++;
continue;
} else {
return;
}
case SK.ElseKeyword:
nextNonWs();
if (tokens[i].synKind == SK.IfKeyword) {
continue; // 'else if' - keep scanning
} else {
i = bkp;
expectBlock();
return;
}
case SK.TryKeyword:
case SK.FinallyKeyword:
expectBlock();
return;
case SK.ClassKeyword:
case SK.NamespaceKeyword:
case SK.ModuleKeyword:
case SK.InterfaceKeyword:
case SK.FunctionKeyword:
skipUntilBlock();
return;
}
Util.assert(!didBlock, "forgot continue/return after expectBlock")
i++;
}
}
}
function isWhitespaceOrNewLine(tok: Token) {
return tok && (tok.kind == TokenKind.Whitespace || tok.kind == TokenKind.NewLine)
}
function removeIndent(tokens: Token[]) {
let output: Token[] = []
let atLineBeg = false;
for (let i = 0; i < tokens.length; ++i) {
if (atLineBeg)
i = skipWhitespace(tokens, i)
if (tokens[i]) {
output.push(tokens[i])
atLineBeg = tokens[i].kind == TokenKind.NewLine
}
}
return output
}
function trimWhitespace(toks: Token[]) {
toks = toks.slice(0)
while (isWhitespaceOrNewLine(toks[0]))
toks.shift()
while (isWhitespaceOrNewLine(toks[toks.length - 1]))
toks.pop()
return toks
}
function normalizeSpace(tokens: Token[]) {
let output: Token[] = []
let i = 0
let lastNonTrivialToken = mkEOF()
tokens = tokens.concat([mkEOF()])
while (i < tokens.length) {
i = skipWhitespace(tokens, i)
let token = tokens[i]
if (token.kind == TokenKind.EOF)
break;
let j = skipWhitespace(tokens, i + 1)
if (token.kind == TokenKind.NewLine && tokens[j].synKind == SK.OpenBraceToken) {
i = j // skip NL
continue
}
let needsSpace = true
let last = output.length == 0 ? mkNewLine(token) : output[output.length - 1]
switch (last.synKind) {
case SK.ExclamationToken:
case SK.TildeToken:
case SK.DotToken:
needsSpace = false
break
case SK.PlusToken:
case SK.MinusToken:
case SK.PlusPlusToken:
case SK.MinusMinusToken:
if (last.isPrefix)
needsSpace = false
break;
}
switch (token.synKind) {
case SK.DotToken:
case SK.CommaToken:
case SK.NewLineTrivia:
case SK.ColonToken:
case SK.SemicolonToken:
case SK.OpenBracketToken:
needsSpace = false
break;
case SK.PlusPlusToken:
case SK.MinusMinusToken:
if (last.kind == TokenKind.Tree || last.kind == TokenKind.Identifier || last.kind == TokenKind.Keyword)
needsSpace = false
/* fall through */
case SK.PlusToken:
case SK.MinusToken:
if (lastNonTrivialToken.kind == TokenKind.EOF ||
infixOperatorPrecedence(lastNonTrivialToken.synKind) ||
lastNonTrivialToken.synKind == SK.SemicolonToken)
token.isPrefix = true
break;
case SK.OpenParenToken:
if (last.kind == TokenKind.Identifier)
needsSpace = false
if (last.kind == TokenKind.Keyword)
switch (last.synKind) {
case SK.IfKeyword:
case SK.ForKeyword:
case SK.WhileKeyword:
case SK.SwitchKeyword:
case SK.ReturnKeyword:
case SK.ThrowKeyword:
case SK.CatchKeyword:
break;
default:
needsSpace = false
}
break;
}
if (last.kind == TokenKind.NewLine)
needsSpace = false
if (needsSpace)
output.push(mkSpace(token, " "))
output.push(token)
if (token.kind != TokenKind.NewLine)
lastNonTrivialToken = token
i++
}
return output
}
function finalFormat(ind: string, token: Token) {
if (token.synKind == SK.NoSubstitutionTemplateLiteral &&
/^`[\s\.#01]*`$/.test(token.text)) {
let lines = token.text.slice(1, token.text.length - 1).split("\n").map(l => l.replace(/\s/g, "")).filter(l => !!l)
if (lines.length < 4 || lines.length > 5) return;
let numFrames = Math.floor((Math.max(...lines.map(l => l.length)) + 2) / 5)
if (numFrames <= 0) numFrames = 1
let out = "`\n"
for (let i = 0; i < 5; ++i) {
let l = lines[i] || ""
while (l.length < numFrames * 5)
l += "."
l = l.replace(/0/g, ".")
l = l.replace(/1/g, "#")
l = l.replace(/...../g, m => "/" + m)
out += ind + l.replace(/./g, m => " " + m).replace(/\//g, " ").slice(3) + "\n"
}
out += ind + "`"
token.text = out
}
}
export function toStr(v: any): string {
if (Array.isArray(v)) return "[[ " + v.map(toStr).join(" ") + " ]]"
if (typeof v.text == "string")
return JSON.stringify(v.text)
return v + ""
}
export function format(input: string, pos: number) {
let r = tokenize(input)
//if (r.braceBalance != 0) return null
let topTokens = r.tokens
topTokens = emptyLinesToComments(topTokens, pos)
topTokens = matchBraces(topTokens)
let topStmts = delimitStmts(topTokens, true)
let ind = ""
let output = ""
let outpos = -1
let indIncrLine = 0
topStmts.forEach(ppStmt)
topStmts.forEach(s => s.tokens.forEach(findNonBlocks))
if (outpos == -1)
outpos = output.length
return {
formatted: output,
pos: outpos
}
function findNonBlocks(t: Token) {
if (t.kind == TokenKind.Tree) {
let tree = t as TreeToken
if (t.synKind == SK.OpenBraceToken) {
//showMsg(t, "left behind X")
}
tree.children.forEach(findNonBlocks)
} else if (t.kind == TokenKind.Block) {
(t as BlockToken).stmts.forEach(s => s.tokens.forEach(findNonBlocks))
}
}
function incrIndent(parToken: Token, f: () => void) {
if (indIncrLine == parToken.lineNo) {
f()
} else {
indIncrLine = parToken.lineNo
let prev = ind
ind += " "
f()
ind = prev
}
}
function ppStmt(s: Stmt) {
let toks = removeIndent(s.tokens)
if (toks.length == 1 && !toks[0].isCursor && toks[0].text == "") {
output += "\n"
return
}
output += ind
incrIndent(toks[0], () => {
ppToks(toks)
})
if (output[output.length - 1] != "\n")
output += "\n"
}
function writeToken(t: Token) {
if (outpos == -1 && t.pos + t.text.length >= pos) {
outpos = output.length + (pos - t.pos);
}
output += t.text;
}
function ppToks(tokens: Token[]) {
tokens = normalizeSpace(tokens)
for (let i = 0; i < tokens.length; ++i) {
let t = tokens[i]
finalFormat(ind, t)
writeToken(t)
switch (t.kind) {
case TokenKind.Tree:
let tree = t as TreeToken
incrIndent(t, () => {
ppToks(removeIndent(tree.children))
})
if (tree.endToken) {
writeToken(tree.endToken)
}
break;
case TokenKind.Block:
let blk = t as BlockToken;
if (blk.stmts.length == 0) {
output += " "
} else {
output += "\n"
blk.stmts.forEach(ppStmt)
output += ind.slice(4)
}
if (blk.endToken)
writeToken(blk.endToken)
else
output += "}"
break;
case TokenKind.NewLine:
if (tokens[i + 1] && tokens[i + 1].kind == TokenKind.CommentLine &&
tokens[i + 1].text == "" && !tokens[i + 1].isCursor)
break; // no indent for empty line
if (i == tokens.length - 1)
output += ind.slice(4)
else
output += ind
break;
case TokenKind.Whitespace:
break;
}
}
}
}
} | the_stack |
export = Paho.MQTT;
declare global {
/**
* Send and receive messages using web browsers.
* <p>
* This programming interface lets a JavaScript client application use the MQTT V3.1 or
* V3.1.1 protocol to connect to an MQTT-supporting messaging server.
*
* The function supported includes:
* <ol>
* <li>Connecting to and disconnecting from a server. The server is identified by its host name and port number.
* <li>Specifying options that relate to the communications link with the server,
* for example the frequency of keep-alive heartbeats, and whether SSL/TLS is required.
* <li>Subscribing to and receiving messages from MQTT Topics.
* <li>Publishing messages to MQTT Topics.
* </ol>
* <p>
* The API consists of two main objects:
* <dl>
* <dt><b>{@link Paho.MQTT.Client}</b></dt>
* <dd>This contains methods that provide the functionality of the API,
* including provision of callbacks that notify the application when a message
* arrives from or is delivered to the messaging server,
* or when the status of its connection to the messaging server changes.</dd>
* <dt><b>{@link Paho.MQTT.Message}</b></dt>
* <dd>This encapsulates the payload of the message along with various attributes
* associated with its delivery, in particular the destination to which it has
* been (or is about to be) sent.</dd>
* </dl>
* <p>
* The programming interface validates parameters passed to it, and will throw
* an Error containing an error message intended for developer use, if it detects
* an error with any parameter.
* <p>
*/
namespace Paho.MQTT {
/**
* The Quality of Service used to deliver a message.
* <dl>
* <dt>0 Best effort (default).</dt>
* <dt>1 At least once.</dt>
* <dt>2 Exactly once.</dt>
* </dl>
*/
type Qos = 0 | 1 | 2;
interface MQTTError {
/** A number indicating the nature of the error. */
errorCode: number;
/** Text describing the error */
errorMessage: string;
}
interface WithInvocationContext {
/**
* <code>invocationContext</code> as passed in with the corresponding field in the connectOptions or
* subscribeOptions.
*/
invocationContext: any;
}
interface ErrorWithInvocationContext extends MQTTError, WithInvocationContext {
}
interface OnSubscribeSuccessParams extends WithInvocationContext {
grantedQos: Qos;
}
/**
* Called when the connect acknowledgement has been received from the server.
* @param o
* A single response object parameter is passed to the onSuccess callback containing the following fields:
* <li><code>invocationContext</code> as passed in with the corresponding field in the connectOptions.
*/
type OnSuccessCallback = (o: WithInvocationContext) => void;
/**
* Called when the subscribe acknowledgement has been received from the server.
* @param o
* A single response object parameter is passed to the onSuccess callback containing the following fields:
* <li><code>invocationContext</code> as passed in with the corresponding field in the connectOptions.
*/
type OnSubscribeSuccessCallback = (o: OnSubscribeSuccessParams) => void;
/**
* Called when the connect request has failed or timed out.
* @param e
* A single response object parameter is passed to the onFailure callback containing the following fields:
* <li><code>invocationContext</code> as passed in with the corresponding field in the connectOptions.
* <li><code>errorCode</code> a number indicating the nature of the error.
* <li><code>errorMessage</code> text describing the error.
*/
type OnFailureCallback = (e: ErrorWithInvocationContext) => void;
/**
* Called when a connection has been lost.
* @param error A single response object parameter is passed to the onConnectionLost callback containing the
* following fields:
* <li>errorCode
* <li>errorMessage
*/
type OnConnectionLostHandler = (error: MQTTError) => void;
/**
* Called when a message was delivered or has arrived.
* @param message The {@link Paho.MQTT.Message} that was delivered or has arrived.
*/
type OnMessageHandler = (message: Message) => void;
/**
* Attributes used with a connection.
*/
interface ConnectionOptions {
/**
* If the connect has not succeeded within this number of seconds, it is deemed to have failed.
* @default The default is 30 seconds.
*/
timeout?: number;
/** Authentication username for this connection. */
userName?: string;
/** Authentication password for this connection. */
password?: string;
/** Sent by the server when the client disconnects abnormally. */
willMessage?: Message;
/**
* The server disconnects this client if there is no activity for this number of seconds.
* @default The default value of 60 seconds is assumed if not set.
*/
keepAliveInterval?: number;
/**
* If true(default) the client and server persistent state is deleted on successful connect.
* @default true
*/
cleanSession?: boolean;
/** If present and true, use an SSL Websocket connection. */
useSSL?: boolean;
/** Passed to the onSuccess callback or onFailure callback. */
invocationContext?: any;
/**
* Called when the connect acknowledgement has been received from the server.
*/
onSuccess?: OnSuccessCallback;
/**
* Specifies the mqtt version to use when connecting
* <dl>
* <dt>3 - MQTT 3.1</dt>
* <dt>4 - MQTT 3.1.1 (default)</dt>
* </dl>
* @default 4
*/
mqttVersion?: 3 | 4;
/**
* Called when the connect request has failed or timed out.
*/
onFailure?: OnFailureCallback;
/**
* If present this contains either a set of hostnames or fully qualified
* WebSocket URIs (ws://example.com:1883/mqtt), that are tried in order in place of the host and port
* paramater on the construtor. The hosts are tried one at at time in order until one of then succeeds.
*/
hosts?: string[];
/**
* If present the set of ports matching the hosts. If hosts contains URIs, this property is not used.
*/
ports?: number[];
}
/**
* Used to control a subscription
*/
interface SubscribeOptions {
/** the maximum qos of any publications sent as a result of making this subscription. */
qos?: Qos;
/** passed to the onSuccess callback or onFailure callback. */
invocationContext?: any;
/** called when the subscribe acknowledgement has been received from the server. */
onSuccess?: OnSubscribeSuccessCallback;
/** called when the subscribe request has failed or timed out. */
onFailure?: OnFailureCallback;
/**
* timeout which, if present, determines the number of seconds after which the onFailure calback is called.
* The presence of a timeout does not prevent the onSuccess callback from being called when the subscribe
* completes.
*/
timeout?: number;
}
interface UnsubscribeOptions {
/** passed to the onSuccess callback or onFailure callback. */
invocationContext?: any;
/** called when the unsubscribe acknowledgement has been received from the server. */
onSuccess?: OnSuccessCallback;
/** called when the unsubscribe request has failed or timed out. */
onFailure?: OnFailureCallback;
/**
* timeout which, if present, determines the number of seconds after which the onFailure calback is called.
* The presence of a timeout does not prevent the onSuccess callback from being called when the unsubscribe
* completes.
*/
timeout?: number;
}
interface TraceElement {
severity: "Debug";
message: string;
}
type TraceFunction = (element: TraceElement) => void;
/**
* The JavaScript application communicates to the server using a {@link Paho.MQTT.Client} object.
*
* Most applications will create just one Client object and then call its connect() method,
* however applications can create more than one Client object if they wish.
* In this case the combination of host, port and clientId attributes must be different for each Client object.
*
* The send, subscribe and unsubscribe methods are implemented as asynchronous JavaScript methods
* (even though the underlying protocol exchange might be synchronous in nature).
* This means they signal their completion by calling back to the application,
* via Success or Failure callback functions provided by the application on the method in question.
* Such callbacks are called at most once per method invocation and do not persist beyond the lifetime
* of the script that made the invocation.
*
* In contrast there are some callback functions, most notably {@link onMessageArrived},
* that are defined on the {@link Paho.MQTT.Client} object.
* These may get called multiple times, and aren't directly related to specific method invocations made by the
* client.
*
*/
class Client {
/** used when connecting to the server. */
readonly clientId: string;
/** the server's DNS hostname or dotted decimal IP address. */
readonly host: string;
/** the server's path. */
readonly path: string;
/** the server's port. */
readonly port: number;
/** function called with trace information, if set */
trace?: TraceFunction;
/**
* called when a connection has been lost. after a connect() method has succeeded.
* Establish the call back used when a connection has been lost. The connection may be
* lost because the client initiates a disconnect or because the server or network
* cause the client to be disconnected. The disconnect call back may be called without
* the connectionComplete call back being invoked if, for example the client fails to
* connect.
* A single response object parameter is passed to the onConnectionLost callback containing the following
* fields:
* <li>errorCode
* <li>errorMessage
*/
onConnectionLost: OnConnectionLostHandler;
/**
* called when a message has been delivered.
* All processing that this Client will ever do has been completed. So, for example,
* in the case of a Qos=2 message sent by this client, the PubComp flow has been received from the server
* and the message has been removed from persistent storage before this callback is invoked.
* Parameters passed to the onMessageDelivered callback are:
* <li>{@link Paho.MQTT.Message} that was delivered.
*/
onMessageDelivered: OnMessageHandler;
/**
* called when a message has arrived in this Paho.MQTT.client.
* Parameters passed to the onMessageArrived callback are:
* <li> {@link Paho.MQTT.Message} that has arrived.
*/
onMessageArrived: OnMessageHandler;
/**
* @param host - the address of the messaging server as a DNS name or dotted decimal IP address.
* @param port - the port number to connect to
* @param path - the path on the host to connect to - only used if host is not a URI. Default: '/mqtt'.
* @param clientId - the Messaging client identifier, between 1 and 23 characters in length.
*/
constructor(host: string, port: number, path: string, clientId: string); // tslint:disable-line unified-signatures (these cannot actually be neatly unified)
/**
* @param host - the address of the messaging server as a DNS name or dotted decimal IP address.
* @param port - the port number to connect to
* @param clientId - the Messaging client identifier, between 1 and 23 characters in length.
*/
constructor(host: string, port: number, clientId: string);
/**
* @param hostUri - the address of the messaging server as a fully qualified WebSocket URI
* @param clientId - the Messaging client identifier, between 1 and 23 characters in length.
*/
constructor(hostUri: string, clientId: string);
/**
* Connect this Messaging client to its server.
* @throws {InvalidState} if the client is not in disconnected state. The client must have received
* connectionLost or disconnected before calling connect for a second or subsequent time.
*/
connect(connectionOptions?: ConnectionOptions): void;
/**
* Normal disconnect of this Messaging client from its server.
*
* @throws {InvalidState} if the client is already disconnected.
*/
disconnect(): void;
/**
* @returns True if the client is currently connected
*/
isConnected(): boolean;
/**
* Get the contents of the trace log.
*
* @return tracebuffer containing the time ordered trace records.
*/
getTraceLog(): any[];
/**
* Start tracing.
*/
startTrace(): void;
/**
* Stop tracing.
*/
stopTrace(): void;
/**
* Send a message to the consumers of the destination in the Message.
*
* @param message - <b>mandatory</b> The {@link Paho.MQTT.Message} object to be sent.
* @throws {InvalidState} if the client is not connected.
*/
send(message: Message): void;
/**
* Send a message to the consumers of the destination in the Message.
*
* @param topic - <b>mandatory</b> The name of the destination to which the message is to be sent.
* @param payload - The message data to be sent.
* @param qos The Quality of Service used to deliver the message.
* <dl>
* <dt>0 Best effort (default).
* <dt>1 At least once.
* <dt>2 Exactly once.
* </dl>
* @param retained If true, the message is to be retained by the server and delivered to both
* current and future subscriptions. If false the server only delivers the message to current subscribers,
* this is the default for new Messages. A received message has the retained boolean set to true if the
* message was published with the retained boolean set to true and the subscrption was made after the
* message has been published.
* @throws {InvalidState} if the client is not connected.
*/
send(topic: string, payload: string | ArrayBuffer, qos?: Qos, retained?: boolean): void;
/**
* Subscribe for messages, request receipt of a copy of messages sent to the destinations described by the
* filter.
*
* @param filter A filter describing the destinations to receive messages from.
* @param subcribeOptions Used to control the subscription
* @throws {InvalidState} if the client is not in connected state.
*/
subscribe(filter: string, subcribeOptions?: SubscribeOptions): void;
/**
* Unsubscribe for messages, stop receiving messages sent to destinations described by the filter.
*
* @param filter - describing the destinations to receive messages from.
* @param unsubscribeOptions - used to control the subscription
* @throws {InvalidState} if the client is not in connected state.
*/
unsubscribe(filter: string, unsubcribeOptions?: UnsubscribeOptions): void;
}
type TypedArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| Float32Array
| Float64Array;
/**
* An application message, sent or received.
*/
class Message {
/**
* The name of the destination to which the message is to be sent
* (for messages about to be sent) or the name of the destination from which the message has been received.
* (for messages received by the onMessage function).
*/
destinationName: string;
/**
* If true, this message might be a duplicate of one which has already been received.
* This is only set on messages received from the server.
*/
readonly duplicate: boolean;
/**
* The payload.
* @return if payload is a string. Return the original otherwise.
*/
readonly payloadBytes: ArrayBuffer | TypedArray;
/**
* The payload as a string if the payload consists of valid UTF-8 characters.
* @throw {Error} if the payload is not valid UTF-8
*/
readonly payloadString: string;
/**
* The Quality of Service used to deliver the message.
* <dl>
* <dt>0 Best effort (default).
* <dt>1 At least once.
* <dt>2 Exactly once.
* </dl>
*
* @default 0
*/
qos: Qos;
/**
* If true, the message is to be retained by the server and delivered to both current and future
* subscriptions. If false the server only delivers the message to current subscribers, this is the default
* for new Messages. A received message has the retained boolean set to true if the message was published
* with the retained boolean set to true and the subscription was made after the message has been published.
*
* @default false
*/
retained: boolean;
/**
* @param payload The message data to be sent.
*/
constructor(payload: string | ArrayBuffer | TypedArray);
}
}
} | the_stack |
import * as i18n from '../../core/i18n/i18n.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as Protocol from '../../generated/protocol.js';
import * as UI from '../../ui/legacy/legacy.js';
const UIStrings = {
/**
*@description Text in Indexed DBViews of the Application panel
*/
version: 'Version',
/**
*@description Table heading for Service Workers update information. Update is a noun.
*/
updateActivity: 'Update Activity',
/**
*@description Title for the timeline tab.
*/
timeline: 'Timeline',
/**
*@description Text in Service Workers Update Life Cycle
*@example {2} PH1
*/
startTimeS: 'Start time: {PH1}',
/**
*@description Text for end time of an event
*@example {2} PH1
*/
endTimeS: 'End time: {PH1}',
};
const str_ = i18n.i18n.registerUIStrings('panels/application/ServiceWorkerUpdateCycleView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class ServiceWorkerUpdateCycleView {
private registration: SDK.ServiceWorkerManager.ServiceWorkerRegistration;
private rows: Array<HTMLTableRowElement>;
private selectedRowIndex: number;
tableElement: HTMLElement;
constructor(registration: SDK.ServiceWorkerManager.ServiceWorkerRegistration) {
this.registration = registration;
this.rows = [];
this.selectedRowIndex = -1;
this.tableElement = document.createElement('table');
this.createTimingTable();
}
calculateServiceWorkerUpdateRanges(): Array<ServiceWorkerUpdateRange> {
function addRange(ranges: Array<ServiceWorkerUpdateRange>, range: ServiceWorkerUpdateRange): void {
if (range.start < Number.MAX_VALUE && range.start <= range.end) {
ranges.push(range);
}
}
/**
* Add ranges representing Install, Wait or Activate of a sw version represented by id.
*/
function addNormalizedRanges(
ranges: Array<ServiceWorkerUpdateRange>, id: string, startInstallTime: number, endInstallTime: number,
startActivateTime: number, endActivateTime: number,
status: Protocol.ServiceWorker.ServiceWorkerVersionStatus): void {
addRange(ranges, {id, phase: ServiceWorkerUpdateNames.Install, start: startInstallTime, end: endInstallTime});
if (status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activating ||
status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activated ||
status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Redundant) {
addRange(ranges, {
id,
phase: ServiceWorkerUpdateNames.Wait,
start: endInstallTime,
end: startActivateTime,
});
addRange(
ranges, {id, phase: ServiceWorkerUpdateNames.Activate, start: startActivateTime, end: endActivateTime});
}
}
function rangesForVersion(version: SDK.ServiceWorkerManager.ServiceWorkerVersion): Array<ServiceWorkerUpdateRange> {
let state: SDK.ServiceWorkerManager.ServiceWorkerVersionState|null = version.currentState;
let endActivateTime: number = 0;
let beginActivateTime: number = 0;
let endInstallTime: number = 0;
let beginInstallTime: number = 0;
const currentStatus = state.status;
if (currentStatus === Protocol.ServiceWorker.ServiceWorkerVersionStatus.New) {
return [];
}
while (state) {
// find the earliest timestamp of different stage on record.
if (state.status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activated) {
endActivateTime = state.last_updated_timestamp;
} else if (state.status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Activating) {
if (endActivateTime === 0) {
endActivateTime = state.last_updated_timestamp;
}
beginActivateTime = state.last_updated_timestamp;
} else if (state.status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installed) {
endInstallTime = state.last_updated_timestamp;
} else if (state.status === Protocol.ServiceWorker.ServiceWorkerVersionStatus.Installing) {
if (endInstallTime === 0) {
endInstallTime = state.last_updated_timestamp;
}
beginInstallTime = state.last_updated_timestamp;
}
state = state.previousState;
}
/** @type {Array <ServiceWorkerUpdateRange>} */
const ranges: Array<ServiceWorkerUpdateRange> = [];
addNormalizedRanges(
ranges, version.id, beginInstallTime, endInstallTime, beginActivateTime, endActivateTime, currentStatus);
return ranges;
}
const versions = this.registration.versionsByMode();
const modes = [
SDK.ServiceWorkerManager.ServiceWorkerVersion.Modes.Active,
SDK.ServiceWorkerManager.ServiceWorkerVersion.Modes.Waiting,
SDK.ServiceWorkerManager.ServiceWorkerVersion.Modes.Installing,
SDK.ServiceWorkerManager.ServiceWorkerVersion.Modes.Redundant,
];
for (const mode of modes) {
const version = versions.get(mode);
if (version) {
const ranges = rangesForVersion(version);
return ranges;
}
}
return [];
}
private createTimingTable(): void {
this.tableElement.classList.add('service-worker-update-timing-table');
const timeRanges = this.calculateServiceWorkerUpdateRanges();
this.updateTimingTable(timeRanges);
}
private createTimingTableHead(): void {
const serverHeader = this.tableElement.createChild('tr', 'service-worker-update-timing-table-header');
UI.UIUtils.createTextChild(serverHeader.createChild('td'), i18nString(UIStrings.version));
UI.UIUtils.createTextChild(serverHeader.createChild('td'), i18nString(UIStrings.updateActivity));
UI.UIUtils.createTextChild(serverHeader.createChild('td'), i18nString(UIStrings.timeline));
}
private removeRows(): void {
const rows = this.tableElement.getElementsByTagName('tr');
while (rows[0]) {
if (rows[0].parentNode) {
rows[0].parentNode.removeChild(rows[0]);
}
}
this.rows = [];
}
private updateTimingTable(timeRanges: Array<ServiceWorkerUpdateRange>): void {
this.selectedRowIndex = -1;
this.removeRows();
this.createTimingTableHead();
/** @type {!Array<ServiceWorkerUpdateRange>} */
const timeRangeArray = timeRanges;
if (timeRangeArray.length === 0) {
return;
}
const startTimes = timeRangeArray.map(r => r.start);
const endTimes = timeRangeArray.map(r => r.end);
const startTime = startTimes.reduce((a, b) => Math.min(a, b));
const endTime = endTimes.reduce((a, b) => Math.max(a, b));
const scale = 100 / (endTime - startTime);
for (const range of timeRangeArray) {
const phaseName = range.phase;
const left = (scale * (range.start - startTime));
const right = (scale * (endTime - range.end));
const tr = this.tableElement.createChild('tr', 'service-worker-update-timeline');
this.rows.push(tr as HTMLTableRowElement);
const timingBarVersionElement = tr.createChild('td');
UI.UIUtils.createTextChild(timingBarVersionElement, '#' + range.id);
timingBarVersionElement.classList.add('service-worker-update-timing-bar-clickable');
timingBarVersionElement.setAttribute('tabindex', '0');
timingBarVersionElement.setAttribute('role', 'switch');
timingBarVersionElement.addEventListener('focus', (event: Event) => {
this.onFocus(event);
});
UI.ARIAUtils.setChecked(timingBarVersionElement, false);
const timingBarTitleElement = tr.createChild('td');
UI.UIUtils.createTextChild(timingBarTitleElement, phaseName);
const barContainer = tr.createChild('td').createChild('div', 'service-worker-update-timing-row');
const bar = barContainer.createChild('span', 'service-worker-update-timing-bar ' + phaseName.toLowerCase());
bar.style.left = left + '%';
bar.style.right = right + '%';
bar.textContent = '\u200B'; // Important for 0-time items to have 0 width.
this.constructUpdateDetails(tr, range);
}
}
/**
* Detailed information about an update phase. Currently starting and ending time.
*/
private constructUpdateDetails(tr: HTMLElement, range: ServiceWorkerUpdateRange): void {
const startRow = this.tableElement.createChild('tr', 'service-worker-update-timing-bar-details');
startRow.classList.add('service-worker-update-timing-bar-details-collapsed');
const startTimeItem = startRow.createChild('td') as HTMLTableCellElement;
startTimeItem.colSpan = 3;
const startTime = (new Date(range.start)).toISOString();
UI.UIUtils.createTextChild(startTimeItem.createChild('span'), i18nString(UIStrings.startTimeS, {PH1: startTime}));
startRow.tabIndex = 0;
const endRow = this.tableElement.createChild('tr', 'service-worker-update-timing-bar-details');
endRow.classList.add('service-worker-update-timing-bar-details-collapsed');
const endTimeItem = endRow.createChild('td') as HTMLTableCellElement;
endTimeItem.colSpan = 3;
const endTime = (new Date(range.end)).toISOString();
UI.UIUtils.createTextChild(endTimeItem.createChild('span'), i18nString(UIStrings.endTimeS, {PH1: endTime}));
endRow.tabIndex = 0;
tr.addEventListener('keydown', (event: Event) => {
this.onKeydown(event, startRow, endRow);
});
tr.addEventListener('click', (event: Event) => {
this.onClick(event, startRow, endRow);
});
}
private toggle(startRow: Element, endRow: Element, target: Element, expanded: boolean): void {
if (target.classList.contains('service-worker-update-timing-bar-clickable')) {
startRow.classList.toggle('service-worker-update-timing-bar-details-collapsed');
startRow.classList.toggle('service-worker-update-timing-bar-details-expanded');
endRow.classList.toggle('service-worker-update-timing-bar-details-collapsed');
endRow.classList.toggle('service-worker-update-timing-bar-details-expanded');
UI.ARIAUtils.setChecked(target, !expanded);
}
}
private onFocus(event: Event): void {
const target = event.target as HTMLElement | null;
if (!target) {
return;
}
const tr = target.parentElement as HTMLTableRowElement | null;
if (!tr) {
return;
}
this.selectedRowIndex = this.rows.indexOf(tr);
}
private onKeydown(event: Event, startRow: HTMLElement, endRow: HTMLElement): void {
if (!event.target) {
return;
}
const target: HTMLElement = event.target as HTMLElement;
const keyboardEvent = event as KeyboardEvent;
const expanded = target.getAttribute('aria-checked') === 'true';
if (keyboardEvent.key === 'Enter' || keyboardEvent.key === ' ') {
this.toggle(startRow, endRow, target, expanded);
event.preventDefault();
return;
}
if ((!expanded && keyboardEvent.key === 'ArrowRight') || (expanded && keyboardEvent.key === 'ArrowLeft')) {
this.toggle(startRow, endRow, target, expanded);
event.preventDefault();
return;
}
if (keyboardEvent.key === 'ArrowDown') {
if (this.selectedRowIndex >= 0) {
this.selectNextRow();
} else {
this.selectFirstRow();
}
event.preventDefault();
}
if (keyboardEvent.key === 'ArrowUp') {
if (this.selectedRowIndex >= 0) {
this.selectPreviousRow();
} else {
this.selectLastRow();
}
event.preventDefault();
}
}
private focusRow(row: HTMLTableRowElement): void {
row.cells[0].focus();
}
private blurRow(row: HTMLTableRowElement): void {
row.cells[0].blur();
}
private selectFirstRow(): void {
if (this.rows.length === 0) {
return;
}
this.selectedRowIndex = 0;
this.focusRow(this.rows[0]);
}
private selectLastRow(): void {
if (this.rows.length === 0) {
return;
}
this.selectedRowIndex = this.rows.length - 1;
this.focusRow(this.rows[this.selectedRowIndex]);
}
private selectNextRow(): void {
if (this.rows.length === 0) {
return;
}
const previousRowIndex = this.selectedRowIndex;
this.selectedRowIndex++;
if (this.selectedRowIndex >= this.rows.length) {
this.selectedRowIndex = 0;
}
this.blurRow(this.rows[previousRowIndex]);
this.focusRow(this.rows[this.selectedRowIndex]);
}
private selectPreviousRow(): void {
if (this.rows.length === 0) {
return;
}
const previousRowIndex = this.selectedRowIndex;
this.selectedRowIndex--;
if (this.selectedRowIndex < 0) {
this.selectedRowIndex = this.rows.length - 1;
}
this.blurRow(this.rows[previousRowIndex]);
this.focusRow(this.rows[this.selectedRowIndex]);
}
private onClick(event: Event, startRow: Element, endRow: Element): void {
const tr = event.target as Element;
if (!tr) {
return;
}
const expanded = tr.getAttribute('aria-checked') === 'true';
this.toggle(startRow, endRow, tr, expanded);
event.preventDefault();
}
refresh(): void {
const timeRanges = this.calculateServiceWorkerUpdateRanges();
this.updateTimingTable(timeRanges);
}
}
export const enum ServiceWorkerUpdateNames {
Install = 'Install',
Wait = 'Wait',
Activate = 'Activate',
}
export interface ServiceWorkerUpdateRange {
id: string;
phase: ServiceWorkerUpdateNames;
start: number;
end: number;
} | the_stack |
import {ByteReader, concatByteArrays, EOF} from "teamten-ts-utils";
import {hi, lo, toHexWord} from "z80-base";
import {ProgramAnnotation} from "./ProgramAnnotation.js";
import {AbstractTrs80File} from "./Trs80File.js";
// There are two types of headers. Basic programs on cassette start with
// three D3 bytes followed by one name byte. Basic programs on floppy disk
// start with a single FF byte.
export const BASIC_TAPE_HEADER_BYTE = 0xD3;
export const BASIC_HEADER_BYTE = 0xFF;
const FIRST_TOKEN = 0x80;
const TOKENS = [
"END", "FOR", "RESET", "SET", "CLS", "CMD", "RANDOM", "NEXT", // 0x80
"DATA", "INPUT", "DIM", "READ", "LET", "GOTO", "RUN", "IF", // 0x88
"RESTORE", "GOSUB", "RETURN", "REM", "STOP", "ELSE", "TRON", "TROFF", // 0x90
"DEFSTR", "DEFINT", "DEFSNG", "DEFDBL", "LINE", "EDIT", "ERROR", "RESUME", // 0x98
"OUT", "ON", "OPEN", "FIELD", "GET", "PUT", "CLOSE", "LOAD", // 0xA0
"MERGE", "NAME", "KILL", "LSET", "RSET", "SAVE", "SYSTEM", "LPRINT", // 0xA8
"DEF", "POKE", "PRINT", "CONT", "LIST", "LLIST", "DELETE", "AUTO", // 0xB0
"CLEAR", "CLOAD", "CSAVE", "NEW", "TAB(", "TO", "FN", "USING", // 0xB8
"VARPTR", "USR", "ERL", "ERR", "STRING$", "INSTR", "POINT", "TIME$", // 0xC0
"MEM", "INKEY$", "THEN", "NOT", "STEP", "+", "-", "*", // 0xC8
"/", "[", "AND", "OR", ">", "=", "<", "SGN", // 0xD0
"INT", "ABS", "FRE", "INP", "POS", "SQR", "RND", "LOG", // 0xD8
"EXP", "COS", "SIN", "TAN", "ATN", "PEEK", "CVI", "CVS", // 0xE0
"CVD", "EOF", "LOC", "LOF", "MKI$", "MKS$", "MKD$", "CINT", // 0xE8
"CSNG", "CDBL", "FIX", "LEN", "STR$", "VAL", "ASC", "CHR$", // 0xF0
"LEFT$", "RIGHT$", "MID$", // 0xF8
];
const DOUBLE_QUOTE = 0x22;
const SINGLE_QUOTE = 0x27;
const COLON = 0x3A;
const REM = 0x93;
const DATA = 0x88;
const REMQUOT = 0xFB;
const ELSE = 0x95;
/**
* Parser state.
*/
enum ParserState {
// Normal part of line.
NORMAL,
// Inside string literal.
STRING,
// After REM token to end of line.
REM,
// After DATA token to end of statement.
DATA,
}
/**
* Get the token for the byte value, or undefined if the value does
* not map to a token.
*/
export function getToken(c: number): string | undefined {
return c >= FIRST_TOKEN && c < FIRST_TOKEN + TOKENS.length ? TOKENS[c - FIRST_TOKEN] : undefined;
}
/**
* Generate a 3-character octal version of a number.
*/
function toOctal(n: number): string {
return n.toString(8).padStart(3, "0");
}
/**
* Type of Basic element, for syntax highlighting.
*/
export enum ElementType {
ERROR,
LINE_NUMBER,
PUNCTUATION,
KEYWORD,
REGULAR,
STRING,
COMMENT,
}
/**
* Piece of a Basic program (token, character, line number).
*/
export class BasicElement {
// Byte offset in "bytes" array, or undefined if this is an error message or otherwise
// not selectable, such as the space between line numbers and the rest of the line.
public offset: number | undefined;
// Length of section in "binary" array.
public length: number;
// Text of element.
public text: string;
// Type of element (line number, token, string literal, etc.).
public elementType: ElementType;
constructor(offset: number | undefined, text: string, elementType: ElementType, length: number = 1) {
this.offset = offset;
this.length = length;
this.text = text;
this.elementType = elementType;
}
/**
* Get the element's text so that it will display properly in "Another Man's Treasure" font.
*
* https://www.kreativekorp.com/software/fonts/trs80.shtml
*/
public asAnotherMansTreasure(): string {
if (this.elementType === ElementType.STRING) {
const parts: string[] = [];
// Convert non-ASCII to the right value for our font.
for (const ch of this.text) {
let c = ch.charCodeAt(0);
if (c < 32 || c >= 127) {
c += 0xE000;
}
parts.push(String.fromCodePoint(c));
}
return parts.join("");
} else {
return this.text;
}
}
/**
* Get the element's text so that it will display properly in ASCII.
*/
public asAscii(): string {
if (this.elementType === ElementType.STRING) {
const parts: string[] = [];
for (const ch of this.text) {
const c = ch.charCodeAt(0);
if (ch === "\r") {
parts.push("\\r");
} else if (c >= 32 && c < 128 && ch !== "\\") {
parts.push(ch);
} else {
parts.push("\\" + toOctal(c));
}
}
return parts.join("");
} else {
return this.text;
}
}
}
/**
* Class representing a Basic program. If the "error" field is set, then something
* went wrong with the program and the data may be partially loaded.
*/
export class BasicProgram extends AbstractTrs80File {
public readonly className = "BasicProgram";
public elements: BasicElement[];
constructor(binary: Uint8Array, error: string | undefined, annotations: ProgramAnnotation[],
elements: BasicElement[]) {
super(binary, error, annotations);
this.elements = elements;
}
public getDescription(): string {
// Don't include filename, it's usually worthless.
return "Basic program";
}
/**
* Generate a plain ASCII version of the Basic program.
*/
public asAscii(): string {
const parts: string[] = [];
for (const basicElement of this.elements) {
if (parts.length > 0 && basicElement.elementType === ElementType.LINE_NUMBER) {
parts.push("\n");
}
parts.push(basicElement.text);
}
parts.push("\n");
return parts.join("");
}
/**
* Get a version of the binary that's appropriate for cassette. This will
* have the D3 header instead of the FF header.
*/
public asCassetteBinary(): Uint8Array {
if (this.binary.length >= 4 &&
this.binary[0] === BASIC_TAPE_HEADER_BYTE &&
this.binary[1] === BASIC_TAPE_HEADER_BYTE &&
this.binary[2] === BASIC_TAPE_HEADER_BYTE) {
// Already in cassette format.
return this.binary;
}
if (this.binary.length >= 1 &&
this.binary[0] === BASIC_HEADER_BYTE) {
// In floppy format. Convert to cassette format.
return concatByteArrays([
new Uint8Array([
BASIC_TAPE_HEADER_BYTE,
BASIC_TAPE_HEADER_BYTE,
BASIC_TAPE_HEADER_BYTE,
0x65]),
this.binary.slice(1)]);
}
// Unknown format. Return as-is.
return this.binary;
}
}
/**
* Set the one-letter Basic name in the binary to the first letter of the name.
*
* @return a new array with the modified name.
*/
export function setBasicName(bytes: Uint8Array, name: string): Uint8Array {
if (name === "") {
// Pick anything.
name = "A";
}
// Make a copy for modifying.
const newName = new Uint8Array(bytes);
if (newName[0] === BASIC_TAPE_HEADER_BYTE &&
newName[1] === BASIC_TAPE_HEADER_BYTE &&
newName[2] === BASIC_TAPE_HEADER_BYTE &&
newName.length > 3) {
newName[3] = name.charCodeAt(0);
} else if (newName[0] === BASIC_HEADER_BYTE &&
newName.length > 1) {
// This type of header does not have a name byte.
}
return newName;
}
/**
* Decode a tokenized Basic program.
* @param binary tokenized program. May be in tape format (D3 D3 D3 followed by a one-letter program
* name) or not (FF).
* @return the Basic program, or undefined if the header did not indicate that this was a Basic program.
*/
export function decodeBasicProgram(binary: Uint8Array): BasicProgram | undefined {
const b = new ByteReader(binary);
let state: ParserState;
let preStringState = ParserState.NORMAL;
let error: string | undefined;
const annotations: ProgramAnnotation[] = [];
// Map from byte address to BasicElement for that byte.
const elements: BasicElement[] = [];
const firstByte = b.read();
if (firstByte === BASIC_TAPE_HEADER_BYTE) {
if (b.read() !== BASIC_TAPE_HEADER_BYTE || b.read() !== BASIC_TAPE_HEADER_BYTE) {
return undefined;
}
annotations.push(new ProgramAnnotation("Header", 0, b.addr()));
// One-byte ASCII program name. This is nearly always meaningless, so we do nothing with it.
b.read();
annotations.push(new ProgramAnnotation("Name", b.addr() - 1, b.addr()));
} else if (firstByte === BASIC_HEADER_BYTE) {
// All good.
annotations.push(new ProgramAnnotation("Header", 0, b.addr()));
} else {
return undefined;
}
while (true) {
// Read the address of the next line. We ignore this (as does Basic when
// loading programs), only using it to detect end of program. (In the real
// Basic these are regenerated after loading.)
const address = b.readShort(true);
if (address === EOF) {
error = "EOF in next line's address";
break;
}
// Zero address indicates end of program.
if (address === 0) {
annotations.push(new ProgramAnnotation("End-of-program marker", b.addr() - 2, b.addr()));
break;
}
annotations.push(new ProgramAnnotation(
"Address of next line (0x" + toHexWord(address) + ")", b.addr() - 2, b.addr()));
// Read current line number.
const lineNumber = b.readShort(false);
if (lineNumber === EOF) {
error = "EOF in line number";
break;
}
annotations.push(new ProgramAnnotation("Line number (" + lineNumber + ")", b.addr() - 2, b.addr()));
elements.push(new BasicElement(b.addr() - 2, lineNumber.toString(), ElementType.LINE_NUMBER, 2));
elements.push(new BasicElement(undefined, " ", ElementType.REGULAR));
// Read rest of line.
const lineAddr = b.addr();
const lineElementsIndex = elements.length;
let c; // Uint8 value.
let ch; // String value.
state = ParserState.NORMAL;
while (true) {
c = b.read();
if (c === EOF || c === 0) {
break;
}
ch = String.fromCharCode(c);
// Special handling of sequences of characters that start with a colon.
if (ch === ":" && state === ParserState.NORMAL) {
const colonAddr = b.addr() - 1;
if (b.peek(0) === ELSE) {
// :ELSE gets translated to just ELSE, probably because an old version
// of Basic only supported ELSE after a colon.
b.read(); // ELSE
elements.push(new BasicElement(colonAddr, "ELSE", ElementType.KEYWORD, b.addr() - colonAddr));
} else if (b.peek(0) === REM && b.peek(1) === REMQUOT) {
// Detect the ":REM'" sequence (colon, REM, single quote), because
// that translates to a single quote. Must be a backward-compatible
// way to add a single quote as a comment.
b.read(); // REM
b.read(); // REMQUOT
elements.push(new BasicElement(colonAddr, "'", ElementType.COMMENT, b.addr() - colonAddr));
state = ParserState.REM;
} else {
elements.push(new BasicElement(colonAddr, ":", ElementType.PUNCTUATION));
}
} else {
switch (state) {
case ParserState.NORMAL:
const token = getToken(c);
elements.push(token !== undefined
? new BasicElement(b.addr() - 1, token,
c === DATA || c === REM ? ElementType.COMMENT
: token.length === 1 ? ElementType.PUNCTUATION
: ElementType.KEYWORD)
: new BasicElement(b.addr() - 1,
ch, ch === '"' ? ElementType.STRING : ElementType.REGULAR));
if (c === REM) {
state = ParserState.REM;
} else if (c === DATA) {
state = ParserState.DATA;
} else if (ch === '"') {
preStringState = state;
state = ParserState.STRING;
}
break;
case ParserState.STRING:
// Put the real value in the string. Code displaying can use the methods of
// BasicElement to convert it before printing.
elements.push(new BasicElement(b.addr() - 1, ch, ElementType.STRING));
if (ch === '"') {
// End of string.
state = preStringState;
}
break;
case ParserState.REM:
elements.push(new BasicElement(b.addr() - 1, ch, ElementType.COMMENT));
break;
case ParserState.DATA:
let elementType = ElementType.COMMENT;
if (ch === ":") {
elementType = ElementType.PUNCTUATION;
state = ParserState.NORMAL;
}
if (ch === '"') {
elementType = ElementType.STRING;
preStringState = state;
state = ParserState.STRING;
}
elements.push(new BasicElement(b.addr() - 1, ch, elementType));
break;
}
}
}
if (c === EOF) {
error = "EOF in line";
annotations.push(new ProgramAnnotation("Partial line", lineAddr, b.addr()));
break;
}
const textLineParts: string[] = [];
for (let i = lineElementsIndex; i < elements.length; i++) {
textLineParts.push(elements[i].text);
}
let textLine = textLineParts.join("").replace(/[\n\r]+/, " ");
if (textLine.length > 33) {
textLine = textLine.substr(0, 30) + "...";
}
annotations.push(new ProgramAnnotation("Line: " + textLine, lineAddr, b.addr() - 1));
annotations.push(new ProgramAnnotation("End-of-line marker", b.addr() - 1, b.addr()));
}
return new BasicProgram(binary, error, annotations, elements);
}
/**
* Parser for a single line of Basic code.
*/
class BasicParser {
private readonly line: string;
private readonly result: number[] = [];
public lineNumber: number | undefined = undefined;
private pos = 0;
constructor(line: string) {
// Only trim the start, spaces at the end should be kept.
this.line = line.trimStart();
}
/**
* Parse the line, returning the binary for it or an error. The binary includes
* the line number and the terminating nul, but not the "next-line" pointer.
*/
public parse(): Uint8Array | string {
// Parse line number.
this.lineNumber = this.readNumber();
if (this.lineNumber === undefined) {
return "Missing line number: " + this.line;
}
this.result.push(lo(this.lineNumber));
this.result.push(hi(this.lineNumber));
// We only trim at the start, so there could be only spaces here, but that's not allowed.
if (this.line.substr(this.pos).trim() === "") {
return "Empty line " + this.lineNumber;
}
// Skip single optional whitespace
if (this.pos < this.line.length && BasicParser.isWhitespace(this.line.charCodeAt(this.pos))) {
this.pos++;
}
while (this.pos < this.line.length) {
let ch = this.line.charCodeAt(this.pos);
// Lower case anything outside of strings.
if (ch >= 0x61 && ch < 0x61 + 26) {
ch -= 0x20;
}
// Handle single-quote comment.
if (ch === SINGLE_QUOTE) {
// Single quote is the start of a comment, but it's encoded in a backward-compatible
// way with several tokens.
this.result.push(COLON, REM, REMQUOT);
this.pos++;
// We're done, copy the rest of the line.
break;
}
// Handle string.
if (ch === DOUBLE_QUOTE) {
this.result.push(ch);
this.pos++;
while (this.pos < this.line.length) {
ch = this.line.charCodeAt(this.pos++);
this.result.push(ch);
if (ch === DOUBLE_QUOTE) {
break;
}
}
} else {
// See if it should be a token.
const token = this.readToken();
if (token === undefined) {
// Just a regular letter.
this.result.push(ch);
this.pos++;
} else {
// Prefix ELSE with colon for backward compatibility.
if (token === ELSE && this.result[this.result.length - 1] !== COLON) {
this.result.push(COLON);
}
this.result.push(token);
this.pos += TOKENS[token - FIRST_TOKEN].length;
if (token === REM) {
// We're done, copy the rest of the line.
break;
}
if (token === DATA) {
// Copy to end of statement.
let inString = false;
while (this.pos < this.line.length) {
ch = this.line.charCodeAt(this.pos);
if (ch === DOUBLE_QUOTE) {
inString = !inString;
} else if (ch === COLON && !inString) {
break;
}
this.result.push(ch);
this.pos++;
}
}
}
}
}
// Copy rest of line (for comments).
while (this.pos < this.line.length) {
this.result.push(this.line.charCodeAt(this.pos++));
}
// End-of-line marker.
this.result.push(0);
return new Uint8Array(this.result);
}
/**
* If we're at a token, return it, else return undefined. Does not advance past the token.
*/
private readToken(): number | undefined {
for (let i = 0; i < TOKENS.length; i++) {
const token = TOKENS[i];
if (token === this.line.substr(this.pos, token.length).toUpperCase()) {
return FIRST_TOKEN + i;
}
}
return undefined;
}
/**
* Reads a decimal number and advances past it, or returns undefined if not at a number.
*/
private readNumber(): number | undefined {
let n: number | undefined;
while (this.pos < this.line.length && BasicParser.isDigit(this.line.charCodeAt(this.pos))) {
if (n === undefined) {
n = 0;
}
n = n*10 + this.line.charCodeAt(this.pos) - 0x30;
this.pos++;
}
return n;
}
/**
* Whether the ASCII value is whitespace.
*/
private static isWhitespace(ch: number): boolean {
return ch === 0x20 || ch === 0x09;
}
/**
* Whether the ASCII value is a digit.
*/
private static isDigit(ch: number): boolean {
return ch >= 0x30 && ch < 0x3A;
}
}
/**
* Parse a Basic program into a binary with the initial 0xFF header.
*
* @return the binary or an error.
*/
export function parseBasicText(text: string | Uint8Array): Uint8Array | string {
// Decode from binary if possible.
if (text instanceof Uint8Array) {
const decoder = new TextDecoder("utf-8", {
// Throw an exception if there's a decoding error. This will help us catch
// binaries that aren't actually text. Might cause problems for programs
// that contain graphics characters in strings.
fatal: true,
});
try {
text = decoder.decode(text);
} catch (e) {
return "Binary cannot be decoded into text";
}
}
// Split into lines. Only trim the start, spaces at the end should be kept.
const lines = text.split(/[\n\r]+/)
.map((line) => line.trimStart())
.filter((line) => line !== "");
const binaryParts: Uint8Array[] = [];
binaryParts.push(new Uint8Array([BASIC_HEADER_BYTE]));
// Parse each line.
let lineNumber: number | undefined;
for (const line of lines) {
const parser = new BasicParser(line);
const binary = parser.parse();
if (typeof binary === "string") {
return binary;
}
// Make sure line numbers are consecutive.
if (lineNumber !== undefined && parser.lineNumber !== undefined && parser.lineNumber <= lineNumber) {
return "Line " + parser.lineNumber + " is out of order";
}
lineNumber = parser.lineNumber;
// Push next-line pointer. Can be anything as long as it's not 0x0000,
// it'll get fixed up later.
binaryParts.push(new Uint8Array([0xFF, 0xFF]));
binaryParts.push(binary);
}
// End-of-program marker.
binaryParts.push(new Uint8Array([0x00, 0x00]));
return concatByteArrays(binaryParts);
} | the_stack |
import { ArgumentException } from "../Exceptions/ArgumentException";
import { AutodiscoverDnsClient } from "./AutodiscoverDnsClient";
import { AutodiscoverEndpoints } from "../Enumerations/AutodiscoverEndpoints";
import { AutodiscoverErrorCode } from "../Enumerations/AutodiscoverErrorCode";
import { AutodiscoverLocalException } from "../Exceptions/AutodiscoverLocalException";
import { AutodiscoverRedirectionUrlValidationCallback } from "./AutodiscoverServiceDelegates";
import { AutodiscoverRequest } from "./Requests/AutodiscoverRequest";
import { DomainSettingName } from "../Enumerations/DomainSettingName";
import { EwsLogging } from "../Core/EwsLogging";
import { EwsUtilities } from "../Core/EwsUtilities";
import { ExchangeVersion } from "../Enumerations/ExchangeVersion";
import { GetDomainSettingsRequest } from "./Requests/GetDomainSettingsRequest";
import { GetDomainSettingsResponse } from "./Responses/GetDomainSettingsResponse";
import { GetDomainSettingsResponseCollection } from "./Responses/GetDomainSettingsResponseCollection";
import { GetUserSettingsRequest } from "./Requests/GetUserSettingsRequest";
import { GetUserSettingsResponse } from "./Responses/GetUserSettingsResponse";
import { GetUserSettingsResponseCollection } from "./Responses/GetUserSettingsResponseCollection";
import { IOutParam } from "../Interfaces/IOutParam";
import { IRefParam } from "../Interfaces/IRefParam";
import { IXHROptions } from "../Interfaces";
import { OAuthCredentials } from "../Credentials/OAuthCredentials";
import { PartnerTokenCredentials } from "../Credentials/PartnerTokenCredentials";
import { Promise } from "../Promise";
import { ServiceValidationException } from "../Exceptions/ServiceValidationException";
import { ServiceVersionException } from "../Exceptions/ServiceVersionException";
import { StringHelper, EnumHelper, UriHelper, hasValue, isNullOrUndefined } from "../ExtensionMethods";
import { Strings } from "../Strings";
import { TraceFlags } from "../Enumerations/TraceFlags";
import { Uri } from "../Uri";
import { UserSettingName } from "../Enumerations/UserSettingName";
import { WindowsLiveCredentials } from "../Credentials/WindowsLiveCredentials";
import { X509CertificateCredentials } from "../Credentials/X509CertificateCredentials";
import { ExchangeServiceBase } from "../Core/ExchangeServiceBase";
/**
* Represents a binding to the Exchange Autodiscover Service.
* @sealed
*/
export class AutodiscoverService extends ExchangeServiceBase {
//#region Static members
/**
* Autodiscover legacy path
*
* @static
*/
private static AutodiscoverLegacyPath: string = "/autodiscover/autodiscover.xml";
/**
* Autodiscover legacy Url with protocol fill-in
*
* @static
*/
private static AutodiscoverLegacyUrl: string = "{0}://{1}" + AutodiscoverService.AutodiscoverLegacyPath;
/**
* Autodiscover legacy HTTPS Url
*
* @static
*/
private static AutodiscoverLegacyHttpsUrl: string = "https://{0}" + AutodiscoverService.AutodiscoverLegacyPath;
/**
* Autodiscover legacy HTTP Url
*
* @static
*/
private static AutodiscoverLegacyHttpUrl: string = "http://{0}" + AutodiscoverService.AutodiscoverLegacyPath;
/**
* Autodiscover SOAP HTTPS Url
*
* @static
*/
private static AutodiscoverSoapHttpsUrl: string = "https://{0}/autodiscover/autodiscover.svc";
/**
* Autodiscover SOAP WS-Security HTTPS Url
*
* @static
*/
private static AutodiscoverSoapWsSecurityHttpsUrl: string = AutodiscoverService.AutodiscoverSoapHttpsUrl + "/wssecurity";
/**
* Autodiscover SOAP WS-Security symmetrickey HTTPS Url
*
* @static
*/
private static AutodiscoverSoapWsSecuritySymmetricKeyHttpsUrl: string = AutodiscoverService.AutodiscoverSoapHttpsUrl + "/wssecurity/symmetrickey";
/**
* Autodiscover SOAP WS-Security x509cert HTTPS Url
*
* @static
*/
private static AutodiscoverSoapWsSecurityX509CertHttpsUrl: string = AutodiscoverService.AutodiscoverSoapHttpsUrl + "/wssecurity/x509cert";
/**
* Autodiscover request namespace
*
* @static
*/
private static AutodiscoverRequestNamespace: string = "http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006";
/**
* Legacy path regular expression.
*
* @static
*/
private static readonly LegacyPathRegex: RegExp = new RegExp("\/autodiscover/([^/]+/)*autodiscover.xml");
/**
* Maximum number of Url (or address) redirections that will be followed by an Autodiscover call
*
* @static
*/
static AutodiscoverMaxRedirections: number = 10;
/**
* HTTP header indicating that SOAP Autodiscover service is enabled.
*
* @static
*/
private static AutodiscoverSoapEnabledHeaderName: string = "X-SOAP-Enabled";
/**
* HTTP header indicating that WS-Security Autodiscover service is enabled.
*
* @static
*/
private static AutodiscoverWsSecurityEnabledHeaderName: string = "X-WSSecurity-Enabled";
/**
* HTTP header indicating that WS-Security/SymmetricKey Autodiscover service is enabled.
*
* @static
*/
private static AutodiscoverWsSecuritySymmetricKeyEnabledHeaderName: string = "X-WSSecurity-SymmetricKey-Enabled";
/**
* HTTP header indicating that WS-Security/X509Cert Autodiscover service is enabled.
*
* @static
*/
private static AutodiscoverWsSecurityX509CertEnabledHeaderName: string = "X-WSSecurity-X509Cert-Enabled";
/**
* HTTP header indicating that OAuth Autodiscover service is enabled.
*
* @static
*/
private static AutodiscoverOAuthEnabledHeaderName: string = "X-OAuth-Enabled";
/**
* Minimum request version for Autodiscover SOAP service.
*
* @static
*/
private static MinimumRequestVersionForAutoDiscoverSoapService: ExchangeVersion = ExchangeVersion.Exchange2010;
//#endregion
//#region static method for setting Office 365 specific autodiscover URl, can be used in O365 in China and govt community cloud
private static o365AutodiscoverUrl = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc";
/**
* Set Autodiscover hard coded url for Office 365, useful in GCC and O365 in China. This is also helpful if O365 need changing url for some reason (beta testing, transition to different url), no need to update lib
*
* @static
* @type {string}
*/
static get Office365AutodiscoverUrl(): string {
return this.o365AutodiscoverUrl;
}
static set Office365AutodiscoverUrl(value) {
this.o365AutodiscoverUrl = value;
}
private static o365AutodiscoverRedirectHeader = "x-federationtrusttokenissueruri";
/**
* Set Autodiscover hard coded check for header when it is auto redirected (skip 302 and follow the redirect in lib, likely browsers)
*
* @static
* @type {string}
*/
static get Office365AutodiscoverRedirectHeader(): string {
return this.o365AutodiscoverRedirectHeader;
}
static set Office365AutodiscoverRedirectHeader(value) {
this.o365AutodiscoverRedirectHeader = value;
}
private static o365AutodiscoverRedirectHeaderValue = "urn:federation:MicrosoftOnline";
/**
* Set Autodiscover hard coded check for header value when it is auto redirected (skip 302 and follow the redirect in lib, likely browsers)
*
* @static
* @type {string}
*/
static get Office365AutodiscoverRedirectHeaderValue(): string {
return this.o365AutodiscoverRedirectHeaderValue;
}
static set Office365AutodiscoverRedirectHeaderValue(value) {
this.o365AutodiscoverRedirectHeaderValue = value;
}
//#endregion
//#region Private members
//ref: can not use initializer value due to super(0 call complexity)
private domain: string;
private url: Uri;
private isExternal: boolean;
private redirectionUrlValidationCallback: AutodiscoverRedirectionUrlValidationCallback;
private dnsClient: AutodiscoverDnsClient;
private dnsServerAddress: any;// System.Net.IPAddress;
private enableScpLookup: boolean;
//#endregion
//#region Properties | Getter/Setter
get Domain(): string {
return this.domain;
}
set Domain(value) {
this.domain = value;
if (value)
this.url = undefined;
}
get Url(): Uri {
return this.url;
}
set Url(value) {
this.url = value;
}
get IsExternal(): boolean | null {
return this.isExternal;
}
set IsExternal(value) {
this.isExternal = value;
}
get RedirectionUrlValidationCallback(): AutodiscoverRedirectionUrlValidationCallback {
return this.redirectionUrlValidationCallback;
}
set RedirectionUrlValidationCallback(value) {
this.redirectionUrlValidationCallback = value;
}
get DnsServerAddress(): any {
return this.dnsServerAddress;
}
set DnsServerAddress(value) {
this.dnsServerAddress = value;
}
get EnableScpLookup(): boolean {
return this.enableScpLookup;
}
set EnableScpLookup(value) {
this.enableScpLookup = value;
}
//#endregion
/**
* Initializes a new instance of the **AutodiscoverService** class.
*/
constructor();
/**
* Initializes a new instance of the **AutodiscoverService** class.
*
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(requestedServerVersion: ExchangeVersion);
/**
* Initializes a new instance of the **AutodiscoverService** class.
*
* @param {string} domain The domain that will be used to determine the URL of the service.
*/
constructor(domain: string);
/**
* Initializes a new instance of the **AutodiscoverService** class.
*
* @param {Uri} url The URL of the service.
* @param {string} domain The domain that will be used to determine the URL of the service.
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(domain: string, requestedServerVersion: ExchangeVersion);
/**
* Initializes a new instance of the **AutodiscoverService** class.
*
* @param {Uri} url The URL of the service.
*/
constructor(url: Uri);
/**
* Initializes a new instance of the **AutodiscoverService** class.
*
* @param {Uri} url The URL of the service.
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(url: Uri, requestedServerVersion: ExchangeVersion);
/**
* @internal Initializes a new instance of the **AutodiscoverService** class.
*
* @param {Uri} url The URL of the service.
* @param {string} domain The domain that will be used to determine the URL of the service.
*/
constructor(url: Uri, domain: string);
/**
* @internal Initializes a new instance of the **AutodiscoverService** class.
*
* @param {ExchangeServiceBase} service The other service
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(service: ExchangeServiceBase);
/**
* @internal Initializes a new instance of the **AutodiscoverService** class.
*
* @param {ExchangeServiceBase} service The other service
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(service: ExchangeServiceBase, requestedServerVersion: ExchangeVersion);
/**
* @internal Initializes a new instance of the **AutodiscoverService** class.
*
* @param {Uri} url The URL of the service.
* @param {string} domain The domain that will be used to determine the URL of the service.
* @param {ExchangeVersion} requestedServerVersion The requested server version.
*/
constructor(url: Uri, domain: string, requestedServerVersion: ExchangeVersion);
constructor(
domainUrlServiceOrVersion: string | Uri | ExchangeServiceBase | ExchangeVersion = null,
domainOrVersion: string | ExchangeVersion = null,
version: ExchangeVersion = ExchangeVersion.Exchange2010
) {
const argsLength = arguments.length;
if (argsLength > 3) {
throw new Error("AutodiscoverService.ts - ctor with " + argsLength + " parameters, invalid number of arguments, check documentation and try again.");
}
let service: ExchangeServiceBase = null;
let domain: string = null;
let url: Uri = null;
let requestedServerVersion: ExchangeVersion = version;
let hasService: boolean = false;
let hasVersion: boolean = false;
if (argsLength >= 1) {
if (domainUrlServiceOrVersion instanceof Uri) {
url = domainUrlServiceOrVersion;
}
else if (domainUrlServiceOrVersion instanceof ExchangeServiceBase) {
service = domainUrlServiceOrVersion;
hasService = true;
}
else if (typeof domainUrlServiceOrVersion === 'string') {
domain = domainUrlServiceOrVersion;
}
else if (typeof domainUrlServiceOrVersion === 'number') {
requestedServerVersion = domainUrlServiceOrVersion;
hasVersion = true;
}
}
if (argsLength >= 2) {
if (typeof domainOrVersion === 'string') {
if (!(domainUrlServiceOrVersion instanceof Uri)) {
throw new Error("AutodiscoverService.ts - ctor with " + argsLength + " parameters - incorrect uses of parameter at 1st position, it must be Uri when using string at 2nd place");
}
domain = domainOrVersion;
}
else if (typeof domainOrVersion === 'number') {
requestedServerVersion = domainOrVersion;
}
}
if (hasValue(service)) {
super(service, requestedServerVersion);
}
else {
EwsUtilities.ValidateDomainNameAllowNull(domain, "domain");
super(requestedServerVersion);
this.url = url;
this.domain = domain;
}
this.dnsClient = new AutodiscoverDnsClient(this);
this.isExternal = true;
this.enableScpLookup = false; // ref: no SCP for nodejs yet.
}
/**
* Calls the redirection URL validation callback.
*
* @remark If the redirection URL validation callback is null, use the default callback which does not allow following any redirections.
* @param {string} redirectionUrl The redirection URL.
* @return {boolean} True if redirection should be followed.
*/
private CallRedirectionUrlValidationCallback(redirectionUrl: string): boolean {
var callback: AutodiscoverRedirectionUrlValidationCallback = (this.RedirectionUrlValidationCallback == null)
? this.DefaultAutodiscoverRedirectionUrlValidationCallback
: this.RedirectionUrlValidationCallback;
return callback(redirectionUrl);
}
/**
* Default implementation of AutodiscoverRedirectionUrlValidationCallback. Always returns true indicating that the URL can be used.
*
* @param {string} redirectionUrl The redirection URL.
* @return {boolean} Returns true.
*/
private DefaultAutodiscoverRedirectionUrlValidationCallback(redirectionUrl: string): boolean {
throw new AutodiscoverLocalException(StringHelper.Format("Autodiscover redirection is blocked for url: {0}"/*Strings.AutodiscoverRedirectBlocked*/, redirectionUrl));
}
/**
* Defaults the get autodiscover service urls for domain.
*
* @param {string} domainName Name of the domain.
* @return {string[]} [description]
*/
private DefaultGetScpUrlsForDomain(domainName: string): string[] { return []; }// System.Collections.Generic.ICollection<string>{ throw new Error("AutodiscoverService.ts - DefaultGetScpUrlsForDomain : Not implemented.");}
/**
* Disables SCP lookup if duplicate email address redirection.
*
* @param {string} emailAddress The email address to use.
* @param {string[]} redirectionEmailAddresses The list of prior redirection email addresses.
*/
DisableScpLookupIfDuplicateRedirection(emailAddress: string, redirectionEmailAddresses: string[]): void {
// SMTP addresses are case-insensitive so entries are converted to lower-case.
emailAddress = emailAddress.toLowerCase();
if (redirectionEmailAddresses.includes(emailAddress)) {
this.EnableScpLookup = false;
}
else {
redirectionEmailAddresses.push(emailAddress);
}
}
/**
* Gets the autodiscover endpoint URL.
*
* @param {string} host The host.
* @return {Promise<Uri>} [description]
*/
private async GetAutodiscoverEndpointUrl(host: string): Promise<Uri> {
const autodiscoverUrlOut: IOutParam<Uri> = { outValue: null };
if (await this.TryGetAutodiscoverEndpointUrl(host, autodiscoverUrlOut)) {
return autodiscoverUrlOut.outValue;
}
else {
throw new AutodiscoverLocalException(Strings.NoSoapOrWsSecurityEndpointAvailable);
}
}
/**
* @internal Gets the list of autodiscover service hosts.
*
* @param {string} domainName Name of the domain.
* @param {IOutParam<number>} scpHostCount Count of SCP hosts that were found.
* @return {string[]} List of host names.
*/
GetAutodiscoverServiceHosts(domainName: string, scpHostCount: IOutParam<number>): string[] {
var serviceHosts: string[] = [];
var urls = this.GetAutodiscoverServiceUrls(domainName, scpHostCount);
for (var url of urls) {
serviceHosts.push(UriHelper.getHost(url));
}
return serviceHosts;
}
/**
* @internal Gets the list of autodiscover service URLs.
*
* @param {string} domainName Domain name.
* @param {IOutParam<number>} scpHostCount Count of hosts found via SCP lookup.
* @return {string[]} List of Autodiscover URLs.
*/
GetAutodiscoverServiceUrls(domainName: string, scpHostCount: IOutParam<number>): string[] {
var urls: string[] = [];
if (this.EnableScpLookup) {
// Get SCP URLs
//Func < string, ICollection <string>> callback = this.GetScpUrlsForDomainCallback ?? this.DefaultGetScpUrlsForDomain;
//ICollection < string> scpUrls = callback(domainName);
//foreach(string str in scpUrls)
//{
// urls.Add(new Uri(str));
//}
}
//scpHostCount = urls.length;
// As a fallback, add autodiscover URLs base on the domain name.
urls.push(StringHelper.Format(AutodiscoverService.AutodiscoverLegacyHttpsUrl, `autodiscover.${domainName}`)); // hard coding for autodiscover domain name
urls.push(StringHelper.Format(AutodiscoverService.AutodiscoverLegacyHttpsUrl, domainName));
return urls;
}
// ref: GetDomainSettings(domains: string[], settings: DomainSettingName[], requestedVersion: ExchangeVersion): Promise<GetDomainSettingsResponseCollection>; - not used, internal method and can be skipped implementing. Implementation is merged with other
/**
* Retrieves the specified settings for a set of domains.
*
* @param {string[]} domains The SMTP addresses of the domains.
* @param {ExchangeVersion} requestedVersion Requested version of the Exchange service.
* @param {...DomainSettingName[]} domainSettingNames The domain setting names.
* @return {Promise<GetDomainSettingsResponseCollection>} A GetDomainSettingsResponseCollection object containing the responses for each individual domain.
*/
async GetDomainSettings(domains: string[], requestedVersion: ExchangeVersion, ...domainSettingNames: DomainSettingName[]): Promise<GetDomainSettingsResponseCollection>;
/**
* Retrieves the specified settings for a domain.
*
* @param {string} domain The domain.
* @param {ExchangeVersion} requestedVersion Requested version of the Exchange service.
* @param {...DomainSettingName[]} domainSettingNames The domain setting names.
* @return {Promise<GetDomainSettingsResponse>} A DomainResponse object containing the requested settings for the specified domain.
*/
async GetDomainSettings(domain: string, requestedVersion: ExchangeVersion, ...domainSettingNames: DomainSettingName[]): Promise<GetDomainSettingsResponse>
async GetDomainSettings(
domainOrDomains: string | string[],
requestedVersion: ExchangeVersion,
...settings: DomainSettingName[]
): Promise<GetDomainSettingsResponse | GetDomainSettingsResponseCollection> {
let domains: string[];
let isCollection: boolean = true;
domains = <string[]>domainOrDomains;
if (!Array.isArray(domainOrDomains)) {
domains = [<string>domainOrDomains]
isCollection = false;
}
EwsUtilities.ValidateParam(domains, "domains");
EwsUtilities.ValidateParam(settings, "settings");
const result = await this.GetSettings<GetDomainSettingsResponseCollection, DomainSettingName>(
domains,
settings,
requestedVersion,
this.InternalGetDomainSettings.bind(this),
() => { return domains[0]; });
if (isCollection) {
return result;
}
else {
return result.__thisIndexer(0);
}
}
/**
* Gets the endpoints from HTTP web response.
*
* @param {XMLHttpRequest} response The response.
* @return {AutodiscoverEndpoints} Endpoints enabled.
*/
private GetEndpointsFromHttpWebResponse(response: XMLHttpRequest): AutodiscoverEndpoints {
var endpoints: AutodiscoverEndpoints = AutodiscoverEndpoints.Legacy;
if (!StringHelper.IsNullOrEmpty(response.getResponseHeader(AutodiscoverService.AutodiscoverSoapEnabledHeaderName))) {
endpoints |= AutodiscoverEndpoints.Soap;
}
if (!StringHelper.IsNullOrEmpty(response.getResponseHeader(AutodiscoverService.AutodiscoverWsSecurityEnabledHeaderName))) {
endpoints |= AutodiscoverEndpoints.WsSecurity;
}
if (!StringHelper.IsNullOrEmpty(response.getResponseHeader(AutodiscoverService.AutodiscoverWsSecuritySymmetricKeyEnabledHeaderName))) {
endpoints |= AutodiscoverEndpoints.WSSecuritySymmetricKey;
}
if (!StringHelper.IsNullOrEmpty(response.getResponseHeader(AutodiscoverService.AutodiscoverWsSecurityX509CertEnabledHeaderName))) {
endpoints |= AutodiscoverEndpoints.WSSecurityX509Cert;
}
if (!StringHelper.IsNullOrEmpty(response.getResponseHeader(AutodiscoverService.AutodiscoverOAuthEnabledHeaderName))) {
endpoints |= AutodiscoverEndpoints.OAuth;
}
return endpoints;
}
//GetLegacyUserSettings(emailAddress: string): any{ throw new Error("AutodiscoverService.ts - GetLegacyUserSettings : Not implemented.");}
//GetLegacyUserSettingsAtUrl(emailAddress: string, url: Uri): any{ throw new Error("AutodiscoverService.ts - GetLegacyUserSettingsAtUrl : Not implemented.");}
/**
* @internal Get an autodiscover SRV record in DNS and construct autodiscover URL.
*
* @param {string} domainName Name of the domain.
* @return {Promise<Uri>} Autodiscover URL (may be null if lookup failed)
*/
async GetRedirectionUrlFromDnsSrvRecord(domainName: string): Promise<Uri> {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Trying to get Autodiscover host from DNS SRV record for {0}.", domainName));
const hostname: string = await this.dnsClient.FindAutodiscoverHostFromSrv(domainName);
if (!StringHelper.IsNullOrEmpty(hostname)) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Autodiscover host {0} was returned.", hostname));
return new Uri(StringHelper.Format(AutodiscoverService.AutodiscoverLegacyHttpsUrl, hostname));
}
else {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
"No matching Autodiscover DNS SRV records were found.");
return null;
}
}
/**
* Gets a redirection URL to an SSL-enabled Autodiscover service from the standard non-SSL Autodiscover URL.
*
* @param {string} domainName The name of the domain to call Autodiscover on.
* @return {Promise<Uri>} A valid SSL-enabled redirection URL. (May be null).
*/
private async GetRedirectUrl(domainName: string): Promise<Uri> {
var url: string = StringHelper.Format(AutodiscoverService.AutodiscoverLegacyHttpUrl, "autodiscover." + domainName);
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Trying to get Autodiscover redirection URL from {0}.", url));
var xhrOptions: IXHROptions = {
type: "GET",
url: url,
allowRedirect: false,
};
let response: XMLHttpRequest = null;
try {
response = await this.XHRApi.xhr(xhrOptions)
} catch (responseError) {
if (responseError.status === 0) {
//catch (IOException ex)
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("I/O error: {0}", "unable to connect"));
return null;
}
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Request error: {0}", responseError.message || responseError.statusText || responseError.status));
response = responseError;
}
if (response != null) {
const redirectUrl: IOutParam<Uri> = { outValue: null };
if (this.TryGetRedirectionResponse(response, redirectUrl)) {
return redirectUrl.outValue;
}
// hard check for redirected office 365 url
this.TraceMessage(TraceFlags.All,
"***hard checking for office 365 with node.js http request and presence of header x-federationtrusttokenissueruri= urn:federation:MicrosoftOnline");
if (!StringHelper.IsNullOrEmpty(response.getResponseHeader(AutodiscoverService.Office365AutodiscoverRedirectHeader))) {
if (response.getResponseHeader(AutodiscoverService.Office365AutodiscoverRedirectHeader) === AutodiscoverService.Office365AutodiscoverRedirectHeaderValue)
redirectUrl.outValue = new Uri(AutodiscoverService.Office365AutodiscoverUrl);
return redirectUrl.outValue;
}
}
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
"No Autodiscover redirection URL was returned.");
return null;
}
/**
* Gets user or domain settings using Autodiscover SOAP service.
*
* @typeparam {TGetSettingsResponseCollection} Type of response collection to return.
* @typeparam {TSettingName} Type of setting name.
*
* @param {string[]} identities Either the domains or the SMTP addresses of the users.
* @param {settings: TSettingName[]} settings The settings.
* @param {ExchangeVersion} requestedVersion Requested version of the Exchange service.
* @param {GetSettingsMethod<TGetSettingsResponseCollection, TSettingName>} getSettingsMethod The method to use.
* @param {() => string} getDomainMethod The method to calculate the domain value.
* @return {Promise<TGetSettingsResponseCollection>} [description]
*/
private async GetSettings<TGetSettingsResponseCollection, TSettingName>(
identities: string[], settings: TSettingName[], requestedVersion: ExchangeVersion,
getSettingsMethod: GetSettingsMethod<TGetSettingsResponseCollection, TSettingName>,
getDomainMethod: () => string): Promise<TGetSettingsResponseCollection> {
// Autodiscover service only exists in E14 or later.
if (this.RequestedServerVersion < AutodiscoverService.MinimumRequestVersionForAutoDiscoverSoapService) {
throw new ServiceVersionException(
StringHelper.Format(
Strings.AutodiscoverServiceIncompatibleWithRequestVersion,
AutodiscoverService.MinimumRequestVersionForAutoDiscoverSoapService));
}
let response: TGetSettingsResponseCollection = null;
let urlRef = null;
let autodiscoverUrlRef: IRefParam<Uri> = { getValue: () => urlRef, setValue: (url) => urlRef = url };
// If Url is specified, call service directly.
if (this.Url != null) {
urlRef = this.url;
response = await getSettingsMethod(
identities,
settings,
requestedVersion,
autodiscoverUrlRef);
this.Url = urlRef;
return response;
} else if (!StringHelper.IsNullOrEmpty(this.Domain)) { // If Domain is specified, determine endpoint Url and call service.
urlRef = await this.GetAutodiscoverEndpointUrl(this.Domain)
response = await getSettingsMethod(
identities,
settings,
requestedVersion,
autodiscoverUrlRef)
// If we got this far, response was successful, set Url.
this.Url = urlRef;
return response;
} else { // No Url or Domain specified, need to figure out which endpoint(s) to try.
// Assume caller is not inside the Intranet, regardless of whether SCP Urls
// were returned or not. SCP Urls are only relevent if one of them returns
// valid Autodiscover settings.
this.IsExternal = true;
let autodiscoverUrlOut: IOutParam<Uri> = { outValue: null };
autodiscoverUrlRef = { getValue: () => autodiscoverUrlOut.outValue, setValue: (url) => { autodiscoverUrlOut.outValue = url; } };
let domainName: string = getDomainMethod();
let scpHostCount: IOutParam<number> = { outValue: 0 };
let hosts = this.GetAutodiscoverServiceHosts(domainName, scpHostCount);
if (hosts.length == 0) {
throw new ServiceValidationException(Strings.AutodiscoverServiceRequestRequiresDomainOrUrl);
}
for (let currentHostIndex = 0; currentHostIndex < hosts.length; currentHostIndex++) {
const host = hosts[currentHostIndex];
const isScpHost = currentHostIndex < scpHostCount.outValue;
if (await this.TryGetAutodiscoverEndpointUrl(host, autodiscoverUrlOut)) {
try {
response = await getSettingsMethod(
identities,
settings,
requestedVersion,
autodiscoverUrlRef);
// If we got this far, the response was successful, set Url.
this.Url = autodiscoverUrlOut.outValue;
// Not external if Autodiscover endpoint found via SCP returned the settings.
if (isScpHost) {
this.IsExternal = false;
}
return response;
} catch (error) {
// skip
}
}
}
this.TraceMessage(TraceFlags.DebugMessage,
"[Next-to-last chance: for autodiscover redirect] --hard checking for office 365 with node.js http request and presence of header x-federationtrusttokenissueruri: urn:federation:MicrosoftOnline. All other redirection wil fail");
// Next-to-last chance: try unauthenticated GET over HTTP to be redirected to appropriate service endpoint.
const autodiscoverUrl: IOutParam<Uri> = { outValue: null };
autodiscoverUrl.outValue = await this.GetRedirectUrl(domainName);
autodiscoverUrlRef = { getValue: () => autodiscoverUrl.outValue, setValue: (url) => { autodiscoverUrl.outValue = url; } };
if ((autodiscoverUrl.outValue != null) &&
this.CallRedirectionUrlValidationCallback(autodiscoverUrl.outValue.ToString()) &&
await this.TryGetAutodiscoverEndpointUrl(autodiscoverUrl.outValue.Host, autodiscoverUrl)) {
const response = await getSettingsMethod(
identities,
settings,
requestedVersion,
{ getValue: () => autodiscoverUrl.outValue })
// If we got this far, response was successful, set Url.
this.Url = autodiscoverUrl.outValue;
return response;
}
// Last Chance: try to read autodiscover SRV Record from DNS. If we find one, use
// the hostname returned to construct an Autodiscover endpoint URL.
autodiscoverUrl.outValue = await this.GetRedirectionUrlFromDnsSrvRecord(domainName);
if ((autodiscoverUrl.outValue != null) &&
this.CallRedirectionUrlValidationCallback(autodiscoverUrl.outValue.ToString()) &&
await this.TryGetAutodiscoverEndpointUrl(autodiscoverUrl.outValue.Host, autodiscoverUrl)) {
response = await getSettingsMethod(
identities,
settings,
requestedVersion,
autodiscoverUrlRef);
// If we got this far, the response was successful, set Url.
this.Url = autodiscoverUrl.outValue;
return response;
}
// else block not needed, if we get this far that mean no autodiscover url can be located
throw new AutodiscoverLocalException(Strings.AutodiscoverCouldNotBeLocated);
}
}
/**
* @internal Gets the user settings using Autodiscover SOAP service.
*
* @param {string[]} smtpAddresses The SMTP addresses of the users.
* @param {UserSettingName[]} settings The settings.
* @return {Promise<GetUserSettingsResponseCollection>} [description]
*/
public async GetUserSettings(smtpAddresses: string[], settings: UserSettingName[]): Promise<GetUserSettingsResponseCollection>;
/**
* Retrieves the specified settings for single SMTP address.
* @remarks This method handles will run the entire Autodiscover "discovery" algorithm and will follow address and URL redirections.
* @param {string} userSmtpAddress The SMTP addresses of the user.
* @param {UserSettingName[]} userSettingNames The user setting names.
* @return {Promise<GetUserSettingsResponse>} A UserResponse object containing the requested settings for the specified user.
*/
public async GetUserSettings(userSmtpAddress: string, userSettingNames: UserSettingName[]): Promise<GetUserSettingsResponse>;
public async GetUserSettings(smtpAddresses: string | string[], userSettings: UserSettingName[]): Promise<GetUserSettingsResponse | GetUserSettingsResponseCollection> {
if (isNullOrUndefined(userSettings) || isNullOrUndefined(userSettings)) {
throw new ArgumentException(`AutodiscoverService.ts - GetUserSettings - Required parameters missing`);
}
if (Array.isArray(smtpAddresses)) {
EwsUtilities.ValidateParam(smtpAddresses, "smtpAddresses");
EwsUtilities.ValidateParam(userSettings, "settings");
return this.GetSettings<GetUserSettingsResponseCollection, UserSettingName>(
smtpAddresses,
userSettings,
null,
this.InternalGetUserSettings.bind(this),
() => { return EwsUtilities.DomainFromEmailAddress(smtpAddresses[0]); });
}
var userSmtpAddress: string = smtpAddresses;
if (StringHelper.IsNullOrEmpty(userSmtpAddress)) {
throw new ServiceValidationException(Strings.InvalidAutodiscoverSmtpAddress);
}
var requestedSettings = userSettings || [];
if (requestedSettings.length == 0) {
throw new ServiceValidationException(Strings.InvalidAutodiscoverSettingsCount);
}
if (this.RequestedServerVersion < AutodiscoverService.MinimumRequestVersionForAutoDiscoverSoapService) {
return this.InternalGetLegacyUserSettings(userSmtpAddress, requestedSettings);
}
else {
return this.InternalGetSoapUserSettings(userSmtpAddress, requestedSettings);
}
}
/**
* Retrieves the specified settings for a set of users.
*
* @param {string[]} userSmtpAddresses The SMTP addresses of the users.
* @param {...UserSettingName[]} userSettingNames The user setting names.
* @return {Promise<GetUserSettingsResponseCollection>} A GetUserSettingsResponseCollection object containing the responses for each individual user.
*/
public async GetUsersSettings(userSmtpAddresses: string[], ...userSettingNames: UserSettingName[]): Promise<GetUserSettingsResponseCollection> {
if (this.RequestedServerVersion < AutodiscoverService.MinimumRequestVersionForAutoDiscoverSoapService) {
throw new ServiceVersionException(
StringHelper.Format(Strings.AutodiscoverServiceIncompatibleWithRequestVersion,
AutodiscoverService.MinimumRequestVersionForAutoDiscoverSoapService));
}
return this.GetUserSettings(userSmtpAddresses, userSettingNames); //calls getsettings
}
/**
* Gets settings for one or more domains.
*
* @param {string[]} domains The domains.
* @param {DomainSettingName[]} settings The settings.
* @param {ExchangeVersion} requestedVersion Requested version of the Exchange service.
* @param {IRefParam<Uri>} autodiscoverUrl The autodiscover URL.
* @return {AutodiscoverService} GetDomainSettingsResponse collection.
*/
private async InternalGetDomainSettings(domains: string[], settings: DomainSettingName[], requestedVersion: ExchangeVersion, autodiscoverUrlRef: IRefParam<Uri>): Promise<GetDomainSettingsResponseCollection> {
// The response to GetDomainSettings can be a redirection. Execute GetDomainSettings until we get back
// a valid response or we've followed too many redirections.
for (let currentHop = 0; currentHop < AutodiscoverService.AutodiscoverMaxRedirections; currentHop++) {
//BUG - Typescript bug, reference for "this" inside multiple layers of IPromise points to global this object;
//(may be not) - this functional is called as delegate under Promise chaining, loss poiters to this.
//var request: GetUserSettingsRequest = new GetUserSettingsRequest(this, autodiscoverUrlRef.refvalue);
var request = new GetDomainSettingsRequest(this, autodiscoverUrlRef.getValue());
request.Domains = domains;
request.Settings = settings;
request.RequestedVersion = requestedVersion;
const response: GetDomainSettingsResponseCollection = await request.Execute();
// Did we get redirected?
if (response.ErrorCode == AutodiscoverErrorCode.RedirectUrl && response.RedirectionUrl != null) {
autodiscoverUrlRef.setValue(response.RedirectionUrl);
}
else {
return response;
}
}
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Maximum number of redirection hops {0} exceeded", AutodiscoverService.AutodiscoverMaxRedirections));
throw new AutodiscoverLocalException(Strings.MaximumRedirectionHopsExceeded);
}
private async InternalGetLegacyUserSettings(emailAddress: string, requestedSettings: UserSettingName[]): Promise<GetUserSettingsResponse> {
throw new Error("Not implemented.");
}
private InternalGetLegacyUserSettingsPrivate<Tsettings>(
emailAddress: string, redirectionEmailAddresses: string[],
currentHop: IRefParam<number>): Tsettings {
throw new Error("Not implemented.");
}
/**
* @internal Calls the SOAP Autodiscover service for user settings for a single SMTP address.
*
* @param {string} smtpAddress SMTP address.
* @param {UserSettingName[]} requestedSettings The requested settings.
* @return {Promise<GetUserSettingsResponse>} [description]
*/
async InternalGetSoapUserSettings(smtpAddress: string, requestedSettings: UserSettingName[]): Promise<GetUserSettingsResponse> {
const smtpAddresses: string[] = [smtpAddress];
const redirectionEmailAddresses: string[] = [smtpAddress.toLowerCase()];
for (let currentHop = 0; currentHop < AutodiscoverService.AutodiscoverMaxRedirections; currentHop++) {
const response: GetUserSettingsResponse = (await this.GetUserSettings(smtpAddresses, requestedSettings)).Responses[0];
// const responses: GetUserSettingsResponseCollection = await this.GetUserSettings(smtpAddresses, requestedSettings);
// const response: GetUserSettingsResponse =responses[0];
switch (response.ErrorCode) {
case AutodiscoverErrorCode.RedirectAddress:
this.TraceMessage(
TraceFlags.AutodiscoverResponse,
StringHelper.Format("Autodiscover service returned redirection email address '{0}'.", response.RedirectTarget));
smtpAddresses.splice(0);
smtpAddresses.push(response.RedirectTarget.toLowerCase());
this.Url = null;
this.Domain = null;
// If this email address was already tried, we may have a loop
// in SCP lookups. Disable consideration of SCP records.
this.ThrowIfDuplicateRedirection(response.RedirectTarget, { getValue: () => redirectionEmailAddresses });
break;
case AutodiscoverErrorCode.RedirectUrl:
this.TraceMessage(
TraceFlags.AutodiscoverResponse,
StringHelper.Format("Autodiscover service returned redirection URL '{0}'.", response.RedirectTarget));
this.Url = this.Credentials.AdjustUrl(new Uri(response.RedirectTarget));
break;
case AutodiscoverErrorCode.NoError:
default:
return response;
}
}
throw new AutodiscoverLocalException(Strings.AutodiscoverCouldNotBeLocated);
}
/**
* Gets settings for one or more users.
*
* @param {string[]} smtpAddresses The SMTP addresses of the users.
* @param {UserSettingName[]} settings The settings.
* @param {ExchangeVersion} requestedVersion Requested version of the Exchange service.
* @param {IRefParam<Uri>} autodiscoverUrl The autodiscover URL.
* @return {Promise<GetUserSettingsResponseCollection>} GetUserSettingsResponse collection.
*/
private async InternalGetUserSettings(smtpAddresses: string[], settings: UserSettingName[],
requestedVersion: ExchangeVersion, autodiscoverUrlRef: IRefParam<Uri>): Promise<GetUserSettingsResponseCollection> {
// The response to GetUserSettings can be a redirection. Execute GetUserSettings until we get back
// a valid response or we've followed too many redirections.
for (let currentHop = 0; currentHop < AutodiscoverService.AutodiscoverMaxRedirections; currentHop++) {
//BUG - Typescript bug, reference for "this" inside multiple layers of IPromise points to global this object;
//(may be not) - this functional is called as delegate under Promise chaining, loss poiters to this.
//var request: GetUserSettingsRequest = new GetUserSettingsRequest(this, autodiscoverUrlRef.refvalue);
var request: GetUserSettingsRequest = new GetUserSettingsRequest(this, autodiscoverUrlRef.getValue());
request.SmtpAddresses = smtpAddresses;
request.Settings = settings;
const response: GetUserSettingsResponseCollection = await request.Execute();
// Did we get redirected?
if (response.ErrorCode == AutodiscoverErrorCode.RedirectUrl && response.RedirectionUrl != null) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Request to {0} returned redirection to {1}", autodiscoverUrlRef.getValue().ToString(), response.RedirectionUrl.ToString()));
// this url need be brought back to the caller.
//
autodiscoverUrlRef.setValue(response.RedirectionUrl);
}
else {
return response;
}
}
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Maximum number of redirection hops {0} exceeded", AutodiscoverService.AutodiscoverMaxRedirections));
throw new AutodiscoverLocalException(Strings.AutodiscoverCouldNotBeLocated);
}
//PrepareHttpWebRequestForUrl(url: Uri): Data.IEwsHttpWebRequest{ throw new Error("AutodiscoverService.ts - PrepareHttpWebRequestForUrl : Not implemented.");}
//ProcessHttpErrorResponse(httpWebResponse: Data.IEwsHttpWebResponse, webException: any): any{ throw new Error("AutodiscoverService.ts - ProcessHttpErrorResponse : Not implemented.");}
ProcessHttpErrorResponse(httpWebResponse: XMLHttpRequest, webException: any): any { /*throw new Error("Not implemented.")*/; }
TraceResponse(response: XMLHttpRequest, memoryStream: any): any {
//todo: implement tracing
//this.ProcessHttpResponseHeaders(TraceFlags.AutodiscoverResponseHttpHeaders, response);
//if (this.TraceEnabled) {
// if (!StringHelper.IsNullOrEmpty(response.ContentType) &&
// (response.ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) ||
// response.ContentType.StartsWith("application/soap", StringComparison.OrdinalIgnoreCase))) {
// this.TraceXml(TraceFlags.AutodiscoverResponse, memoryStream);
// }
// else {
// this.TraceMessage(TraceFlags.AutodiscoverResponse, "Non-textual response");
// }
//}
}
/**
* Tries the get Autodiscover Service endpoint URL.
*
* @param {string} host The host.
* @param {IOutParam<Uri>} url The URL.
* @return {Promise<boolean>} [description]
*/
private async TryGetAutodiscoverEndpointUrl(hostref: string, url: IOutParam<Uri>): Promise<boolean> {
url.outValue = null;
const endpointsOut: IOutParam<AutodiscoverEndpoints> = { outValue: AutodiscoverEndpoints.None };
let host = hostref;
const hostRefParam: IRefParam<string> = { getValue: () => host, setValue: (value) => { host = value; } }
if (await this.TryGetEnabledEndpointsForHost(hostRefParam, endpointsOut)) {
// host = hostref;
url.outValue = new Uri(StringHelper.Format(AutodiscoverService.AutodiscoverSoapHttpsUrl, host));
const endpoints = endpointsOut.outValue;
// Make sure that at least one of the non-legacy endpoints is available.
if (((endpoints & AutodiscoverEndpoints.Soap) != AutodiscoverEndpoints.Soap) &&
((endpoints & AutodiscoverEndpoints.WsSecurity) != AutodiscoverEndpoints.WsSecurity) &&
((endpoints & AutodiscoverEndpoints.WSSecuritySymmetricKey) != AutodiscoverEndpoints.WSSecuritySymmetricKey) &&
((endpoints & AutodiscoverEndpoints.WSSecurityX509Cert) != AutodiscoverEndpoints.WSSecurityX509Cert) &&
((endpoints & AutodiscoverEndpoints.OAuth) != AutodiscoverEndpoints.OAuth)) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("No Autodiscover endpoints are available for host {0}", host));
return false;
}
// If we have WLID credentials, make sure that we have a WS-Security endpoint
if (this.Credentials instanceof WindowsLiveCredentials) {
if ((endpoints & AutodiscoverEndpoints.WsSecurity) != AutodiscoverEndpoints.WsSecurity) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("No Autodiscover WS-Security endpoint is available for host {0}", host));
return false;
}
else {
url.outValue = new Uri(StringHelper.Format(AutodiscoverService.AutodiscoverSoapWsSecurityHttpsUrl, host));
}
}
else if (this.Credentials instanceof PartnerTokenCredentials) {
if ((endpoints & AutodiscoverEndpoints.WSSecuritySymmetricKey) != AutodiscoverEndpoints.WSSecuritySymmetricKey) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("No Autodiscover WS-Security/SymmetricKey endpoint is available for host {0}", host));
return false;
}
else {
url.outValue = new Uri(StringHelper.Format(AutodiscoverService.AutodiscoverSoapWsSecuritySymmetricKeyHttpsUrl, host));
}
}
else if (this.Credentials instanceof X509CertificateCredentials) {
if ((endpoints & AutodiscoverEndpoints.WSSecurityX509Cert) != AutodiscoverEndpoints.WSSecurityX509Cert) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("No Autodiscover WS-Security/X509Cert endpoint is available for host {0}", host));
return false;
}
else {
url.outValue = new Uri(StringHelper.Format(AutodiscoverService.AutodiscoverSoapWsSecurityX509CertHttpsUrl, host));
}
}
else if (this.Credentials instanceof OAuthCredentials) {
// If the credential is OAuthCredentials, no matter whether we have
// the corresponding x-header, we will go with OAuth.
url.outValue = new Uri(StringHelper.Format(AutodiscoverService.AutodiscoverSoapHttpsUrl, host));
}
return true;
}
else {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("No Autodiscover endpoints are available for host {0}", host));
return false;
}
}
/**
* Gets the enabled autodiscover endpoints on a specific host.
*
* @param {host: IRefParam<string>} host The host.
* @param {IOutParam<AutodiscoverEndpoints>} endpoints Endpoints found for host.
*/
private async TryGetEnabledEndpointsForHost(host: IRefParam<string>, endpoints: IOutParam<AutodiscoverEndpoints>): Promise<boolean> {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Determining which endpoints are enabled for host {0}", host.getValue()));
// We may get redirected to another host. And therefore need to limit the number
// of redirections we'll tolerate.
for (let currentHop = 0; currentHop < AutodiscoverService.AutodiscoverMaxRedirections; currentHop++) {
const autoDiscoverUrl: string = StringHelper.Format(AutodiscoverService.AutodiscoverLegacyHttpsUrl, host.getValue());
endpoints.outValue = AutodiscoverEndpoints.None;
var xhrOptions: IXHROptions = {
type: "GET",
url: autoDiscoverUrl,
allowRedirect: false,
};
let response = null;
try {
// try get response, in most cases this will not be a status 200.
response = await this.XHRApi.xhr(xhrOptions);
} catch (responseError) {
if (responseError.status === 0) {
//catch (IOException ex) and return false
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("I/O error: {0}", "unable to connect"));
return false;
}
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Request error: {0}", responseError.message || responseError.statusText || responseError.status));
// assign error to response
response = responseError;
}
if (response != null) {
// check redirect url if any for next hop
var redirectUrl: IOutParam<Uri> = { outValue: null };
if (this.TryGetRedirectionResponse(response, redirectUrl)) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Host returned redirection to host '{0}'", redirectUrl.outValue.Host));
host.setValue(redirectUrl.outValue.Host);
} else {
endpoints.outValue = this.GetEndpointsFromHttpWebResponse(response);
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Host returned enabled endpoint flags: {0}", EnumHelper.ToString(AutodiscoverEndpoints, endpoints.outValue)));
return true;
// hold it for bug reports, if not delete after few version later (0.10)
// if (resperr.status === 401) {
// endpoints.outValue = this.GetEndpointsFromHttpWebResponse(resperr);
// this.TraceMessage(
// TraceFlags.AutodiscoverConfiguration,
// StringHelper.Format("Host returned enabled endpoint flags: {0}", EnumHelper.ToString(AutodiscoverEndpoints, endpoints.outValue)));
// return true;
// } else {
// //catch (WebException ex)
// this.TraceMessage(
// TraceFlags.AutodiscoverConfiguration,
// StringHelper.Format("Request error: {0}, {1}", resperr.status, resperr.statusText));
// }
// return false;
}
} else {
return false;
}
}
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Maximum number of redirection hops {0} exceeded", AutodiscoverService.AutodiscoverMaxRedirections));
throw new AutodiscoverLocalException(Strings.MaximumRedirectionHopsExceeded);
}
ThrowIfDuplicateRedirection(emailAddress: string, redirectionEmailAddresses: IRefParam<string[]>): void {
// SMTP addresses are case-insensitive so entries are converted to lower-case.
emailAddress = emailAddress.toLowerCase();
if (redirectionEmailAddresses.getValue().includes(emailAddress)) {
//this.EnableScpLookup = false;
throw new AutodiscoverLocalException("Detected redirection loop, Redirection address already tried");
}
else {
var oldcount = redirectionEmailAddresses.getValue().length;
redirectionEmailAddresses.getValue().push(emailAddress);
if (oldcount === redirectionEmailAddresses.getValue().length) {
throw new Error("AutodiscoverService.ts - error in ref param logic, need to fix array type getter");
}
EwsLogging.Assert(false,
"AutodiscoverService.ts - ThrowIfDuplicateRedirection",
"AutodiscoverService.ts - array getter worked:), remove this message and throw statement");
}
}
//TryGetPartnerAccess(targetTenantDomain: string, partnerAccessCredentials: any, targetTenantAutodiscoverUrl: any): boolean{ throw new Error("AutodiscoverService.ts - TryGetPartnerAccess : Not implemented.");}
/**
* Tries the get redirection response.
*
* @param {XMLHttpRequest} response The response.
* @param {IOutParam<Uri>} redirectUrl The redirect URL.
* @return {boolean} True if a valid redirection URL was found.
*/
private TryGetRedirectionResponse(response: XMLHttpRequest, redirectUrl: IOutParam<Uri>): boolean {
redirectUrl.outValue = null;
if (AutodiscoverRequest.IsRedirectionResponse(response)) {
// Get the redirect location and verify that it's valid.
const location = response.getResponseHeader("Location"); // HttpResponseHeader.Location
if (!StringHelper.IsNullOrEmpty(location)) {
try {
redirectUrl.outValue = new Uri(location);
// Check if URL is SSL and that the path matches.
const match = AutodiscoverService.LegacyPathRegex.test(redirectUrl.outValue.AbsoluteUri);
if ((redirectUrl.outValue.Scheme == Uri.UriSchemeHttps) &&
match) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Redirection URL found: '{0}'", redirectUrl.outValue));
return true;
}
}
catch (UriFormatException) {
this.TraceMessage(
TraceFlags.AutodiscoverConfiguration,
StringHelper.Format("Invalid redirection URL was returned: '{0}'", location));
return false;
}
}
}
return false;
}
//TryLastChanceHostRedirection(emailAddress: string, redirectionUrl: string, settings: any): boolean{ throw new Error("AutodiscoverService.ts - TryLastChanceHostRedirection : Not implemented.");}
//WriteLegacyAutodiscoverRequest(emailAddress: string, settings: ConfigurationSettingsBase, writer: any): any{ throw new Error("AutodiscoverService.ts - WriteLegacyAutodiscoverRequest : Not implemented.");}
}
//ref: converted to delegate type interface
export interface GetSettingsMethod<TGetSettingsResponseCollection, TSettingName> {
(smtpAddresses: string[], settings: TSettingName[], requestedVersion: ExchangeVersion, autodiscoverUrl: IRefParam<Uri>): Promise<TGetSettingsResponseCollection>
}
//class GetSettingsMethod<TGetSettingsResponseCollection, TSettingName> extends System.MulticastDelegate {
// BeginInvoke(smtpAddresses: System.Collections.Generic.List<string>, settings: System.Collections.Generic.List<T>, requestedVersion: Data.ExchangeVersion, autodiscoverUrl: any, callback: System.AsyncCallback, object: any): System.IAsyncResult { throw new Error("AutodiscoverService.ts - BeginInvoke : Not implemented."); }
// EndInvoke(autodiscoverUrl: any, result: System.IAsyncResult): TGetSettingsResponseCollection { throw new Error("AutodiscoverService.ts - EndInvoke : Not implemented."); }
// Invoke(smtpAddresses: System.Collections.Generic.List<string>, settings: System.Collections.Generic.List<T>, requestedVersion: Data.ExchangeVersion, autodiscoverUrl: any): TGetSettingsResponseCollection { throw new Error("AutodiscoverService.ts - Invoke : Not implemented."); }
//}
// delete - function getAutodiscoverConstructorSuperParameters(
// domainUrlServiceOrVersion: string | Uri | ExchangeServiceBase | ExchangeVersion = null,
// domainOrVersion: string | ExchangeVersion = null,
// version: ExchangeVersion = ExchangeVersion.Exchange2010
// ) {
// const service: ExchangeServiceBase = domainUrlServiceOrVersion instanceof ExchangeServiceBase ? domainUrlServiceOrVersion : null;
// let serviceVersion: ExchangeVersion = version;
// if(service) {
// serviceVersion = service.RequestedServerVersion;
// }
// if(typeof domainOrVersion === 'number') {
// serviceVersion = domainOrVersion;
// }
// return { service, version };
// } | the_stack |
import {TemplateAnalyzer} from '../template-analyzer';
import {parse} from 'espree';
import * as ESTree from 'estree';
import {SourceCode} from 'eslint';
import {expect} from 'chai';
import * as parse5 from 'parse5-htmlparser2-tree-adapter';
const parseOptions = {
ecmaVersion: 6,
range: true,
loc: true,
comments: true
};
interface ParsedTemplate {
node: ESTree.TaggedTemplateExpression;
analyzer: TemplateAnalyzer;
source: SourceCode;
}
/**
* Parses a template into an AST, analyzer instance and ESLint source code
* @param {string} code Code to parse
* @return {*}
*/
function parseTemplate(code: string): ParsedTemplate {
const ast = parse(code, parseOptions) as ESTree.Program;
const source = new SourceCode({
text: code,
ast: {
...ast,
tokens: [],
comments: ast.comments ?? [],
loc: ast.loc!,
range: ast.range!
}
});
const node = ((ast as ESTree.Program).body[0] as ESTree.ExpressionStatement)
.expression as ESTree.TaggedTemplateExpression;
const analyzer = new TemplateAnalyzer(node);
return {node, analyzer, source};
}
describe('TemplateAnalyzer', () => {
let result: ParsedTemplate;
beforeEach(() => {
result = parseTemplate(`
html\`<div title="party"></div>\`;
`);
});
describe('getAttributeValue', () => {
it('should return literals as-is', () => {
result.analyzer.traverse({
enterElement(element) {
expect(element.attribs['title']).to.equal('party');
expect(
result.analyzer.getAttributeValue(element, 'title', result.source)
).to.equal('party');
}
});
});
it('should return expressions', () => {
result = parseTemplate(`
html\`<div title=$\{808\}></div>\`;
`);
result.analyzer.traverse({
enterElement(element) {
expect(element.attribs['title']).to.equal('{{__Q:0__}}');
const expr = result.analyzer.getAttributeValue(
element,
'title',
result.source
) as ESTree.Literal;
expect(expr.type).to.equal('Literal');
expect(expr.value).to.equal(808);
}
});
});
it('should return expression if mixed', () => {
result = parseTemplate(`
html\`<div title="foo $\{808\}"></div>\`;
`);
result.analyzer.traverse({
enterElement(element) {
expect(element.attribs['title']).to.equal('foo {{__Q:0__}}');
const expr = result.analyzer.getAttributeValue(
element,
'title',
result.source
) as ESTree.Literal;
expect(expr.type).to.equal('Literal');
expect(expr.value).to.equal(808);
}
});
});
it('should return first expression if multiple', () => {
result = parseTemplate(`
html\`<div title="$\{303\} $\{808\}"></div>\`;
`);
result.analyzer.traverse({
enterElement(element) {
expect(element.attribs['title']).to.equal('{{__Q:0__}} {{__Q:1__}}');
const expr = result.analyzer.getAttributeValue(
element,
'title',
result.source
) as ESTree.Literal;
expect(expr.type).to.equal('Literal');
expect(expr.value).to.equal(303);
}
});
});
it('should handle non-existent attributes', () => {
result = parseTemplate(`
html\`<div></div>\`;
`);
result.analyzer.traverse({
enterElement(element) {
const expr = result.analyzer.getAttributeValue(
element,
'idontexist',
result.source
);
expect(expr).to.equal(null);
}
});
});
it('should return falsy expressions', () => {
result = parseTemplate(`
html\`<div title=$\{null\}></div>\`;
`);
result.analyzer.traverse({
enterElement(element) {
const expr = result.analyzer.getAttributeValue(
element,
'title',
result.source
) as ESTree.Literal;
expect(expr.type).to.equal('Literal');
expect(expr.value).to.equal(null);
}
});
});
});
describe('traverse', () => {
beforeEach(() => {
result = parseTemplate(`
html\`
<div title="jeden"></div>
<div title="dwa"></div>
Text
<!-- Comment -->
\`;
`);
});
describe('enter', () => {
it('should be called for every node', () => {
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enter: (node) => {
if (parse5.isTextNode(node) && node.data.trim() === '') {
return;
}
nodes.push(node);
}
});
expect(nodes.length).to.equal(5);
expect(nodes[0].type).to.equal('root');
expect(nodes[1].type).to.equal('tag');
expect(nodes[2].type).to.equal('tag');
expect(nodes[3].type).to.equal('text');
expect(nodes[4].type).to.equal('comment');
});
});
describe('enterDocumentFragment', () => {
it('should be called for the root fragment', () => {
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enterDocumentFragment: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(1);
expect(nodes[0].type).to.equal('root');
});
});
describe('enterCommentNode', () => {
it('should be called for comment nodes', () => {
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enterCommentNode: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(1);
expect(nodes[0].type).to.equal('comment');
});
});
describe('enterTextNode', () => {
it('should be called for text nodes', () => {
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enterTextNode: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(4);
expect(nodes[0].type).to.equal('text');
expect(nodes[1].type).to.equal('text');
expect(nodes[2].type).to.equal('text');
expect(nodes[3].type).to.equal('text');
});
});
describe('enterElement', () => {
it('should be called for elements', () => {
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enterElement: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(2);
expect(nodes[0].type).to.equal('tag');
expect(nodes[1].type).to.equal('tag');
});
});
describe('exit', () => {
it('should be called for every node', () => {
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
exit: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(8);
expect(nodes[0].type).to.equal('text');
expect(nodes[1].type).to.equal('tag');
expect(nodes[2].type).to.equal('text');
expect(nodes[3].type).to.equal('tag');
expect(nodes[4].type).to.equal('text');
expect(nodes[5].type).to.equal('comment');
expect(nodes[6].type).to.equal('text');
expect(nodes[7].type).to.equal('root');
});
});
it('should visit children', () => {
result = parseTemplate(`
html\`
<div title="jeden">
<div title="dwa"></div>
</div>
\`;
`);
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enter: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(7);
expect(nodes[0].type).to.equal('root');
expect(nodes[1].type).to.equal('text');
expect(nodes[2].type).to.equal('tag');
expect((nodes[2] as parse5.Element).attribs['title']).to.equal('jeden');
expect(nodes[3].type).to.equal('text');
expect(nodes[4].type).to.equal('tag');
expect((nodes[4] as parse5.Element).attribs['title']).to.equal('dwa');
expect(nodes[5].type).to.equal('text');
expect(nodes[6].type).to.equal('text');
});
});
it('should handle HTML documents', () => {
result = parseTemplate(`
html\`<html><body>Foo</body></html>\`;
`);
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enter: (node) => {
nodes.push(node);
}
});
const body = nodes[3] as parse5.Element;
expect(nodes.length).to.equal(5);
expect(nodes[0].type).to.equal('root');
expect(nodes[1].type).to.equal('tag');
expect((nodes[1] as parse5.Element).name).to.equal('html');
expect(nodes[2].type).to.equal('tag');
expect((nodes[2] as parse5.Element).name).to.equal('head');
expect(nodes[3].type).to.equal('tag');
expect((nodes[3] as parse5.Element).name).to.equal('body');
expect(nodes[4].type).to.equal('text');
expect(body.sourceCodeLocation).to.deep.equal({
startLine: 1,
startCol: 7,
startOffset: 6,
endLine: 1,
endCol: 30,
endOffset: 29,
startTag: {
startLine: 1,
startCol: 7,
startOffset: 6,
endLine: 1,
endCol: 13,
endOffset: 12
},
endTag: {
startLine: 1,
startCol: 16,
startOffset: 15,
endLine: 1,
endCol: 23,
endOffset: 22
}
});
});
it('should handle uppercase HTML tags', () => {
result = parseTemplate(`
html\`<HTML><body>Foo</body></HTML>\`;
`);
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enter: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(5);
expect(nodes[0].type).to.equal('root');
expect(nodes[1].type).to.equal('tag');
expect((nodes[1] as parse5.Element).name).to.equal('html');
});
it('should have correct position for normalised attributes', () => {
result = parseTemplate(`
html\`<div hidden></div>\`;
`);
const nodes: parse5.Node[] = [];
result.analyzer.traverse({
enter: (node) => {
nodes.push(node);
}
});
expect(nodes.length).to.equal(2);
expect(nodes[0].type).to.equal('root');
expect(nodes[1].type).to.equal('tag');
const div = nodes[1] as parse5.Element;
const attrLoc = div.sourceCodeLocation!.attrs['hidden'];
expect(attrLoc).to.deep.equal({
startLine: 1,
startCol: 6,
startOffset: 5,
endLine: 1,
endCol: 12,
endOffset: 11
});
});
}); | the_stack |
import { InMemoryDocumentSessionOperations } from "../InMemoryDocumentSessionOperations";
import { throwError } from "../../../Exceptions";
import { CONSTANTS } from "../../../Constants";
import { SessionAfterSaveChangesEventArgs } from "../SessionEvents";
import { DocumentInfo } from "../DocumentInfo";
import { ActionsToRunOnSuccess, CommandType } from "../../Commands/CommandData";
import { CaseInsensitiveKeysMap } from "../../../Primitives/CaseInsensitiveKeysMap";
import { PatchStatus } from "../../Operations/PatchStatus";
import { CounterTracking } from "../CounterInternalTypes";
import { TypeUtil } from "../../../Utility/TypeUtil";
import { BatchCommandResult } from "./BatchCommandResult";
import { ObjectUtil } from "../../../Utility/ObjectUtil";
import { ClusterWideBatchCommand } from "../../Commands/Batches/ClusterWideBatchCommand";
import { SingleNodeBatchCommand } from "../../Commands/Batches/SingleNodeBatchCommand";
export class BatchOperation {
private readonly _session: InMemoryDocumentSessionOperations;
public constructor(session: InMemoryDocumentSessionOperations) {
this._session = session;
}
private _entities: object[];
private _sessionCommandsCount: number;
private _allCommandsCount: number;
private _onSuccessfulRequest: ActionsToRunOnSuccess;
private _modifications: Map<string, DocumentInfo>;
public createRequest(): SingleNodeBatchCommand {
const result = this._session.prepareForSaveChanges();
this._onSuccessfulRequest = result.onSuccess;
this._sessionCommandsCount = result.sessionCommands.length;
result.sessionCommands.push(...result.deferredCommands);
this._session.validateClusterTransaction(result);
this._allCommandsCount = result.sessionCommands.length;
if (this._allCommandsCount === 0) {
return null;
}
this._session.incrementRequestCount();
this._entities = result.entities;
if (this._session.transactionMode === "ClusterWide") {
return new ClusterWideBatchCommand(
this._session.conventions,
result.sessionCommands,
result.options,
this._session.disableAtomicDocumentWritesInClusterWideTransaction
);
}
return new SingleNodeBatchCommand(this._session.conventions, result.sessionCommands, result.options);
}
private static _throwOnNullResults() {
throwError("InvalidOperationException",
"Received empty response from the server. This is not supposed to happen and is likely a bug.");
}
public setResult(result: BatchCommandResult): void {
if (!result.results) {
BatchOperation._throwOnNullResults();
return;
}
this._onSuccessfulRequest.clearSessionStateAfterSuccessfulSaveChanges();
if (this._session.transactionMode === "ClusterWide") {
if (result.transactionIndex <= 0) {
throwError(
"ClientVersionMismatchException",
"Cluster transaction was send to a node that is not supporting it. "
+ "So it was executed ONLY on the requested node on "
+ this._session.requestExecutor.getUrl());
}
}
const results = result.results;
for (let i = 0; i < this._sessionCommandsCount; i++) {
const batchResult = results[i];
if (!batchResult) {
continue;
}
const type = getCommandType(batchResult);
switch (type) {
case "PUT":
this._handlePut(i, batchResult, false);
break;
case "ForceRevisionCreation":
this._handleForceRevisionCreation(batchResult);
break;
case "DELETE":
this._handleDelete(batchResult);
break;
case "CompareExchangePUT":
this._handleCompareExchangePut(batchResult);
break;
case "CompareExchangeDELETE":
this._handleCompareExchangeDelete(batchResult);
break;
default:
throwError("InvalidOperationException", `Command '${type}' is not supported.`);
}
}
for (let i = this._sessionCommandsCount; i < this._allCommandsCount; i++) {
const batchResult = result.results[i];
if (!batchResult) {
continue;
}
const type = getCommandType(batchResult);
switch (type) {
case "PUT":
this._handlePut(i, batchResult, true);
break;
case "DELETE":
this._handleDelete(batchResult);
break;
case "PATCH":
this._handlePatch(batchResult);
break;
case "AttachmentPUT":
this._handleAttachmentPut(batchResult);
break;
case "AttachmentDELETE":
this._handleAttachmentDelete(batchResult);
break;
case "AttachmentMOVE":
this._handleAttachmentMove(batchResult);
break;
case "AttachmentCOPY":
this._handleAttachmentCopy(batchResult);
break;
case "CompareExchangePUT":
case "CompareExchangeDELETE":
case "ForceRevisionCreation":
break;
case "Counters":
this._handleCounters(batchResult);
break;
case "TimeSeries":
//TODO: RavenDB-13474 add to time series cache
break;
case "TimeSeriesCopy":
break;
case "BatchPATCH":
break;
default:
throwError("InvalidOperationException", `Command '${type}' is not supported.`);
}
}
this._finalizeResults();
}
private _finalizeResults(): void {
if (!this._modifications) {
return;
}
for (const [ id, docInfo ] of this._modifications.entries()) {
this._applyMetadataModifications(id, docInfo);
}
}
private _applyMetadataModifications(id: string, documentInfo: DocumentInfo): void {
documentInfo.metadataInstance = null;
documentInfo.metadata = ObjectUtil.deepLiteralClone(documentInfo.metadata);
documentInfo.metadata["@change-vector"] = documentInfo.changeVector;
const documentCopy = ObjectUtil.deepLiteralClone(documentInfo.document);
documentCopy[CONSTANTS.Documents.Metadata.KEY] = documentInfo.metadata;
documentInfo.document = documentCopy;
}
private _getOrAddModifications(
id: string, documentInfo: DocumentInfo, applyModifications: boolean): DocumentInfo {
if (!this._modifications) {
this._modifications = CaseInsensitiveKeysMap.create<DocumentInfo>();
}
let modifiedDocumentInfo = this._modifications.get(id);
if (modifiedDocumentInfo) {
if (applyModifications) {
this._applyMetadataModifications(id, modifiedDocumentInfo);
}
} else {
modifiedDocumentInfo = documentInfo;
this._modifications.set(id, documentInfo);
}
return modifiedDocumentInfo;
}
private _handleCompareExchangePut(batchResult: object) {
this._handleCompareExchangeInternal("CompareExchangePUT", batchResult);
}
private _handleCompareExchangeDelete(batchResult: object) {
this._handleCompareExchangeInternal("CompareExchangeDELETE", batchResult);
}
private _handleCompareExchangeInternal(commandType: CommandType, batchResult: any) {
const key = batchResult.key;
if (!key) {
BatchOperation._throwMissingField(commandType, "Key");
}
const index = batchResult.index;
if (TypeUtil.isNullOrUndefined(index)) {
BatchOperation._throwMissingField(commandType, "Index");
}
const clusterSession = this._session.clusterSession;
clusterSession.updateState(key, index);
}
private _handleAttachmentCopy(batchResult: object): void {
this._handleAttachmentPutInternal(batchResult, "AttachmentCOPY", "id", "name", "documentChangeVector");
}
private _handleAttachmentMove(batchResult: object): void {
this._handleAttachmentDeleteInternal(batchResult, "AttachmentMOVE", "id", "name", "documentChangeVector");
this._handleAttachmentPutInternal(batchResult, "AttachmentMOVE", "destinationId", "destinationName", "documentChangeVector");
}
private _handleAttachmentDelete(batchResult: object): void {
this._handleAttachmentDeleteInternal(
batchResult, "AttachmentDELETE", CONSTANTS.Documents.Metadata.ID, "name", "documentChangeVector");
}
private _handleAttachmentDeleteInternal(
batchResult: object, type: CommandType, idFieldName: string, attachmentNameFieldName: string, documentChangeVectorFieldName: string) {
const id = BatchOperation._getStringField(batchResult, type, idFieldName);
const sessionDocumentInfo = this._session.documentsById.getValue(id);
if (!sessionDocumentInfo) {
return;
}
const documentInfo = this._getOrAddModifications(id, sessionDocumentInfo, true);
const documentChangeVector = BatchOperation._getStringField(batchResult, type, documentChangeVectorFieldName, false);
if (documentChangeVector) {
documentInfo.changeVector = documentChangeVector;
}
const attachmentsJson = documentInfo.metadata["@attachments"];
if (!attachmentsJson || !Object.keys(attachmentsJson).length) {
return;
}
const name = BatchOperation._getStringField(batchResult, type, attachmentNameFieldName);
const attachments = [];
documentInfo.metadata["@attachments"] = attachments;
for (const attachment of attachmentsJson) {
const attachmentName = BatchOperation._getStringField(attachment, type, "name");
if (attachmentName === name) {
continue;
}
attachments.push(attachment);
}
}
private _handleAttachmentPut(batchResult: object): void {
this._handleAttachmentPutInternal(
batchResult, "AttachmentPUT", "id", "name", "documentChangeVector");
}
private _handleAttachmentPutInternal(
batchResult: object, type: CommandType, idFieldName: string, attachmentNameFieldName: string, documentChangeVectorFieldName: string): void {
const id = BatchOperation._getStringField(batchResult, type, idFieldName);
const sessionDocumentInfo = this._session.documentsById.getValue(id);
if (!sessionDocumentInfo) {
return;
}
const documentInfo = this._getOrAddModifications(id, sessionDocumentInfo, false);
const documentChangeVector = BatchOperation._getStringField(batchResult, type, documentChangeVectorFieldName, false);
if (documentChangeVector) {
documentInfo.changeVector = documentChangeVector;
}
let attachments = documentInfo.metadata["@attachments"];
if (!attachments) {
attachments = [];
documentInfo.metadata["@attachments"] = attachments;
}
attachments.push({
changeVector: BatchOperation._getStringField(batchResult, type, "changeVector"),
contentType: BatchOperation._getStringField(batchResult, type, "contentType"),
hash: BatchOperation._getStringField(batchResult, type, "hash"),
name: BatchOperation._getStringField(batchResult, type, "name"),
size: BatchOperation._getNumberField(batchResult, type, "size")
});
}
private _handlePatch(batchResult: object): void {
const status = batchResult["patchStatus"] as PatchStatus;
if (!status) {
BatchOperation._throwMissingField("PATCH", "PatchStatus");
}
switch (status) {
case "Created":
case "Patched":
const document = batchResult["modifiedDocument"];
if (!document) {
return;
}
const id = BatchOperation._getStringField(batchResult, "PUT", "id");
const sessionDocumentInfo = this._session.documentsById.getValue(id);
if (!sessionDocumentInfo) {
return;
}
const documentInfo = this._getOrAddModifications(id, sessionDocumentInfo, true);
const changeVector = BatchOperation._getStringField(batchResult, "PATCH", "changeVector");
const lastModified = BatchOperation._getStringField(batchResult, "PATCH", "lastModified");
documentInfo.changeVector = changeVector;
documentInfo.metadata[CONSTANTS.Documents.Metadata.ID] = id;
documentInfo.metadata[CONSTANTS.Documents.Metadata.CHANGE_VECTOR] = changeVector;
documentInfo.metadata[CONSTANTS.Documents.Metadata.LAST_MODIFIED] = lastModified;
documentInfo.document = document;
this._applyMetadataModifications(id, documentInfo);
if (documentInfo.entity) {
this._session.entityToJson.populateEntity(
documentInfo.entity, id, documentInfo.document);
const afterSaveChangesEventArgs =
new SessionAfterSaveChangesEventArgs(
this._session, documentInfo.id, documentInfo.entity);
this._session.emit("afterSaveChanges", afterSaveChangesEventArgs);
}
break;
}
}
private _handleDelete(batchResult: object) {
this._handleDeleteInternal(batchResult, "DELETE");
}
private _handleDeleteInternal(batchResult: object, type: CommandType): void {
const id = BatchOperation._getStringField(batchResult, type, "id");
const documentInfo = this._session.documentsById.getValue(id);
if (!documentInfo) {
return;
}
this._session.documentsById.remove(id);
if (documentInfo.entity) {
this._session.documentsByEntity.remove(documentInfo.entity);
this._session.deletedEntities.remove(documentInfo.entity);
}
}
private _handleForceRevisionCreation(batchResult: object) {
// When forcing a revision for a document that does Not have any revisions yet then the HasRevisions flag is added to the document.
// In this case we need to update the tracked entities in the session with the document new change-vector.
if (!BatchOperation._getBooleanField(batchResult, "ForceRevisionCreation", "revisionCreated")) {
// no forced revision was created...nothing to update.
return;
}
const id = BatchOperation._getStringField(batchResult, "ForceRevisionCreation", CONSTANTS.Documents.Metadata.ID);
const changeVector = BatchOperation._getStringField(batchResult, "ForceRevisionCreation", CONSTANTS.Documents.Metadata.CHANGE_VECTOR);
const documentInfo = this._session.documentsById.getValue(id);
if (!documentInfo) {
return;
}
documentInfo.changeVector = changeVector;
this._handleMetadataModifications(documentInfo, batchResult, id, changeVector);
const afterSaveChangesEventArgs = new SessionAfterSaveChangesEventArgs(this._session, documentInfo.id, documentInfo.entity);
this._session.emit("afterSaveChanges", afterSaveChangesEventArgs);
}
private _handlePut(index: number, batchResult: object, isDeferred: boolean): void {
let entity = null;
let documentInfo = null;
if (!isDeferred) {
entity = this._entities[index];
documentInfo = this._session.documentsByEntity.get(entity);
if (!documentInfo) {
return;
}
}
const id = BatchOperation._getStringField(batchResult, "PUT", CONSTANTS.Documents.Metadata.ID);
const changeVector = BatchOperation._getStringField(
batchResult, "PUT", CONSTANTS.Documents.Metadata.CHANGE_VECTOR);
if (isDeferred) {
const sessionDocumentInfo = this._session.documentsById.getValue(id);
if (!sessionDocumentInfo) {
return;
}
documentInfo = this._getOrAddModifications(id, sessionDocumentInfo, true);
entity = documentInfo.entity;
}
this._handleMetadataModifications(documentInfo, batchResult, id, changeVector);
this._session.documentsById.add(documentInfo);
if (entity) {
this._session.generateEntityIdOnTheClient.trySetIdentity(entity, id);
}
const afterSaveChangesEventArgs = new SessionAfterSaveChangesEventArgs(
this._session, documentInfo.id, documentInfo.entity);
this._session.emit("afterSaveChanges", afterSaveChangesEventArgs);
}
private _handleMetadataModifications(documentInfo: DocumentInfo, batchResult: object, id: string, changeVector: string) {
for (const propertyName of Object.keys(batchResult)) {
if (propertyName === "type") {
continue;
}
documentInfo.metadata[propertyName] = batchResult[propertyName];
}
documentInfo.id = id;
documentInfo.changeVector = changeVector;
this._applyMetadataModifications(id, documentInfo);
}
private _handleCounters(batchResult: object): void {
const docId = BatchOperation._getStringField(batchResult, "Counters", "id");
const countersDetail = batchResult["countersDetail"];
if (!countersDetail) {
BatchOperation._throwMissingField("Counters", "CountersDetail");
}
const counters = countersDetail["counters"] as object[];
if (!counters) {
BatchOperation._throwMissingField("Counters", "Counters");
}
let cache = this._session.countersByDocId.get(docId);
if (!cache) {
cache = {
gotAll: false,
data: CaseInsensitiveKeysMap.create<number>()
} as CounterTracking;
this._session.countersByDocId.set(docId, cache);
}
const changeVector = BatchOperation._getStringField(batchResult, "Counters", "documentChangeVector", false);
if (changeVector) {
const documentInfo = this._session.documentsById.getValue(docId);
if (documentInfo) {
documentInfo.changeVector = changeVector;
}
}
for (const counter of counters) {
const name = counter["counterName"];
const value = counter["totalValue"];
if (name && value) {
cache.data.set(name, value);
}
}
}
private static _getStringField(json: object, type: CommandType, fieldName: string, throwOnMissing: boolean = true): string {
if ((!(fieldName in json) || TypeUtil.isNullOrUndefined(json[fieldName])) && throwOnMissing) {
BatchOperation._throwMissingField(type, fieldName);
}
const jsonNode = json[fieldName];
if (jsonNode && !TypeUtil.isString(jsonNode)) {
throwError("InvalidOperationException", `Expected response field ${fieldName} to be a string.`);
}
return jsonNode;
}
private static _getNumberField(json: object, type: CommandType, fieldName: string): number {
if (!(fieldName in json)) {
BatchOperation._throwMissingField(type, fieldName);
}
const jsonNode = json[fieldName];
return jsonNode;
}
private static _getBooleanField(json: object, type: CommandType, fieldName: string): boolean {
if (!(fieldName in json)) {
BatchOperation._throwMissingField(type, fieldName);
}
const jsonNode = json[fieldName];
return jsonNode;
}
private static _throwMissingField(type: CommandType, fieldName: string): void {
throwError("InvalidOperationException", type + " response is invalid. Field '" + fieldName + "' is missing.");
}
}
function getCommandType(batchResult: object): CommandType {
return batchResult["type"] || "None";
} | the_stack |
import test from 'japa'
import { DateTime } from 'luxon'
import supertest from 'supertest'
import { createServer } from 'http'
import { ApplicationContract } from '@ioc:Adonis/Core/Application'
import { OpaqueToken } from '../../src/Tokens/OpaqueToken'
import { ProviderToken } from '../../src/Tokens/ProviderToken'
import {
setup,
reset,
cleanup,
getUserModel,
setupApplication,
getLucidProvider,
getApiTokensGuard,
getTokensDbProvider,
getLucidProviderConfig,
} from '../../test-helpers'
let app: ApplicationContract
test.group('OAT Guard | Verify Credentials', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
app.container.use('Adonis/Core/Event')['clearAllListeners']()
})
test('raise exception when unable to lookup user', async (assert) => {
assert.plan(1)
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await apiTokensGuard.verifyCredentials('virk@adonisjs.com', 'password')
} catch (error) {
assert.deepEqual(error.message, 'E_INVALID_AUTH_UID: User not found')
}
})
test('raise exception when password is incorrect', async (assert) => {
assert.plan(1)
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await apiTokensGuard.verifyCredentials('virk@adonisjs.com', 'password')
} catch (error) {
assert.deepEqual(error.message, 'E_INVALID_AUTH_PASSWORD: Password mis-match')
}
})
test('return user when able to verify credentials', async (assert) => {
assert.plan(1)
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
const user = await apiTokensGuard.verifyCredentials('virk@adonisjs.com', 'secret')
assert.instanceOf(user, User)
})
})
test.group('OAT Guard | attempt', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
app.container.use('Adonis/Core/Event')['clearAllListeners']()
})
test('return token with user from the attempt call', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container.use('Adonis/Core/Event').once('adonis:api:login', ({ name, user, token }) => {
assert.equal(name, 'api')
assert.instanceOf(user, User)
assert.instanceOf(token, OpaqueToken)
})
const token = await apiTokensGuard.attempt('virk@adonisjs.com', 'secret')
const tokens = await app.container.use('Adonis/Lucid/Database').query().from('api_tokens')
/**
* Assert correct token is generated and persisted to the db
*/
assert.equal(token.type, 'bearer')
assert.instanceOf(token.user, User)
assert.isUndefined(token.expiresAt)
assert.lengthOf(tokens, 1)
assert.isNull(tokens[0].expires_at)
})
test('define custom expiry', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:login', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, OpaqueToken)
})
const token = await apiTokensGuard.attempt('virk@adonisjs.com', 'secret', {
expiresIn: '3mins',
})
const tokens = await app.container.use('Adonis/Lucid/Database').query().from('api_tokens')
/**
* Assert correct token is generated and persisted to the db
*/
assert.lengthOf(tokens, 1)
assert.isBelow(token.expiresAt.diff(DateTime.local(), 'minutes').minutes, 4)
assert.isBelow(
DateTime.fromSQL(tokens[0].expires_at).diff(DateTime.local(), 'minutes').minutes,
4
)
})
test('define custom name for the token', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:login', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, OpaqueToken)
})
const token = await apiTokensGuard.attempt('virk@adonisjs.com', 'secret', {
name: 'Android token',
})
const tokens = await app.container
.use('Adonis/Lucid/Database')
.query()
.from('api_tokens')
.where('user_id', user.id)
/**
* Assert correct token is generated and persisted to the db
*/
assert.lengthOf(tokens, 1)
assert.equal(token.name, 'Android token')
assert.equal(tokens[0].name, 'Android token')
})
test('define meta data to be persisted inside the database', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:login', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, OpaqueToken)
})
const token = await apiTokensGuard.attempt('virk@adonisjs.com', 'secret', {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const tokens = await app.container
.use('Adonis/Lucid/Database')
.query()
.from('api_tokens')
.where('user_id', user.id)
/**
* Assert correct token is generated and persisted to the db
*/
assert.lengthOf(tokens, 1)
assert.equal(tokens[0].device_name, 'Android')
assert.equal(tokens[0].ip_address, '192.168.1.1')
assert.deepEqual(token.meta, { device_name: 'Android', ip_address: '192.168.1.1' })
})
})
test.group('OAT Guard | login', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
app.container.use('Adonis/Core/Event')['clearAllListeners']()
})
test('login using user instance', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:login', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, OpaqueToken)
})
const token = await apiTokensGuard.login(user, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const tokens = await app.container
.use('Adonis/Lucid/Database')
.query()
.from('api_tokens')
.where('user_id', user.id)
/**
* Assert correct token is generated and persisted to the db
*/
assert.lengthOf(tokens, 1)
assert.equal(tokens[0].device_name, 'Android')
assert.equal(tokens[0].ip_address, '192.168.1.1')
assert.deepEqual(token.meta, { device_name: 'Android', ip_address: '192.168.1.1' })
})
test('use custom token type', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database')),
{
driver: 'database',
table: 'api_tokens',
type: 'access_token',
}
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:login', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, OpaqueToken)
assert.equal(token.type, 'bearer')
})
const token = await apiTokensGuard.login(user, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const tokens = await app.container
.use('Adonis/Lucid/Database')
.query()
.from('api_tokens')
.where('user_id', user.id)
/**
* Assert correct token is generated and persisted to the db
*/
assert.lengthOf(tokens, 1)
assert.equal(tokens[0].device_name, 'Android')
assert.equal(tokens[0].ip_address, '192.168.1.1')
assert.equal(tokens[0].type, 'access_token')
assert.deepEqual(token.meta, { device_name: 'Android', ip_address: '192.168.1.1' })
})
})
test.group('OAT Guard | loginViaId', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
app.container.use('Adonis/Core/Event')['clearAllListeners']()
})
test('login using user id', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:login', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, OpaqueToken)
})
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const tokens = await app.container
.use('Adonis/Lucid/Database')
.query()
.from('api_tokens')
.where('user_id', user.id)
/**
* Assert correct token is generated and persisted to the db
*/
assert.lengthOf(tokens, 1)
assert.equal(tokens[0].device_name, 'Android')
assert.equal(tokens[0].ip_address, '192.168.1.1')
assert.deepEqual(token.meta, { device_name: 'Android', ip_address: '192.168.1.1' })
})
})
test.group('OAT Guard | authenticate', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
app.container.use('Adonis/Core/Event')['clearAllListeners']()
})
test('authenticate request by reading the bearer token', async (assert) => {
assert.plan(6)
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:authenticate', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, ProviderToken)
})
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
ctx.response.status(500).send(error)
}
ctx.response.finish()
})
const { body } = await supertest(server)
.get('/')
.set('Authorization', `${token.type} ${token.token}`)
.expect(200)
assert.equal(body.name, 'Opaque Access Token')
assert.equal(body.type, 'opaque_token')
assert.exists(body.tokenHash)
})
test('raise error when Authorization header is missing', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
error.handle(error, { ...ctx, auth: { use: () => oat1 } as any })
}
ctx.response.finish()
})
const { body } = await supertest(server).get('/').set('Accept', 'application/json').expect(401)
assert.deepEqual(body, {
errors: [{ message: 'E_INVALID_API_TOKEN: Invalid API token' }],
})
})
test('raise error when token is malformed', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
error.handle(error, { ...ctx, auth: { use: () => oat1 } as any })
}
ctx.response.finish()
})
const { body } = await supertest(server)
.get('/')
.set('Accept', 'application/json')
.set('Authorization', 'Bearer foobar')
.expect(401)
assert.deepEqual(body, {
errors: [{ message: 'E_INVALID_API_TOKEN: Invalid API token' }],
})
})
test('raise error when token is missing in the database', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
error.handle(error, { ...ctx, auth: { use: () => oat1 } as any })
}
ctx.response.finish()
})
await app.container.use('Adonis/Lucid/Database').from('api_tokens').del()
const { body } = await supertest(server)
.get('/')
.set('Accept', 'application/json')
.set('Authorization', `${token.type} ${token.token}`)
.expect(401)
assert.deepEqual(body, {
errors: [{ message: 'E_INVALID_API_TOKEN: Invalid API token' }],
})
})
test('raise error when token is valid but user is missing', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
error.handle(error, { ...ctx, auth: { use: () => oat1 } as any })
}
ctx.response.finish()
})
await app.container.use('Adonis/Lucid/Database').from('users').del()
const { body } = await supertest(server)
.get('/')
.set('Accept', 'application/json')
.set('Authorization', `${token.type} ${token.token}`)
.expect(401)
assert.deepEqual(body, {
errors: [{ message: 'E_INVALID_API_TOKEN: Invalid API token' }],
})
})
test('raise error when token is expired', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
await app.container
.use('Adonis/Lucid/Database')
.from('api_tokens')
.update({
expires_at: DateTime.local().minus({ days: 1 }).toJSDate(),
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
error.handle(error, { ...ctx, auth: { use: () => oat1 } as any })
}
ctx.response.finish()
})
const { body } = await supertest(server)
.get('/')
.set('Accept', 'application/json')
.set('Authorization', `${token.type} ${token.token}`)
.expect(401)
assert.deepEqual(body, {
errors: [{ message: 'E_INVALID_API_TOKEN: Invalid API token' }],
})
})
test('work fine when token is not expired', async (assert) => {
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
expiresIn: '30 mins',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.authenticate()
ctx.response.send(oat1.token)
} catch (error) {
error.handle(error, { ...ctx, auth: { use: () => oat1 } as any })
}
ctx.response.finish()
})
const { body } = await supertest(server)
.get('/')
.set('Accept', 'application/json')
.set('Authorization', `${token.type} ${token.token}`)
.expect(200)
assert.equal(body.name, 'Opaque Access Token')
assert.equal(body.type, 'opaque_token')
assert.exists(body.tokenHash)
})
})
test.group('OAT Guard | logout', (group) => {
group.before(async () => {
app = await setupApplication()
await setup(app)
})
group.after(async () => {
await cleanup(app)
})
group.afterEach(async () => {
await reset(app)
app.container.use('Adonis/Core/Event')['clearAllListeners']()
})
test('delete user token during logout', async (assert) => {
assert.plan(6)
const User = getUserModel(app.container.use('Adonis/Lucid/Orm').BaseModel)
const user = await User.create({
username: 'virk',
email: 'virk@adonisjs.com',
password: await app.container.use('Adonis/Core/Hash').make('secret'),
})
const apiTokensGuard = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
app.container.use('Adonis/Core/HttpContext').create('/', {}),
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
/**
* Assert the event is fired with correct set of arguments
*/
app.container
.use('Adonis/Core/Event')
.once('adonis:api:authenticate', ({ name, user: model, token }) => {
assert.equal(name, 'api')
assert.instanceOf(model, User)
assert.instanceOf(token, ProviderToken)
})
const token = await apiTokensGuard.loginViaId(user.id, {
device_name: 'Android',
ip_address: '192.168.1.1',
})
const server = createServer(async (req, res) => {
const ctx = app.container.use('Adonis/Core/HttpContext').create('/', {}, req, res)
const oat1 = getApiTokensGuard(
app,
getLucidProvider(app, { model: async () => User }),
getLucidProviderConfig({ model: async () => User }),
ctx,
getTokensDbProvider(app.container.use('Adonis/Lucid/Database'))
)
try {
await oat1.logout()
ctx.response.send(oat1.toJSON())
} catch (error) {
ctx.response.status(500).send(error)
}
ctx.response.finish()
})
const { body } = await supertest(server)
.get('/')
.set('Authorization', `${token.type} ${token.token}`)
.expect(200)
const tokens = await app.container.use('Adonis/Lucid/Database').query().from('api_tokens')
assert.lengthOf(tokens, 0)
assert.isFalse(body.isLoggedIn)
assert.isTrue(body.authenticationAttempted)
})
}) | the_stack |
import {getEnvContent, LocalActionBundle} from 'app/common/ActionBundle';
import {ActionSummary, ColumnDelta, createEmptyActionSummary,
createEmptyTableDelta, defunctTableName, LabelDelta, TableDelta} from 'app/common/ActionSummary';
import {DocAction} from 'app/common/DocActions';
import * as Action from 'app/common/DocActions';
import {arrayExtend} from 'app/common/gutil';
import {CellDelta} from 'app/common/TabularDiff';
import fromPairs = require('lodash/fromPairs');
import keyBy = require('lodash/keyBy');
import sortBy = require('lodash/sortBy');
import toPairs = require('lodash/toPairs');
import values = require('lodash/values');
/**
* The maximum number of rows in a single bulk change that will be recorded
* individually. Bulk changes that touch more than this number of rows
* will be summarized only by the number of rows touched.
*/
const MAXIMUM_INLINE_ROWS = 10;
/** helper function to access summary changes for a specific table by name */
function _forTable(summary: ActionSummary, tableId: string): TableDelta {
return summary.tableDeltas[tableId] || (summary.tableDeltas[tableId] = createEmptyTableDelta());
}
/** helper function to access summary changes for a specific cell by rowId and colId */
function _forCell(td: TableDelta, rowId: number, colId: string): CellDelta {
const cd = td.columnDeltas[colId] || (td.columnDeltas[colId] = {});
return cd[rowId] || (cd[rowId] = [null, null]);
}
/**
* helper function to store detailed cell changes for a single row.
* Direction parameter is 0 if values are prior values of cells, 1 if values are new values.
*/
function _addRow(td: TableDelta, rowId: number, colValues: Action.ColValues,
direction: 0|1) {
for (const [colId, colChanges] of toPairs(colValues)) {
const cell = _forCell(td, rowId, colId);
cell[direction] = [colChanges];
}
}
/** helper function to store detailed cell changes for a set of rows */
function _addRows(tableId: string, td: TableDelta, rowIds: number[],
colValues: Action.BulkColValues, direction: 0|1) {
let rows: Array<[number, number]>;
if (rowIds.length <= MAXIMUM_INLINE_ROWS || tableId.startsWith("_grist_")) {
rows = [...rowIds.entries()];
} else {
// if many rows, just take some from start and one from end as examples
rows = [...rowIds.slice(0, MAXIMUM_INLINE_ROWS - 1).entries()];
rows.push([rowIds.length - 1, rowIds[rowIds.length - 1]]);
}
for (const [colId, colChanges] of toPairs(colValues)) {
rows.forEach(([idx, rowId]) => {
const cell = _forCell(td, rowId, colId);
cell[direction] = [colChanges[idx]];
});
}
}
/** add a rename to a list, avoiding duplicates */
function _addRename(renames: LabelDelta[], rename: LabelDelta) {
if (renames.find(r => r[0] === rename[0] && r[1] === rename[1])) { return; }
renames.push(rename);
}
/** add information about an action based on the forward direction */
function _addForwardAction(summary: ActionSummary, act: DocAction) {
const tableId = act[1];
if (Action.isAddTable(act)) {
summary.tableRenames.push([null, tableId]);
for (const info of act[2]) {
_forTable(summary, tableId).columnRenames.push([null, info.id]);
}
} else if (Action.isRenameTable(act)) {
_addRename(summary.tableRenames, [tableId, act[2]]);
} else if (Action.isRenameColumn(act)) {
_addRename(_forTable(summary, tableId).columnRenames, [act[2], act[3]]);
} else if (Action.isAddColumn(act)) {
_forTable(summary, tableId).columnRenames.push([null, act[2]]);
} else if (Action.isRemoveColumn(act)) {
_forTable(summary, tableId).columnRenames.push([act[2], null]);
} else if (Action.isAddRecord(act)) {
const td = _forTable(summary, tableId);
td.addRows.push(act[2]);
_addRow(td, act[2], act[3], 1);
} else if (Action.isUpdateRecord(act)) {
const td = _forTable(summary, tableId);
td.updateRows.push(act[2]);
_addRow(td, act[2], act[3], 1);
} else if (Action.isBulkAddRecord(act)) {
const td = _forTable(summary, tableId);
arrayExtend(td.addRows, act[2]);
_addRows(tableId, td, act[2], act[3], 1);
} else if (Action.isBulkUpdateRecord(act)) {
const td = _forTable(summary, tableId);
arrayExtend(td.updateRows, act[2]);
_addRows(tableId, td, act[2], act[3], 1);
} else if (Action.isReplaceTableData(act)) {
const td = _forTable(summary, tableId);
arrayExtend(td.addRows, act[2]);
_addRows(tableId, td, act[2], act[3], 1);
}
}
/** add information about an action based on undo information */
function _addReverseAction(summary: ActionSummary, act: DocAction) {
const tableId = act[1];
if (Action.isAddTable(act)) { // undoing, so this is a table removal
summary.tableRenames.push([tableId, null]);
for (const info of act[2]) {
_forTable(summary, tableId).columnRenames.push([info.id, null]);
}
} else if (Action.isAddRecord(act)) { // undoing, so this is a record removal
const td = _forTable(summary, tableId);
td.removeRows.push(act[2]);
_addRow(td, act[2], act[3], 0);
} else if (Action.isUpdateRecord(act)) { // undoing, so this is reversal of a record update
const td = _forTable(summary, tableId);
_addRow(td, act[2], act[3], 0);
} else if (Action.isBulkAddRecord(act)) { // undoing, this may be reversing a table delete
const td = _forTable(summary, tableId);
arrayExtend(td.removeRows, act[2]);
_addRows(tableId, td, act[2], act[3], 0);
} else if (Action.isBulkUpdateRecord(act)) { // undoing, so this is reversal of a bulk record update
const td = _forTable(summary, tableId);
arrayExtend(td.updateRows, act[2]);
_addRows(tableId, td, act[2], act[3], 0);
} else if (Action.isRenameTable(act)) { // undoing - sometimes renames only in undo info
_addRename(summary.tableRenames, [act[2], tableId]);
} else if (Action.isRenameColumn(act)) { // undoing - sometimes renames only in undo info
_addRename(_forTable(summary, tableId).columnRenames, [act[3], act[2]]);
} else if (Action.isReplaceTableData(act)) { // undoing
const td = _forTable(summary, tableId);
arrayExtend(td.removeRows, act[2]);
_addRows(tableId, td, act[2], act[3], 0);
}
}
/**
* Summarize the tabular changes that a LocalActionBundle results in, in a form
* that will be suitable for composition.
*/
export function summarizeAction(body: LocalActionBundle): ActionSummary {
const summary = createEmptyActionSummary();
for (const act of getEnvContent(body.stored)) {
_addForwardAction(summary, act);
}
for (const act of Array.from(body.undo).reverse()) {
_addReverseAction(summary, act);
}
// Name tables consistently, by their ultimate name, now we know it.
for (const renames of summary.tableRenames) {
const pre = renames[0];
let post = renames[1];
if (pre === null) { continue; }
if (post === null) { post = defunctTableName(pre); }
if (summary.tableDeltas[pre]) {
summary.tableDeltas[post] = summary.tableDeltas[pre];
delete summary.tableDeltas[pre];
}
}
for (const td of values(summary.tableDeltas)) {
// Name columns consistently, by their ultimate name, now we know it.
for (const renames of td.columnRenames) {
const pre = renames[0];
let post = renames[1];
if (pre === null) { continue; }
if (post === null) { post = defunctTableName(pre); }
if (td.columnDeltas[pre]) {
td.columnDeltas[post] = td.columnDeltas[pre];
delete td.columnDeltas[pre];
}
}
// remove any duplicates that crept in
td.addRows = Array.from(new Set(td.addRows));
td.updateRows = Array.from(new Set(td.updateRows));
td.removeRows = Array.from(new Set(td.removeRows));
}
return summary;
}
/**
* Once we can produce an ActionSummary for each LocalActionBundle, it is useful to be able
* to compose them. Take the case of an ActionSummary pair, part 1 and part 2. NameMerge
* is an internal structure to help merging table/column name changes across two parts.
*/
interface NameMerge {
dead1: Set<string>; /** anything of this name in part 1 should be removed from merge */
dead2: Set<string>; /** anything of this name in part 2 should be removed from merge */
rename1: Map<string, string>; /** replace these names in part 1 */
rename2: Map<string, string>; /** replace these names in part 2 */
merge: LabelDelta[]; /** a merged list of adds/removes/renames for the result */
}
/**
* Looks at a pair of name change lists (could be tables or columns) and figures out what
* changes would need to be made to a data structure keyed on those names in order to key
* it consistently on final names.
*/
function planNameMerge(names1: LabelDelta[], names2: LabelDelta[]): NameMerge {
const result: NameMerge = {
dead1: new Set(),
dead2: new Set(),
rename1: new Map<string, string>(),
rename2: new Map<string, string>(),
merge: new Array<LabelDelta>(),
};
const names1ByFinalName: {[name: string]: LabelDelta} = keyBy(names1, p => p[1]!);
const names2ByInitialName: {[name: string]: LabelDelta} = keyBy(names2, p => p[0]!);
for (const [before1, after1] of names1) {
if (!after1) {
if (!before1) { throw new Error("invalid name change found"); }
// Table/column was deleted in part 1.
result.dead1.add(before1);
result.merge.push([before1, null]);
continue;
}
// At this point, we know the table/column existed at end of part 1.
const pair2 = names2ByInitialName[after1];
if (!pair2) {
// Table/column's name was stable in part 2, so only change was in part 1.
result.merge.push([before1, after1]);
continue;
}
const after2 = pair2[1];
if (!after2) {
// Table/column was deleted in part 2.
result.dead2.add(after1);
if (before1) {
// Table/column existed prior to part 1, so we need to expose its history.
result.dead1.add(before1);
result.merge.push([before1, null]);
} else {
// Table/column did not exist prior to part 1, so we erase it from history.
result.dead1.add(after1);
result.dead2.add(defunctTableName(after1));
}
continue;
}
// It we made it this far, our table/column exists after part 2. Any information
// keyed to its name in part 1 will need to be rekeyed to its final name.
result.rename1.set(after1, after2);
result.merge.push([before1, after2]);
}
// Look through part 2 for any changes not already covered.
for (const [before2, after2] of names2) {
if (!before2 && !after2) { throw new Error("invalid name change found"); }
if (before2 && names1ByFinalName[before2]) { continue; } // Already handled
result.merge.push([before2, after2]);
// If table/column is renamed in part 2, and name was stable in part 1,
// rekey any information about it in part 1.
if (before2 && after2) { result.rename1.set(before2, after2); }
}
// For neatness, sort the merge order. Not essential.
result.merge = sortBy(result.merge, ([a, b]) => [a || "", b || ""]);
return result;
}
/**
* Re-key nested data to match name changes / removals. Needs to be done a little carefully
* since it is perfectly possible for names to be swapped or shuffled.
*
* Entries may be TableDeltas in the case of table renames or ColumnDeltas for column renames.
*
* @param entries: a dictionary of nested data - TableDeltas for tables, ColumnDeltas for columns.
* @param dead: a set of keys to remove from the dictionary.
* @param rename: changes of names to apply to the dictionary.
*/
function renameAndDelete<T>(entries: {[name: string]: T}, dead: Set<string>,
rename: Map<string, string>) {
// Remove all entries marked as dead.
for (const key of dead) { delete entries[key]; }
// Move all entries that are going to be renamed out to a cache temporarily.
const cache: {[name: string]: any} = {};
for (const key of rename.keys()) {
if (entries[key]) {
cache[key] = entries[key];
delete entries[key];
}
}
// Move all renamed entries back in with their new names.
for (const [key, val] of rename.entries()) { if (cache[key]) { entries[val] = cache[key]; } }
}
/**
* Apply planned name changes to a pair of entries, and return a merged entry encorporating
* their composition.
*
* @param names: the planned name changes as calculated by planNameMerge()
* @param entries1: the first dictionary of nested data keyed on the names
* @param entries2: test second dictionary of nested data keyed on the names
* @param mergeEntry: a function to apply any further corrections needed to the entries
*
*/
function mergeNames<T>(names: NameMerge,
entries1: {[name: string]: T},
entries2: {[name: string]: T},
mergeEntry: (e1: T, e2: T) => T): {[name: string]: T} {
// Update the keys of the entries1 and entries2 dictionaries to be consistent.
renameAndDelete(entries1, names.dead1, names.rename1);
renameAndDelete(entries2, names.dead2, names.rename2);
// Prepare the composition of the two dictionaries.
const entries = entries2; // Start with the second dictionary.
for (const key of Object.keys(entries1)) { // Add material from the first.
const e1 = entries1[key];
if (!entries[key]) { entries[key] = e1; continue; } // No overlap - just add and move on.
entries[key] = mergeEntry(e1, entries[key]); // Recursive merge if overlap.
}
return entries;
}
/**
* Track whether a specific row was added, removed or updated.
*/
interface RowChange {
added: boolean;
removed: boolean;
updated: boolean;
}
/** RowChange for each row in a table */
export interface RowChanges {
[rowId: number]: RowChange;
}
/**
* This is used when we hit a cell that we know has changed but don't know its
* value due to it being part of a bulk input. This produces a cell that
* represents the unknowns.
*/
function bulkCellFor(rc: RowChange|undefined): CellDelta|undefined {
if (!rc) { return undefined; }
const result: CellDelta = [null, null];
if (rc.removed || rc.updated) { result[0] = '?'; }
if (rc.added || rc.updated) { result[1] = '?'; }
return result;
}
/**
* Merge changes that apply to a particular column.
*
* @param present1: affected rows in part 1
* @param present2: affected rows in part 2
* @param e1: cached cell values for the column in part 1
* @param e2: cached cell values for the column in part 2
*/
function mergeColumn(present1: RowChanges, present2: RowChanges,
e1: ColumnDelta, e2: ColumnDelta): ColumnDelta {
for (const key of (Object.keys(present1) as unknown as number[])) {
let v1 = e1[key];
let v2 = e2[key];
if (!v1 && !v2) { continue; }
v1 = v1 || bulkCellFor(present1[key]);
v2 = v2 || bulkCellFor(present2[key]);
if (!v2) { e2[key] = e1[key]; continue; }
if (!v1[1]) { continue; } // Deleted row.
e2[key] = [v1[0], v2[1]]; // Change is from initial value in e1 to final value in e2.
}
return e2;
}
/** Put list of numbers in ascending order, with duplicates removed. */
function uniqueAndSorted(lst: number[]) {
return [...new Set(lst)].sort((a, b) => a - b);
}
/** For each row changed, figure out whether it was added/removed/updated */
/** TODO: need for this method suggests maybe a better core representation for this info */
function getRowChanges(e: TableDelta): RowChanges {
const all = new Set([...e.addRows, ...e.removeRows, ...e.updateRows]);
const added = new Set(e.addRows);
const removed = new Set(e.removeRows);
const updated = new Set(e.updateRows);
return fromPairs([...all].map(x => {
return [x, {added: added.has(x),
removed: removed.has(x),
updated: updated.has(x)}] as [number, RowChange];
}));
}
/**
* Merge changes that apply to a particular table. For updating addRows and removeRows, care is
* needed, since it is fine to remove and add the same rowId within a single summary -- this is just
* rowId reuse. It needs to be tracked so we know lifetime of rows though.
*/
function mergeTable(e1: TableDelta, e2: TableDelta): TableDelta {
// First, sort out any changes to names of columns.
const names = planNameMerge(e1.columnRenames, e2.columnRenames);
mergeNames(names, e1.columnDeltas, e2.columnDeltas,
mergeColumn.bind(null,
getRowChanges(e1),
getRowChanges(e2)));
e2.columnRenames = names.merge;
// All the columnar data is now merged. What remains is to merge the summary lists of rowIds
// that we maintain.
const addRows1 = new Set(e1.addRows); // Non-transient rows we have clearly added.
const removeRows2 = new Set(e2.removeRows); // Non-transient rows we have clearly removed.
const transients = e1.addRows.filter(x => removeRows2.has(x));
e2.addRows = uniqueAndSorted([...e2.addRows, ...e1.addRows.filter(x => !removeRows2.has(x))]);
e2.removeRows = uniqueAndSorted([...e2.removeRows.filter(x => !addRows1.has(x)), ...e1.removeRows]);
e2.updateRows = uniqueAndSorted([...e1.updateRows.filter(x => !removeRows2.has(x)),
...e2.updateRows.filter(x => !addRows1.has(x))]);
// Remove all traces of transients (rows that were created and destroyed) from history.
for (const cols of values(e2.columnDeltas)) {
for (const key of transients) { delete cols[key]; }
}
return e2;
}
/** Finally, merge a pair of summaries. */
export function concatenateSummaryPair(sum1: ActionSummary, sum2: ActionSummary): ActionSummary {
const names = planNameMerge(sum1.tableRenames, sum2.tableRenames);
const rowChanges = mergeNames(names, sum1.tableDeltas, sum2.tableDeltas, mergeTable);
const sum: ActionSummary = {
tableRenames: names.merge,
tableDeltas: rowChanges
};
return sum;
}
/** Generalize to merging a list of summaries. */
export function concatenateSummaries(sums: ActionSummary[]): ActionSummary {
if (sums.length === 0) { return createEmptyActionSummary(); }
let result = sums[0];
for (let i = 1; i < sums.length; i++) {
result = concatenateSummaryPair(result, sums[i]);
}
return result;
} | the_stack |
import * as pb_1 from "google-protobuf";
export namespace common.verification_policy {
export class VerificationPolicy extends pb_1.Message {
constructor(data?: any[] | {
securityDomain?: string;
identifiers?: Identifier[];
}) {
super();
pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], []);
if (!Array.isArray(data) && typeof data == "object") {
if ("securityDomain" in data && data.securityDomain != undefined) {
this.securityDomain = data.securityDomain;
}
if ("identifiers" in data && data.identifiers != undefined) {
this.identifiers = data.identifiers;
}
}
}
get securityDomain() {
return pb_1.Message.getField(this, 1) as string;
}
set securityDomain(value: string) {
pb_1.Message.setField(this, 1, value);
}
get identifiers() {
return pb_1.Message.getRepeatedWrapperField(this, Identifier, 2) as Identifier[];
}
set identifiers(value: Identifier[]) {
pb_1.Message.setRepeatedWrapperField(this, 2, value);
}
static fromObject(data: {
securityDomain?: string;
identifiers?: ReturnType<typeof Identifier.prototype.toObject>[];
}) {
const message = new VerificationPolicy({});
if (data.securityDomain != null) {
message.securityDomain = data.securityDomain;
}
if (data.identifiers != null) {
message.identifiers = data.identifiers.map(item => Identifier.fromObject(item));
}
return message;
}
toObject() {
const data: {
securityDomain?: string;
identifiers?: ReturnType<typeof Identifier.prototype.toObject>[];
} = {};
if (this.securityDomain != null) {
data.securityDomain = this.securityDomain;
}
if (this.identifiers != null) {
data.identifiers = this.identifiers.map((item: Identifier) => item.toObject());
}
return data;
}
serialize(): Uint8Array;
serialize(w: pb_1.BinaryWriter): void;
serialize(w?: pb_1.BinaryWriter): Uint8Array | void {
const writer = w || new pb_1.BinaryWriter();
if (typeof this.securityDomain === "string" && this.securityDomain.length)
writer.writeString(1, this.securityDomain);
if (this.identifiers !== undefined)
writer.writeRepeatedMessage(2, this.identifiers, (item: Identifier) => item.serialize(writer));
if (!w)
return writer.getResultBuffer();
}
static deserialize(bytes: Uint8Array | pb_1.BinaryReader): VerificationPolicy {
const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new VerificationPolicy();
while (reader.nextField()) {
if (reader.isEndGroup())
break;
switch (reader.getFieldNumber()) {
case 1:
message.securityDomain = reader.readString();
break;
case 2:
reader.readMessage(message.identifiers, () => pb_1.Message.addToRepeatedWrapperField(message, 2, Identifier.deserialize(reader), Identifier));
break;
default: reader.skipField();
}
}
return message;
}
serializeBinary(): Uint8Array {
return this.serialize();
}
static deserializeBinary(bytes: Uint8Array): VerificationPolicy {
return VerificationPolicy.deserialize(bytes);
}
}
export class Policy extends pb_1.Message {
constructor(data?: any[] | {
type?: string;
criteria?: string[];
}) {
super();
pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], []);
if (!Array.isArray(data) && typeof data == "object") {
if ("type" in data && data.type != undefined) {
this.type = data.type;
}
if ("criteria" in data && data.criteria != undefined) {
this.criteria = data.criteria;
}
}
}
get type() {
return pb_1.Message.getField(this, 1) as string;
}
set type(value: string) {
pb_1.Message.setField(this, 1, value);
}
get criteria() {
return pb_1.Message.getField(this, 2) as string[];
}
set criteria(value: string[]) {
pb_1.Message.setField(this, 2, value);
}
static fromObject(data: {
type?: string;
criteria?: string[];
}) {
const message = new Policy({});
if (data.type != null) {
message.type = data.type;
}
if (data.criteria != null) {
message.criteria = data.criteria;
}
return message;
}
toObject() {
const data: {
type?: string;
criteria?: string[];
} = {};
if (this.type != null) {
data.type = this.type;
}
if (this.criteria != null) {
data.criteria = this.criteria;
}
return data;
}
serialize(): Uint8Array;
serialize(w: pb_1.BinaryWriter): void;
serialize(w?: pb_1.BinaryWriter): Uint8Array | void {
const writer = w || new pb_1.BinaryWriter();
if (typeof this.type === "string" && this.type.length)
writer.writeString(1, this.type);
if (this.criteria !== undefined)
writer.writeRepeatedString(2, this.criteria);
if (!w)
return writer.getResultBuffer();
}
static deserialize(bytes: Uint8Array | pb_1.BinaryReader): Policy {
const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new Policy();
while (reader.nextField()) {
if (reader.isEndGroup())
break;
switch (reader.getFieldNumber()) {
case 1:
message.type = reader.readString();
break;
case 2:
pb_1.Message.addToRepeatedField(message, 2, reader.readString());
break;
default: reader.skipField();
}
}
return message;
}
serializeBinary(): Uint8Array {
return this.serialize();
}
static deserializeBinary(bytes: Uint8Array): Policy {
return Policy.deserialize(bytes);
}
}
export class Identifier extends pb_1.Message {
constructor(data?: any[] | {
pattern?: string;
policy?: Policy;
}) {
super();
pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], []);
if (!Array.isArray(data) && typeof data == "object") {
if ("pattern" in data && data.pattern != undefined) {
this.pattern = data.pattern;
}
if ("policy" in data && data.policy != undefined) {
this.policy = data.policy;
}
}
}
get pattern() {
return pb_1.Message.getField(this, 1) as string;
}
set pattern(value: string) {
pb_1.Message.setField(this, 1, value);
}
get policy() {
return pb_1.Message.getWrapperField(this, Policy, 2) as Policy;
}
set policy(value: Policy) {
pb_1.Message.setWrapperField(this, 2, value);
}
static fromObject(data: {
pattern?: string;
policy?: ReturnType<typeof Policy.prototype.toObject>;
}) {
const message = new Identifier({});
if (data.pattern != null) {
message.pattern = data.pattern;
}
if (data.policy != null) {
message.policy = Policy.fromObject(data.policy);
}
return message;
}
toObject() {
const data: {
pattern?: string;
policy?: ReturnType<typeof Policy.prototype.toObject>;
} = {};
if (this.pattern != null) {
data.pattern = this.pattern;
}
if (this.policy != null) {
data.policy = this.policy.toObject();
}
return data;
}
serialize(): Uint8Array;
serialize(w: pb_1.BinaryWriter): void;
serialize(w?: pb_1.BinaryWriter): Uint8Array | void {
const writer = w || new pb_1.BinaryWriter();
if (typeof this.pattern === "string" && this.pattern.length)
writer.writeString(1, this.pattern);
if (this.policy !== undefined)
writer.writeMessage(2, this.policy, () => this.policy.serialize(writer));
if (!w)
return writer.getResultBuffer();
}
static deserialize(bytes: Uint8Array | pb_1.BinaryReader): Identifier {
const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new Identifier();
while (reader.nextField()) {
if (reader.isEndGroup())
break;
switch (reader.getFieldNumber()) {
case 1:
message.pattern = reader.readString();
break;
case 2:
reader.readMessage(message.policy, () => message.policy = Policy.deserialize(reader));
break;
default: reader.skipField();
}
}
return message;
}
serializeBinary(): Uint8Array {
return this.serialize();
}
static deserializeBinary(bytes: Uint8Array): Identifier {
return Identifier.deserialize(bytes);
}
}
} | the_stack |
import {FS, Utils} from '../../lib';
import type {ModlogSearch, ModlogEntry} from '../modlog';
import {
TicketState, getBattleLog, getBattleLinks,
writeTickets, notifyStaff, writeStats, HelpTicket,
tickets,
} from './helptickets';
import * as Artemis from '../artemis';
const ORDERED_PUNISHMENTS = ['WARN', 'FORCERENAME', 'LOCK', 'NAMELOCK', 'WEEKLOCK', 'WEEKNAMELOCK'];
const PMLOG_IGNORE_TIME = 24 * 60 * 60 * 1000;
const WHITELIST = ['mia'];
export interface AutoPunishment {
modlogCount?: number;
severity?: {type: string[], certainty: number};
/**
* Should it be run on just one message?
* or is it safe to run on averages (for the types that use averages)
*/
isSingleMessage?: boolean;
punishment: string;
ticketType: string;
}
export interface AutoSettings {
punishments: AutoPunishment[];
applyPunishments: boolean;
}
const defaults: AutoSettings = {
punishments: [{
ticketType: 'inapname',
punishment: 'forcerename',
severity: {type: ['sexual_explicit', 'severe_toxicity', 'identity_attack'], certainty: 0.4},
}, {
ticketType: 'pmharassment',
punishment: 'warn',
severity: {type: ['sexual_explicit', 'severe_toxicity', 'identity_attack'], certainty: 0.15},
}],
applyPunishments: false,
};
export const settings: AutoSettings = (() => {
try {
// spreading w/ default means that
// adding new things won't crash by not existing
return {...defaults, ...JSON.parse(FS('config/chat-plugins/ht-auto.json').readSync())};
} catch {
return defaults;
}
})();
function saveSettings() {
return FS('config/chat-plugins/ht-auto.json').writeUpdate(() => JSON.stringify(settings));
}
function visualizePunishment(punishment: AutoPunishment) {
const buf = [`punishment: ${punishment.punishment?.toUpperCase()}`];
buf.push(`ticket type: ${punishment.ticketType}`);
if (punishment.severity) {
buf.push(`severity: ${punishment.severity.certainty} (for ${punishment.severity.type.join(', ')})`);
}
if (punishment.modlogCount) {
buf.push(`required modlog: ${punishment.modlogCount}`);
}
if (punishment.isSingleMessage) {
buf.push(`for single messages only`);
}
return buf.join(', ');
}
function checkAccess(context: Chat.CommandContext | Chat.PageContext) {
if (!WHITELIST.includes(context.user.id)) context.checkCan('bypassall');
}
export function punishmentsFor(type: string) {
return settings.punishments.filter(t => t.ticketType === type);
}
/** Is punishment1 higher than punishment2 on the list? */
function supersedes(p1: string, p2: string) {
return ORDERED_PUNISHMENTS.indexOf(p1) > ORDERED_PUNISHMENTS.indexOf(p2);
}
export function determinePunishment(
ticketType: string, results: Record<string, number>, modlog: ModlogEntry[], isSingleMessage = false
) {
const punishments = punishmentsFor(ticketType);
let action: string | null = null;
const types = [];
Utils.sortBy(punishments, p => -ORDERED_PUNISHMENTS.indexOf(p.punishment));
for (const punishment of punishments) {
if (isSingleMessage && !punishment.isSingleMessage) continue;
if (punishment.modlogCount && modlog.length < punishment.modlogCount) continue;
if (punishment.severity) {
let hit = false;
for (const type of punishment.severity.type) {
if (results[type] < punishment.severity.certainty) continue;
hit = true;
types.push(type);
break;
}
if (!hit) continue;
}
if (!action || supersedes(punishment.punishment, action)) {
action = punishment.punishment;
}
}
return {action, types};
}
export function globalModlog(action: string, user: User | ID | null, note: string, roomid?: string) {
user = Users.get(user) || user;
void Rooms.Modlog.write(roomid || 'global', {
action,
ip: user && typeof user === 'object' ? user.latestIp : undefined,
userid: toID(user) || undefined,
loggedBy: 'artemis' as ID,
note,
});
}
export function addModAction(message: string) {
Rooms.get('staff')?.add(`|c|&|/log ${message}`).update();
}
export async function getModlog(params: {user?: ID, ip?: string, actions?: string[]}) {
const search: ModlogSearch = {
note: [],
user: [],
ip: [],
action: [],
actionTaker: [],
};
if (params.user) search.user = [{search: params.user, isExact: true}];
if (params.ip) search.ip = [{search: params.ip}];
if (params.actions) search.action = params.actions.map(s => ({search: s}));
const res = await Rooms.Modlog.search('global', search);
return res?.results || [];
}
function closeTicket(ticket: TicketState, msg?: string) {
if (!ticket.open) return;
ticket.open = false;
ticket.active = false;
ticket.resolved = {
time: Date.now(),
by: 'the Artemis AI', // we want it to be clear to end users that it was not a human
seen: false,
staffReason: '',
result: msg || '',
note: (
`Want to learn more about the AI? ` +
`<a href="https://www.smogon.com/forums/threads/3570628/#post-9056769">Visit the information thread</a>.`
),
};
writeTickets();
notifyStaff();
const tarUser = Users.get(ticket.userid);
if (tarUser) {
HelpTicket.notifyResolved(tarUser, ticket, ticket.userid);
}
// TODO: Support closing as invalid
writeStats(`${ticket.type}\t${Date.now() - ticket.created}\t0\t0\tresolved\tvalid\tartemis`);
}
async function lock(
user: User | ID,
result: CheckerResult,
ticket: TicketState,
isWeek?: boolean,
isName?: boolean
) {
const id = toID(user);
let desc, type;
const expireTime = isWeek ? Date.now() + 7 * 24 * 60 * 60 * 1000 : null;
if (isName) {
if (typeof user === 'object') user.resetName();
desc = 'locked your username and prevented you from changing names';
type = `locked from talking${isWeek ? ` for a week` : ""}`;
await Punishments.namelock(id, expireTime, null, false, result.reason || "Automatically locked due to a user report");
} else {
type = isWeek ? 'weeknamelocked' : 'namelocked';
desc = 'locked you from talking in chats, battles, and PMing regular users';
await Punishments.lock(id, expireTime, null, false, result.reason || "Automatically locked due to a user report");
}
if (typeof user !== 'string') {
let message = `|popup||html|${user.name} has ${desc} for ${isWeek ? '7' : '2'} days.`;
if (result.reason) message += `\n\nReason: ${result.reason}`;
let appeal = '';
if (Chat.pages.help) {
appeal += `<a href="view-help-request--appeal"><button class="button"><strong>Appeal your punishment</strong></button></a>`;
} else if (Config.appealurl) {
appeal += `appeal: <a href="${Config.appealurl}">${Config.appealurl}</a>`;
}
if (appeal) message += `\n\nIf you feel that your lock was unjustified, you can ${appeal}.`;
message += `\n\nYour lock will expire in a few days.`;
user.send(message);
}
addModAction(`${id} was ${type} by Artemis. (${result.reason || `report from ${ticket.creator}`})`);
globalModlog(
`${isWeek ? 'WEEK' : ""}${isName ? "NAME" : ""}LOCK`, id,
(result.reason || `report from ${ticket.creator}`) + (result.proof ? ` PROOF: ${result.proof}` : "")
);
}
export const actionHandlers: {
[k: string]: (user: User | ID, result: CheckerResult, ticket: TicketState) => string | void | Promise<string | void>,
} = {
forcerename(user, result, ticket) {
if (typeof user === 'string') return; // they can only submit users with existing userobjects anyway
const id = toID(user);
user.resetName();
user.trackRename = id;
Monitor.forceRenames.set(id, true);
user.send(
'|nametaken|Your name was detected to be breaking our name rules. ' +
`${result.reason ? `Reason: ${result.reason}. ` : ""}` +
'Please change it, or submit a help ticket by typing /ht in chat to appeal this action.'
);
Rooms.get('staff')?.add(
`|html|<span class="username">${id}</span> ` +
`was automatically forced to choose a new name by Artemis (report from ${ticket.userid}).`
).update();
globalModlog(
'FORCERENAME', id, `username determined to be inappropriate due to a report by ${ticket.creator}`, result.roomid
);
return `${id} was automatically forcerenamed. Thank you for reporting.`;
},
async namelock(user, result, ticket) {
await lock(user, result, ticket, false, true);
return `${toID(user)} was automatically namelocked. Thank you for reporting.`;
},
async weeknamelock(user, result, ticket) {
await lock(user, result, ticket, true, true);
return `${toID(user)} was automatically weeknamelocked. Thank you for reporting.`;
},
async lock(user, result, ticket) {
await lock(user, result, ticket);
return `${toID(user)} was automatically locked. Thank you for reporting.`;
},
async weeklock(user, result, ticket) {
await lock(user, result, ticket, true);
return `${toID(user)} was automatically weeklocked. Thank you for reporting.`;
},
warn(user, result, ticket) {
user = toID(user);
user = Users.get(user) || user;
if (typeof user === 'object') {
user.send(`|c|~|/warn ${result.reason || ""}`);
} else {
Punishments.offlineWarns.set(user, result.reason);
}
addModAction(
`${user} was warned by Artemis. ${typeof user === 'string' ? 'while offline ' : ""}` +
`(${result.reason || `report from ${ticket.creator}`})`
);
globalModlog(
'WARN', user, result.reason || `report from ${ticket.creator}`
);
return `${user} was automatically warned. Thank you for reporting.`;
},
};
function shouldNotProcess(message: string) {
return (
// special 'command', blocks things like /log, /raw, /html
// (but not a // message)
(message.startsWith('/') && !message.startsWith('//')) ||
// broadcasted chat command
message.startsWith('!')
);
}
export async function getMessageAverages(messages: string[]) {
const counts: Record<string, {count: number, raw: number}> = {};
const classified = [];
for (const message of messages) {
if (shouldNotProcess(message)) continue;
const res = await classifier.classify(message);
if (!res) continue;
classified.push(res);
for (const k in res) {
if (!counts[k]) counts[k] = {count: 0, raw: 0};
counts[k].count++;
counts[k].raw += res[k];
}
}
const averages: Record<string, number> = {};
for (const k in counts) {
averages[k] = counts[k].raw / counts[k].count;
}
return {averages, classified};
}
interface CheckerResult {
action: string;
user: User | ID;
result: Record<string, number>;
reason: string;
roomid?: string;
displayReason?: string;
proof?: string;
}
type CheckerOutput = void | Map<string, CheckerResult>;
export const checkers: {
[k: string]: (ticket: TicketState & {text: [string, string]}) => CheckerOutput | Promise<CheckerOutput>,
} = {
async inapname(ticket) {
const id = toID(ticket.text[0]);
const user = Users.getExact(id);
if (user && !user.trusted) {
const result = await classifier.classify(user.name);
if (!result) return;
const keys = ['identity_attack', 'sexual_explicit', 'severe_toxicity'];
const matched = keys.some(k => result[k] >= 0.4);
if (matched) {
const modlog = await getModlog({
ip: user.latestIp,
actions: ['FORCERENAME', 'NAMELOCK', 'WEEKNAMELOCK'],
});
let {action} = determinePunishment('inapname', result, modlog);
if (!action) action = 'forcerename';
return new Map([[user.id, {
action,
user,
result,
reason: "Username detected to be breaking username rules",
}]]);
}
}
},
async inappokemon(ticket) {
const actions = new Map();
const links = [...getBattleLinks(ticket.text[0]), ...getBattleLinks(ticket.text[1])];
for (const link of links) {
const log = await getBattleLog(link);
if (!log) continue;
for (const [user, pokemon] of Object.entries(log.pokemon)) {
const userid = toID(user);
let result: {
action: string, name: string, result: Record<string, number>, replay: string,
} | null = null;
for (const set of pokemon) {
if (!set.name) continue;
const results = await classifier.classify(set.name);
if (!results) continue;
// atm don't factor in modlog
const curAction = determinePunishment('inappokemon', results, []).action;
if (curAction && (!result || supersedes(curAction, result.action))) {
result = {action: curAction, name: set.name, result: results, replay: link};
}
}
if (result) {
actions.set(user, {
action: result.action,
user: userid,
result: result.result,
reason: `Pokemon name detected to be breaking rules - '${result.name}'`,
roomid: link,
});
}
}
}
if (actions.size) return actions;
},
async battleharassment(ticket) {
const urls = getBattleLinks(ticket.text[0]);
const actions = new Map<string, CheckerResult>();
for (const url of urls) {
const log = await getBattleLog(url);
if (!log) continue;
const messages: Record<string, string[]> = {};
for (const message of log.log) {
const [username, text] = Utils.splitFirst(message.slice(3), '|').map(f => f.trim());
const id = toID(username);
if (!id) continue;
if (!messages[id]) messages[id] = [];
messages[id].push(text);
}
for (const [id, messageList] of Object.entries(messages)) {
const {averages, classified} = await getMessageAverages(messageList);
const {action} = determinePunishment('battleharassment', averages, []);
if (action) {
const existingPunishment = actions.get(id);
if (!existingPunishment || supersedes(action, existingPunishment.action)) {
actions.set(id, {
action,
user: toID(id),
result: averages,
reason: `Not following rules in battles (https://${Config.routes.client}/${url})`,
proof: urls.join(', '),
});
}
}
for (const result of classified) {
const curPunishment = determinePunishment('battleharassment', result, [], true).action;
if (!curPunishment) continue;
const exists = actions.get(id);
if (!exists || supersedes(curPunishment, exists.action)) {
actions.set(id, {
action: curPunishment,
user: toID(id),
result: averages,
reason: `Not following rules in battles (https://${Config.routes.client}/${url})`,
proof: urls.join(', '),
});
}
}
}
}
// ensure reasons are clear
const creatorWasPunished = actions.get(ticket.userid);
if (creatorWasPunished) {
let displayReason = 'You were punished for your behavior.';
if (actions.size !== 1) { // more than 1 was punished
displayReason += ` ${actions.size - 1} other(s) were also punished.`;
}
creatorWasPunished.displayReason = displayReason;
}
if (actions.size) return actions;
},
async pmharassment(ticket) {
const actions = new Map<string, CheckerResult>();
const targetId = toID(ticket.text[0]);
const creator = ticket.userid;
if (!Config.getpmlog) return;
const pmLog = await Config.getpmlog(targetId, creator) as {
message: string, from: string, to: string, timestamp: string,
}[];
const messages: Record<string, string[]> = {};
const ids = new Set<ID>();
// sort messages by user who sent them, also filter out old ones
for (const {from, message, timestamp} of pmLog) {
// ignore pmlogs more than 24h old
if ((Date.now() - new Date(timestamp).getTime()) > PMLOG_IGNORE_TIME) continue;
const id = toID(from);
ids.add(id);
if (!messages[id]) messages[id] = [];
messages[id].push(message);
}
for (const id of ids) {
let punishment;
const {averages, classified} = await getMessageAverages(messages[id]);
const curPunishment = determinePunishment('pmharassment', averages, []).action;
if (curPunishment) {
if (!punishment || supersedes(curPunishment, punishment)) {
punishment = curPunishment;
}
if (punishment) {
actions.set(id, {
action: punishment,
user: id,
result: {},
reason: `PM harassment (against ${ticket.userid === id ? targetId : ticket.userid})`,
});
}
}
for (const result of classified) {
const {action} = determinePunishment('pmharassment', result, [], true);
if (!action) continue;
const exists = actions.get(id);
if (!exists || supersedes(action, exists.action)) {
actions.set(id, {
action,
user: id,
result: {},
reason: `PM harassment (against ${ticket.userid === id ? targetId : ticket.userid})`,
});
}
}
}
const creatorWasPunished = actions.get(ticket.userid);
if (creatorWasPunished) {
let displayReason = `You were punished for your behavior. `;
if (actions.has(targetId) && targetId !== ticket.userid) {
displayReason += ` The person you reported was also punished.`;
}
creatorWasPunished.displayReason = displayReason;
}
if (actions.size) return actions;
},
};
export const classifier = new Artemis.LocalClassifier();
export async function runPunishments(ticket: TicketState & {text: [string, string]}, typeId: string) {
let result: Map<string, CheckerResult> | null = null;
if (checkers[typeId]) {
result = await checkers[typeId](ticket) || null;
}
if (result) {
if (settings.applyPunishments) {
const responses: [string, string][] = [];
for (const res of result.values()) {
const curResult = await actionHandlers[res.action.toLowerCase()](res.user, res, ticket);
if (curResult) responses.push([res.action, res.displayReason || curResult]);
if (toID(res.user) === ticket.creator) {
// just close the ticket here.
closeTicket(ticket, res.displayReason);
}
}
if (responses.length) {
// if we don't have one for the user, find one.
Utils.sortBy(responses, r => -ORDERED_PUNISHMENTS.indexOf(r[0]));
closeTicket(ticket, responses[0][1]);
} else {
closeTicket(ticket); // no good response. just close it, because we __have__ dispatched an action.
}
} else {
ticket.recommended = [];
for (const res of result.values()) {
Rooms.get('abuselog')?.add(
`|c|&|/log [${ticket.type} Monitor] Recommended: ${res.action}: for ${res.user} (${res.reason})`
).update();
ticket.recommended.push(`${res.action}: for ${res.user} (${res.reason})`);
}
}
}
}
export const commands: Chat.ChatCommands = {
aht: 'autohelpticket',
autohelpticket: {
''() {
return this.parse(`/help autohelpticket`);
},
async test(target) {
checkAccess(this);
target = target.trim();
const response = await classifier.classify(target) || {};
let buf = Utils.html`<strong>Results for "${target}":</strong><br />`;
buf += `<strong>Score breakdown:</strong><br />`;
for (const k in response) {
buf += `• ${k}: ${response[k]}<br />`;
}
this.runBroadcast();
this.sendReplyBox(buf);
},
ap: 'addpunishment',
add: 'addpunishment',
addpunishment(target, room, user) {
checkAccess(this);
if (!toID(target)) return this.parse(`/help autohelpticket`);
const args = Chat.parseArguments(target);
const punishment: Partial<AutoPunishment> = {};
for (const [k, list] of Object.entries(args)) {
if (k !== 'type' && list.length > 1) throw new Chat.ErrorMessage(`More than one ${k} param provided.`);
const val = list[0]; // if key exists, val must exist too
switch (k) {
case 'type': case 't':
const types = list.map(f => f.toLowerCase().replace(/\s/g, '_'));
for (const type of types) {
if (!Artemis.LocalClassifier.ATTRIBUTES[type]) {
return this.errorReply(
`Invalid classifier type '${type}'. Valid types are ` +
Object.keys(Artemis.LocalClassifier.ATTRIBUTES).join(', ')
);
}
}
if (!punishment.severity) {
punishment.severity = {certainty: 0, type: []};
}
punishment.severity.type.push(...types);
break;
case 'certainty': case 'c':
const num = parseFloat(val);
if (isNaN(num) || num < 0 || num > 1) {
return this.errorReply(`Certainty must be a number below 1 and above 0.`);
}
if (!punishment.severity) {
punishment.severity = {certainty: 0, type: []};
}
punishment.severity.certainty = num;
break;
case 'modlog': case 'm':
const count = parseInt(val);
if (isNaN(count) || count < 0) {
return this.errorReply(`Modlog count must be a number above 0.`);
}
punishment.modlogCount = count;
break;
case 'ticket': case 'tt': case 'tickettype':
const type = toID(val);
if (!(type in checkers)) {
return this.errorReply(
`The ticket type '${type}' does not exist or is not supported. ` +
`Supported types are ${Object.keys(checkers).join(', ')}.`
);
}
punishment.ticketType = type;
break;
case 'p': case 'punishment':
const name = toID(val).toUpperCase();
if (!ORDERED_PUNISHMENTS.includes(name)) {
return this.errorReply(
`Punishment '${name}' not supported. ` +
`Supported punishments: ${ORDERED_PUNISHMENTS.join(', ')}`
);
}
punishment.punishment = name;
break;
case 'single': case 's':
if (!this.meansYes(toID(val))) {
return this.errorReply(
`The 'single' value must always be 'on'. ` +
`If you don't want it enabled, just do not use this argument type.`
);
}
punishment.isSingleMessage = true;
break;
}
}
if (!punishment.ticketType) {
return this.errorReply(`Must specify a ticket type to handle.`);
}
if (!punishment.punishment) {
return this.errorReply(`Must specify a punishment to apply.`);
}
if (!(punishment.severity?.certainty && punishment.severity?.type.length)) {
return this.errorReply(`A severity to monitor for must be specified (certainty).`);
}
for (const curP of settings.punishments) {
let matches = 0;
for (const k in curP) {
if (punishment[k as keyof AutoPunishment] === curP[k as keyof AutoPunishment]) {
matches++;
}
}
if (matches === Object.keys(punishment).length) {
return this.errorReply(`That punishment is already added.`);
}
}
settings.punishments.push(punishment as AutoPunishment);
saveSettings();
this.privateGlobalModAction(
`${user.name} added a ${punishment.punishment} punishment to the Artemis helpticket handler.`
);
this.globalModlog(`AUTOHELPTICKET ADDPUNISHMENT`, null, visualizePunishment(punishment as AutoPunishment));
},
dp: 'deletepunishment',
delete: 'deletepunishment',
deletepunishment(target, room, user) {
checkAccess(this);
const num = parseInt(target) - 1;
if (isNaN(num)) return this.parse(`/h autohelpticket`);
const punishment = settings.punishments[num];
if (!punishment) return this.errorReply(`There is no punishment at index ${num + 1}.`);
settings.punishments.splice(num, 1);
this.privateGlobalModAction(
`${user.name} removed the Artemis helpticket ${punishment.punishment} punishment indexed at ${num + 1}`
);
this.globalModlog(`AUTOHELPTICKET REMOVE`, null, visualizePunishment(punishment));
},
vp: 'viewpunishments',
view: 'viewpunishments',
viewpunishments() {
checkAccess(this);
let buf = `<strong>Artemis helpticket punishments</strong><hr />`;
if (!settings.punishments.length) {
buf += `None.`;
return this.sendReplyBox(buf);
}
buf += settings.punishments.map(
(curP, i) => `<strong>${i + 1}:</strong> ${visualizePunishment(curP)}`
).join('<br />');
return this.sendReplyBox(buf);
},
togglepunishments(target, room, user) {
checkAccess(this);
let message;
if (this.meansYes(target)) {
if (settings.applyPunishments) {
return this.errorReply(`Automatic punishments are already enabled.`);
}
settings.applyPunishments = true;
message = `${user.name} enabled automatic punishments for the Artemis ticket handler`;
} else if (this.meansNo(target)) {
if (!settings.applyPunishments) {
return this.errorReply(`Automatic punishments are already disabled.`);
}
settings.applyPunishments = false;
message = `${user.name} disabled automatic punishments for the Artemis ticket handler`;
} else {
return this.errorReply(`Invalid setting. Must be 'on' or 'off'.`);
}
this.privateGlobalModAction(message);
this.globalModlog(`AUTOHELPTICKET TOGGLE`, null, settings.applyPunishments ? 'on' : 'off');
saveSettings();
},
stats(target) {
if (!target) target = Chat.toTimestamp(new Date()).split(' ')[0];
return this.parse(`/j view-autohelpticket-stats-${target}`);
},
logs(target) {
if (!target) target = Chat.toTimestamp(new Date()).split(' ')[0];
return this.parse(`/j view-autohelpticket-logs-${target}`);
},
resolve(target, room, user) {
this.checkCan('lock');
const [ticketId, result] = Utils.splitFirst(target, ',').map(toID);
const ticket = tickets[ticketId];
if (!ticket?.open) {
return this.popupReply(`The user '${ticketId}' does not have a ticket open at present.`);
}
if (!['success', 'failure'].includes(result)) {
return this.popupReply(`The result must be 'success' or 'failure'.`);
}
(ticket.state ||= {}).recommendResult = result;
writeTickets();
Chat.refreshPageFor(`help-text-${ticketId}`, 'staff');
},
},
autohelptickethelp: [
`/aht addpunishment [args] - Adds a punishment with the given [args]. Requires: whitelist &`,
`/aht deletepunishment [index] - Deletes the automatic helpticket punishment at [index]. Requires: whitelist &`,
`/aht viewpunishments - View automatic helpticket punishments. Requires: whitelist &`,
`/aht togglepunishments [on | off] - Turn [on | off] automatic helpticket punishments. Requires: whitelist &`,
`/aht stats - View success rates of the Artemis ticket handler. Requires: whitelist &`,
],
};
export const pages: Chat.PageTable = {
autohelpticket: {
async stats(query, user) {
checkAccess(this);
let month;
if (query.length) {
month = /[0-9]{4}-[0-9]{2}/.exec(query.join('-'))?.[0];
} else {
month = Chat.toTimestamp(new Date()).split(' ')[0].slice(0, -3);
}
if (!month) {
return this.errorReply(`Invalid month. Must be in YYYY-MM format.`);
}
this.title = `[Artemis Ticket Stats] ${month}`;
this.setHTML(`<div class="pad"><h3>Artemis ticket stats</h3><hr />Searching...`);
const found = await HelpTicket.getTextLogs(['recommendResult'], month);
const percent = (numerator: number, denom: number) => Math.floor((numerator / denom) * 100);
let buf = `<div class="pad">`;
buf += `<button style="float:right;" class="button" name="send" value="/join ${this.pageid}">`;
buf += `<i class="fa fa-refresh"></i> Refresh</button>`;
buf += `<h3>Artemis ticket stats</h3><hr />`;
const dayStats: Record<string, {successes: number, failures: number, total: number}> = {};
const total = {successes: 0, failures: 0, total: 0};
const failed = [];
for (const ticket of found) {
const day = Chat.toTimestamp(new Date(ticket.created)).split(' ')[0];
if (!dayStats[day]) dayStats[day] = {successes: 0, failures: 0, total: 0};
dayStats[day].total++;
total.total++;
switch (ticket.state.recommendResult) {
case 'success':
dayStats[day].successes++;
total.successes++;
break;
case 'failure':
dayStats[day].failures++;
total.failures++;
failed.push([ticket.userid, ticket.type]);
break;
}
}
buf += `<strong>Total:</strong> ${total.total}<br />`;
buf += `<strong>Success rate:</strong> ${percent(total.successes, total.total)}% (${total.successes})<br />`;
buf += `<strong>Failure rate:</strong> ${percent(total.failures, total.total)}% (${total.failures})<br />`;
buf += `<strong>Day stats:</strong><br />`;
buf += `<div class="ladder pad"><table>`;
let header = '';
let data = '';
const sortedDays = Utils.sortBy(Object.keys(dayStats), d => new Date(d).getTime());
for (const [i, day] of sortedDays.entries()) {
const cur = dayStats[day];
if (!cur.total) continue;
header += `<th>${day.split('-')[2]} (${cur.total})</th>`;
data += `<td><small>${cur.successes} (${percent(cur.successes, cur.total)}%)`;
if (cur.failures) {
data += ` | ${cur.failures} (${percent(cur.failures, cur.total)}%)`;
} else { // so one cannot confuse dead tickets & false hit tickets
data += ' | 0 (0%)';
}
data += '</small></td>';
// i + 1 ensures it's above 0 always (0 % 5 === 0)
if ((i + 1) % 5 === 0 && sortedDays[i + 1]) {
buf += `<tr>${header}</tr><tr>${data}</tr>`;
buf += `</div></table>`;
buf += `<div class="ladder pad"><table>`;
header = '';
data = '';
}
}
buf += `<tr>${header}</tr><tr>${data}</tr>`;
buf += `</div></table>`;
buf += `<br />`;
if (failed.length) {
buf += `<details class="readmore"><summary>Marked as inaccurate</summary>`;
buf += failed.map(([userid, type]) => (
`<a href="/view-help-text-${userid}">${userid}</a> (${type})`
)).join('<br />');
buf += `</details>`;
}
return buf;
},
async logs(query, user) {
checkAccess(this);
let month;
if (query.length) {
month = /[0-9]{4}-[0-9]{2}/.exec(query.join('-'))?.[0];
} else {
month = Chat.toTimestamp(new Date()).split(' ')[0].slice(0, -3);
}
if (!month) {
return this.errorReply(`Invalid month. Must be in YYYY-MM format.`);
}
this.title = `[Artemis Ticket Logs]`;
let buf = `<div class="pad"><h3>Artemis ticket logs</h3><hr />`;
const allHits = await HelpTicket.getTextLogs(['recommended'], month);
Utils.sortBy(allHits, h => -h.created);
if (allHits.length) {
buf += `<strong>All hits:</strong><hr />`;
for (const hit of allHits) {
if (!hit.recommended) continue; // ???
buf += `<a href="/view-help-text-${hit.userid}">${hit.userid}</a> (${hit.type}) `;
buf += `[${Chat.toTimestamp(new Date(hit.created))}]<br />`;
buf += Utils.html`• <code><small>${hit.recommended.join(', ')}</small></code><hr />`;
}
} else {
buf += `<div class="message-error">No hits found.</div>`;
}
return buf;
},
},
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/dedicatedCloudNodesMappers";
import * as Parameters from "../models/parameters";
import { VMwareCloudSimpleClientContext } from "../vMwareCloudSimpleClientContext";
/** Class representing a DedicatedCloudNodes. */
export class DedicatedCloudNodes {
private readonly client: VMwareCloudSimpleClientContext;
/**
* Create a DedicatedCloudNodes.
* @param {VMwareCloudSimpleClientContext} client Reference to the service client.
*/
constructor(client: VMwareCloudSimpleClientContext) {
this.client = client;
}
/**
* Returns list of dedicate cloud nodes within subscription
* @summary Implements list of dedicated cloud nodes within subscription method
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesListBySubscriptionResponse>
*/
listBySubscription(options?: Models.DedicatedCloudNodesListBySubscriptionOptionalParams): Promise<Models.DedicatedCloudNodesListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: Models.DedicatedCloudNodesListBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
listBySubscription(options?: Models.DedicatedCloudNodesListBySubscriptionOptionalParams | msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): Promise<Models.DedicatedCloudNodesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesListBySubscriptionResponse>;
}
/**
* Returns list of dedicate cloud nodes within resource group
* @summary Implements list of dedicated cloud nodes within RG method
* @param resourceGroupName The name of the resource group
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: Models.DedicatedCloudNodesListByResourceGroupOptionalParams): Promise<Models.DedicatedCloudNodesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
/**
* @param resourceGroupName The name of the resource group
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: Models.DedicatedCloudNodesListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
listByResourceGroup(resourceGroupName: string, options?: Models.DedicatedCloudNodesListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): Promise<Models.DedicatedCloudNodesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesListByResourceGroupResponse>;
}
/**
* Returns dedicated cloud node
* @summary Implements dedicated cloud node GET method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesGetResponse>
*/
get(resourceGroupName: string, dedicatedCloudNodeName: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudNodesGetResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param callback The callback
*/
get(resourceGroupName: string, dedicatedCloudNodeName: string, callback: msRest.ServiceCallback<Models.DedicatedCloudNode>): void;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, dedicatedCloudNodeName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudNode>): void;
get(resourceGroupName: string, dedicatedCloudNodeName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudNode>, callback?: msRest.ServiceCallback<Models.DedicatedCloudNode>): Promise<Models.DedicatedCloudNodesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
dedicatedCloudNodeName,
options
},
getOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesGetResponse>;
}
/**
* Returns dedicated cloud node by its name
* @summary Implements dedicated cloud node PUT method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param dedicatedCloudNodeRequest Create Dedicated Cloud Node request
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, dedicatedCloudNodeName: string, dedicatedCloudNodeRequest: Models.DedicatedCloudNode, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudNodesCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(resourceGroupName,dedicatedCloudNodeName,dedicatedCloudNodeRequest,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.DedicatedCloudNodesCreateOrUpdateResponse>;
}
/**
* Delete dedicated cloud node
* @summary Implements dedicated cloud node DELETE method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesDeleteResponse>
*/
deleteMethod(resourceGroupName: string, dedicatedCloudNodeName: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudNodesDeleteResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, dedicatedCloudNodeName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, dedicatedCloudNodeName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, dedicatedCloudNodeName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.DedicatedCloudNodesDeleteResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
dedicatedCloudNodeName,
options
},
deleteMethodOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesDeleteResponse>;
}
/**
* Patches dedicated node properties
* @summary Implements dedicated cloud node PATCH method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesUpdateResponse>
*/
update(resourceGroupName: string, dedicatedCloudNodeName: string, options?: Models.DedicatedCloudNodesUpdateOptionalParams): Promise<Models.DedicatedCloudNodesUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param callback The callback
*/
update(resourceGroupName: string, dedicatedCloudNodeName: string, callback: msRest.ServiceCallback<Models.DedicatedCloudNode>): void;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, dedicatedCloudNodeName: string, options: Models.DedicatedCloudNodesUpdateOptionalParams, callback: msRest.ServiceCallback<Models.DedicatedCloudNode>): void;
update(resourceGroupName: string, dedicatedCloudNodeName: string, options?: Models.DedicatedCloudNodesUpdateOptionalParams | msRest.ServiceCallback<Models.DedicatedCloudNode>, callback?: msRest.ServiceCallback<Models.DedicatedCloudNode>): Promise<Models.DedicatedCloudNodesUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
dedicatedCloudNodeName,
options
},
updateOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesUpdateResponse>;
}
/**
* Returns dedicated cloud node by its name
* @summary Implements dedicated cloud node PUT method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudNodeName dedicated cloud node name
* @param dedicatedCloudNodeRequest Create Dedicated Cloud Node request
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(resourceGroupName: string, dedicatedCloudNodeName: string, dedicatedCloudNodeRequest: Models.DedicatedCloudNode, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
dedicatedCloudNodeName,
dedicatedCloudNodeRequest,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Returns list of dedicate cloud nodes within subscription
* @summary Implements list of dedicated cloud nodes within subscription method
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesListBySubscriptionNextResponse>
*/
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudNodesListBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): Promise<Models.DedicatedCloudNodesListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBySubscriptionNextOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesListBySubscriptionNextResponse>;
}
/**
* Returns list of dedicate cloud nodes within resource group
* @summary Implements list of dedicated cloud nodes within RG method
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudNodesListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudNodesListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudNodeListResponse>): Promise<Models.DedicatedCloudNodesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.DedicatedCloudNodesListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudNodes",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.top,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNodeListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudNodes",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.top,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNodeListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudNodes/{dedicatedCloudNodeName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudNodeName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNode
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudNodes/{dedicatedCloudNodeName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudNodeName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
204: {
headersMapper: Mappers.DedicatedCloudNodesDeleteHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudNodes/{dedicatedCloudNodeName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudNodeName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: {
tags: [
"options",
"tags"
]
},
mapper: {
...Mappers.PatchPayload,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNode
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudNodes/{dedicatedCloudNodeName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudNodeName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.referer,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "dedicatedCloudNodeRequest",
mapper: {
...Mappers.DedicatedCloudNode,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNode,
headersMapper: Mappers.DedicatedCloudNodesCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNodeListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudNodeListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
}; | the_stack |
import Jaco from '../jaco';
/**
* `U+D7FF` 上位サロゲートのコードポイントひとつ前の文字
*/
const BEFORE_HIGH = '\uD7FF';
/**
* `U+D800` 最初の上位サロゲート文字
*/
const START_HIGH = '\uD800';
/**
* `U+DBFF` 最後の上位サロゲート文字
*/
const END_HIGH = '\uDBFF';
/**
* `U+DC00` 最初の上位サロゲート文字
*/
const START_LOW = '\uDC00';
/**
* `U+DFFF` 最後の下位サロゲート文字
*/
const END_LOW = '\uDFFF';
/**
* `U+E000` 最後の下位サロゲート文字のコードポイントひとつ次の文字
*/
const AFTER_LOW = '\uE000';
// constructor
test('newされたインスタンスは別のオブジェクト', () => {
const a = new Jaco('あ');
const b = new Jaco('あ');
expect(a).not.toBe(b);
});
// length
test('文字列長', () => {
const a = new Jaco('魚花');
expect(a).toHaveLength(2);
});
// length
test('文字列長2', () => {
const a = new Jaco('𩸽のひらき');
expect(a).toHaveLength(5);
});
// addVoicedMarks()
test('濁点付加', () => {
const a = new Jaco('あかうはひふへほハヒフヘホ');
expect(a.addVoicedMarks().toString()).toBe('あがうばびぶべぼバビブベボ');
});
// addSemivoicedMarks()
test('半濁点付加', () => {
const a = new Jaco('あかうはひふへほハヒフヘホ');
expect(a.addSemivoicedMarks().toString()).toBe('あかうぱぴぷぺぽパピプペポ');
});
// append()
test('後方結合', () => {
const a = new Jaco('あい');
expect(a.append('うえお').toString()).toBe('あいうえお');
});
// append()
test('後方結合2', () => {
const a = new Jaco('いろは');
expect(a.append(new Jaco('にほへと')).toString()).toBe('いろはにほへと');
});
// byteSize()
test('バイト数', () => {
const a = new Jaco('あいうえおabc');
expect(a.byteSize()).toBe(18);
});
// byteSize()
test('バイト数2', () => {
const a = new Jaco('あ い う え\nお a b c');
expect(a.byteSize()).toBe(25);
});
// charAt()
test('抜き出し', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charAt().toString()).toBe('𩸽');
});
// charAt()
test('抜き出し2', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charAt(0).toString()).toBe('𩸽');
});
// charAt()
test('抜き出し3', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charAt(1).toString()).toBe('の');
});
// charAt()
test('抜き出し4', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charAt(99).toString()).toBe('');
});
// charCodeAt()
test('コード抜き出し', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charCodeAt()).toBe(0x29e3d);
});
// charCodeAt()
test('コード抜き出し2', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charCodeAt(0)).toBe(0x29e3d);
});
// charCodeAt()
test('コード抜き出し3', () => {
const a = new Jaco('𩸽のひらき');
expect(a.charCodeAt(1)).toBe(0x306e);
});
// charCodeAt()
test('コード抜き出し4', () => {
const a = new Jaco('𩸽のひらき');
expect(isNaN(a.charCodeAt(99))).toBe(true);
});
// clone()
test('コピー', () => {
const a = new Jaco('あ');
const b = a.clone();
expect(a).not.toBe(b);
});
// clone()
test('コピー2', () => {
const a = new Jaco('あ');
const b = a.clone();
expect(a.toString()).toBe(b.toString());
});
// combinateSoundMarks()
test('濁点・半濁点の結合', () => {
const a = new Jaco('か゛き゛く゛け゛こ゛');
expect(a.combinateSoundMarks(true).toString()).toBe('がぎぐげご');
});
// combinateSoundMarks()
test('濁点・半濁点の結合2', () => {
const a = new Jaco('は゜ひ゜ふ゜へ゜ほ゜');
expect(a.combinateSoundMarks(true).toString()).toBe('ぱぴぷぺぽ');
});
// combinateSoundMarks()
test('濁点・半濁点の結合3', () => {
const a = new Jaco('か゛き゛く゛け゛こ゛');
expect(a.combinateSoundMarks().toString()).toBe('がぎぐげご');
});
// combinateSoundMarks()
test('濁点・半濁点の結合4', () => {
const a = new Jaco('は゜ひ゜ふ゜へ゜ほ゜');
expect(a.combinateSoundMarks().toString()).toBe('ぱぴぷぺぽ');
});
// combinateSoundMarks()
test('濁点・半濁点の結合5', () => {
const a = new Jaco('がぎぐげご');
expect(a.combinateSoundMarks().toString()).toBe('がぎぐげご');
});
// combinateSoundMarks()
test('濁点・半濁点の結合6', () => {
const a = new Jaco('ぱぴぷぺぽ');
expect(a.combinateSoundMarks().toString()).toBe('ぱぴぷぺぽ');
});
// concat()
test('連結', () => {
const a = new Jaco('あ');
expect(
a
.concat('い', new Jaco('う'), 'え', new Jaco('お'), [
'か',
new Jaco('き')
])
.toString()
).toBe('あいうえおかき');
});
// convertIterationMarks()
test('繰り返し記号変換', () => {
expect(new Jaco('がくもんのすゝめ').convertIterationMarks().toString()).toBe(
'がくもんのすすめ'
);
});
// convertIterationMarks()
test('繰り返し記号変換2', () => {
expect(
new Jaco('がくもんのすゝゝゝゝゝゝゝゝゝゝゝゝめ')
.convertIterationMarks()
.toString()
).toBe('がくもんのすすすすすすすすすすすすすめ');
});
// convertIterationMarks()
test('繰り返し記号変換3', () => {
expect(
new Jaco('がくもんのすゝゝゝゞゝゝゝゝゝゝゝゝゝめ')
.convertIterationMarks()
.toString()
).toBe('がくもんのすすすすずすすすすすすすすすめ');
});
// convertIterationMarks()
test('繰り返し記号変換4', () => {
expect(
new Jaco('ゝゞあゝゞかゞゝがゝゞゝ').convertIterationMarks().toString()
).toBe('ゝゞあああかがかがかがか');
});
// convertIterationMarks()
test('繰り返し記号変換5', () => {
expect(
new Jaco('ガクモンノスヽヽヽヽヽヽヽヽヽヽヽヽメ')
.convertIterationMarks()
.toString()
).toBe('ガクモンノスススススススススススススメ');
});
// convertIterationMarks()
test('繰り返し記号変換6', () => {
expect(
new Jaco('ヽヾアヽヾカヾヽガヽヾヽ').convertIterationMarks().toString()
).toBe('ヽヾアアアカガカガカガカ');
});
// convertProlongedSoundMarks()
test('長音符変換', () => {
const a = [
'あーぁーかーゕーがーさーざーたーだーなーはーばーぱーまーやーゃーらー',
'わーゎーいーぃーきーぎーしーじーちーぢーにーひーびーぴーみーりーゐー',
'うーぅーゔーくーぐーすーずーつーづーぬーふーぶーぷーむーゆーゅーるー',
'えーぇーけーゖーげーせーぜーてーでーねーへーべーぺーめーれーゑーおー',
'ぉーこーごーそーぞーとーどーのーほーぼーぽーもーよーょーろーをー',
'アーァーカーヵーガーサーザーターダーナーハーバーパーマーヤーャーラー',
'ワーヮーイーィーキーギーシージーチーヂーニーヒービーピーミーリーヰー',
'ウーゥーヴークーグースーズーツーヅーヌーフーブープームーユーュールー',
'エーェーケーヶーゲーセーゼーテーデーネーヘーベーペーメーレーヱーオー',
'ォーコーゴーソーゾートードーノーホーボーポーモーヨーョーローヲー',
'ヷーヸーヹーヺー',
'んーっーンーッー'
].join('');
const a2 = new Jaco(a);
const b = [
'ああぁあかあゕあがあさあざあたあだあなあはあばあぱあまあやあゃあらあ',
'わあゎあいいぃいきいぎいしいじいちいぢいにいひいびいぴいみいりいゐい',
'ううぅうゔうくうぐうすうずうつうづうぬうふうぶうぷうむうゆうゅうるう',
'ええぇえけえゖえげえせえぜえてえでえねえへえべえぺえめえれえゑえおお',
'ぉおこおごおそおぞおとおどおのおほおぼおぽおもおよおょおろおをお',
'アアァアカアヵアガアサアザアタアダアナアハアバアパアマアヤアャアラア',
'ワアヮアイイィイキイギイシイジイチイヂイニイヒイビイピイミイリイヰイ',
'ウウゥウヴウクウグウスウズウツウヅウヌウフウブウプウムウユウュウルウ',
'エエェエケエヶエゲエセエゼエテエデエネエヘエベエペエメエレエヱエオオ',
'ォオコオゴオソオゾオトオドオノオホオボオポオモオヨオョオロオヲオ',
'ヷアヸイヹエヺオ',
'んんっっンンッッ'
].join('');
expect(a2.convertProlongedSoundMarks().toString()).toBe(b);
});
// convertProlongedSoundMarks()
test('長音符変換2', () => {
expect(
new Jaco('ウバッシャアーーーーーーーーー')
.convertProlongedSoundMarks()
.toString()
).toBe('ウバッシャアアアアアアアアアア');
});
// endWith()
test('末尾合致 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.endWith('ひらき')).toBe(true);
});
// endWith()
test('末尾合致2 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.endWith('𩸽の')).toBe(false);
});
// endWith()
test('末尾合致3 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.endWith('ひら', 4)).toBe(true);
});
// endWith()
test('末尾合致4 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.endWith('𩸽の', 2)).toBe(true);
});
// endWith()
test('末尾合致5 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.endWith(new Jaco('ひら'), 4)).toBe(true);
});
// endWith()
test('末尾合致6 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.endWith(new Jaco('𩸽の'), 2)).toBe(true);
});
// has()
test('含むかどうか', () => {
const a = new Jaco('いろは');
expect(a.has('い')).toBe(true);
});
// has()
test('含むかどうか2', () => {
const a = new Jaco('いろは');
expect(a.has(new Jaco('い'))).toBe(true);
});
// has()
test('含むかどうか3', () => {
const a = new Jaco('いろは');
expect(a.has(new Jaco('あ'))).toBe(false);
});
// has()
test('含むかどうか4', () => {
const a = new Jaco('いろは');
expect(a.has('いろ')).toBe(true);
});
// has()
test('含むかどうか5', () => {
const a = new Jaco('いろは');
expect(a.has('いは')).toBe(true);
});
// has()
test('含むかどうか6', () => {
const a = new Jaco('いろは');
expect(a.has('ろは')).toBe(true);
});
// has()
test('含むかどうか7', () => {
const a = new Jaco('いろは');
expect(a.has('にほへと')).toBe(false);
});
// has()
test('含むかどうか8', () => {
const a = new Jaco('いろは');
expect(a.has('a-z')).toBe(false);
});
// has()
test('含むかどうか9', () => {
const a = new Jaco('いろは');
expect(a.has('あ-ん')).toBe(true);
});
// hasSmallLetter
test('小書き文字の検知', () => {
expect(
new Jaco(
'ぁぃぅぇぉっゃゅょゎァィゥェォヵㇰヶㇱㇲッㇳㇴㇵㇶㇷㇸㇹㇺャュョㇻㇼㇽㇾㇿヮ'
).hasSmallLetter()
).toBe(true);
});
// hasSmallLetter
test('小書き文字の検知2', () => {
expect(new Jaco('あァァァんまりだァァアァ').hasSmallLetter()).toBe(true);
});
// hasSmallLetter
test('小書き文字の検知3', () => {
expect(new Jaco('あいうえお').hasSmallLetter()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知', () => {
expect(new Jaco('𩸽のひらき').hasSurrogatePair()).toBe(true);
});
// hasSurrogatePair
test('サロゲートペア検知2', () => {
expect(new Jaco('ほっけのひらき').hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知3 (上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知4 (上位サロゲートのみ)', () => {
expect(new Jaco(START_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知5 (上位サロゲートのみ 最後のコードポイント)', () => {
expect(new Jaco(END_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知6 (下位サロゲートのみ)', () => {
expect(new Jaco(START_LOW).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知7 (下位サロゲートのみ 最後のコードポイント)', () => {
expect(new Jaco(END_LOW).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知8 (下位サロゲートのコードポイントひとつ次の文字)', () => {
expect(new Jaco(AFTER_LOW).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知9 (上位サロゲートのコードポイントひとつ前の文字 + 上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(BEFORE_HIGH + BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知10 (上位サロゲートのみ + 上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(START_HIGH + BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知11 (上位サロゲートのみ 最後のコードポイント + 上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(END_HIGH + BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知12 (下位サロゲートのみ + 上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(START_LOW + BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知13 (下位サロゲートのコードポイントひとつ次の文字 + 上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(AFTER_LOW + BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知14 (下位サロゲート コードポイントひとつ次 + 上位サロゲートのコードポイントひとつ前の文字)', () => {
expect(new Jaco(AFTER_LOW + BEFORE_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知15 (上位サロゲートのコードポイントひとつ前の文字 + 上位サロゲート)', () => {
expect(new Jaco(BEFORE_HIGH + START_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知16 (上位サロゲートのみ + 上位サロゲート)', () => {
expect(new Jaco(START_HIGH + START_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知17 (上位サロゲートのみ 最後のコードポイント + 上位サロゲート)', () => {
expect(new Jaco(END_HIGH + START_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知18 (下位サロゲートのみ + 上位サロゲート)', () => {
expect(new Jaco(END_LOW + START_LOW).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知19 (下位サロゲートのコードポイントひとつ次の文字 + 上位サロゲート)', () => {
expect(new Jaco(AFTER_LOW + START_HIGH).hasSurrogatePair()).toBe(false);
});
// hasSurrogatePair
test('サロゲートペア検知20 (下位サロゲート コードポイントひとつ次 + 上位サロゲート)', () => {
expect(new Jaco(AFTER_LOW + START_LOW).hasSurrogatePair()).toBe(false);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知', () => {
expect(new Jaco('𩸽のひらき').hasUnpairedSurrogate()).toBe(false);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知2', () => {
expect(new Jaco('𩸽𩸽𩸽𩸽𩸽').hasUnpairedSurrogate()).toBe(false);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知3', () => {
expect(new Jaco('ほっけのひらき').hasUnpairedSurrogate()).toBe(false);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知4', () => {
expect(new Jaco(BEFORE_HIGH).hasUnpairedSurrogate()).toBe(false);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知5', () => {
expect(new Jaco(BEFORE_HIGH + START_HIGH).hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知6', () => {
expect(
new Jaco(BEFORE_HIGH + START_HIGH + END_HIGH).hasUnpairedSurrogate()
).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知7', () => {
expect(new Jaco('\ud867ほっけのひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知8', () => {
expect(new Jaco('ほっけのひらき\ud867').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知9', () => {
expect(new Jaco('ほっけ\ud867のひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知10', () => {
expect(new Jaco('ほっけ\ude3dのひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知11', () => {
expect(new Jaco('𩸽\ude3dのひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知12', () => {
expect(new Jaco('𩸽\ud867のひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知13', () => {
expect(new Jaco('\ude3d𩸽のひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知14', () => {
expect(new Jaco('\ud867𩸽のひらき').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知15', () => {
expect(new Jaco('ひらきにする𩸽\ud867').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知16', () => {
expect(new Jaco('ひらきにする𩸽\ude3d').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知17', () => {
expect(new Jaco('ひらきにする\ud867𩸽').hasUnpairedSurrogate()).toBe(true);
});
// hasUnpairedSurrogate
test('不完全サロゲートペア検知18', () => {
expect(new Jaco('ひらきにする\ude3d𩸽').hasUnpairedSurrogate()).toBe(true);
});
// includes()
test('部分合致', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.includes('𩸽の')).toBe(true);
});
// includes()
test('部分合致2', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.includes('の刺し身の切り')).toBe(true);
});
// includes()
test('部分合致3', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.includes('𩸽の刺しの切り身')).toBe(false);
});
// indexOf()
test('前方検索', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf('の')).toBe(1);
});
// indexOf()
test('前方検索2', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf('の', 3)).toBe(5);
});
// indexOf()
test('前方検索3', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf(new Jaco('の'))).toBe(1);
});
// indexOf()
test('前方検索4', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf(new Jaco('の'), 3)).toBe(5);
});
// indexOf()
test('前方検索5', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf(new Jaco('挿し'))).toBe(-1);
});
// indexOf()
test('前方検索6', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf(new Jaco('𩸽の刺し'))).toBe(0);
});
// indexOf()
test('前方検索7', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.indexOf(new Jaco('身の切り身'))).toBe(4);
});
// is()
test('完全マッチ', () => {
const a = new Jaco('いろは');
expect(a.is('いろは')).toBe(true);
});
// is()
test('完全マッチ2', () => {
const a = new Jaco('いろは');
expect(a.is(new Jaco('いろは'))).toBe(true);
});
// is()
test('完全マッチ3', () => {
const a = new Jaco('いろは');
expect(a.is('いろはに')).toBe(false);
});
// is()
test('完全マッチ4', () => {
const a = new Jaco('いろは');
expect(a.is(new Jaco('いろはに'))).toBe(false);
});
// isEmpty()
test('空', () => {
const a = new Jaco('');
expect(a.isEmpty()).toBe(true);
});
test('空2', () => {
const a = new Jaco(' ');
expect(a.isEmpty()).toBe(false);
});
// isNumeric()
test('数字かどうか1', () => {
const a = new Jaco(' 23s03sdkふぁえ');
expect(a.isNumeric()).toBe(false);
});
// isNumeric()
test('数字かどうか2', () => {
const a = new Jaco('2303');
expect(a.isNumeric()).toBe(false);
});
// isNumeric()
test('数字かどうか3', () => {
const a = new Jaco('000012303234');
expect(a.isNumeric()).toBe(true);
});
// isNumeric()
test('数字かどうか4', () => {
const a = new Jaco('-123.3234');
expect(a.isNumeric()).toBe(true);
});
// isNumeric()
test('数字かどうか5', () => {
const a = new Jaco('-123.3234.');
expect(a.isNumeric()).toBe(false);
});
// isNumeric()
test('数字かどうか6', () => {
const a = new Jaco('12-3.3234.');
expect(a.isNumeric()).toBe(false);
});
// isNumeric()
test('数字かどうか7', () => {
const a = new Jaco('.3234');
expect(a.isNumeric()).toBe(true);
});
// isNumeric()
test('数字かどうか8', () => {
const a = new Jaco('-.3234');
expect(a.isNumeric()).toBe(true);
});
// isNumeric()
test('数字かどうか9', () => {
const a = new Jaco('.3234');
expect(a.isNumeric(false)).toBe(true);
});
// isNumeric()
test('数字かどうか10', () => {
const a = new Jaco('-.3234');
expect(a.isNumeric(true)).toBe(true);
});
// isNumeric()
test('数字かどうか11', () => {
const a = new Jaco('.3234');
expect(a.isNumeric(true, true)).toBe(true);
});
// isNumeric()
test('数字かどうか12', () => {
const a = new Jaco('-.3234');
expect(a.isNumeric(true, false)).toBe(false);
});
// isNumeric()
test('数字かどうか13', () => {
const a = new Jaco('.3234');
expect(a.isNumeric(false, false)).toBe(false);
});
// isNumeric()
test('数字かどうか14', () => {
const a = new Jaco('-.3234');
expect(a.isNumeric(false, true)).toBe(false);
});
// isOnly()
test('該当の文字のみ', () => {
const a = new Jaco('いろは');
expect(a.isOnly('いろはにほへと')).toBe(true);
});
// isOnly()
test('該当の文字のみ2', () => {
const a = new Jaco('いろは');
expect(a.isOnly('いはにほへと')).toBe(false);
});
// isOnly()
test('該当の文字のみ3', () => {
const a = new Jaco('abcいろは');
expect(a.isOnly('いろはにほへと')).toBe(false);
});
// isOnly()
test('該当の文字のみ4', () => {
const a = new Jaco('いろは');
expect(a.isOnly('いろは')).toBe(true);
});
// isOnly()
test('該当の文字のみ5', () => {
const a = new Jaco('いろは');
expect(a.isOnly('いろ')).toBe(false);
});
// isOnly()
test('該当の文字のみ6', () => {
const a = new Jaco('いろは');
expect(a.isOnly('いろろろろははははにににに')).toBe(true);
});
// isOnly()
test('該当の文字のみ7', () => {
const a = new Jaco('いろはち');
expect(a.isOnly('いろはにほへと')).toBe(false);
});
// isOnly()
test('該当の文字のみ8', () => {
const a = new Jaco('いろはち');
expect(a.isOnly(']()[][')).toBe(false);
});
// isOnly()
test('該当の文字のみ9', () => {
const a = new Jaco('\\');
expect(a.isOnly(']()[]\\')).toBe(true);
});
// isOnly()
test('該当の文字のみ10', () => {
const a = new Jaco('\\');
expect(a.isOnly('\\')).toBe(true);
});
// isOnly()
test('該当の文字のみ11', () => {
const a = new Jaco('\\あ\\');
expect(a.isOnly('\\あ')).toBe(true);
});
// isOnly()
test('該当の文字のみ12', () => {
const a = new Jaco('^^^');
expect(a.isOnly('^')).toBe(true);
});
// isOnly()
test('該当の文字のみ13', () => {
const a = new Jaco('^$^');
expect(a.isOnly('$^')).toBe(true);
});
// isOnly()
test('該当の文字のみ14', () => {
const a = new Jaco('あいうえお');
expect(a.isOnly('あ-お')).toBe(true);
});
// isOnly()
test('該当の文字のみ15', () => {
const a = new Jaco('あいうえおか');
expect(a.isOnly('あ-お')).toBe(false);
});
// isOnlyHiragana()
test('ひらがなのみ', () => {
const test = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('');
const a = new Jaco(test);
expect(a.isOnlyHiragana()).toBe(true);
});
// isOnlyHiragana()
test('ひらがなのみ2', () => {
const test = [
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
const a = new Jaco(test);
expect(a.isOnlyHiragana()).toBe(false);
});
// isOnlyHiragana()
test('ひらがなのみ3', () => {
const test = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛漢字'
].join('');
const a = new Jaco(test);
expect(a.isOnlyHiragana()).toBe(false);
});
// isOnlyHiragana()
test('ひらがなのみ4', () => {
const test = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛123'
].join('');
const a = new Jaco(test);
expect(a.isOnlyHiragana()).toBe(false);
});
// isOnlyHiragana()
test('ひらがなのみ5', () => {
const test = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛abc'
].join('');
const a = new Jaco(test);
expect(a.isOnlyHiragana()).toBe(false);
});
// isOnlyKatakana()
test('カタカナのみ', () => {
const test = [
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゜'
].join('');
const a = new Jaco(test);
expect(a.isOnlyKatakana()).toBe(true);
});
// isOnlyKatakana()
test('カタカナのみ2', () => {
const test = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('');
const a = new Jaco(test);
expect(a.isOnlyKatakana()).toBe(false);
});
// isOnlyKatakana()
test('カタカナのみ3', () => {
const test = [
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゜漢字'
].join('');
const a = new Jaco(test);
expect(a.isOnlyKatakana()).toBe(false);
});
// isOnlyKatakana()
test('カタカナのみ4', () => {
const test = [
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゜123'
].join('');
const a = new Jaco(test);
expect(a.isOnlyKatakana()).toBe(false);
});
// isOnlyKatakana()
test('カタカナのみ5', () => {
const test = [
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゜abc'
].join('');
const a = new Jaco(test);
expect(a.isOnlyKatakana()).toBe(false);
});
// lastIndexOf()
test('後方検索', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.lastIndexOf('の')).toBe(5);
});
// lastIndexOf()
test('後方検索2', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.lastIndexOf('の', 0)).toBe(-1);
});
// lastIndexOf()
test('後方検索3', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.lastIndexOf(new Jaco('の'))).toBe(5);
});
// lastIndexOf()
test('後方検索4', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.lastIndexOf(new Jaco('の'), 0)).toBe(-1);
});
// lastIndexOf()
test('後方検索5', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.lastIndexOf(new Jaco('挿し'))).toBe(-1);
});
// match()
test('マッチ', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(Array.from(a.match(/の/g) || [])).toEqual(['の', 'の']);
});
// match()
test('マッチ2', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(Array.from(a.match(/.+(の).+/) || [])).toEqual([
'𩸽の刺し身の切り身',
'の'
]);
});
// match()
test('マッチ3', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(a.match(/挿し/)).toBeFalsy();
});
// matches()
test('マッチ取得', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(Array.from(a.matches(/の/g))).toEqual(['の', 'の']);
});
// matches()
test('マッチ取得2', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(Array.from(a.matches(/.+(の).+/))).toEqual([
'𩸽の刺し身の切り身',
'の'
]);
});
// matches()
test('マッチ取得3', () => {
const a = new Jaco('𩸽の刺し身の切り身');
expect(Array.from(a.matches(/挿し/))).toEqual([]);
});
// padEnd()
test('後ろ埋め', () => {
const a = new Jaco('𩸽');
expect(a.padEnd(3).toString()).toBe('𩸽 ');
});
// padEnd()
test('後ろ埋め2', () => {
const a = new Jaco('𩸽');
expect(a.padEnd(3, '𩸽').toString()).toBe('𩸽𩸽𩸽');
});
// padEnd()
test('後ろ埋め3', () => {
const a = new Jaco('a');
expect(a.padEnd(3, '𩸽').toString()).toBe('a𩸽𩸽');
});
// padEnd()
test('後ろ埋め4', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padEnd(3).toString()).toBe('𩸽のひ');
});
// padEnd()
test('後ろ埋め5', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padEnd(3, 'abc').toString()).toBe('𩸽のひ');
});
// padEnd()
test('後ろ埋め6', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padEnd(10, 'abc').toString()).toBe('𩸽のひらきabcab');
});
// padEnd()
test('後ろ埋め7', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padEnd(-1).toString()).toBe('𩸽のひらき');
});
// padStart()
test('前埋め', () => {
const a = new Jaco('𩸽');
expect(a.padStart(3).toString()).toBe(' 𩸽');
});
// padStart()
test('前埋め2', () => {
const a = new Jaco('𩸽');
expect(a.padStart(3, '𩸽').toString()).toBe('𩸽𩸽𩸽');
});
// padStart()
test('前埋め3', () => {
const a = new Jaco('a');
expect(a.padStart(3, '𩸽').toString()).toBe('𩸽𩸽a');
});
// padStart()
test('前埋め4', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padStart(3).toString()).toBe('𩸽のひ');
});
// padStart()
test('前埋め5', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padStart(3, 'abc').toString()).toBe('𩸽のひ');
});
// padStart()
test('前埋め6', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padStart(10, 'abc').toString()).toBe('abcab𩸽のひらき');
});
// padStart()
test('前埋め7', () => {
const a = new Jaco('𩸽のひらき');
expect(a.padStart(-1).toString()).toBe('𩸽のひらき');
});
// prepend()
test('前方結合', () => {
const a = new Jaco('うえお');
expect(a.prepend('あい').toString()).toBe('あいうえお');
});
// prepend()
test('前方結合2', () => {
const a = new Jaco('にほへと');
expect(a.prepend(new Jaco('いろは')).toString()).toBe('いろはにほへと');
});
// remove()
test('削除', () => {
const a = new Jaco('aBcDeFgHiJkLmNoPqRsTuVwXyZ');
expect(a.remove('aBc').toString()).toBe('DeFgHiJkLmNoPqRsTuVwXyZ');
});
// remove()
test('削除2', () => {
const a = new Jaco('aBcDeFgHiJkLmNoPqRsTuVwXyZ');
expect(a.remove(/[a-z]/).toString()).toBe('BcDeFgHiJkLmNoPqRsTuVwXyZ');
});
// remove()
test('削除3', () => {
const a = new Jaco('aBcDeFgHiJkLmNoPqRsTuVwXyZ');
expect(a.remove(/[a-z]/g).toString()).toBe('BDFHJLNPRTVXZ');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除', () => {
expect(new Jaco('𩸽のひらき').removeUnpairedSurrogate().toString()).toBe(
'𩸽のひらき'
);
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除2', () => {
expect(new Jaco('𩸽𩸽𩸽𩸽𩸽').removeUnpairedSurrogate().toString()).toBe(
'𩸽𩸽𩸽𩸽𩸽'
);
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除3', () => {
expect(
new Jaco('\ude3d\ud867\ude3d\ud867\ude3d\ud867')
.removeUnpairedSurrogate()
.toString()
).toBe('𩸽𩸽');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除4', () => {
expect(new Jaco('ほっけのひらき').removeUnpairedSurrogate().toString()).toBe(
'ほっけのひらき'
);
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除5', () => {
expect(
new Jaco(`${START_HIGH}ほっけのひらき`).removeUnpairedSurrogate().toString()
).toBe('ほっけのひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除6', () => {
expect(
new Jaco(`ほっけのひらき${END_LOW}`).removeUnpairedSurrogate().toString()
).toBe('ほっけのひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除7', () => {
expect(
new Jaco(`${START_HIGH}ほっけのひらき`).removeUnpairedSurrogate().toString()
).toBe('ほっけのひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除8', () => {
expect(
new Jaco(`ほっけのひらき${END_LOW}`).removeUnpairedSurrogate().toString()
).toBe('ほっけのひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除9', () => {
expect(
new Jaco('ほっけ\ud867のひらき').removeUnpairedSurrogate().toString()
).toBe('ほっけのひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除10', () => {
expect(
new Jaco('ほっけ\ude3dのひらき').removeUnpairedSurrogate().toString()
).toBe('ほっけのひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除11', () => {
expect(
new Jaco('𩸽\ude3dのひらき').removeUnpairedSurrogate().toString()
).toBe('𩸽のひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除12', () => {
expect(
new Jaco('𩸽\ud867のひらき').removeUnpairedSurrogate().toString()
).toBe('𩸽のひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除13', () => {
expect(
new Jaco('\ude3d𩸽のひらき').removeUnpairedSurrogate().toString()
).toBe('𩸽のひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除14', () => {
expect(
new Jaco('\ud867𩸽のひらき').removeUnpairedSurrogate().toString()
).toBe('𩸽のひらき');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除15', () => {
expect(
new Jaco('ひらきにする𩸽\ud867').removeUnpairedSurrogate().toString()
).toBe('ひらきにする𩸽');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除16', () => {
expect(
new Jaco('ひらきにする𩸽\ude3d').removeUnpairedSurrogate().toString()
).toBe('ひらきにする𩸽');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除17', () => {
expect(
new Jaco('ひらきにする\ud867𩸽').removeUnpairedSurrogate().toString()
).toBe('ひらきにする𩸽');
});
// removeUnpairedSurrogate
test('不完全サロゲートペアの削除18', () => {
expect(
new Jaco('ひらきにする\ude3d𩸽').removeUnpairedSurrogate().toString()
).toBe('ひらきにする𩸽');
});
// removeVoicedMarks()
test('濁点・半濁点除去', () => {
const a = [
'がぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺぽ',
'ガギグゲゴザジズゼゾダヂヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
const a2 = new Jaco(a);
const b = [
'かきくけこさしすせそたちつてとはひふへほはひふへほ',
'カキクケコサシスセソタチツテトハヒフヘホハヒフヘホワイウエヲ'
].join('');
expect(a2.removeVoicedMarks().toString()).toBe(b);
});
// repeat()
test('くりかえし', () => {
const a = new Jaco('あ');
expect(a.repeat(3).toString()).toBe('あああ');
});
// repeat()
test('くりかえし2', () => {
const a = new Jaco('𩸽と');
expect(a.repeat(6).toString()).toBe('𩸽と𩸽と𩸽と𩸽と𩸽と𩸽と');
});
// repeat()
test('くりかえし3', () => {
const a = new Jaco('𩸽');
expect(a.repeat(0).toString()).toBe('');
});
// repeat()
test('くりかえし4', () => {
const a = new Jaco('𩸽');
expect(a.repeat().toString()).toBe('');
});
// repeat()
test('くりかえし5 小数点切り捨て', () => {
const a = new Jaco('𩸽');
expect(a.repeat(3.5).toString()).toBe('𩸽𩸽𩸽');
});
// repeat()
test('くりかえし6 負の数は0強制', () => {
const a = new Jaco('𩸽');
expect(a.repeat(-1).toString()).toBe('');
});
// repeat()
test('くりかえし7 無限エラー', () => {
const a = new Jaco('𩸽');
try {
a.repeat(Infinity);
} catch (e) {
// never
}
});
// replace()
test('置換', () => {
const a = new Jaco('abcdeABCDE');
expect(a.replace(/abc/gi, 'z').toString()).toBe('zdezDE');
});
// replace()
test('置換2', () => {
const a = new Jaco('abcdeABCDE');
expect(a.replace('abc', 'z').toString()).toBe('zdeABCDE');
});
// replace()
test('置換3', () => {
const a = new Jaco('abcdeABCDE');
expect(a.replace(new Jaco('abc'), 'z').toString()).toBe('zdeABCDE');
});
// replaceFromMap()
test('マップから置換', () => {
const a = new Jaco('abcdeABCDE');
expect(
a
.replaceFromMap({
abc: 'z',
ABC: 'Z'
})
.toString()
).toBe('zdeZDE');
});
// search()
test('検索', () => {
const a = new Jaco('食べたい𩸽');
expect(a.search(/𩸽/)).toBe(4);
});
// search()
test('検索2', () => {
const a = new Jaco('𩸽の刺し身');
expect(a.search(/の/)).toBe(1);
});
// search()
test('検索3', () => {
const a = new Jaco('食べたい𩸽の刺し身');
expect(a.search('の')).toBe(5);
});
// search()
test('検索4', () => {
const a = new Jaco('𩸽の刺し身');
expect(a.search(new Jaco('の'))).toBe(1);
});
// slice()
test('抽出', () => {
const a = new Jaco('いろはにほへと');
const b = a.slice(1, 5);
expect(b.toString()).toBe('ろはにほ');
});
// slice()
test('抽出2', () => {
const a = new Jaco('いろはにほへと');
const b = a.slice(1);
expect(b.toString()).toBe('ろはにほへと');
});
// slice()
test('抽出3', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.slice(1, 3);
expect(b.toString()).toBe('の刺');
});
// slice()
test('抽出4', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.slice(1);
expect(b.toString()).toBe('の刺し身');
});
// split()
test('分割', () => {
const a = new Jaco('𩸽の刺し身');
expect(a.split('の')).toEqual(['𩸽', '刺し身']);
});
// split()
test('分割2', () => {
const a = new Jaco('asadafa');
expect(a.split('a')).toEqual(['', 's', 'd', 'f', '']);
});
// split()
test('分割3', () => {
const a = new Jaco('asadafa');
expect(a.split(/a/)).toEqual(['', 's', 'd', 'f', '']);
});
// split()
test('分割4', () => {
const a = new Jaco('asadafa');
expect(a.split(/a/g)).toEqual(['', 's', 'd', 'f', '']);
});
// split()
test('分割5', () => {
const a = new Jaco('asadafa');
expect(a.split(/(a)/)).toEqual(['', 'a', 's', 'a', 'd', 'a', 'f', 'a', '']);
});
// startsWith()
test('先頭合致 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.startsWith('𩸽のひらき')).toBe(true);
});
// startsWith()
test('先頭合致2 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.startsWith('のひらき')).toBe(false);
});
// startsWith()
test('先頭合致3 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.startsWith('ひら', 2)).toBe(true);
});
// startsWith()
test('先頭合致4 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.startsWith('ひらき', 2)).toBe(true);
});
// startsWith()
test('先頭合致5 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.startsWith(new Jaco('ら'), 3)).toBe(true);
});
// startsWith()
test('先頭合致6 ', () => {
const a = new Jaco('𩸽のひらき');
expect(a.startsWith(new Jaco('𩸽の'), 0)).toBe(true);
});
// substr()
test('長さで抽出', () => {
const a = new Jaco('いろはにほへと');
const b = a.substr(1, 2);
expect(b.toString()).toBe('ろは');
});
// substr()
test('長さで抽出2', () => {
const a = new Jaco('いろはにほへと');
const b = a.substr(1);
expect(b.toString()).toBe('ろはにほへと');
});
// substr()
test('長さで抽出3', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.substr(2, 3);
expect(b.toString()).toBe('刺し身');
});
// substr()
test('長さで抽出4', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.substr(-1, 1);
expect(b.toString()).toBe('身');
});
// substring()
test('インデックスから抽出', () => {
const a = new Jaco('いろはにほへと');
const b = a.substring(0, 2);
expect(b.toString()).toBe('いろ');
});
// substring()
test('インデックスから抽出2', () => {
const a = new Jaco('いろはにほへと');
const b = a.substring(1, 3);
expect(b.toString()).toBe('ろは');
});
// substring()
test('インデックスから抽出3', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.substring(1, 4);
expect(b.toString()).toBe('の刺し');
});
// substring()
test('インデックスから抽出4', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.substring(4, 1);
expect(b.toString()).toBe('の刺し');
});
// substring()
test('インデックスから抽出5', () => {
const a = new Jaco('𩸽の刺し身');
const b = a.substring(-5, 16);
expect(b.toString()).toBe('𩸽の刺し身');
});
// test()
test('テスト', () => {
const a = new Jaco('あいう');
expect(a.test('あいう')).toBe(true);
});
// test()
test('テスト2', () => {
const a = new Jaco('あいう');
expect(a.test(/^あ/)).toBe(true);
});
// test()
test('テスト3', () => {
const a = new Jaco('あいう');
expect(a.test('あいうえ')).toBe(false);
});
// test()
test('テスト4', () => {
const a = new Jaco('あいう');
expect(a.test(/あ$/)).toBe(false);
});
// toBasicLetter()
test('小書き文字を基底文字に変換', () => {
const a = new Jaco('あァァァんまりだァァアァ');
expect(a.toBasicLetter().toString()).toBe('あアアアんまりだアアアア');
});
// toHiragana()
test('ひらがなに変換', () => {
const a = new Jaco(
[
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺヲァィゥェォャ',
'ュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホ',
'マミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂヅデドバビブベ',
'ボパピプペポヷヸヴヹヺ'
].join('')
);
const b = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛をぁぃぅぇぉゃゅょっーあ',
'いうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも',
'やゆよらりるれろわんがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺ',
'ぽわ゛ゐ゛ゔゑ゛を゛'
].join('');
expect(a.toHiragana().toString()).toBe(b);
});
// toHiragana()
test('ひらがなに変換2', () => {
const a = new Jaco(
[
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺヲァィゥェォャ',
'ュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホ',
'マミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂヅデドバビブベ',
'ボパピプペポヷヸヴヹヺ'
].join('')
);
const b = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙をぁぃぅぇぉゃゅょっーあ',
'いうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも',
'やゆよらりるれろわんがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺ',
'ぽわ゙ゐ゙ゔゑ゙を゙'
].join('');
expect(a.toHiragana(true).toString()).toBe(b);
});
// toHiragana()
test('ひらがなに変換3', () => {
const a = new Jaco(
[
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺヲァィゥェォャ',
'ュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホ',
'マミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂヅデドバビブベ',
'ボパピプペポヷヸヴヹヺ'
].join('')
);
const b = [
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛をぁぃぅぇぉゃゅょっーあ',
'いうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめも',
'やゆよらりるれろわんがぎぐげござじずぜぞだぢづでどばびぶべぼぱぴぷぺ',
'ぽわ゛ゐ゛ゔゑ゛を゛'
].join('');
expect(a.toHiragana(false).toString()).toBe(b);
});
// toHiragana()
test('ひらがな以外は変換しない', () => {
const a = new Jaco('012012abcabcABCABC!"#$%&\'()!"#$%&'()');
const b = '012012abcabcABCABC!"#$%&\'()!"#$%&'()';
expect(a.toHiragana().toString()).toBe(b);
});
// toHiragana()
test('ひらがな以外は変換しない2', () => {
const a = new Jaco('012012abcabcABCABC!"#$%&\'()!"#$%&'()');
const b = '012012abcabcABCABC!"#$%&\'()!"#$%&'()';
expect(a.toHiragana(true).toString()).toBe(b);
});
// toKatakana()
test('カタカナに変換', () => {
const a = new Jaco(
[
'。「」、・',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
expect(a.toKatakana().toString()).toBe(b);
});
// toKatakana()
test('カタカナに変換2', () => {
const a = new Jaco(
[
'。「」、・',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙' // 結合文字濁点・半濁点
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
expect(a.toKatakana().toString()).toBe(b);
});
// toKatakana()
test('カタカナに変換3', () => {
const a = new Jaco(
[
'。「」、・',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
expect(a.toKatakana(true).toString()).toBe(b);
});
// toKatakana()
test('カタカナに変換4', () => {
const a = new Jaco(
[
'。「」、・',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙' // 結合文字濁点・半濁点
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
expect(a.toKatakana(true).toString()).toBe(b);
});
// toKatakana()
test('カタカナに変換5', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
expect(a.toKatakana(true).toString()).toBe(b);
});
// toKatakana()
test('カタカナに変換6', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙' // 結合文字濁点・半濁点
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ'
].join('');
expect(a.toKatakana(false).toString()).toBe(b);
});
// toKatakana()
test('カタカナ以外は変換しない', () => {
const a = new Jaco(
'012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・'
);
const b = '012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・';
expect(a.toKatakana().toString()).toBe(b);
});
// toKatakana()
test('カタカナ以外は変換しない2', () => {
const a = new Jaco(
'012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・'
);
const b = '012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・';
expect(a.toKatakana(true).toString()).toBe(b);
});
// toLowerCase()
test('小文字に変換', () => {
const a = new Jaco('aBcDeFgHiJkLmNoPqRsTuVwXyZ');
expect(a.toLowerCase().toString()).toBe('abcdefghijklmnopqrstuvwxyz');
});
// toNarrow()
test('半角化', () => {
const a = new Jaco(
[
' !"#$%&'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}~',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜ガギグゲゴザジズゼゾ',
'ダヂヅデドバビブベボパピプペポヷヸヴヹヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛わ゙ゐ゙ゔゑ゙を゙',
'。「」、・'
].join('')
);
const b = [
' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}~',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜ガギグゲゴザジズゼゾ',
'ダヂヅデドバビブベボパピプペポヷヸヴヹヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛わ゙ゐ゙ゔゑ゙を゙',
'。「」、・'
].join('');
expect(a.toNarrow().toString()).toBe(b);
});
// toNarrow()
test('半角化2', () => {
const a = new Jaco(
[
' !"#$%&'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}~',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜ガギグゲゴザジズゼゾ',
'ダヂヅデドバビブベボパピプペポヷヸヴヹヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛わ゙ゐ゙ゔゑ゙を゙',
'。「」、・'
].join('')
);
const b = [
' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}~',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚ガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙わ゙ゐ゙ゔゑ゙を゙',
'。「」、・'
].join('');
expect(a.toNarrow(true).toString()).toBe(b);
});
// toNarrow()
test('半角化3', () => {
const a = new Jaco(['A', '\n', 'B'].join(''));
const b = ['A', '\n', 'B'].join('');
expect(a.toNarrow(true).toString()).toBe(b);
});
// toNarrow()
test('半角化4', () => {
const a = new Jaco(['A', '\r', 'B'].join(''));
const b = ['A', '\r', 'B'].join('');
expect(a.toNarrow(true).toString()).toBe(b);
});
// toNarrow()
test('半角化5', () => {
const a = new Jaco(['A', '\r\n', 'B'].join(''));
const b = ['A', '\r\n', 'B'].join('');
expect(a.toNarrow(true).toString()).toBe(b);
});
// toNarrow()
test('半角化6', () => {
const a = new Jaco(['A', '\r\n', 'B'].join(''));
const b = ['A', ' ', 'B'].join('');
expect(a.toNarrow(true).toString()).not.toBe(b);
});
// toNarrow()
test('半角化7', () => {
const a = new Jaco(['A', '\r\n', 'B'].join(''));
const b = ['A', '\r', 'B'].join('');
expect(a.toNarrow(true).toString()).not.toBe(b);
});
// toNarrow()
test('半角化8', () => {
const a = new Jaco(['A', '\r', 'B'].join(''));
const b = ['A', '\r\n', 'B'].join('');
expect(a.toNarrow(true).toString()).not.toBe(b);
});
// toNarrowAlphanumeric()
test('英数字を半角に変換', () => {
const a = new Jaco(
[
'!"#$%&'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}'
].join('')
);
const b = [
'!"#$%&'()*+,-./0123456789:;<=>?@',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}'
].join('');
expect(a.toNarrowAlphanumeric().toString()).toBe(b);
});
// toNarrowJapanese()
test('日本語半角化', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゛',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ゙゙',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙'
].join('');
expect(a.toNarrowJapanese().toString()).toBe(b);
});
// toNarrowKatakana()
test('半角カタカナに変換', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゛',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ゙゙',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙'
].join('');
expect(a.toNarrowKatakana().toString()).toBe(b);
});
// toNarrowKatakana()
test('半角カタカナに変換2', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ゛゛',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ゙゙',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ'
].join('');
expect(a.toNarrowKatakana(true).toString()).toBe(b);
});
// toNarrowKatakana()
test('カタカナとひらがな以外は変換しない', () => {
const a = new Jaco(
'012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・'
);
const b = '012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・';
expect(a.toNarrowKatakana().toString()).toBe(b);
});
// toNarrowKatakana()
test('カタカナとひらがな以外は変換しない2', () => {
const a = new Jaco(
'012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・'
);
const b = '012012abcabcABCABC!"#$%&\'()!"#$%&'()。「」、・';
expect(a.toNarrowKatakana(true).toString()).toBe(b);
});
// toNarrowSign()
test('記号を半角に変換', () => {
const a = new Jaco(
[
'!"#$%&'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}'
].join('')
);
const b = [
'!"#$%&\'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}'
].join('');
expect(a.toNarrowSign().toString()).toBe(b);
});
// toNarrowSymbolForJapanese()
test('日本語記号の半角化', () => {
const a = new Jaco('。「」、・');
const b = '。「」、・';
expect(a.toNarrowSymbolForJapanese().toString()).toBe(b);
});
// toNumber()
test('数値変換', () => {
const a = new Jaco('123');
expect(a.toNumber()).toBe(123);
});
// toNumber()
test('数値変換2', () => {
const a = new Jaco('123.45');
expect(a.toNumber()).toBe(123.45);
});
// toNumber()
test('数値変換3', () => {
const a = new Jaco('-123');
expect(a.toNumber()).toBe(-123);
});
// toNumber()
test('数値変換4', () => {
const a = new Jaco('0123');
expect(a.toNumber()).toBe(123);
});
// toNumber()
test('数値変換5', () => {
const a = new Jaco('0.123');
expect(a.toNumber()).toBe(0.123);
});
// toNumber()
test('数値変換6', () => {
const a = new Jaco('.123');
expect(a.toNumber()).toBe(0.123);
});
// toNumber()
test('数値変換7', () => {
const a = new Jaco('あ');
expect(isNaN(a.toNumber())).toBe(true);
});
// toNumeric()
test('数字化', () => {
const a = new Jaco(' 23s03sdkふぁえ');
const b = '2303';
expect(a.toNumeric().toString()).toBe(b);
});
// toNumeric()
test('数字化2', () => {
const a = new Jaco(' ー-.。2.3s0。3.sdkふぁえ');
const b = '2303';
expect(a.toNumeric().toString()).toBe(b);
});
// toNumeric()
test('数字化3', () => {
const a = new Jaco(' 2-3s03sdkふぁえ');
const b = '2303';
expect(a.toNumeric(true).toString()).toBe(b);
});
// toNumeric()
test('数字化4', () => {
const a = new Jaco('- 23s03sdkふぁえ');
const b = '-2303';
expect(a.toNumeric(true).toString()).toBe(b);
});
// toNumeric()
test('数字化5', () => {
const a = new Jaco(' -2-3-.s0.3sdkふぁえ');
const b = '-23.03';
expect(a.toNumeric(true, true).toString()).toBe(b);
});
// toNumeric()
test('数字化6', () => {
const a = new Jaco(' 23.-.-s03.sdkふぁえ');
const b = '23.03';
expect(a.toNumeric(true, true).toString()).toBe(b);
});
// toNumeric()
test('数字化7', () => {
const a = new Jaco('- 23s03sdkふぁえ...');
const b = '2303';
expect(a.toNumeric(false, true).toString()).toBe(b);
});
// toPhoeticKana
test('よみ変換', () => {
expect(new Jaco('あーぁあゝアア').toPhoeticKana().toString()).toBe(
'あああああああ'
);
});
// toString()
test('暗黙の型変換 文字列に変換', () => {
const a = new Jaco('あ');
expect(`${a}い`).toBe('あい');
});
// toUpperCase()
test('大文字に変換', () => {
const a = new Jaco('aBcDeFgHiJkLmNoPqRsTuVwXyZ');
expect(a.toUpperCase().toString()).toBe('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
});
// toWide()
test('全角化', () => {
const a = new Jaco(
[
' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}~',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚ガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゙ゐ゙ゔゑ゙を゙わ゙ゐ゙ゔゑ゙を゙',
'。「」、・'
].join('')
);
const b = [
' !"#$%&'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}~',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜ガギグゲゴザジズゼゾ',
'ダヂヅデドバビブベボパピプペポヷヸヴヹヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛わ゛ゐ゛ゔゑ゛を゛',
'。「」、・'
].join('');
expect(a.toWide().toString()).toBe(b);
});
// toWideAlphanumeric()
test('英数字を全角に変換', () => {
const a = new Jaco(
[
'!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}'
].join('')
);
const b = [
'!"#$%&\'()*+,-./0123456789:;<=>?@A',
'BCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcd',
'efghijklmnopqrstuvwxyz{|}'
].join('');
expect(a.toWideAlphanumeric().toString()).toBe(b);
});
// toWideJapanese()
test('日本語全角化', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('');
expect(a.toWideJapanese().toString()).toBe(b);
});
// toWideKatakana()
test('全角カタカナに変換', () => {
const a = new Jaco(
[
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲ',
'ゴザジズゼゾダヂヅデドバビブベボパピプペポヷイ゙ヴエ゙ヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('')
);
const b = [
'。「」、・',
'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌ',
'ネノハヒフヘホマミムメモヤユヨラリルレロワンガギグゲゴザジズゼゾダヂ',
'ヅデドバビブベボパピプペポヷヸヴヹヺ',
'をぁぃぅぇぉゃゅょっーあいうえおかきくけこさしすせそたちつてとなにぬ',
'ねのはひふへほまみむめもやゆよらりるれろわんがぎぐげござじずぜぞだぢ',
'づでどばびぶべぼぱぴぷぺぽわ゛ゐ゛ゔゑ゛を゛'
].join('');
expect(a.toWideKatakana().toString()).toBe(b);
});
// toWideSign()
test('記号を全角に変換', () => {
const a = new Jaco(
[
'!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}'
].join('')
);
const b = [
'!"#$%&'()*+,-./0123456789:;<=>?@',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`',
'abcdefghijklmnopqrstuvwxyz{|}'
].join('');
expect(a.toWideSign().toString()).toBe(b);
});
// toWideSymbolForJapanese()
test('日本語記号の全角化', () => {
const a = new Jaco('。「」、・');
const b = '。「」、・';
expect(a.toWideSymbolForJapanese().toString()).toBe(b);
});
// valueOf()
test('暗黙の型変換 文字列に変換後さらに数値に変換される', () => {
const a = new Jaco('1');
expect(+a).toBe(1);
});
// trim()
test('前後の空白を削除', () => {
const a = new Jaco('a b');
a.trim();
expect(a.toString()).toBe('a b');
});
// trim()
test('前後の空白を削除2', () => {
const a = new Jaco(' a b');
expect(a.trim().toString()).toBe('a b');
});
// trim()
test('前後の空白を削除3', () => {
const a = new Jaco('a b ');
expect(a.trim().toString()).toBe('a b');
});
// trim()
test('前後の空白を削除4', () => {
const a = new Jaco(' a b\n');
expect(a.trim().toString()).toBe('a b');
});
// trimLeft()
test('前の空白を削除', () => {
const a = new Jaco('a b');
expect(a.trimLeft().toString()).toBe('a b');
});
// trimLeft()
test('前の空白を削除2', () => {
const a = new Jaco(' a b');
expect(a.trimLeft().toString()).toBe('a b');
});
// trimLeft()
test('前の空白を削除3', () => {
const a = new Jaco('a b ');
expect(a.trimLeft().toString()).toBe('a b ');
});
// trimLeft()
test('前の空白を削除4', () => {
const a = new Jaco(' a b\n');
expect(a.trimLeft().toString()).toBe('a b\n');
});
// trimRight()
test('後ろの空白を削除', () => {
const a = new Jaco('a b');
expect(a.trimRight().toString()).toBe('a b');
});
// trimRight()
test('後ろの空白を削除2', () => {
const a = new Jaco(' a b');
expect(a.trimRight().toString()).toBe(' a b');
});
// trimRight()
test('後ろの空白を削除3', () => {
const a = new Jaco('a b ');
expect(a.trimRight().toString()).toBe('a b');
});
// trimRight()
test('後ろの空白を削除4', () => {
const a = new Jaco(' a b\n');
expect(a.trimRight().toString()).toBe(' a b');
});
// [@@iterator]()
test('イテレータ', () => {
const a = new Jaco('𩸽のひらき');
const b = [];
for (const j of a) {
b.push(j.toString());
}
expect(b.join('')).toBe('𩸽のひらき');
});
// [@@iterator]()
test('イテレータ2', () => {
const a = new Jaco('𩸽のひらき');
const b = Array.from(a);
expect(b.join('')).toBe('𩸽のひらき');
}); | the_stack |
import * as MathUtils from './MathUtils'
import { Euler, EulerRotationOrder } from './Euler'
// import {Vector3} from './Vector3'
import { Matrix4 } from './Matrix4'
type ChangeCallback = () => void
/**
* Implementation of a quaternion. This is used for rotating things without
* incurring the dreaded gimbal lock issue, amongst other advantages.
*
* @example
* const quaternion = new THREE.Quaternion();
* quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Mathf.PI / 2 );
* const vector = new THREE.Vector3( 1, 0, 0 );
* vector.applyQuaternion( quaternion );
*/
export class Quaternion {
_x: f32
_y: f32
_z: f32
_w: f32
readonly isQuaternion: boolean = true
onChangeCallback: ChangeCallback = (): void => {}
/**
* @param x x coordinate
* @param y y coordinate
* @param z z coordinate
* @param w w coordinate
*/
constructor(x: f32 = 0, y: f32 = 0, z: f32 = 0, w: f32 = 1) {
this._x = x
this._y = y
this._z = z
this._w = w
}
get x(): f32 {
return this._x
}
set x(value: f32) {
this._x = value
this.onChangeCallback()
}
get y(): f32 {
return this._y
}
set y(value: f32) {
this._y = value
this.onChangeCallback()
}
get z(): f32 {
return this._z
}
set z(value: f32) {
this._z = value
this.onChangeCallback()
}
get w(): f32 {
return this._w
}
set w(value: f32) {
this._w = value
this.onChangeCallback()
}
// /**
// * Sets values of this quaternion.
// * @param x x coordinate
// * @param y y coordinate
// * @param z z coordinate
// * @param w w coordinate
// */
// set(x: f32, y: f32, z: f32, w: f32): this {
// this._x = x
// this._y = y
// this._z = z
// this._w = w
// this.onChangeCallback()
// return this
// }
// /**
// * Clones this quaternion, returning a new one with all the same property values.
// */
// clone(): Quaternion {
// return new Quaternion(this._x, this._y, this._z, this._w)
// }
/**
* Copies all data of the source quaternion to this quaternion.
* @param source The quaternion to copy from.
*/
copy(source: Quaternion): this {
this._x = source.x
this._y = source.y
this._z = source.z
this._w = source.w
this.onChangeCallback()
return this
}
/**
* Sets this quaternion from rotation specified by Euler angles.
* Adapted from http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
* @param euler The Euler angles from which to get rotation from.
* @param update
*/
setFromEuler(euler: Euler, update: boolean = true): this {
// if (!(euler && euler.isEuler)) {
// throw new Error(
// 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.'
// )
// }
const x = euler._x,
y = euler._y,
z = euler._z,
order = euler.order
Mathf.sincos(x / 2)
const c1 = Mathf.sincos_cos,
s1 = Mathf.sincos_sin
Mathf.sincos(y / 2)
const c2 = Mathf.sincos_cos,
s2 = Mathf.sincos_sin
Mathf.sincos(z / 2)
const c3 = Mathf.sincos_cos,
s3 = Mathf.sincos_sin
if (order === EulerRotationOrder.XYZ) {
this._x = s1 * c2 * c3 + c1 * s2 * s3
this._y = c1 * s2 * c3 - s1 * c2 * s3
this._z = c1 * c2 * s3 + s1 * s2 * c3
this._w = c1 * c2 * c3 - s1 * s2 * s3
} else if (order === EulerRotationOrder.YXZ) {
this._x = s1 * c2 * c3 + c1 * s2 * s3
this._y = c1 * s2 * c3 - s1 * c2 * s3
this._z = c1 * c2 * s3 - s1 * s2 * c3
this._w = c1 * c2 * c3 + s1 * s2 * s3
} else if (order === EulerRotationOrder.ZXY) {
this._x = s1 * c2 * c3 - c1 * s2 * s3
this._y = c1 * s2 * c3 + s1 * c2 * s3
this._z = c1 * c2 * s3 + s1 * s2 * c3
this._w = c1 * c2 * c3 - s1 * s2 * s3
} else if (order === EulerRotationOrder.ZYX) {
this._x = s1 * c2 * c3 - c1 * s2 * s3
this._y = c1 * s2 * c3 + s1 * c2 * s3
this._z = c1 * c2 * s3 - s1 * s2 * c3
this._w = c1 * c2 * c3 + s1 * s2 * s3
} else if (order === EulerRotationOrder.YZX) {
this._x = s1 * c2 * c3 + c1 * s2 * s3
this._y = c1 * s2 * c3 + s1 * c2 * s3
this._z = c1 * c2 * s3 - s1 * s2 * c3
this._w = c1 * c2 * c3 - s1 * s2 * s3
} else if (order === EulerRotationOrder.XZY) {
this._x = s1 * c2 * c3 - c1 * s2 * s3
this._y = c1 * s2 * c3 - s1 * c2 * s3
this._z = c1 * c2 * s3 + s1 * s2 * c3
this._w = c1 * c2 * c3 + s1 * s2 * s3
}
if (update) this.onChangeCallback()
return this
}
// /**
// * Sets this quaternion from rotation specified by *axis* and *angle*.
// * Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm.
// * Axis have to be normalized, angle is in radians.
// * @param axis A vector representing the axis of rotation, assumed to be normalized.
// * @param angle The angle of rotation around the axis.
// */
// setFromAxisAngle(axis: Vector3, angle: f32): this {
// const halfAngle = angle / 2
// const s = Mathf.sin(halfAngle)
// this._x = axis.x * s
// this._y = axis.y * s
// this._z = axis.z * s
// this._w = Mathf.cos(halfAngle)
// this.onChangeCallback()
// return this
// }
// /**
// * Sets this quaternion from rotation component of *m*.
// * Adapted from http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm.
// * @param m The matrix containing the rotation. The upper 3x3 of m is assumed
// * to be a pure rotation matrix (i.e, unscaled).
// */
setFromRotationMatrix(m: Matrix4): Quaternion {
const te = m.elements,
m11 = te[0],
m12 = te[4],
m13 = te[8],
m21 = te[1],
m22 = te[5],
m23 = te[9],
m31 = te[2],
m32 = te[6],
m33 = te[10],
trace = m11 + m22 + m33
let s: f32 = 0
if (trace > 0) {
s = 0.5 / Mathf.sqrt(trace + 1.0)
this._w = 0.25 / s
this._x = (m32 - m23) * s
this._y = (m13 - m31) * s
this._z = (m21 - m12) * s
} else if (m11 > m22 && m11 > m33) {
s = 2.0 * Mathf.sqrt(1.0 + m11 - m22 - m33)
this._w = (m32 - m23) / s
this._x = 0.25 * s
this._y = (m12 + m21) / s
this._z = (m13 + m31) / s
} else if (m22 > m33) {
s = 2.0 * Mathf.sqrt(1.0 + m22 - m11 - m33)
this._w = (m13 - m31) / s
this._x = (m12 + m21) / s
this._y = 0.25 * s
this._z = (m23 + m32) / s
} else {
s = 2.0 * Mathf.sqrt(1.0 + m33 - m11 - m22)
this._w = (m21 - m12) / s
this._x = (m13 + m31) / s
this._y = (m23 + m32) / s
this._z = 0.25 * s
}
this.onChangeCallback()
return this
}
// /**
// * Sets this quaternion from the rotation found between vectors, where rotation is from *vFrom* to *vTo*.
// * Assumes direction vectors *vFrom* and *vTo* are normalized.
// * @param vFrom The vector that rotation starts from.
// * @param vTo The vector that rotation goes to.
// */
// setFromUnitVectors(vFrom: Vector3, vTo: Vector3): this {
// const EPS = 0.000001
// let r = vFrom.dot(vTo) + 1
// if (r < EPS) {
// r = 0
// if (Mathf.abs(vFrom.x) > Mathf.abs(vFrom.z)) {
// this._x = -vFrom.y
// this._y = vFrom.x
// this._z = 0
// this._w = r
// } else {
// this._x = 0
// this._y = -vFrom.z
// this._z = vFrom.y
// this._w = r
// }
// } else {
// // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
// this._x = vFrom.y * vTo.z - vFrom.z * vTo.y
// this._y = vFrom.z * vTo.x - vFrom.x * vTo.z
// this._z = vFrom.x * vTo.y - vFrom.y * vTo.x
// this._w = r
// }
// return this.normalize()
// }
// /**
// * Returns the angle between this quaternion and quaternion *q* in radians.
// * @param q Another quaternion.
// */
// angleTo(q: Quaternion): f32 {
// return 2 * Mathf.acos(Mathf.abs(_Math.clamp(this.dot(q), -1, 1)))
// }
// /**
// * Rotates this quaternion by a given angular step to the defined quaternion q. The method ensures that the final quaternion will not overshoot q.
// * @param q The target quaternion.
// * @param step The angular step in radians.
// */
// rotateTowards(q: Quaternion, step: f32): this {
// var angle = this.angleTo(q)
// if (angle === 0) return this
// var t = Mathf.min(1, step / angle)
// this.slerp(q, t)
// return this
// }
// /**
// * Inverts this quaternion (). The quaternion is assumed to have unit length.
// */
// inverse(): this {
// return this.conjugate()
// }
// /**
// * Returns the rotational conjugate of this quaternion. The conjugate of a
// * quaternion represents the same rotation in the opposite direction about the
// * rotational axis.
// */
// conjugate(): this {
// this._x *= -1
// this._y *= -1
// this._z *= -1
// this.onChangeCallback()
// return this
// }
// /**
// * Calculates the [dot](https://en.wikipedia.org/wiki/Dot_product) product of
// * quaternion *v* and this one.
// * @param v Another quaternion.
// */
// dot(v: Quaternion): f32 {
// return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w
// }
// /**
// * Computes the [Euclidean length](https://en.wikipedia.org/wiki/Euclidean_distance) (straight-line
// * length) of this quaternion, squared, considered as a 4 dimensional vector (what's a
// * straight line in 4D?). This can be useful if you are comparing the lengths
// * of two quaternions, as this is a slightly more efficient calculation than
// * [page:.length length]().
// */
// lengthSq(): f32 {
// return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w
// }
/**
* Computes the [Euclidean length](https://en.wikipedia.org/wiki/Euclidean_distance) (straight-line
* length) of this quaternion, considered as a 4 dimensional vector (what's a
* straight line in 4D?).
*/
length(): f32 {
return Mathf.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w)
}
// /**
// * [Normalizes](https://en.wikipedia.org/wiki/Normalized_vector) this
// * quaternion - that is, calculates the quaternion that performs the same
// * rotation as this one, but has [page:.length length] equal to *1*.
// */
// normalize(): this {
// var l = this.length()
// if (l === 0) {
// this._x = 0
// this._y = 0
// this._z = 0
// this._w = 1
// } else {
// l = 1 / l
// this._x = this._x * l
// this._y = this._y * l
// this._z = this._z * l
// this._w = this._w * l
// }
// this.onChangeCallback()
// return this
// }
// /**
// * Multiplies this quaternion by *q*.
// */
// multiply(q: Quaternion): this {
// return this.multiplyQuaternions(this, q)
// }
// /**
// * Pre-multiplies this quaternion by *q*.
// */
// premultiply(q: Quaternion): this {
// return this.multiplyQuaternions(q, this)
// }
// /**
// * Sets this quaternion to a x b
// * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm.
// */
// multiplyQuaternions(a: Quaternion, b: Quaternion): this {
// var qax = a._x,
// qay = a._y,
// qaz = a._z,
// qaw = a._w
// var qbx = b._x,
// qby = b._y,
// qbz = b._z,
// qbw = b._w
// this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby
// this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz
// this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx
// this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz
// this.onChangeCallback()
// return this
// }
// /**
// * Handles the spherical linear interpolation between quaternions. *t*
// * represents the amount of rotation between this quaternion (where *t* is 0)
// * and *qb* (where *t* is 1). This quaternion is set to the result. Also see
// * the static version of *slerp*.
// * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/.
// * @param qb The other quaternion rotation.
// * @param t Interpolation factor in the closed interval [0, 1].
// */
// slerp(qb: Quaternion, t: f32): this {
// if (t === 0) return this
// if (t === 1) return this.copy(qb)
// var x = this._x,
// y = this._y,
// z = this._z,
// w = this._w
// var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z
// if (cosHalfTheta < 0) {
// this._w = -qb._w
// this._x = -qb._x
// this._y = -qb._y
// this._z = -qb._z
// cosHalfTheta = -cosHalfTheta
// } else {
// this.copy(qb)
// }
// if (cosHalfTheta >= 1.0) {
// this._w = w
// this._x = x
// this._y = y
// this._z = z
// return this
// }
// var sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta
// // TODO is it possible to have a number smaller than f32.EPSILON
// if (sqrSinHalfTheta <= F64.EPSILON) {
// var s = 1 - t
// this._w = s * w + t * this._w
// this._x = s * x + t * this._x
// this._y = s * y + t * this._y
// this._z = s * z + t * this._z
// return this.normalize()
// }
// var sinHalfTheta = Mathf.sqrt(sqrSinHalfTheta)
// var halfTheta = Mathf.atan2(sinHalfTheta, cosHalfTheta)
// var ratioA = Mathf.sin((1 - t) * halfTheta) / sinHalfTheta,
// ratioB = Mathf.sin(t * halfTheta) / sinHalfTheta
// this._w = w * ratioA + this._w * ratioB
// this._x = x * ratioA + this._x * ratioB
// this._y = y * ratioA + this._y * ratioB
// this._z = z * ratioA + this._z * ratioB
// this.onChangeCallback()
// return this
// }
// equals(q: Quaternion): boolean {
// return q._x === this._x && q._y === this._y && q._z === this._z && q._w === this._w
// }
// fromArray(array: f32[], offset: i32 = 0): this {
// this._x = array[offset]
// this._y = array[offset + 1]
// this._z = array[offset + 2]
// this._w = array[offset + 3]
// this.onChangeCallback()
// return this
// }
// toArray(array: f32[] = [], offset: i32 = 0): f32[] {
// if (array === undefined) array = []
// if (offset === undefined) offset = 0
// array[offset] = this._x
// array[offset + 1] = this._y
// array[offset + 2] = this._z
// array[offset + 3] = this._w
// return array
// }
onChange(callback: ChangeCallback): Quaternion {
this.onChangeCallback = callback
return this
}
// /**
// * Static version of *slerp* that helps assign the result on a re-usable cache object.
// */
// static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: f32): Quaternion {
// return qm.copy(qa).slerp(qb, t)
// }
// /**
// * Fuzz-free, array-based Quaternion SLERP operation.
// * @param dst
// * @param dstOffset
// * @param src0
// * @param srcOffset0
// * @param src1
// * @param srcOffset1
// * @param t
// */
// static slerpFlat(
// dst: f32[],
// dstOffset: i32,
// src0: f32[],
// srcOffset0: i32,
// src1: f32[],
// srcOffset1: i32,
// t: f32
// ): void {
// var x0 = src0[srcOffset0 + 0],
// y0 = src0[srcOffset0 + 1],
// z0 = src0[srcOffset0 + 2],
// w0 = src0[srcOffset0 + 3],
// x1 = src1[srcOffset1 + 0],
// y1 = src1[srcOffset1 + 1],
// z1 = src1[srcOffset1 + 2],
// w1 = src1[srcOffset1 + 3]
// if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
// var s = 1 - t,
// cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
// dir = cos >= 0 ? 1 : -1,
// sqrSin = 1 - cos * cos
// // Skip the Slerp for tiny steps to avoid numeric problems:
// if (sqrSin > F64.EPSILON) {
// var sin = Mathf.sqrt(sqrSin),
// len = Mathf.atan2(sin, cos * dir)
// s = Mathf.sin(s * len) / sin
// t = Mathf.sin(t * len) / sin
// }
// var tDir = t * dir
// x0 = x0 * s + x1 * tDir
// y0 = y0 * s + y1 * tDir
// z0 = z0 * s + z1 * tDir
// w0 = w0 * s + w1 * tDir
// // Normalize in case we just did a lerp:
// if (s === 1 - t) {
// var f = 1 / Mathf.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0)
// x0 *= f
// y0 *= f
// z0 *= f
// w0 *= f
// }
// }
// dst[dstOffset] = x0
// dst[dstOffset + 1] = y0
// dst[dstOffset + 2] = z0
// dst[dstOffset + 3] = w0
// }
}
export function quatEquals(a: Quaternion, b: Quaternion, tolerance: f32 = 0.0001): boolean {
const diff = Mathf.abs(a.x - b.x) + Mathf.abs(a.y - b.y) + Mathf.abs(a.z - b.z) + Mathf.abs(a.w - b.w)
return diff < tolerance
} | the_stack |
import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import { lucidClassNames } from '../../util/style-helpers';
import {
findTypes,
omitProps,
StandardProps,
Overwrite,
} from '../../util/component-types';
import { buildModernHybridComponent } from '../../util/state-management';
import * as reducers from './VerticalListMenu.reducers';
import ChevronIcon from '../Icon/ChevronIcon/ChevronIcon';
import Collapsible, { ICollapsibleProps } from '../Collapsible/Collapsible';
const cx = lucidClassNames.bind('&-VerticalListMenu');
const { func, arrayOf, bool, string, number, node, object, shape } = PropTypes;
export interface IVerticalListMenuPropsRaw extends StandardProps {
/** Indicates which of the \`VerticalListMenu.Item\` children are currently
selected. You can also put the \`isSelected\` prop directly on the
\`VerticalListMenu.Item\`s if you wish. */
selectedIndices: number[];
/** Indicates which of the \`VerticalListMenu.Item\` children are currently
expanded. You can also put the \`isExpanded\` prop directly on the
\`VerticalListMenu.Item\`s if you wish. */
expandedIndices: number[];
/** Callback fired when the user selects a \`VerticalListMenu.Item\`.*/
onSelect: (
index: number,
{
event,
props,
}: {
event: React.MouseEvent;
props: IVerticalListMenuItemProps;
}
) => void;
/** Callback fired when the user expands or collapses an expandable
\`VerticalListMenu.Item\`. */
onToggle: (
index: number,
{
event,
props,
}: {
event: React.MouseEvent;
props: IVerticalListMenuItemProps;
}
) => void;
}
export type IVerticalListMenuProps = Overwrite<
React.DetailedHTMLProps<
React.HTMLAttributes<HTMLUListElement>,
HTMLUListElement
>,
IVerticalListMenuPropsRaw
>;
interface IVerticalListMenuItemPropsRaw extends StandardProps {
/**
* Show or hide the expand button. Should be \`true\` if you want to nest menus.
*/
hasExpander?: boolean;
/**
* Determines the visibility of nested menus.
*/
isExpanded?: boolean;
/**
* If \`true\` then a small bar on the left side of the item will be
* shown indicating this item is selected.
*/
isSelected?: boolean;
/**
* Determines the visibility of the small bar on the left when the user
* hovers over the item. This should indicate to the user that an item
* is clickable.
*/
isActionable?: boolean;
/** Called when the user clicks the main body of the item. */
onSelect?: (
index: number,
{
event,
props,
}: {
event: React.MouseEvent;
props: IVerticalListMenuItemProps;
}
) => void;
/** Called when the user clicks the expand button. */
onToggle?: (
index: number,
{
event,
props,
}: {
event: React.MouseEvent;
props: IVerticalListMenuItemProps;
}
) => void;
/** Props that are passed through to the underlying Collapsible component
if the item has children. */
Collapsible?: Partial<ICollapsibleProps>;
}
export type IVerticalListMenuItemProps = Overwrite<
React.DetailedHTMLProps<React.LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>,
IVerticalListMenuItemPropsRaw
>;
const Item = (_props: IVerticalListMenuItemProps): null => null;
Item.peek = {
description: `
A child item that can contain content or another VerticalListMenu.
`,
};
Item.displayName = 'VerticalListMenu.Item';
Item.propTypes = {
/**
Show or hide the expand button. Should be \`true\` if you want to
nest menus.
*/
hasExpander: bool,
/**
Determines the visibility of nested menus.
*/
isExpanded: bool,
/**
If \`true\` then a small bar on the left side of the item will be
shown indicating this item is selected.
*/
isSelected: bool,
/**
Determines the visibility of the small bar on the left when the user
hovers over the item. This should indicate to the user that an item
is clickable.
*/
isActionable: bool,
/**
Called when the user clicks the main body of the item. Signature:
\`(index, { event, props}) => {}\`
*/
onSelect: func,
/**
Called when the user clicks the expand button. Signature:
\`(index, { event, props}) => {}\`
*/
onToggle: func,
/**
Props that are passed through to the underlying Collapsible component
if the item has children.
*/
Collapsible: shape(Collapsible.propTypes),
};
export interface IVerticalListMenuState {
selectedIndices?: number[];
expandedIndices?: number[];
}
const defaultProps = {
onSelect: _.noop,
onToggle: _.noop,
expandedIndices: [],
selectedIndices: [],
};
class VerticalListMenu extends React.Component<
IVerticalListMenuProps,
IVerticalListMenuState
> {
static displayName = 'VerticalListMenu';
static Item = Item;
static peek = {
description: `Used primarily for navigation lists. It supports nesting \`VerticalListMenu\`s below \`VerticalListMenu.Item\`s and animating expanding of those sub lists. The default reducer behavior is for only one \`VerticalListMenu.Item\` to be selected at any given time; that default is easily overridden by handling \`onSelect\` yourself.`,
categories: ['navigation'],
madeFrom: ['ChevronIcon'],
};
static reducers = reducers;
// TODO: remove this once we move to only buildModernHybridComponent
static definition = {
statics: {
Item,
reducers,
peek: {
description: `Used primarily for navigation lists. It supports nesting \`VerticalListMenu\`s below \`VerticalListMenu.Item\`s and animating expanding of those sub lists. The default reducer behavior is for only one \`VerticalListMenu.Item\` to be selected at any given time; that is easily overridden by handling \`onSelect\` yourself.`,
categories: ['navigation'],
madeFrom: ['ChevronIcon'],
},
},
};
static propTypes = {
/**
Regular \`children\` aren't really used in this component, but if you do
add them they will be placed at the end of the component. You should be
using \`VerticalListMenu.Item\`s instead of regular children.
*/
children: node,
/**
Appended to the component-specific class names set on the root element.
*/
className: string,
/**
Passed through to the root element.
*/
style: object,
/**
Indicates which of the \`VerticalListMenu.Item\` children are currently
selected. You can also put the \`isSelected\` prop directly on the
\`VerticalListMenu.Item\`s if you wish.
*/
selectedIndices: arrayOf(number),
/**
Indicates which of the \`VerticalListMenu.Item\` children are currently
expanded. You can also put the \`isExpanded\` prop directly on the
\`VerticalListMenu.Item\`s if you wish.
*/
expandedIndices: arrayOf(number),
/**
Callback fired when the user selects a \`VerticalListMenu.Item\`.
Signature: \`(index, { event, props }) => {}\`
*/
onSelect: func,
/**
Callback fired when the user expands or collapses an expandable
\`VerticalListMenu.Item\`. Signature:
\`(index, { event, props }) => {}\`
*/
onToggle: func,
};
static defaultProps = defaultProps;
render() {
const {
children,
className,
style,
selectedIndices,
expandedIndices,
...passThroughs
} = this.props;
const itemChildProps = _.map(
findTypes(this.props, VerticalListMenu.Item),
'props'
);
return (
<ul
{...omitProps(
passThroughs,
undefined,
_.keys(VerticalListMenu.propTypes)
)}
className={cx('&', className)}
style={style}
>
{_.map(itemChildProps, (itemChildProp, index) => {
const {
hasExpander = false,
isActionable = true,
Collapsible: collapsibleProps = Collapsible.defaultProps,
} = itemChildProp;
const itemChildrenAsArray = React.Children.toArray(
itemChildProp.children
);
// Was not able to get `child.Type` to work correctly, I suspect this
// is due to the way we wrap components with createLucidComponentDefinition
const listChildren = _.filter(
itemChildrenAsArray,
(child) =>
_.get(child, 'type.displayName', '') === 'VerticalListMenu'
);
const otherChildren = _.filter(
itemChildrenAsArray,
(child) =>
_.get(child, 'type.displayName', '') !== 'VerticalListMenu'
);
// If the prop is found on the child, it should override what was
// passed in at the top level for selectedIndices and expandedIndices
const actualIsExpanded = _.has(itemChildProp, 'isExpanded')
? _.get(itemChildProp, 'isExpanded', true)
: _.includes(expandedIndices, index);
const actualIsSelected = _.has(itemChildProp, 'isSelected')
? _.get(itemChildProp, 'isSelected', false)
: _.includes(selectedIndices, index);
return (
<li
key={index}
{...itemChildProp.passThroughs}
className={cx('&-Item', itemChildProp.className)}
>
<div
className={cx('&-Item-content', {
'&-Item-content-is-selected': actualIsSelected,
'&-Item-content-is-not-selected': !actualIsSelected,
'&-Item-content-is-expanded': actualIsExpanded,
'&-Item-content-is-actionable': isActionable,
})}
onClick={_.partial(this.handleClickItem, index, itemChildProp)}
>
<div className={cx('&-Item-content-body')}>
<div className={cx('&-Item-content-text')}>
{otherChildren}
</div>
{hasExpander ? (
<div
className={cx('&-Item-expander')}
onClick={_.partial(
this.handleToggle,
index,
itemChildProp
)}
>
<ChevronIcon
size={12}
direction={actualIsExpanded ? 'up' : 'down'}
/>
</div>
) : null}
</div>
</div>
{!_.isEmpty(listChildren) ? (
<Collapsible
{...collapsibleProps}
className={cx('&-Item-nested-list')}
isExpanded={actualIsExpanded}
>
{listChildren}
</Collapsible>
) : null}
</li>
);
})}
{children}
</ul>
);
}
handleToggle = (
index: number,
itemChildProp: IVerticalListMenuItemProps,
event: React.MouseEvent
) => {
const { onToggle } = itemChildProp;
// Prevent the user from also selecting the current item.
event.stopPropagation();
this.props.onToggle(index, { event, props: itemChildProp });
if (onToggle) {
onToggle(index, { event, props: itemChildProp });
}
};
handleClickItem = (
index: number,
itemChildProp: IVerticalListMenuItemProps,
event: React.MouseEvent
) => {
const { onSelect } = itemChildProp;
this.props.onSelect(index, { event, props: itemChildProp });
if (onSelect) {
onSelect(index, { event, props: itemChildProp });
}
};
}
export default buildModernHybridComponent<
IVerticalListMenuProps,
IVerticalListMenuState,
typeof VerticalListMenu
>(VerticalListMenu as any, { reducers });
export { VerticalListMenu as VerticalListMenuDumb }; | the_stack |
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
findVisSelectorTabs,
mockConsoleMethod,
renderApp,
selectExplorerNode,
} from '../test-utils';
import { NexusVis } from '../vis-packs/nexus/visualizations';
test('visualize NXdata group with "spectrum" interpretation', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/spectrum');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxSpectrum);
});
test('visualize NXdata group with "image" interpretation', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/image');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxImage);
});
test('visualize NXdata group with 2D signal', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/nx_process/nx_data');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxImage);
});
test('visualize NXentry group with relative path to 2D default signal', async () => {
await renderApp();
await selectExplorerNode('nexus_entry');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxImage);
});
test('visualize NXentry group with absolute path to 2D default signal', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/nx_process/absolute_default_path');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxImage);
});
test('visualize NXroot group with 2D default signal', async () => {
await renderApp();
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxImage);
});
test('visualize NXdata group with 2D complex signal', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/complex_image');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxImage);
});
test('visualize NXdata group with 1D complex signal', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/complex_spectrum');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxSpectrum);
});
test('visualize NXdata group with "rgb-image" interpretation', async () => {
await renderApp();
await selectExplorerNode('nexus_entry/rgb-image');
const tabs = await findVisSelectorTabs();
expect(tabs).toHaveLength(1);
expect(tabs[0]).toHaveTextContent(NexusVis.NxRGB);
});
test('show error when encountering malformed NeXus metadata', async () => {
await renderApp();
const errorSpy = mockConsoleMethod('error');
await selectExplorerNode('nexus_malformed');
await selectExplorerNode('default_not_string');
expect(await screen.findByText(/to be a string/)).toBeVisible();
await selectExplorerNode('default_not_found');
expect(
await screen.findByText(/No entity found at NeXus default path/)
).toBeVisible();
await selectExplorerNode('no_signal');
expect(await screen.findByText(/'signal' attribute/)).toBeVisible();
await selectExplorerNode('signal_not_found');
expect(await screen.findByText(/to exist/)).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(8); // React logs two stack traces per error
});
test('cancel and retry slow fetch of NxSpectrum', async () => {
jest.useFakeTimers('modern');
await renderApp();
// Select NXdata group with spectrum interpretation and start fetching dataset values
await selectExplorerNode('resilience/slow_nx_spectrum');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Cancel all fetches at once
const errorSpy = mockConsoleMethod('error');
userEvent.click(await screen.findByRole('button', { name: /Cancel/ }));
expect(await screen.findByText('Request cancelled')).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(2); // React logs two stack traces
errorSpy.mockRestore();
// Retry all fetches at once
userEvent.click(await screen.findByRole('button', { name: /Retry/ }));
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetches succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
test('cancel and retry slow fetch of NxImage', async () => {
jest.useFakeTimers('modern');
await renderApp();
// Select NXdata group with image interpretation and start fetching dataset values
await selectExplorerNode('resilience/slow_nx_image');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Cancel all fetches at once
const errorSpy = mockConsoleMethod('error');
userEvent.click(await screen.findByRole('button', { name: /Cancel/ }));
expect(await screen.findByText('Request cancelled')).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(2); // React logs two stack traces
errorSpy.mockRestore();
// Retry all fetches at once
userEvent.click(await screen.findByRole('button', { name: /Retry/ }));
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetches succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
test('retry fetching automatically when re-selecting NxSpectrum', async () => {
jest.useFakeTimers('modern');
await renderApp();
// Select NXdata group with spectrum interpretation and start fetching dataset values
await selectExplorerNode('resilience/slow_nx_spectrum');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Cancel all fetches at once
const errorSpy = mockConsoleMethod('error');
userEvent.click(await screen.findByRole('button', { name: /Cancel/ }));
expect(await screen.findByText('Request cancelled')).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(2); // React logs two stack traces
errorSpy.mockRestore();
// Switch to other entity
await selectExplorerNode('resilience');
expect(await screen.findByText(/No visualization/)).toBeVisible();
// Select dataset again
await selectExplorerNode('slow_nx_spectrum');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetches succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
test('retry fetching automatically when re-selecting NxImage', async () => {
jest.useFakeTimers('modern');
await renderApp();
// Select NXdata group with image interpretation and start fetching dataset values
await selectExplorerNode('resilience/slow_nx_image');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Cancel all fetches at once
const errorSpy = mockConsoleMethod('error');
userEvent.click(await screen.findByRole('button', { name: /Cancel/ }));
expect(await screen.findByText('Request cancelled')).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(2); // React logs two stack traces
errorSpy.mockRestore();
// Switch to other entity
await selectExplorerNode('resilience');
expect(await screen.findByText(/No visualization/)).toBeVisible();
// Select dataset again
await selectExplorerNode('slow_nx_image');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetches succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
test('retry fetching automatically when selecting other NxSpectrum slice', async () => {
jest.useFakeTimers('modern');
await renderApp();
// Select NXdata group with spectrum interpretation and start fetching dataset values
await selectExplorerNode('resilience/slow_nx_spectrum');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Cancel all fetches at once
const errorSpy = mockConsoleMethod('error');
userEvent.click(await screen.findByRole('button', { name: /Cancel/ }));
expect(await screen.findByText('Request cancelled')).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(2); // React logs two stack traces
errorSpy.mockRestore();
// Move to other slice to retry fetching automatically
const d0Slider = screen.getByRole('slider', { name: 'Dimension slider' });
d0Slider.focus();
userEvent.keyboard('{PageUp}');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetches succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
// Check that entire spectrum signal is fetched
userEvent.keyboard('{PageDown}');
expect(await screen.findByRole('figure')).toBeVisible();
d0Slider.blur(); // remove focus to avoid state update after unmount
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
test('retry fetching supporting datasets automatically when selecting other NxImage slice', async () => {
jest.useFakeTimers('modern');
await renderApp();
// Select NXdata group with image interpretation and start fetching dataset values
await selectExplorerNode('resilience/slow_nx_image');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Cancel all fetches at once
const errorSpy = mockConsoleMethod('error');
userEvent.click(await screen.findByRole('button', { name: /Cancel/ }));
expect(await screen.findByText('Request cancelled')).toBeVisible();
expect(errorSpy).toHaveBeenCalledTimes(2); // React logs two stack traces
errorSpy.mockRestore();
// Move to other slice to fetch new slice and retry fetching supporting datasets automatically
const d0Slider = screen.getByRole('slider', { name: 'Dimension slider' });
d0Slider.focus();
userEvent.keyboard('{PageUp}');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetches succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
// Move back to first slice to retry fetching it automatically
userEvent.keyboard('{PageDown}');
expect(await screen.findByText(/Loading data/)).toBeVisible();
// Let fetch of first slice succeed
jest.runAllTimers();
expect(await screen.findByRole('figure')).toBeVisible();
d0Slider.blur(); // remove focus to avoid state update after unmount
jest.runOnlyPendingTimers();
jest.useRealTimers();
}); | the_stack |
import type { Router, Result } from '../../router'
import { METHOD_NAME_ALL } from '../../router'
import type { ParamMap } from './trie'
import { Trie } from './trie'
interface Hint {
components: string[]
regExpComponents: Array<true | string>
componentsLength: number
endWithWildcard: boolean
paramIndexList: number[]
maybeHandler: boolean
namedParams: [number, string, string][]
}
interface HandlerWithSortIndex<T> {
handler: T
index: number
componentsLength: number
}
interface Route<T> {
method: string
path: string
hint: Hint
handlers: HandlerWithSortIndex<T>[]
middleware: HandlerWithSortIndex<T>[]
paramAliasMap: Record<string, string[]>
}
type HandlerData<T> = [T[], ParamMap | null]
type Matcher<T> = [RegExp, HandlerData<T>[]]
type HandlerDataWithSortIndex<T> = [HandlerWithSortIndex<T>[], ParamMap | null]
type MatcherWithSortIndex<T> = [RegExp, HandlerDataWithSortIndex<T>[]]
type AnyMatcher<T> = Matcher<T> | MatcherWithSortIndex<T>
type CompareResult =
| 0 // different
| 1 // included
| 2 // ambiguous
const emptyParam = {}
const nullMatcher: Matcher<any> = [/^$/, []]
function initHint(path: string): Hint {
const components = path.match(/\/(?::\w+{[^}]+}|[^\/]*)/g) || []
let componentsLength = components.length
const paramIndexList: number[] = []
const regExpComponents: Array<true | string> = []
const namedParams: [number, string, string][] = []
for (let i = 0, len = components.length; i < len; i++) {
if (i === len - 1 && components[i] === '/*') {
componentsLength--
break
}
const m = components[i].match(/^\/:(\w+)({[^}]+})?/)
if (m) {
namedParams.push([i, m[1], m[2] || '[^/]+'])
regExpComponents[i] = m[2] || true
} else if (components[i] === '/*') {
regExpComponents[i] = true
} else {
regExpComponents[i] = components[i]
}
if (/\/(?::|\*)/.test(components[i])) {
paramIndexList.push(i)
}
}
return {
components,
regExpComponents,
componentsLength,
endWithWildcard: path.endsWith('*'),
paramIndexList,
namedParams,
maybeHandler: true,
}
}
function compareRoute<T>(a: Route<T>, b: Route<T>): CompareResult {
if (a.path === '*') {
return 1
}
let i = 0
const len = a.hint.regExpComponents.length
for (; i < len; i++) {
if (a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]) {
if (a.hint.regExpComponents[i] === true) {
break
}
return 0
}
}
// may be ambiguous
for (; i < len; i++) {
if (
a.hint.regExpComponents[i] !== true &&
a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]
) {
return 2
}
}
return i === b.hint.regExpComponents.length || a.hint.endWithWildcard ? 1 : 0
}
function compareHandler(a: HandlerWithSortIndex<any>, b: HandlerWithSortIndex<any>) {
return a.componentsLength !== b.componentsLength
? a.componentsLength - b.componentsLength
: a.index - b.index
}
function getSortedHandlers<T>(
handlers: HandlerWithSortIndex<T>[] | IterableIterator<HandlerWithSortIndex<T>>
): T[] {
return [...handlers].sort(compareHandler).map((h) => h.handler)
}
function buildMatcherFromPreprocessedRoutes<T>(
routes: Route<T>[],
hasAmbiguous: boolean = false
): AnyMatcher<T> {
const trie = new Trie({ reverse: hasAmbiguous })
const handlers: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []
if (routes.length === 0) {
return nullMatcher
}
for (let i = 0, len = routes.length; i < len; i++) {
const paramMap = trie.insert(routes[i].path, i)
handlers[i] = [
[...routes[i].middleware, ...routes[i].handlers],
Object.keys(paramMap).length !== 0 ? paramMap : null,
]
if (!hasAmbiguous) {
handlers[i][0] = getSortedHandlers(handlers[i][0] as HandlerWithSortIndex<T>[])
}
}
const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()
for (let i = 0, len = handlers.length; i < len; i++) {
const paramMap = handlers[i][1]
if (paramMap) {
for (let j = 0, len = paramMap.length; j < len; j++) {
paramMap[j][1] = paramReplacementMap[paramMap[j][1]]
const aliasTo = routes[i].paramAliasMap[paramMap[j][0]]
if (aliasTo) {
for (let k = 0, len = aliasTo.length; k < len; k++) {
paramMap.push([aliasTo[k], paramMap[j][1]])
}
}
}
}
}
const handlerMap: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []
// using `in` because indexReplacementMap is a sparse array
for (const i in indexReplacementMap) {
handlerMap[i] = handlers[indexReplacementMap[i]]
}
return [regexp, handlerMap] as AnyMatcher<T>
}
function verifyDuplicateParam<T>(routes: Route<T>[]): boolean {
const nameMap: Record<string, number> = {}
for (let i = 0, len = routes.length; i < len; i++) {
const route = routes[i]
for (let k = 0, len = route.hint.namedParams.length; k < len; k++) {
const [index, name] = route.hint.namedParams[k]
if (name in nameMap && index !== nameMap[name]) {
return false
} else {
nameMap[name] = index
}
}
const paramAliasMap = route.paramAliasMap
const paramAliasMapKeys = Object.keys(paramAliasMap)
for (let k = 0, len = paramAliasMapKeys.length; k < len; k++) {
const aliasFrom = paramAliasMapKeys[k]
for (let l = 0, len = paramAliasMap[aliasFrom].length; l < len; l++) {
const aliasTo = paramAliasMap[aliasFrom][l]
const index = nameMap[aliasFrom]
if (aliasTo in nameMap && index !== nameMap[aliasTo]) {
return false
} else {
nameMap[aliasTo] = index
}
}
}
}
return true
}
export class RegExpRouter<T> implements Router<T> {
routeData?: {
index: number
routes: Route<T>[]
methods: Set<string>
} = { index: 0, routes: [], methods: new Set() }
add(method: string, path: string, handler: T) {
if (!this.routeData) {
throw new Error('Can not add a route since the matcher is already built.')
}
this.routeData.index++
const { index, routes, methods } = this.routeData
if (path === '/*') {
path = '*'
}
const hint = initHint(path)
const handlerWithSortIndex = {
index,
handler,
componentsLength: hint.components.length || 1,
}
for (let i = 0, len = routes.length; i < len; i++) {
if (routes[i].method === method && routes[i].path === path) {
routes[i].handlers.push(handlerWithSortIndex)
return
}
}
methods.add(method)
routes.push({
method,
path,
hint,
handlers: [handlerWithSortIndex],
middleware: [],
paramAliasMap: {},
})
}
match(method: string, path: string): Result<T> | null {
const [primaryMatchers, secondaryMatchers, hasAmbiguous] = this.buildAllMatchers()
this.match = hasAmbiguous
? (method, path) => {
const matcher = (primaryMatchers[method] ||
primaryMatchers[METHOD_NAME_ALL]) as MatcherWithSortIndex<T>
let match = path.match(matcher[0])
if (!match) {
// do not support secondary matchers here.
return null
}
const params: Record<string, string> = {}
const handlers: Set<HandlerWithSortIndex<T>> = new Set()
let regExpSrc = matcher[0].source
while (match) {
let index = match.indexOf('', 1)
for (;;) {
const [handler, paramMap] = matcher[1][index]
if (paramMap) {
for (let i = 0, len = paramMap.length; i < len; i++) {
params[paramMap[i][0]] = match[paramMap[i][1]]
}
}
for (let i = 0, len = handler.length; i < len; i++) {
handlers.add(handler[i])
}
const newIndex = match.indexOf('', index + 1)
if (newIndex === -1) {
break
}
index = newIndex
}
regExpSrc = regExpSrc.replace(
new RegExp(`((?:(?:\\(\\?:|.)*?\\([^)]*\\)){${index - 1}}.*?)\\(\\)`),
'$1(^)'
)
match = path.match(new RegExp(regExpSrc))
}
return { handlers: getSortedHandlers(handlers.values()), params }
}
: (method, path) => {
let matcher = (primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]) as Matcher<T>
let match = path.match(matcher[0])
if (!match) {
const matchers = secondaryMatchers[method] || secondaryMatchers[METHOD_NAME_ALL]
for (let i = 0, len = matchers.length; i < len && !match; i++) {
matcher = matchers[i] as Matcher<T>
match = path.match(matcher[0])
}
if (!match) {
return null
}
}
const index = match.indexOf('', 1)
const [handlers, paramMap] = matcher[1][index]
if (!paramMap) {
return { handlers, params: emptyParam }
}
const params: Record<string, string> = {}
for (let i = 0, len = paramMap.length; i < len; i++) {
params[paramMap[i][0]] = match[paramMap[i][1]]
}
return { handlers, params }
}
return this.match(method, path)
}
private buildAllMatchers(): [
Record<string, AnyMatcher<T>>,
Record<string, AnyMatcher<T>[]>,
boolean
] {
// @ts-ignore
this.routeData.routes.sort(({ hint: a }, { hint: b }) => {
if (a.componentsLength !== b.componentsLength) {
return a.componentsLength - b.componentsLength
}
for (
let i = 0, len = Math.min(a.paramIndexList.length, b.paramIndexList.length) + 1;
i < len;
i++
) {
if (a.paramIndexList[i] !== b.paramIndexList[i]) {
if (a.paramIndexList[i] === undefined) {
return -1
} else if (b.paramIndexList[i] === undefined) {
return 1
} else {
return a.paramIndexList[i] - b.paramIndexList[i]
}
}
}
if (a.endWithWildcard !== b.endWithWildcard) {
return a.endWithWildcard ? -1 : 1
}
return 0
})
const primaryMatchers: Record<string, AnyMatcher<T>> = {}
const secondaryMatchers: Record<string, AnyMatcher<T>[]> = {}
let hasAmbiguous = false
// @ts-ignore
this.routeData.methods.forEach((method) => {
let _hasAmbiguous
;[primaryMatchers[method], secondaryMatchers[method], _hasAmbiguous] =
this.buildMatcher(method)
hasAmbiguous = hasAmbiguous || _hasAmbiguous
})
primaryMatchers[METHOD_NAME_ALL] ||= nullMatcher
secondaryMatchers[METHOD_NAME_ALL] ||= []
delete this.routeData // to reduce memory usage
return [primaryMatchers, secondaryMatchers, hasAmbiguous]
}
private buildMatcher(method: string): [AnyMatcher<T>, AnyMatcher<T>[], boolean] {
let hasAmbiguous = false
const targetMethods = new Set([method, METHOD_NAME_ALL])
// @ts-ignore
const routes = this.routeData.routes.filter(({ method }) => targetMethods.has(method))
// Reset temporary data per method
for (let i = 0, len = routes.length; i < len; i++) {
routes[i].middleware = []
routes[i].paramAliasMap = {}
}
// preprocess routes
for (let i = 0, len = routes.length; i < len; i++) {
for (let j = i + 1; j < len; j++) {
const compareResult = compareRoute(routes[i], routes[j])
// i includes j
if (compareResult === 1) {
const components = routes[j].hint.components
const namedParams = routes[i].hint.namedParams
for (let k = 0, len = namedParams.length; k < len; k++) {
const c = components[namedParams[k][0]]
const m = c.match(/^\/:(\w+)({[^}]+})?/)
if (m && namedParams[k][1] === m[1]) {
continue
}
if (m) {
routes[j].paramAliasMap[m[1]] ||= []
routes[j].paramAliasMap[m[1]].push(namedParams[k][1])
} else {
components[namedParams[k][0]] = `/:${namedParams[k][1]}{${c.substring(1)}}`
routes[j].hint.namedParams.push([
namedParams[k][0],
namedParams[k][1],
c.substring(1),
])
routes[j].path = components.join('')
}
}
if (routes[j].hint.components.length < routes[i].hint.components.length) {
const componentsLength = routes[j].hint.components.length || 1
routes[j].middleware.push(
...routes[i].handlers.map((h) => ({
componentsLength,
index: h.index,
handler: h.handler,
}))
)
} else {
routes[j].middleware.push(...routes[i].handlers)
}
routes[i].hint.maybeHandler = false
} else if (compareResult === 2) {
// ambiguous
hasAmbiguous = true
if (!verifyDuplicateParam([routes[i], routes[j]])) {
throw new Error('Duplicate param name')
}
}
}
if (!verifyDuplicateParam([routes[i]])) {
throw new Error('Duplicate param name')
}
}
if (hasAmbiguous) {
return [buildMatcherFromPreprocessedRoutes(routes, hasAmbiguous), [], hasAmbiguous]
}
const primaryRoutes = []
const secondaryRoutes = []
for (let i = 0, len = routes.length; i < len; i++) {
if (routes[i].hint.maybeHandler || !routes[i].hint.endWithWildcard) {
primaryRoutes.push(routes[i])
} else {
secondaryRoutes.push(routes[i])
}
}
return [
buildMatcherFromPreprocessedRoutes(primaryRoutes, hasAmbiguous),
[buildMatcherFromPreprocessedRoutes(secondaryRoutes, hasAmbiguous)],
hasAmbiguous,
]
}
} | the_stack |
import { Promise } from 'bluebird'
import axios from 'axios'
import dayjs from 'dayjs'
import { omit } from 'lodash'
import { KiteOrder } from '../../types/kite'
import { DIRECTIONAL_OPTION_SELLING_TRADE } from '../../types/trade'
import {
INSTRUMENT_DETAILS,
PRODUCT_TYPE,
STRATEGIES_DETAILS
} from '../constants'
import { doSquareOffPositions } from '../exit-strategies/autoSquareOff'
import individualLegExitOrders from '../exit-strategies/individualLegExitOrders'
import console from '../logging'
import {
addToAutoSquareOffQueue,
addToNextQueue,
EXIT_TRADING_Q_NAME,
TRADING_Q_NAME
} from '../queue'
import {
getExpiryTradingSymbol,
attemptBrokerOrders,
getInstrumentPrice,
getLastOpenDateSince,
getNearestCandleTime,
getNextNthMinute,
getTimeLeftInMarketClosingMs,
getTradingSymbolsByOptionPrice,
isUntestedFeaturesEnabled,
ms,
remoteOrderSuccessEnsurer,
syncGetKiteInstance,
TradingSymbolInterface,
withRemoteRetry,
logDeep
} from '../utils'
const SIGNALX_URL = process.env.SIGNALX_URL ?? 'https://indicator.signalx.trade'
// grab the instrument id of the most recent expiry of banknifty
// get the supertrend value (10,3)
// round up the supertrend to nearest strike
// if supertrend < LTP
// sell CE and call exit strategy of 1x SLM order
// record the order id of the exit order and watch for 'Completed' event
// get supertrend value of CE option every 5mins
// update SL = min(SLM%, Supertrend)
async function fetchSuperTrend ({
instrument_token,
from_date,
to_date,
...otherProps
}) {
//eslint-disable-line
const props = {
instrument_token,
from_date,
to_date,
interval: '5minute',
period: 10,
multiplier: 3,
...otherProps
}
const { data } = await axios.post(
`${SIGNALX_URL}/api/indicator/supertrend`,
props,
{
headers: {
'X-API-KEY': process.env.SIGNALX_API_KEY
}
}
)
return data
}
export default async function directionalOptionSelling (
initialJobData: DIRECTIONAL_OPTION_SELLING_TRADE & {
lastTrend: string
lastTradeOrders: KiteOrder[]
}
) {
try {
const {
instrument,
lots = 1,
martingaleIncrementSize = 0,
maxTrades = 0,
entryStrategy = STRATEGIES_DETAILS.DIRECTIONAL_OPTION_SELLING
.ENTRY_STRATEGIES.FIXED_TIME,
lastTrend,
lastTradeOrders,
user,
expiryType
} = initialJobData
if (getTimeLeftInMarketClosingMs() < 40 * 60 * 1000) {
return `🟢 [dos] Terminating DOS trade. ${maxTrades.toString()} attempts left but less than 40 mins in market closing.`
}
const { nfoSymbol } = INSTRUMENT_DETAILS[instrument]
const {
instrument_token: futInstrumentToken
} = (await getExpiryTradingSymbol({
nfoSymbol,
instrumentType: 'FUT',
expiry: expiryType
})) as TradingSymbolInterface
const DATE_FORMAT = 'YYYY-MM-DD'
const DATE_TIME_FORMAT = `${DATE_FORMAT} HH:mm:ss`
const lastOpenDate = getLastOpenDateSince(dayjs()).format(DATE_FORMAT)
const nearestClosedCandleTime = getNearestCandleTime(5 * 60 * 1000).format(
DATE_TIME_FORMAT
)
const supertrendProps = {
instrument_token: futInstrumentToken,
from_date: lastOpenDate,
to_date: nearestClosedCandleTime
}
const supertrendResponse = await withRemoteRetry(async () =>
fetchSuperTrend(supertrendProps)
)
if (
!(Array.isArray(supertrendResponse) && supertrendResponse.length >= 2)
) {
console.log('🔴 [dos] supertrendResponse unlengthy')
logDeep({ stRequest: supertrendProps, stResponse: supertrendResponse })
return Promise.reject(new Error('[dos] supertrendResponse unlengthy'))
}
const [currentTrendData] = supertrendResponse.slice(-1)
const currentTrendAsPerST = currentTrendData.STX_10_3
if (
entryStrategy ===
STRATEGIES_DETAILS.DIRECTIONAL_OPTION_SELLING.ENTRY_STRATEGIES.ST_CHANGE
) {
const lastTrendAsPerST = supertrendResponse.slice(-2)[0].STX_10_3
const wasLastTrendAccurate = lastTrend === lastTrendAsPerST
if (!wasLastTrendAccurate) {
// only if currentTrend is not same as the previous position that was taken
/**
* possible scenarios
* on incorrect trend,
*
* say at 9.45am
* ST data comes in as [up, up, down]
* a short position gets taken
*
* then at 9.50am
* Case 1. ST data comes in as [up, up, up, down]
* then it's all okay - even though previous trend was inaccurate,
* the new position would have been same as existing positon
* Action: No action required
*
* Case 2. ST data comes in as [up, up, up, up]
* then it's a problem as now a new long position will be taken
* even though nothing has changed on the futures chart
* but 3 trades would have been taken already
* Action: Revert previous trade, and retain lot size and maxTrades from incoming initialJobData
*/
console.log('🔴 [dos] last trend was inaccurate')
if (currentTrendAsPerST !== lastTrend && lastTradeOrders?.length) {
// [NB] let this happen at least once before enabling it for everyone else
if (isUntestedFeaturesEnabled()) {
console.log('🔴 [dos black swan] reverting bad position')
const kite = syncGetKiteInstance(user)
// 1. square off last trade
await doSquareOffPositions(lastTradeOrders, kite, initialJobData)
// 2. prevent next trade from happening
// 3. increase back maxTrades by 1
return await addToNextQueue(
{
...initialJobData,
entryStrategy:
STRATEGIES_DETAILS.DIRECTIONAL_OPTION_SELLING.ENTRY_STRATEGIES
.ST_CHANGE,
lastTrend: currentTrendAsPerST,
runNow: false,
runAt: getNextNthMinute(ms(5 * 60))
},
{
_nextTradingQueue: TRADING_Q_NAME
}
)
}
}
}
const compareWithTrendValue = lastTrend || lastTrendAsPerST
if (compareWithTrendValue === currentTrendAsPerST) {
const error = `[dos] no change in ST ("${currentTrendAsPerST as string}")`
return Promise.reject(new Error(error))
}
}
const punchedOrders = await punchOrders(initialJobData, currentTrendData)
if (maxTrades > 1) {
// flow should never reach here if the orders haven't been punched in
await addToNextQueue(
{
...initialJobData,
entryStrategy:
STRATEGIES_DETAILS.DIRECTIONAL_OPTION_SELLING.ENTRY_STRATEGIES
.ST_CHANGE,
lastTrend: currentTrendAsPerST,
maxTrades: maxTrades - 1,
lots: Number(lots) + Number(martingaleIncrementSize),
runNow: false,
runAt: getNextNthMinute(ms(5 * 60)),
lastTradeOrders: punchedOrders
},
{
_nextTradingQueue: TRADING_Q_NAME
}
)
}
return punchedOrders
} catch (e) {
console.log('🔴 [dos] parent caught', e)
// [TODO] update db job with `status`: ERROR and an appropriate `reason`
return Promise.resolve(
'🔴 [dos] Terminating DOS trade. non recoverable error'
)
}
}
async function punchOrders (
initialJobData: DIRECTIONAL_OPTION_SELLING_TRADE,
superTrend
) {
const {
_kite,
instrument,
user,
lots,
isAutoSquareOffEnabled,
strikeByPrice,
orderTag,
rollback,
productType = PRODUCT_TYPE.MIS,
isHedgeEnabled = false,
hedgeDistance = 1700,
expiryType
} = initialJobData
const strikeByPriceNumber = strikeByPrice ? Number(strikeByPrice) : null
const kite = _kite || syncGetKiteInstance(user)
const { nfoSymbol, strikeStepSize, lotSize } = INSTRUMENT_DETAILS[instrument]
const { close, ST_10_3 } = superTrend
const atmStrike = Math.round(close / strikeStepSize) * strikeStepSize
const superTrendStrike = Math.round(ST_10_3 / strikeStepSize) * strikeStepSize
const instrumentType = ST_10_3 > close ? 'CE' : 'PE'
const {
tradingsymbol: optionTradingSymbol,
instrument_token: optionInstrumentToken,
strike: optionStrike
} = strikeByPriceNumber
? await withRemoteRetry(async () =>
getTradingSymbolsByOptionPrice({
nfoSymbol,
price: strikeByPriceNumber,
pivotStrike: atmStrike,
instrumentType,
user: user!,
expiry: expiryType
})
)
: await getExpiryTradingSymbol({
nfoSymbol,
strike: superTrendStrike,
instrumentType,
expiry: expiryType
})
const ltp = await withRemoteRetry(async () =>
getInstrumentPrice(kite, optionTradingSymbol, kite.EXCHANGE_NFO)
)
if (ltp < 10) {
console.log(
'🔴 [directionalOptionSelling] not punching order as option price less than 10 bucks'
)
return
}
let hedgeOrder
let hedgeOrdersResponse: KiteOrder[] = []
if (isHedgeEnabled && Number(hedgeDistance) > 0) {
const hedgeStrike =
Number(optionStrike) +
Number(hedgeDistance) * (instrumentType === 'PE' ? -1 : 1)
const hedgeStrikeData = (await getExpiryTradingSymbol({
nfoSymbol,
strike: hedgeStrike,
instrumentType,
expiry: expiryType
})) as TradingSymbolInterface
if (hedgeStrikeData) {
const { tradingsymbol: hedgeTradingSymbol } = hedgeStrikeData
hedgeOrder = {
tradingsymbol: hedgeTradingSymbol,
quantity: Number(lots) * lotSize,
exchange: kite.EXCHANGE_NFO,
transaction_type: kite.TRANSACTION_TYPE_BUY,
order_type: kite.ORDER_TYPE_MARKET,
product: productType,
validity: kite.VALIDITY_DAY,
tag: orderTag
}
try {
const brokerOrderPr = remoteOrderSuccessEnsurer({
_kite: kite,
orderProps: hedgeOrder,
instrument,
ensureOrderState: kite.STATUS_COMPLETE,
user: user!
})
const { allOk, statefulOrders } = await attemptBrokerOrders([
brokerOrderPr
])
if (allOk) {
hedgeOrdersResponse = statefulOrders
} else {
const error =
'🔴 hedge order id exists, but status unknown after several retries! terminating dos'
console.log(error)
throw new Error(error)
}
} catch (e) {
if (rollback?.onBrokenHedgeOrders) {
await doSquareOffPositions(hedgeOrdersResponse, kite, initialJobData)
}
throw e
}
}
}
const order = {
tradingsymbol: optionTradingSymbol,
quantity: Number(lots) * lotSize,
exchange: kite.EXCHANGE_NFO,
transaction_type: kite.TRANSACTION_TYPE_SELL,
order_type: kite.ORDER_TYPE_MARKET,
product: productType,
validity: kite.VALIDITY_DAY,
tag: orderTag
}
let rawKiteOrdersResponse: KiteOrder[] = []
try {
const brokerOrderPr = remoteOrderSuccessEnsurer({
_kite: kite,
orderProps: order,
instrument,
ensureOrderState: kite.STATUS_COMPLETE,
user: user!
})
const { allOk, statefulOrders } = await attemptBrokerOrders([brokerOrderPr])
if (allOk) {
rawKiteOrdersResponse = statefulOrders
} else {
// [TODO] lets see if this ever happens.
const error =
'🔴 DOS order exists, but status unknown several retries! terminating dos'
console.log(error)
throw new Error(error)
}
} catch (e) {
// squaring off the hedge if this times out
console.log(e)
if (rollback?.onBrokenPrimaryOrders) {
await doSquareOffPositions(
[...hedgeOrdersResponse, ...rawKiteOrdersResponse].filter(o => o),
kite,
initialJobData
)
}
throw e
}
let exitOrders
try {
exitOrders = await individualLegExitOrders({
_kite: kite,
initialJobData,
rawKiteOrdersResponse
})
} catch (e) {
// if this throws, then the initial SL order for the sold option is not in system
if (rollback?.onBrokenExitOrders) {
await doSquareOffPositions(
[...hedgeOrdersResponse, ...rawKiteOrdersResponse].filter(o => o),
kite,
initialJobData
)
}
throw e
}
const nextQueueData = omit(initialJobData, '_kite')
await Promise.map(exitOrders, async (exitOrder, idx) => {
return await addToNextQueue(nextQueueData, {
_nextTradingQueue: EXIT_TRADING_Q_NAME,
rawKiteOrdersResponse: [exitOrder],
optionInstrumentToken,
hedgeOrderResponse: hedgeOrdersResponse[idx]
})
})
console.log('🟢 [directionalOptionSelling] trailing SL now..')
const allPunchedOrders = [
...rawKiteOrdersResponse,
...hedgeOrdersResponse
].filter(o => o)
if (isAutoSquareOffEnabled) {
try {
const asoResponse = await addToAutoSquareOffQueue({
initialJobData: nextQueueData,
jobResponse: {
rawKiteOrdersResponse: allPunchedOrders
}
})
const { data, name } = asoResponse
console.log(
'🟢 [directionalOptionSelling] success enable auto square off',
{ data, name }
)
} catch (e) {
console.log(
'🔴 [directionalOptionSelling] failed to enable auto square off',
e
)
}
}
return allPunchedOrders
} | the_stack |
import { DEPOSIT_STATE_TIMEOUT } from "@connext/apps";
import { MinimumViableMultisig, ERC20 } from "@connext/contracts";
import {
Address,
Contract,
DepositAppName,
DepositAppState,
MinimalTransaction,
Bytes32,
FreeBalanceResponse,
} from "@connext/types";
import { getSignerAddressFromPublicIdentifier, stringify } from "@connext/utils";
import { Injectable } from "@nestjs/common";
import { BigNumber, constants, providers } from "ethers";
import { CFCoreService } from "../cfCore/cfCore.service";
import { Channel } from "../channel/channel.entity";
import { LoggerService } from "../logger/logger.service";
import {
OnchainTransactionService,
OnchainTransactionResponse,
} from "../onchainTransactions/onchainTransaction.service";
import { ConfigService } from "../config/config.service";
import {
OnchainTransaction,
TransactionReason,
TransactionStatus,
} from "../onchainTransactions/onchainTransaction.entity";
import { AppInstance, AppType } from "../appInstance/appInstance.entity";
import { AppInstanceRepository } from "../appInstance/appInstance.repository";
import { ChannelRepository } from "../channel/channel.repository";
const { Zero, AddressZero } = constants;
@Injectable()
export class DepositService {
constructor(
private readonly configService: ConfigService,
private readonly cfCoreService: CFCoreService,
private readonly onchainTransactionService: OnchainTransactionService,
private readonly log: LoggerService,
private readonly appInstanceRepository: AppInstanceRepository,
private readonly channelRepository: ChannelRepository,
) {
this.log.setContext("DepositService");
}
async deposit(
channel: Channel,
amount: BigNumber,
assetId: string,
): Promise<
| {
completed: () => Promise<FreeBalanceResponse>;
appIdentityHash: string;
transaction: providers.TransactionResponse;
}
| undefined
> {
this.log.info(
`Deposit started: ${JSON.stringify({ channel: channel.multisigAddress, amount, assetId })}`,
);
// evaluate the installed deposit apps in the channel
const depositRegistry = this.cfCoreService.getAppInfoByNameAndChain(
DepositAppName,
channel.chainId,
);
const depositApp: AppInstance<"DepositApp"> | undefined = channel.appInstances.find(
(app) =>
app.appDefinition === depositRegistry!.appDefinitionAddress &&
app.latestState.assetId === assetId,
);
if (depositApp) {
// if it is the users deposit, throw an error
if (
depositApp.latestState.transfers[0].to ===
getSignerAddressFromPublicIdentifier(channel.userIdentifier)
) {
this.log.warn(
`Cannot deposit, user has deposit app installed for asset ${assetId} on chain ${channel.chainId}, app: ${depositApp.identityHash}`,
);
return undefined;
} // otherwise it is our deposit app
// check to see if the associated transaction has been completed
// or app has been uninstalled
// NOTE: theoretically the app should not be pulled from the channel if
// it is uninstalled. However, this could be racy, so use the transaction
// flag as the source of truth
const transaction = await this.onchainTransactionService.findByAppId(depositApp.identityHash);
if (!transaction) {
throw new Error(
`There is a deposit app installed in channel ${channel.multisigAddress} without an associated onchain transaction stored`,
);
}
// if the transaction is still pending, throw an error
if (transaction.status === TransactionStatus.PENDING) {
this.log.warn(
`Transaction ${transaction.hash} on ${channel.chainId} associated with deposit app ${depositApp.identityHash} is still pending, cannot deposit.`,
);
return undefined;
}
const uninstallDepositApp = async () => {
let appUninstallError: Error | undefined = undefined;
try {
await this.rescindDepositRights(depositApp.identityHash, channel.multisigAddress);
} catch (e) {
// In this case, we could error because the app has been uninstalled
// by some other process. Before hard erroring, double check against
// the app repository that it is not uninstalled
const app = await this.appInstanceRepository.findByIdentityHashOrThrow(
depositApp.identityHash,
);
if (app.type !== AppType.UNINSTALLED) {
appUninstallError = e;
}
}
return appUninstallError;
};
// if the transaction failed, uninstall app
if (transaction.status === TransactionStatus.FAILED) {
const appUninstallError = await uninstallDepositApp();
if (appUninstallError) {
throw appUninstallError;
}
}
// if the transaction is complete and the app was never uninstalled,
// try to uninstall the app again before proceeding
if (!transaction.appUninstalled) {
const appUninstallError = await uninstallDepositApp();
if (appUninstallError) {
this.log.warn(
`Transaction ${transaction.hash} on ${channel.chainId} completed, but unable to uninstall app ${depositApp.identityHash}: ${appUninstallError.message}`,
);
return undefined;
}
}
}
// install a new deposit app and create a new transaction
let appIdentityHash: Bytes32;
let response: OnchainTransactionResponse;
const cleanUpDepositRights = async () => {
const freshChannel = await this.channelRepository.findByMultisigAddressOrThrow(
channel.multisigAddress,
);
const depositApp = freshChannel.appInstances.find((app) => {
return (
app.appDefinition === depositRegistry!.appDefinitionAddress &&
app.latestState.assetId === assetId &&
(app.latestState as DepositAppState).transfers[0].to ===
getSignerAddressFromPublicIdentifier(freshChannel.nodeIdentifier)
);
});
if (depositApp) {
this.log.info(
`Releasing deposit rights on chain ${channel.chainId} for ${channel.multisigAddress}`,
);
try {
await this.rescindDepositRights(depositApp.identityHash, channel.multisigAddress);
} catch (e) {
this.log.warn(e.message);
}
this.log.info(
`Released deposit rights on chain ${channel.chainId} for ${channel.multisigAddress}`,
);
}
};
try {
this.log.info(
`Requesting deposit rights before depositing on chain ${channel.chainId} for ${channel.multisigAddress}`,
);
appIdentityHash = await this.requestDepositRights(channel, assetId);
this.log.info(
`Requested deposit rights, sending deposit to chain on chain ${channel.chainId} for ${channel.multisigAddress}`,
);
response = await this.sendDepositToChain(channel, amount, assetId, appIdentityHash);
this.log.info(
`Deposit transaction broadcast on chain ${channel.chainId} for ${channel.multisigAddress}: ${response.hash}`,
);
} catch (e) {
await cleanUpDepositRights();
this.log.warn(
`Caught error collateralizing on chain ${channel.chainId} for ${channel.multisigAddress}: ${
e.stack || e
}`,
);
return undefined;
}
// remove the deposit rights when transaction fails or is mined
const completed: Promise<FreeBalanceResponse> = new Promise(async (resolve, reject) => {
try {
await response.completed();
const freeBalance = await this.cfCoreService.getFreeBalance(
channel.userIdentifier,
channel.multisigAddress,
assetId,
);
resolve({ freeBalance });
} catch (e) {
this.log.error(`Error in node deposit: ${e.message}`);
reject(e);
} finally {
await cleanUpDepositRights();
}
});
return { completed: () => completed, appIdentityHash, transaction: response };
}
async requestDepositRights(
channel: Channel,
tokenAddress: string = AddressZero,
): Promise<string> {
const appIdentityHash = await this.proposeDepositInstall(channel, tokenAddress);
if (!appIdentityHash) {
throw new Error(
`Failed to install deposit app for ${tokenAddress} in channel ${channel.multisigAddress}`,
);
}
return appIdentityHash;
}
async rescindDepositRights(appIdentityHash: string, multisigAddress: string): Promise<void> {
this.log.debug(`Uninstalling deposit app for ${multisigAddress} with ${appIdentityHash}`);
const onchain = await this.onchainTransactionService.findByAppId(appIdentityHash);
if (!onchain) {
throw new Error(`Onchain tx doesn't exist for app ${appIdentityHash}`);
}
if (onchain.appUninstalled) {
return;
}
if (onchain.status === TransactionStatus.PENDING) {
throw new Error(
`Can't uninstall deposit app when associated transaction is pending: ${stringify(onchain)}`,
);
}
const channel = await this.channelRepository.findByMultisigAddressOrThrow(multisigAddress);
await this.cfCoreService.uninstallApp(appIdentityHash, channel);
await this.onchainTransactionService.setAppUninstalled(true, onchain.hash);
}
async findCollateralizationByHash(hash: string): Promise<OnchainTransaction | undefined> {
const tx = await this.onchainTransactionService.findByHash(hash);
if (!tx || tx.reason !== TransactionReason.COLLATERALIZATION) {
return undefined;
}
return tx;
}
private async sendDepositToChain(
channel: Channel,
amount: BigNumber,
tokenAddress: Address,
appIdentityHash: string,
): Promise<OnchainTransactionResponse> {
// derive the proper minimal transaction for the
// onchain transaction service
let tx: MinimalTransaction;
if (tokenAddress === AddressZero) {
tx = {
to: channel.multisigAddress,
value: amount,
data: "0x",
};
} else {
const token = new Contract(
tokenAddress,
ERC20.abi,
this.configService.getEthProvider(channel.chainId),
);
tx = {
to: tokenAddress,
value: 0,
data: token.interface.encodeFunctionData("transfer", [channel.multisigAddress, amount]),
};
}
this.log.info(
`Creating transaction on ${channel.chainId} for ${
channel.multisigAddress
} for amount ${amount.toString()}: ${stringify(tx)}`,
);
return this.onchainTransactionService.sendDeposit(channel, tx, appIdentityHash);
}
private async proposeDepositInstall(
channel: Channel,
tokenAddress: string = AddressZero,
): Promise<string | undefined> {
const ethProvider = this.configService.getEthProvider(channel.chainId);
// generate initial totalAmountWithdrawn
const multisig = new Contract(channel.multisigAddress, MinimumViableMultisig.abi, ethProvider);
let startingTotalAmountWithdrawn: BigNumber;
try {
this.log.info(`Checking withdrawn amount using ethProvider ${ethProvider!.connection.url}`);
startingTotalAmountWithdrawn = await multisig.totalAmountWithdrawn(tokenAddress);
} catch (e) {
const NOT_DEPLOYED_ERR = `CALL_EXCEPTION`;
if (!e.message.includes(NOT_DEPLOYED_ERR)) {
throw new Error(e);
}
// multisig is deployed on withdrawal, if not
// deployed withdrawal amount is 0
startingTotalAmountWithdrawn = Zero;
}
this.log.info(`startingTotalAmountWithdrawn: ${startingTotalAmountWithdrawn.toString()}`);
// generate starting multisig balance
this.log.info(
`Checking starting multisig balance of ${channel.multisigAddress} asset ${tokenAddress} on chain ${channel.chainId} using ethProvider ${ethProvider?.connection.url}`,
);
const startingMultisigBalance =
tokenAddress === AddressZero
? await ethProvider!.getBalance(channel.multisigAddress)
: await new Contract(tokenAddress, ERC20.abi, ethProvider).balanceOf(
channel.multisigAddress,
);
this.log.info(
`startingMultisigBalance of ${channel.multisigAddress} asset ${tokenAddress} on chain ${
channel.chainId
}: ${startingMultisigBalance.toString()}`,
);
const initialState: DepositAppState = {
transfers: [
{
amount: Zero,
to: await this.configService.getSignerAddress(),
},
{
amount: Zero,
to: getSignerAddressFromPublicIdentifier(channel.userIdentifier),
},
],
multisigAddress: channel.multisigAddress,
assetId: tokenAddress,
startingTotalAmountWithdrawn,
startingMultisigBalance,
};
const res = await this.cfCoreService.proposeAndWaitForInstallApp(
channel,
initialState,
Zero,
tokenAddress,
Zero,
tokenAddress,
this.cfCoreService.getAppInfoByNameAndChain(DepositAppName, channel.chainId),
{ reason: "Node deposit" }, // meta
DEPOSIT_STATE_TIMEOUT,
);
return res ? res.appIdentityHash : undefined;
}
} | the_stack |
import classNames from "classnames";
import React, { CSSProperties } from "react";
import { pick } from "../../common";
import { mergeRefs } from "../../react-utils";
export interface ImageLoader {
supportsUrl: (url: string) => boolean;
transformUrl: (opts: {
src: string;
width?: number;
quality?: number;
format?: "webp";
}) => string;
}
type ImgTagProps = Omit<
React.ComponentProps<"img">,
"src" | "srcSet" | "ref" | "style"
>;
// Default image sizes to snap to
// TODO: make this configurable?
const IMG_SIZES = [16, 32, 48, 64, 96, 128, 256, 384];
const DEVICE_SIZES = [640, 750, 828, 1080, 1200, 1920, 2048, 3840];
const ALL_SIZES = [...IMG_SIZES, ...DEVICE_SIZES];
export interface PlasmicImgProps extends ImgTagProps {
/**
* Either an object with the src string, and its full width and height,
* or just a src string with unknown intrinsic dimensions.
*/
src?:
| string
| {
src: string;
fullHeight: number;
fullWidth: number;
// We might also get a more precise aspectRatio for SVGs
// instead of relyiing on fullWidth / fullHeight, because
// those values might be rounded and not so accurate.
aspectRatio?: number;
};
/**
* className applied to the wrapper element if one is used.
*/
className?: string;
/**
* css width
*/
displayWidth?: number | string;
/**
* css height
*/
displayHeight?: number | string;
/**
* css min-width
*/
displayMinWidth?: number | string;
/**
* css min-height
*/
displayMinHeight?: number | string;
/**
* css max-width
*/
displayMaxWidth?: number | string;
/**
* css max-height
*/
displayMaxHeight?: number | string;
/**
* For variable quality formats like jpg, the quality from 0 to 100
*/
quality?: number;
/**
* ImageLoader to use for loading different dimensions of the image.
* If none specified, will not attempt to load different dimensions.
*/
loader?: "plasmic" | ImageLoader;
/**
* Style applied to the wrapper element. objectFit and objectPosition
* rules are applied to the img element.
*/
style?: React.CSSProperties;
/**
* Ref for the img element. The normal <PlasmicImg ref={...} />
* prop gives the root element instead, which may be the img element
* or a wrapper element
*/
imgRef?: React.Ref<HTMLImageElement>;
}
export const PlasmicImg = React.forwardRef(function PlasmicImg(
props: PlasmicImgProps,
outerRef: React.Ref<HTMLElement>
) {
let {
src,
className,
displayWidth,
displayHeight,
displayMinWidth,
displayMinHeight,
displayMaxWidth,
displayMaxHeight,
quality,
loader,
imgRef,
style,
loading,
...rest
} = props;
const imgProps = Object.assign({}, rest, {
// Default loading to "lazy" if not specified (which is different from the
// html img, which defaults to eager!)
loading: loading ?? "lazy",
});
const { fullWidth, fullHeight, aspectRatio } =
typeof src === "string" || !src
? { fullWidth: undefined, fullHeight: undefined, aspectRatio: undefined }
: src;
const srcStr = src ? (typeof src === "string" ? src : src.src) : "";
// Assume external image if either dimension is null and use usual <img>
if (fullHeight == null || fullWidth == null) {
return (
<img
src={srcStr}
className={className}
style={style}
{...imgProps}
loading={loading}
ref={mergeRefs(imgRef, outerRef) as any}
/>
);
}
if (
isSvg(srcStr) &&
(displayHeight == null || displayHeight === "auto") &&
(displayWidth == null || displayWidth === "auto")
) {
displayWidth = "100%";
}
if (
fullWidth &&
fullHeight &&
(!displayWidth || displayWidth === "auto") &&
!!getPixelLength(displayHeight)
) {
// If there's a pixel length specified for displayHeight but not displayWidth,
// then we can derive the pixel length for displayWidth. Having an explicit
// displayWidth makes this a fixed-size image, which makes it possible for us to
// generate better markup!
if (!isSvg(srcStr)) {
// We shouldn't do it for SVGs though, because `fullWidth` and
// `fullHeight` might have rounded values so the final
// `displayWidth` could differ by 1px or so.
displayWidth = (getPixelLength(displayHeight)! * fullWidth) / fullHeight;
}
}
let spacerWidth = fullWidth;
let spacerHeight = fullHeight;
if (aspectRatio && isFinite(aspectRatio) && isSvg(srcStr)) {
// For SVGs, fullWidth and fullHeight can be rounded values, which would
// cause some discrepancy between the actual aspect ratio and the aspect
// ratio from those values. So, for those cases, we set large width / height
// values to get a more precise ratio from the spacer.
spacerWidth = DEFAULT_SVG_WIDTH;
spacerHeight = Math.round(spacerWidth / aspectRatio);
}
const { sizes, widthDescs } = getWidths(displayWidth, fullWidth, {
minWidth: displayMinWidth,
});
const imageLoader = getImageLoader(loader);
const spacerSvg = `<svg width="${spacerWidth}" height="${spacerHeight}" xmlns="http://www.w3.org/2000/svg" version="1.1"/>`;
const spacerSvgBase64 =
typeof window === "undefined"
? Buffer.from(spacerSvg).toString("base64")
: window.btoa(spacerSvg);
let wrapperStyle: CSSProperties = { ...(style || {}) };
let spacerStyle: CSSProperties = pick(
style || {},
"objectFit",
"objectPosition"
);
if (displayWidth != null && displayWidth !== "auto") {
// If width is set, set it on the wrapper along with min/max width
// and just use `width: 100%` on the spacer
spacerStyle.width = "100%";
wrapperStyle.width = displayWidth;
wrapperStyle.minWidth = displayMinWidth;
wrapperStyle.maxWidth = displayMaxWidth;
} else {
// Otherwise, we want auto sizing from the spacer, so set width there.
//
// But if we have min/max width, it should be set in the wrapper and it
// can be percentage values (and we add corresponding min/max width to
// 100% in the spacer). In general it ends up with the correct effect,
// but some edge cases might make `min-width: 100%` shrink the image more
// than it should.
spacerStyle.width = displayWidth;
wrapperStyle.width = "auto";
if (displayMinWidth) {
spacerStyle.minWidth = "100%";
wrapperStyle.minWidth = displayMinWidth;
}
if (displayMaxWidth != null && displayMaxWidth !== "none") {
spacerStyle.maxWidth = "100%";
wrapperStyle.maxWidth = displayMaxWidth;
}
}
if (displayHeight != null && displayHeight !== "auto") {
spacerStyle.height = "100%";
wrapperStyle.height = displayHeight;
wrapperStyle.minHeight = displayMinHeight;
wrapperStyle.maxHeight = displayMaxHeight;
} else {
spacerStyle.height = displayHeight;
wrapperStyle.height = "auto";
if (displayMinHeight) {
spacerStyle.minHeight = "100%";
wrapperStyle.minHeight = displayMinHeight;
}
if (displayMaxHeight != null && displayMaxHeight !== "none") {
spacerStyle.maxHeight = "100%";
wrapperStyle.maxHeight = displayMaxHeight;
}
}
return (
<div
className={classNames(className, "__wab_img-wrapper")}
ref={outerRef as any}
style={wrapperStyle}
>
<img
alt=""
aria-hidden
className="__wab_img-spacer-svg"
src={`data:image/svg+xml;base64,${spacerSvgBase64}`}
style={spacerStyle}
/>
{makePicture({
imageLoader,
widthDescs,
sizes,
src: srcStr,
quality,
ref: imgRef,
style: style ? pick(style, "objectFit", "objectPosition") : undefined,
imgProps,
className: "__wab_img",
})}
</div>
);
});
function makePicture(opts: {
imageLoader?: ImageLoader;
widthDescs: WidthDesc[];
sizes?: string;
src: string;
quality?: number;
style?: React.CSSProperties;
className?: string;
imgProps: ImgTagProps;
ref?: React.Ref<HTMLImageElement>;
}) {
// If imageLoader is undefined, then this renders to just a normal
// <img />. Else it will render to a <picture> with a <source> for
// webp, and srcSet/sizes set according to width requirements.
const {
imageLoader,
widthDescs,
src,
quality,
style,
className,
sizes,
imgProps,
ref,
} = opts;
return (
<picture className="__wab_picture">
{imageLoader && imageLoader.supportsUrl(src) && (
<source
type="image/webp"
srcSet={widthDescs
.map(
(wd) =>
`${imageLoader.transformUrl({
src,
quality,
width: wd.width,
format: "webp",
})} ${wd.desc}`
)
.join(", ")}
/>
)}
<img
{...imgProps}
ref={ref}
className={className}
decoding="async"
src={
imageLoader && imageLoader.supportsUrl(src)
? imageLoader.transformUrl({
src,
quality,
width: widthDescs[widthDescs.length - 1].width,
})
: src
}
srcSet={
imageLoader && imageLoader.supportsUrl(src)
? widthDescs
.map(
(wd) =>
`${imageLoader.transformUrl({
src,
quality,
width: wd.width,
})} ${wd.desc}`
)
.join(", ")
: undefined
}
sizes={imageLoader && imageLoader.supportsUrl(src) ? sizes : undefined}
style={{
...(style ? pick(style, "objectFit", "objectPosition") : {}),
width: 0,
height: 0,
}}
/>
</picture>
);
}
const DEFAULT_SVG_WIDTH = 10000;
function isSvg(src: string) {
return src.endsWith(".svg") || src.startsWith("data:image/svg");
}
interface WidthDesc {
width?: number;
desc: string;
}
function getClosestPresetSize(width: number, fullWidth: number) {
const nextBiggerIndex =
ALL_SIZES.findIndex((w) => w >= width) ?? ALL_SIZES.length - 1;
const nextBigger = ALL_SIZES[nextBiggerIndex];
if (nextBigger >= fullWidth) {
// If the requested width is larger than the fullWidth,
// we just use the original width instead. It's impossible
// to make an image bigger than fullWidth!
return undefined;
} else if (
nextBiggerIndex + 1 < ALL_SIZES.length &&
fullWidth <= ALL_SIZES[nextBiggerIndex + 1]
) {
// If the fullWidth is just between nextBigger and the one after that,
// then also might as well just use the original size (so, width is 30,
// nextBigger is 32, then we just use the original as long as fullWidth is
// less than 48)
return undefined;
}
return nextBigger;
}
/**
* Computes the appropriate srcSet and sizes to use
*/
function getWidths(
width: number | string | undefined,
fullWidth: number,
extra?: { minWidth: string | number | undefined }
): { sizes: string | undefined; widthDescs: WidthDesc[] } {
const minWidth = extra?.minWidth;
const pixelWidth = getPixelLength(width);
const pixelMinWidth = getPixelLength(minWidth);
if (pixelWidth != null && (!minWidth || pixelMinWidth != null)) {
// If there's an exact width, then we just need to display it at 1x and 2x density
return {
widthDescs: [
{
width: getClosestPresetSize(
Math.max(pixelWidth, pixelMinWidth ?? 0),
fullWidth
),
desc: "1x",
},
{
width: getClosestPresetSize(
Math.max(pixelWidth, pixelMinWidth ?? 0) * 2,
fullWidth
),
desc: "2x",
},
],
sizes: undefined,
};
}
// Otherwise we don't know what sizes we'll end up, so we just cap it at
// device width. TODO: do better!
const usefulSizes = DEVICE_SIZES.filter(
(size) => !fullWidth || size < fullWidth
);
if (!!fullWidth && usefulSizes.length === 0) {
// image fullWidth is smaller than all device sizes. So all we can do
// is offer 1x
return {
widthDescs: [
{
width: getClosestPresetSize(fullWidth, fullWidth),
desc: "1x",
},
],
sizes: undefined,
};
}
return {
widthDescs: usefulSizes.map((size) => ({
width: getClosestPresetSize(size, fullWidth),
// If this is the last (buggest) useful width, but it is
// still within the bounds set by DEVICE_SIZES, then just
// use the original, unresized image. This means if we match
// the largest size, we use unresized and best quality image.
// We only do this, though, if fullWidth is "reasonable" --
// smaller than the largest size we would consider.
// i === usefulSizes.length - 1 &&
// fullWidth < DEVICE_SIZES[DEVICE_SIZES.length - 1]
// ? undefined
// : size,
desc: `${size}w`,
})),
sizes: "100vw",
};
}
function getPixelLength(length: number | string | undefined) {
if (length == null || length == "") {
return undefined;
}
if (typeof length === "number") {
return length;
}
const parsed = parseNumeric(length);
if (parsed && (!parsed.units || parsed.units === "px")) {
return parsed.num;
}
return undefined;
}
function parseNumeric(val: string) {
// Parse strings like "30", "30px", "30%", "30px /* blah blah */"
const res = val.match(
/^\s*(-?(?:\d+\.\d*|\d*\.\d+|\d+))\s*([a-z]*|%)\s*(?:\/\*.*)?$/i
);
if (res == null) {
return undefined;
}
const num = res[1];
const units = res[2];
return { num: +num, units };
}
function getImageLoader(loader: "plasmic" | ImageLoader | undefined) {
if (loader == null) {
return undefined;
} else if (loader === "plasmic") {
return PLASMIC_IMAGE_LOADER;
} else {
return loader;
}
}
const PLASMIC_IMAGE_LOADER: ImageLoader = {
supportsUrl: (src) => {
return src.startsWith("https://img.plasmic.app") && !isSvg(src);
},
transformUrl: (opts) => {
const params = [
opts.width ? `w=${opts.width}` : undefined,
`q=${opts.quality ?? 75}`,
opts.format ? `f=${opts.format}` : undefined,
].filter((x) => !!x);
return `${opts.src}?${params.join("&")}`;
},
}; | the_stack |
import { IEntityAnnotationObject } from "./IEntityAnnotationObject";
import { ITextIntentSequenceLabelObjectByPosition} from "./ITextIntentSequenceLabelObjectByPosition";
import { Data } from "./Data";
import { DataWithSubwordFeaturizer } from "./DataWithSubwordFeaturizer";
import { NgramSubwordFeaturizer } from "../model/language_understanding/featurizer/NgramSubwordFeaturizer";
import { Utility } from "../utility/Utility";
export class EntityAnnotatedCorpusDataWithSubwordFeaturizer extends DataWithSubwordFeaturizer {
// tslint:disable-next-line: max-line-length
public static createEntityAnnotatedCorpusDataWithSubwordFeaturizerFromSamplingExistingEntityAnnotatedCorpusDataUtterances(
existingEntityAnnotatedCorpusDataWithSubwordFeaturizer: EntityAnnotatedCorpusDataWithSubwordFeaturizer,
linesToSkip: number,
samplingIndexArray: number[],
toResetFeaturizerLabelFeatureMaps: boolean): EntityAnnotatedCorpusDataWithSubwordFeaturizer {
// -------------------------------------------------------------------
const entityAnnotatedCorpusDataWithSubwordFeaturizer: EntityAnnotatedCorpusDataWithSubwordFeaturizer =
EntityAnnotatedCorpusDataWithSubwordFeaturizer.createEntityAnnotatedCorpusDataWithSubwordFeaturizer(
existingEntityAnnotatedCorpusDataWithSubwordFeaturizer.getContent(),
existingEntityAnnotatedCorpusDataWithSubwordFeaturizer.getFeaturizer(),
linesToSkip,
toResetFeaturizerLabelFeatureMaps);
// -------------------------------------------------------------------
const luUtterances: ITextIntentSequenceLabelObjectByPosition[] =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances;
const lengthUtterancesArray: number =
luUtterances.length;
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances = [];
for (const index of samplingIndexArray) {
if ((index < 0) || (index > lengthUtterancesArray)) {
Utility.debuggingThrow(`(index|${index}|<0)||(index|${index}|>lengthUtterancesArray|${lengthUtterancesArray}|)`);
}
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.push(luUtterances[index]);
}
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentInstanceIndexMapArray =
entityAnnotatedCorpusDataWithSubwordFeaturizer.collectIntents(
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances);
entityAnnotatedCorpusDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray =
entityAnnotatedCorpusDataWithSubwordFeaturizer.collectEntityTypes(
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.intents =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.text);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.weights =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight);
// -------------------------------------------------------------------
if (toResetFeaturizerLabelFeatureMaps) {
entityAnnotatedCorpusDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps();
}
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.featurizeIntentsUtterances();
// -------------------------------------------------------------------
return entityAnnotatedCorpusDataWithSubwordFeaturizer;
}
// tslint:disable-next-line: max-line-length
public static createEntityAnnotatedCorpusDataWithSubwordFeaturizerFromFilteringExistingEntityAnnotatedCorpusDataUtterances(
existingEntityAnnotatedCorpusDataWithSubwordFeaturizer: EntityAnnotatedCorpusDataWithSubwordFeaturizer,
linesToSkip: number,
filteringIndexSet: Set<number>,
toResetFeaturizerLabelFeatureMaps: boolean): EntityAnnotatedCorpusDataWithSubwordFeaturizer {
// -------------------------------------------------------------------
const entityAnnotatedCorpusDataWithSubwordFeaturizer: EntityAnnotatedCorpusDataWithSubwordFeaturizer =
EntityAnnotatedCorpusDataWithSubwordFeaturizer.createEntityAnnotatedCorpusDataWithSubwordFeaturizer(
existingEntityAnnotatedCorpusDataWithSubwordFeaturizer.getContent(),
existingEntityAnnotatedCorpusDataWithSubwordFeaturizer.getFeaturizer(),
linesToSkip,
toResetFeaturizerLabelFeatureMaps);
// -------------------------------------------------------------------
const luUtterances: ITextIntentSequenceLabelObjectByPosition[] =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances;
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances = luUtterances.filter(
(value: ITextIntentSequenceLabelObjectByPosition,
index: number,
array: ITextIntentSequenceLabelObjectByPosition[]) => {
return (filteringIndexSet.has(index));
});
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentInstanceIndexMapArray =
entityAnnotatedCorpusDataWithSubwordFeaturizer.collectIntents(
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances);
entityAnnotatedCorpusDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray =
entityAnnotatedCorpusDataWithSubwordFeaturizer.collectEntityTypes(
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.intents =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.text);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.weights =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight);
// -------------------------------------------------------------------
if (toResetFeaturizerLabelFeatureMaps) {
entityAnnotatedCorpusDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps();
}
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.featurizeIntentsUtterances();
// -------------------------------------------------------------------
return entityAnnotatedCorpusDataWithSubwordFeaturizer;
}
public static createEntityAnnotatedCorpusDataWithSubwordFeaturizer(
content: string,
featurizer: NgramSubwordFeaturizer,
linesToSkip: number,
toResetFeaturizerLabelFeatureMaps: boolean): EntityAnnotatedCorpusDataWithSubwordFeaturizer {
// -------------------------------------------------------------------
const entityAnnotatedCorpusDataWithSubwordFeaturizer: EntityAnnotatedCorpusDataWithSubwordFeaturizer =
new EntityAnnotatedCorpusDataWithSubwordFeaturizer(
featurizer,
linesToSkip);
entityAnnotatedCorpusDataWithSubwordFeaturizer.content =
content;
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances =
entityAnnotatedCorpusDataWithSubwordFeaturizer.retrieveEntityAnnotatedCorpusUtterances(
content);
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentInstanceIndexMapArray =
entityAnnotatedCorpusDataWithSubwordFeaturizer.collectIntents(
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances);
entityAnnotatedCorpusDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray =
entityAnnotatedCorpusDataWithSubwordFeaturizer.collectEntityTypes(
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.intents =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.text);
entityAnnotatedCorpusDataWithSubwordFeaturizer.intentsUtterancesWeights.weights =
entityAnnotatedCorpusDataWithSubwordFeaturizer.luUtterances.map(
(entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight);
// -------------------------------------------------------------------
if (toResetFeaturizerLabelFeatureMaps) {
entityAnnotatedCorpusDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps();
}
// -------------------------------------------------------------------
entityAnnotatedCorpusDataWithSubwordFeaturizer.featurizeIntentsUtterances();
// -------------------------------------------------------------------
return entityAnnotatedCorpusDataWithSubwordFeaturizer;
}
protected linesToSkip: number = 0;
protected constructor(
featurizer: NgramSubwordFeaturizer,
linesToSkip: number = 0) {
super(featurizer);
this.linesToSkip = linesToSkip;
}
public async createDataFromSamplingExistingDataUtterances(
existingDataWithSubwordFeaturizer: DataWithSubwordFeaturizer,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number,
samplingIndexArray: number[],
toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> {
if (!(existingDataWithSubwordFeaturizer instanceof EntityAnnotatedCorpusDataWithSubwordFeaturizer)) {
Utility.debuggingThrow("logic error: the input DataWithSubwordFeaturizer object should be a EntityAnnotatedCorpusDataWithSubwordFeaturizer object.");
}
// tslint:disable-next-line: max-line-length
return EntityAnnotatedCorpusDataWithSubwordFeaturizer.createEntityAnnotatedCorpusDataWithSubwordFeaturizerFromSamplingExistingEntityAnnotatedCorpusDataUtterances(
existingDataWithSubwordFeaturizer as EntityAnnotatedCorpusDataWithSubwordFeaturizer,
linesToSkip,
samplingIndexArray,
toResetFeaturizerLabelFeatureMaps);
}
public async createDataFromFilteringExistingDataUtterances(
existingDataWithSubwordFeaturizer: DataWithSubwordFeaturizer,
labelColumnIndex: number,
textColumnIndex: number,
weightColumnIndex: number,
linesToSkip: number,
filteringIndexSet: Set<number>,
toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> {
if (!(existingDataWithSubwordFeaturizer instanceof EntityAnnotatedCorpusDataWithSubwordFeaturizer)) {
Utility.debuggingThrow("logic error: the input DataWithSubwordFeaturizer object should be a EntityAnnotatedCorpusDataWithSubwordFeaturizer object.");
}
// tslint:disable-next-line: max-line-length
return EntityAnnotatedCorpusDataWithSubwordFeaturizer.createEntityAnnotatedCorpusDataWithSubwordFeaturizerFromFilteringExistingEntityAnnotatedCorpusDataUtterances(
existingDataWithSubwordFeaturizer as EntityAnnotatedCorpusDataWithSubwordFeaturizer,
linesToSkip,
filteringIndexSet,
toResetFeaturizerLabelFeatureMaps);
}
// tslint:disable-next-line: max-line-length
public retrieveEntityAnnotatedCorpusUtterances(
// ---- NOTE ---- the return is newly allocated, unlike the one in LuDataWithSubwordFeaturizer
content: string,
includePartOfSpeechTagTagAsEntities: boolean = true,
utteranceReconstructionDelimiter: string = " ",
defaultEntityTag: string = "O",
useIdForIntent: boolean = true): ITextIntentSequenceLabelObjectByPosition[] {
const entityAnnotatedCorpusTypes: IEntityAnnotationObject =
Utility.loadEntityAnnotatedCorpusContent(
content, // ---- filename: string,
this.getLinesToSkip(), // ---- lineIndexToStart: number = 0,
",", // ---- columnDelimiter: string = ",",
"\n", // ---- rowDelimiter: string = "\n",
-1, // ---- lineIndexToEnd: number = -1
);
const entityAnnotatedCorpusUtterances: ITextIntentSequenceLabelObjectByPosition[] =
Utility.entityAnnotatedCorpusTypesToEntityAnnotatedCorpusUtterances(
entityAnnotatedCorpusTypes,
includePartOfSpeechTagTagAsEntities,
utteranceReconstructionDelimiter,
defaultEntityTag,
useIdForIntent);
return entityAnnotatedCorpusUtterances;
}
public getLuObject(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"EntityAnnotatedCorpusDataWithSubwordFeaturizer object to generate a LU object.");
}
public getLuLuisJsonStructure(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"EntityAnnotatedCorpusDataWithSubwordFeaturizer object to generate a LUIS JSON object.");
}
public getLuQnaJsonStructure(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"EntityAnnotatedCorpusDataWithSubwordFeaturizer object to generate a QnA JSON object.");
}
public getLuQnaAlterationsJsonStructure(): any { // ---- NOTE: can be overriden by a child class.
throw new Error("Logical error as it's not implemented for a " +
"EntityAnnotatedCorpusDataWithSubwordFeaturizer to generate a QnA Alterations JSON object.");
}
public getLinesToSkip(): number {
return this.linesToSkip;
}
} | the_stack |
import {RCRETestUtil} from 'rcre-test-tools';
import React from 'react';
import {componentLoader, Connect} from 'rcre';
describe('CommonConnect', () => {
const TYPE = 'testButton';
beforeEach(() => {
componentLoader.removeComponent(TYPE);
});
it('propsMapping', () => {
interface ButtonTest extends Connect.BasicConnectProps {
type: string;
}
class Button extends React.PureComponent<ButtonTest, {}> {
render() {
const {
tools,
...props
} = this.props;
expect(props.type).toBe('demoType');
// @ts-ignore
return <button {...props}>{props.children}</button>;
}
}
const connectOptions = {
propsMapping: {
text: 'children',
buttonType: 'type'
}
};
componentLoader.addComponent(TYPE, Connect.commonConnect(connectOptions)(Button));
let config = {
body: [{
type: 'testButton',
text: 'helloworld',
buttonType: 'demoType'
}]
};
let test = new RCRETestUtil(config);
let wrapper = test.wrapper;
let button = wrapper.find('button');
expect(button.text()).toBe('helloworld');
test.unmount();
});
it('provider build in events', () => {
interface ButtonTest extends Connect.BasicConnectProps {
otherOptions: string;
}
class Button extends React.PureComponent<ButtonTest, {}> {
render() {
const {
tools,
otherOptions,
...props
} = this.props;
expect(otherOptions).toBe('1234');
return <button {...props}>{props.children}</button>;
}
}
const connectOptions = {
propsMapping: {
text: 'children',
buttonType: 'type'
}
};
componentLoader.addComponent(TYPE, Connect.commonConnect(connectOptions)(Button));
let config = {
body: [{
type: 'testButton',
text: 'helloworld',
otherOptions: '1234'
}]
};
let test = new RCRETestUtil(config);
let wrapper = test.wrapper;
let button = wrapper.find('button');
expect(button.text()).toBe('helloworld');
test.unmount();
});
//
it('debounce feature', () => {
return new Promise((resolve, reject) => {
let config: any = {
body: [{
type: 'container',
model: 'sampleDemo',
children: [
{
type: 'input',
name: 'username',
debounce: 500
},
{
type: 'button',
text: 'click',
trigger: [{
event: 'onClick',
targetCustomer: '$this',
params: {
username: 'event'
}
}]
}
]
}]
};
let test = new RCRETestUtil(config);
let input = test.wrapper.find('input').at(0);
test.setContainer('sampleDemo');
input.simulate('change', {
target: {
value: 'helloworld'
}
});
let instance: any = input.getDOMNode();
expect(instance.value).toBe('helloworld');
let state = test.getState();
expect(state.container.sampleDemo.username).toBe(undefined);
setTimeout(() => {
state = test.getState();
expect(state.container.sampleDemo.username).toBe('helloworld');
let button = test.getComponentByType('button');
test.simulate(button, 'onClick').then(() => {
state = test.getState();
expect(state.container.sampleDemo.username).toBe('event');
instance = input.getDOMNode();
expect(instance.value).toBe('event');
test.unmount();
resolve();
});
}, 600);
});
});
it('debounce input can be updated by others', async () => {
let config = {
body: [{
type: 'container',
model: 'demo',
children: [{
type: 'input',
name: 'username',
debounce: 300
}, {
type: 'button',
text: 'update',
trigger: [{
event: 'onClick',
targetCustomer: '$this',
params: {
username: 'helloworld'
}
}]
}]
}]
};
let test = new RCRETestUtil(config);
test.setContainer('demo');
let button = test.getComponentByType('button');
await test.simulate(button, 'onClick');
let input = test.getComponentByName('username');
let inputElement = input.find('input');
let value = inputElement.prop('value');
expect(value).toBe('helloworld');
test.unmount();
});
it('debounce can be init during mount', () => {
let config = {
body: [{
type: 'container',
model: 'demo',
data: {
username: 'helloworld'
},
children: [{
type: 'input',
name: 'username',
debounce: 300
}]
}]
};
let test = new RCRETestUtil(config);
test.setContainer('demo');
let username = test.getComponentByName('username');
let input = username.find('input');
expect(input.prop('value')).toBe('helloworld');
test.unmount();
});
it('$item update will trigger connect to update', async () => {
let config = {
body: [{
type: 'container',
model: 'demo',
data: {
list: [{
name: '111'
}, {
name: '222',
}, {
name: '333'
}]
},
children: [
{
type: 'foreach',
dataSource: '#ES{$data.list}',
control: {
type: 'text',
text: '#ES{$item.name}'
}
},
{
type: 'button',
text: 'updateList',
trigger: [{
event: 'onClick',
targetCustomer: '$this',
params: {
'list[0].name': '444'
}
}]
}
]
}]
};
let test = new RCRETestUtil(config);
test.setContainer('demo');
let button = test.getComponentByType('button');
await test.simulate(button, 'onClick');
let textA = test.getComponentByType('text', 0);
let textB = test.getComponentByType('text', 1);
let textC = test.getComponentByType('text', 2);
console.log(textA.text());
console.log(textB.text());
console.log(textC.text());
expect(textA.text()).toBe('444');
expect(textB.text()).toBe('222');
expect(textC.text()).toBe('333');
test.unmount();
});
it('component with defaultValue boolean', () => {
let config = {
body: [
{
type: 'container',
model: 'checkboxDemo',
data: {
test: true
},
children: [
{
type: 'checkbox',
name: 'checked',
text: 'isChecked',
disabled: true,
defaultValue: '#ES{$data.test}'
},
{
type: 'text',
text: '#ES{$data.checked}'
}
]
}
]
};
let test = new RCRETestUtil(config);
let input = test.wrapper.find('input');
let instance: any = input.getDOMNode();
expect(instance.value).toBe('true');
});
it('component with defaultValue array', () => {
let config = {
body: [
{
type: 'container',
model: 'checkboxGroup',
data: {
groups: [
{
key: 'name',
text: '姓名'
},
{
key: 'age',
text: '年龄'
},
{
key: 'company',
text: '公司'
}
]
},
children: [
{
type: 'checkbox',
name: 'boxGroup',
groups: '#ES{$data.groups}',
groupSelectAll: true,
defaultValue: ['name']
},
{
type: 'text',
htmlType: 'code',
style: {
marginTop: 10,
display: 'block'
},
text: '#ES{$data.boxGroup}'
}
]
}
]
};
let test = new RCRETestUtil(config);
test.setContainer('checkboxGroup');
let checkbox = test.getComponentByName('boxGroup');
expect(test.getComponentNameValue(checkbox)).toEqual(['name']);
});
it('hidden component with defaultValue boolean', async () => {
let config = {
body: [
{
type: 'container',
model: 'checkboxDemo',
data: {
test: true,
show: false
},
children: [
{
type: 'div',
show: '#ES{$data.show}',
children: [
{
type: 'checkbox',
name: 'checked',
text: 'isChecked',
disabled: true,
defaultValue: '#ES{$data.test}'
}
]
},
{
type: 'button',
text: 'click',
trigger: [{
event: 'onClick',
targetCustomer: '$this',
params: {
show: true
}
}]
}
]
}
]
};
let test = new RCRETestUtil(config);
test.setContainer('checkboxDemo');
let state = test.getState();
expect(state.container.checkboxDemo.show).toBe(false);
let inputBeforeClick = test.wrapper.find('input');
expect(inputBeforeClick.length).toBe(0);
let button = test.getComponentByType('button');
await test.simulate(button, 'onClick');
let inputAfterClick = test.wrapper.find('input');
let instance: any = inputAfterClick.getDOMNode();
state = test.getState();
expect(state.container.checkboxDemo.show).toBe(true);
expect(instance.value).toBe('true');
});
it('hidden component with defaultValue array', async () => {
let config = {
body: [
{
type: 'container',
model: 'checkboxGroup',
data: {
show: false,
groups: [
{
key: 'name',
text: '姓名'
},
{
key: 'age',
text: '年龄'
},
{
key: 'company',
text: '公司'
}
]
},
children: [
{
type: 'div',
show: '#ES{$data.show}',
children: [{
type: 'checkbox',
name: 'boxGroup',
groups: '#ES{$data.groups}',
groupSelectAll: true,
defaultValue: ['name']
}]
},
{
type: 'button',
text: 'click',
trigger: [{
event: 'onClick',
targetCustomer: '$this',
params: {
show: true
}
}]
}
]
}
]
};
let test = new RCRETestUtil(config);
test.setContainer('checkboxGroup');
let state = test.getState();
expect(state.container.checkboxGroup.show).toBe(false);
let inputBeforeClick = test.wrapper.find('input');
expect(inputBeforeClick.length).toBe(0);
let button = test.getComponentByType('button');
await test.simulate(button, 'onClick');
state = test.getState();
expect(state.container.checkboxGroup.show).toBe(true);
let checkbox = test.getComponentByName('boxGroup');
expect(test.getComponentNameValue(checkbox)).toEqual(['name']);
});
it('When the name value is a combined path, the defaultValue can still be initialized.', () => {
let config = {
body: [{
type: 'container',
model: 'demo',
children: [{
type: 'input',
name: 'user.name',
defaultValue: 'helloworld'
}]
}]
};
let test = new RCRETestUtil(config);
test.setContainer('demo');
expect(test.getContainerState()).toEqual({
user: {
name: 'helloworld'
}
});
});
it('DefaultValue is 0 will still initialize', () => {
let config = {
body: [{
type: 'container',
model: 'demo',
children: [{
type: 'input',
name: 'username',
defaultValue: 0
}]
}]
};
let test = new RCRETestUtil(config);
test.setContainer('demo');
console.log(test.store.getState());
expect(test.getContainerState()).toEqual({
username: 0
});
});
it('defaultValue does not perform the function of transform', () => {
let config = {
body: [{
type: 'container',
model: 'demo',
children: [{
type: 'input',
name: 'username',
transform: {
in: '#ES{$args.value === "A" ? "0" : "1"}',
out: '#ES{$args.value === "0" ? "A" : "B"}'
},
defaultValue: 'A'
}]
}]
};
let test = new RCRETestUtil(config);
console.log(test.store.getState());
test.setContainer('demo');
console.log(test.getContainerState());
expect(test.getContainerState()).toEqual({
username: 'A'
});
});
// it('multiple select component update', async () => {
// let config = {
// body: [
// {
// type: 'container',
// model: 'multiple',
// data: {
// options: [
// {
// key: 'A',
// value: 'a'
// },
// {
// key: 'B',
// value: 'b'
// }
// ]
// },
// children: [
// {
// type: 'select',
// name: 'list',
// mode: 'multiple',
// options: '#ES{$data.options}'
// },
// {
// type: 'text',
// text: 'select value: #ES{$data.list.join(",")}'
// }
// ]
// }
// ]
// };
//
// let wrapper = mount(<JSONRender code={JSON.stringify(config)}/>);
// let select = wrapper.find('.ant-select').at(0);
// select.simulate('click');
//
// let selectItems = document.getElementsByClassName('ant-select-dropdown-menu-item');
// let selectItemA: any = selectItems[0];
// let selectItemB: any = selectItems[1];
//
// let text = wrapper.find('RCRE(text)').at(0).getDOMNode();
//
// expect(text.innerHTML).toEqual('select value: ');
// selectItemA.click();
// expect(text.innerHTML).toEqual('select value: a');
// selectItemB.click();
// expect(text.innerHTML).toEqual('select value: a,b');
// selectItemA.click();
// expect(text.innerHTML).toEqual('select value: b');
// });
it('autoClearCondition: component will auto delete value when satisfy the condition expression', async () => {
let autoClearComponent = ((props: any) => {
return (
<input
value={props.value || ''}
onChange={event => {
props.tools.updateNameValue(event.target.value);
}}
/>
);
});
componentLoader.addComponent('autoClear', Connect.commonConnect({
autoClearCondition: (value, props) => {
console.log(value);
if (value === 'AAA') {
return true;
}
return false;
}
})(autoClearComponent));
let config = {
body: [{
type: 'container',
model: 'demo',
children: [{
type: 'autoClear',
name: 'username'
}]
}]
};
let test = new RCRETestUtil(config);
test.setContainer('demo');
let autoClear = test.getComponentByName('username');
test.setData(autoClear, 'helloworld');
expect(test.getComponentNameValue(autoClear)).toBe('helloworld');
test.setData(autoClear, 'AAA');
expect(test.getComponentNameValue(autoClear)).toBe(undefined);
});
}); | the_stack |
export const enum StandardTokenType {
Other = 0,
Comment = 1,
String = 2,
RegEx = 4,
}
const enum IgnoreBracketsInTokens {
value = StandardTokenType.Comment |
StandardTokenType.String |
StandardTokenType.RegEx,
}
export function ignoreBracketsInToken(
standardTokenType: StandardTokenType,
): boolean {
return (standardTokenType & IgnoreBracketsInTokens.value) !== 0;
}
export const enum MetadataConsts {
LANGUAGEID_MASK = 255,
TOKEN_TYPE_MASK = 1792,
FONT_STYLE_MASK = 14336,
FOREGROUND_MASK = 8372224,
BACKGROUND_MASK = 4286578688,
LANGUAGEID_OFFSET = 0,
TOKEN_TYPE_OFFSET = 8,
FONT_STYLE_OFFSET = 11,
FOREGROUND_OFFSET = 14,
BACKGROUND_OFFSET = 23,
}
export const enum FontStyle {
NotSet = -1,
None = 0,
Italic = 1,
Bold = 2,
Underline = 4,
}
export const enum ColorId {
None = 0,
DefaultForeground = 1,
DefaultBackground = 2,
}
export const enum LanguageId {
Null = 0,
PlainText = 1,
}
export interface IViewLineTokens {
equals(other: IViewLineTokens): boolean;
getCount(): number;
getForeground(tokenIndex: number): ColorId;
getEndOffset(tokenIndex: number): number;
getClassName(tokenIndex: number): string;
getInlineStyle(tokenIndex: number, colorMap: string[]): string;
findTokenIndexAtOffset(offset: number): number;
}
export class LineTokens implements IViewLineTokens {
_lineTokensBrand: void;
private readonly _tokens: Uint32Array;
private readonly _tokensCount: number;
private readonly _text: string;
constructor(tokens: Uint32Array, text: string) {
this._tokens = tokens;
this._tokensCount = this._tokens.length >>> 1;
this._text = text;
}
public equals(other: IViewLineTokens): boolean {
if (other instanceof LineTokens) {
return this.slicedEquals(other, 0, this._tokensCount);
}
return false;
}
public slicedEquals(
other: LineTokens,
sliceFromTokenIndex: number,
sliceTokenCount: number,
): boolean {
if (this._text !== other._text) {
return false;
}
if (this._tokensCount !== other._tokensCount) {
return false;
}
const from = sliceFromTokenIndex << 1;
const to = from + (sliceTokenCount << 1);
for (let i = from; i < to; i++) {
if (this._tokens[i] !== other._tokens[i]) {
return false;
}
}
return true;
}
public getLineContent(): string {
return this._text;
}
public getCount(): number {
return this._tokensCount;
}
public getStartOffset(tokenIndex: number): number {
if (tokenIndex > 0) {
return this._tokens[(tokenIndex - 1) << 1];
}
return 0;
}
public getLanguageId(tokenIndex: number): LanguageId {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return TokenMetadata.getLanguageId(metadata);
}
public getStandardTokenType(tokenIndex: number): StandardTokenType {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return TokenMetadata.getTokenType(metadata);
}
public getForeground(tokenIndex: number): ColorId {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return TokenMetadata.getForeground(metadata);
}
public getClassName(tokenIndex: number): string {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return TokenMetadata.getClassNameFromMetadata(metadata);
}
public getInlineStyle(tokenIndex: number, colorMap: string[]): string {
const metadata = this._tokens[(tokenIndex << 1) + 1];
return TokenMetadata.getInlineStyleFromMetadata(metadata, colorMap);
}
public getEndOffset(tokenIndex: number): number {
return this._tokens[tokenIndex << 1];
}
/**
* Find the token containing offset `offset`.
* @param offset The search offset
* @return The index of the token containing the offset.
*/
public findTokenIndexAtOffset(offset: number): number {
return LineTokens.findIndexInTokensArray(this._tokens, offset);
}
public inflate(): IViewLineTokens {
return this;
}
public sliceAndInflate(
startOffset: number,
endOffset: number,
deltaOffset: number,
): IViewLineTokens {
return new SlicedLineTokens(this, startOffset, endOffset, deltaOffset);
}
public static convertToEndOffset(
tokens: Uint32Array,
lineTextLength: number,
): void {
const tokenCount = tokens.length >>> 1;
const lastTokenIndex = tokenCount - 1;
for (let tokenIndex = 0; tokenIndex < lastTokenIndex; tokenIndex++) {
tokens[tokenIndex << 1] = tokens[(tokenIndex + 1) << 1];
}
tokens[lastTokenIndex << 1] = lineTextLength;
}
public static findIndexInTokensArray(
tokens: Uint32Array,
desiredIndex: number,
): number {
if (tokens.length <= 2) {
return 0;
}
let low = 0;
let high = (tokens.length >>> 1) - 1;
while (low < high) {
let mid = low + Math.floor((high - low) / 2);
let endOffset = tokens[mid << 1];
if (endOffset === desiredIndex) {
return mid + 1;
} else if (endOffset < desiredIndex) {
low = mid + 1;
} else if (endOffset > desiredIndex) {
high = mid;
}
}
return low;
}
}
export class SlicedLineTokens implements IViewLineTokens {
private readonly _source: LineTokens;
private readonly _startOffset: number;
private readonly _endOffset: number;
private readonly _deltaOffset: number;
private readonly _firstTokenIndex: number;
private readonly _tokensCount: number;
constructor(
source: LineTokens,
startOffset: number,
endOffset: number,
deltaOffset: number,
) {
this._source = source;
this._startOffset = startOffset;
this._endOffset = endOffset;
this._deltaOffset = deltaOffset;
this._firstTokenIndex = source.findTokenIndexAtOffset(startOffset);
this._tokensCount = 0;
for (
let i = this._firstTokenIndex, len = source.getCount();
i < len;
i++
) {
const tokenStartOffset = source.getStartOffset(i);
if (tokenStartOffset >= endOffset) {
break;
}
this._tokensCount++;
}
}
public equals(other: IViewLineTokens): boolean {
if (other instanceof SlicedLineTokens) {
return (
this._startOffset === other._startOffset &&
this._endOffset === other._endOffset &&
this._deltaOffset === other._deltaOffset &&
this._source.slicedEquals(
other._source,
this._firstTokenIndex,
this._tokensCount,
)
);
}
return false;
}
public getCount(): number {
return this._tokensCount;
}
public getForeground(tokenIndex: number): ColorId {
return this._source.getForeground(this._firstTokenIndex + tokenIndex);
}
public getEndOffset(tokenIndex: number): number {
const tokenEndOffset = this._source.getEndOffset(
this._firstTokenIndex + tokenIndex,
);
return (
Math.min(this._endOffset, tokenEndOffset) -
this._startOffset +
this._deltaOffset
);
}
public getClassName(tokenIndex: number): string {
return this._source.getClassName(this._firstTokenIndex + tokenIndex);
}
public getInlineStyle(tokenIndex: number, colorMap: string[]): string {
return this._source.getInlineStyle(
this._firstTokenIndex + tokenIndex,
colorMap,
);
}
public findTokenIndexAtOffset(offset: number): number {
return (
this._source.findTokenIndexAtOffset(
offset + this._startOffset - this._deltaOffset,
) - this._firstTokenIndex
);
}
}
export class TokenMetadata {
public static getLanguageId(metadata: number): LanguageId {
return (
(metadata & MetadataConsts.LANGUAGEID_MASK) >>>
MetadataConsts.LANGUAGEID_OFFSET
);
}
public static getTokenType(metadata: number): StandardTokenType {
return (
(metadata & MetadataConsts.TOKEN_TYPE_MASK) >>>
MetadataConsts.TOKEN_TYPE_OFFSET
);
}
public static getFontStyle(metadata: number): FontStyle {
return (
(metadata & MetadataConsts.FONT_STYLE_MASK) >>>
MetadataConsts.FONT_STYLE_OFFSET
);
}
public static getForeground(metadata: number): ColorId {
return (
(metadata & MetadataConsts.FOREGROUND_MASK) >>>
MetadataConsts.FOREGROUND_OFFSET
);
}
public static getBackground(metadata: number): ColorId {
return (
(metadata & MetadataConsts.BACKGROUND_MASK) >>>
MetadataConsts.BACKGROUND_OFFSET
);
}
public static getClassNameFromMetadata(metadata: number): string {
let foreground = this.getForeground(metadata);
let className = "mtk" + foreground;
let fontStyle = this.getFontStyle(metadata);
if (fontStyle & FontStyle.Italic) {
className += " mtki";
}
if (fontStyle & FontStyle.Bold) {
className += " mtkb";
}
if (fontStyle & FontStyle.Underline) {
className += " mtku";
}
return className;
}
public static getInlineStyleFromMetadata(
metadata: number,
colorMap: string[],
): string {
const foreground = this.getForeground(metadata);
const fontStyle = this.getFontStyle(metadata);
let result = `color: ${colorMap[foreground]};`;
if (fontStyle & FontStyle.Italic) {
result += "font-style: italic;";
}
if (fontStyle & FontStyle.Bold) {
result += "font-weight: bold;";
}
if (fontStyle & FontStyle.Underline) {
result += "text-decoration: underline;";
}
return result;
}
} | the_stack |
import * as ui from '../ui';
import { types } from '../api_types';
import { myRunsStore } from './runsStore';
import { omegaup } from '../omegaup';
import { getMaxScore } from './navigation';
import T from '../lang';
import rankingStore from './rankingStore';
export const scoreboardColors = [
'#FB3F51',
'#FF5D40',
'#FFA240',
'#FFC740',
'#59EA3A',
'#37DD6F',
'#34D0BA',
'#3AAACF',
'#8144D6',
'#CD35D3',
];
export interface RankingRequest {
problemsetId: number;
scoreboardToken: string;
currentUsername: string;
navbarProblems: types.NavbarProblemsetProblem[];
}
export function onRankingEvents({
events,
currentRanking,
startTimestamp = 0,
finishTimestamp = Date.now(),
placesToShowInChart = 10,
}: {
events: types.ScoreboardEvent[];
currentRanking: { [username: string]: number };
startTimestamp?: number;
finishTimestamp?: number;
placesToShowInChart?: number;
}): {
series: (Highcharts.SeriesLineOptions & { rank: number })[];
navigatorData: number[][];
} {
const dataInSeries: { [name: string]: number[][] } = {};
const navigatorData: number[][] = [[startTimestamp, 0]];
const series: (Highcharts.SeriesLineOptions & { rank: number })[] = [];
const usernames: { [name: string]: string } = {};
// Don't trust input data (data might not be sorted)
events.sort((a, b) => a.delta - b.delta);
// group points by person
for (const curr of events) {
// limit chart to top n users
if (currentRanking[curr.username] > placesToShowInChart) continue;
const name = curr.name ?? curr.username;
if (!dataInSeries[name]) {
dataInSeries[name] = [[startTimestamp, 0]];
usernames[name] = curr.username;
}
dataInSeries[name].push([
startTimestamp + curr.delta * 60 * 1000,
curr.total.points,
]);
// check if to add to navigator
if (curr.total.points > navigatorData[navigatorData.length - 1][1]) {
navigatorData.push([
startTimestamp + curr.delta * 60 * 1000,
curr.total.points,
]);
}
}
// convert datas to series
for (const name of Object.keys(dataInSeries)) {
dataInSeries[name].push([
finishTimestamp,
dataInSeries[name][dataInSeries[name].length - 1][1],
]);
series.push({
type: 'line',
name: name,
rank: currentRanking[usernames[name]],
data: dataInSeries[name],
step: 'right',
});
}
series.sort((a, b) => a.rank - b.rank);
navigatorData.push([
finishTimestamp,
navigatorData[navigatorData.length - 1][1],
]);
return { series, navigatorData };
}
export function createChart({
series,
navigatorData,
maxPoints,
startTimestamp,
finishTimestamp,
}: {
series: (Highcharts.SeriesLineOptions & { rank: number })[];
navigatorData: number[][];
maxPoints: number;
startTimestamp: number;
finishTimestamp: number;
}): Highcharts.Options {
return {
chart: { height: 300, spacingTop: 20 },
colors: scoreboardColors,
xAxis: {
type: 'datetime',
ordinal: false,
min: startTimestamp,
max: finishTimestamp,
},
yAxis: {
showLastLabel: true,
showFirstLabel: false,
min: 0,
max: maxPoints,
title: {
text: T.wordsSubmissions,
},
},
plotOptions: {
series: {
animation: false,
lineWidth: 3,
states: { hover: { lineWidth: 3 } },
marker: { radius: 5, symbol: 'circle', lineWidth: 1 },
},
},
title: {
text: T.wordsSubmissions,
},
navigator: {
series: {
type: 'line',
step: 'left',
lineWidth: 3,
lineColor: '#333',
data: navigatorData,
},
},
rangeSelector: { enabled: false },
series: series,
};
}
export function updateProblemScore({
alias,
previousScore,
scoreboard,
username,
}: {
alias: string;
previousScore: number;
scoreboard: types.Scoreboard;
username: string;
}): types.ScoreboardRankingEntry[] {
return scoreboard.ranking.map((rank) => {
const ranking = rank;
if (ranking.username === username) {
ranking.problems = rank.problems.map((problem) => {
const problemRanking = problem;
if (problemRanking.alias == alias) {
const maxScore = getMaxScore(
myRunsStore.state.runs.filter((run) => run.alias === problem.alias),
problemRanking.alias,
previousScore,
);
problemRanking.points = maxScore;
}
return problemRanking;
});
ranking.total.points = rank.problems.reduce(
(accumulator, problem) => accumulator + problem.points,
0,
);
}
return ranking;
});
}
export function onRankingChanged({
scoreboard,
currentUsername,
navbarProblems,
}: {
scoreboard: types.Scoreboard;
currentUsername: string;
navbarProblems: types.NavbarProblemsetProblem[];
}): {
ranking: types.ScoreboardRankingEntry[];
users: omegaup.UserRank[];
currentRanking: { [username: string]: number };
maxPoints: number;
lastTimeUpdated: Date;
} {
const users: omegaup.UserRank[] = [];
const problems: { [alias: string]: types.NavbarProblemsetProblem } = {};
const ranking: types.ScoreboardRankingEntry[] = scoreboard.ranking;
const currentRanking: { [username: string]: number } = {};
const order: { [problemAlias: string]: number } = {};
const currentRankingState: { [username: string]: { place: number } } = {};
let maxPoints: number = 0;
for (const [i, problem] of scoreboard.problems.entries()) {
order[problem.alias] = i;
}
for (const problem of navbarProblems) {
problems[problem.alias] = problem;
maxPoints += problem.maxScore;
}
// Push scoreboard to ranking table
for (const [i, rank] of scoreboard.ranking.entries()) {
currentRanking[rank.username] = i;
const username = ui.rankingUsername(rank);
currentRankingState[username] = { place: rank.place ?? 0 };
// Update problem scores.
for (const alias of Object.keys(order)) {
const problem = rank.problems[order[alias]];
if (
problems[alias] &&
rank.username === currentUsername &&
problems[alias].acceptsSubmissions
) {
const currentProblem = problems[alias];
currentProblem.hasRuns = problem.runs > 0;
currentProblem.bestScore = getMaxScore(
myRunsStore.state.runs.filter((run) => run.alias === problem.alias),
alias,
problem.points,
);
}
}
// update miniranking
if (i < 10) {
const username = ui.rankingUsername(rank);
users.push({
position: currentRankingState[username].place,
username,
country: rank.country,
classname: rank.classname,
points: rank.total.points,
penalty: rank.total.penalty,
});
}
}
return {
ranking,
users,
currentRanking,
maxPoints,
lastTimeUpdated: scoreboard.time,
};
}
export function mergeRankings({
scoreboard,
originalScoreboardEvents,
navbarProblems,
}: {
scoreboard: types.Scoreboard;
originalScoreboardEvents: types.ScoreboardEvent[];
navbarProblems: types.NavbarProblemsetProblem[];
}): {
mergedScoreboard: types.Scoreboard;
originalContestEvents: types.ScoreboardEvent[];
} {
// This clones virtualContestData to data so that virtualContestData values
// won't be overriden by processes below
const data = JSON.parse(JSON.stringify(scoreboard)) as types.Scoreboard;
const dataRanking: (types.ScoreboardRankingEntry & {
virtual?: boolean;
})[] = data.ranking;
const events = originalScoreboardEvents;
const currentDelta =
(new Date().getTime() - scoreboard.start_time.getTime()) / (1000 * 60);
for (const rank of dataRanking) rank.virtual = true;
const problemOrder: { [problemAlias: string]: number } = {};
const problems: { order: number; alias: string }[] = [];
const initialProblems: types.ScoreboardRankingProblem[] = [];
for (const problem of Object.values(navbarProblems)) {
problemOrder[problem.alias] = problems.length;
initialProblems.push({
alias: problem.alias,
penalty: 0,
percent: 0,
points: 0,
runs: 0,
});
problems.push({ order: problems.length + 1, alias: problem.alias });
}
// Calculate original contest scoreboard with current delta time
const originalContestRanking: {
[username: string]: types.ScoreboardRankingEntry;
} = {};
const originalContestEvents: types.ScoreboardEvent[] = [];
// Refresh after time T
let refreshTime = 30 * 1000; // 30 seconds
events.forEach((evt: types.ScoreboardEvent) => {
const key = evt.username;
if (!Object.prototype.hasOwnProperty.call(originalContestRanking, key)) {
originalContestRanking[key] = {
country: evt.country,
name: evt.name,
username: evt.username,
classname: evt.classname,
is_invited: evt.is_invited,
problems: Array.from(initialProblems),
total: {
penalty: 0,
points: 0,
},
place: 0,
};
}
if (evt.delta > currentDelta) {
refreshTime = Math.min(
refreshTime,
(evt.delta - currentDelta) * 60 * 1000,
);
return;
}
originalContestEvents.push(evt);
const problem =
originalContestRanking[key].problems[problemOrder[evt.problem.alias]];
originalContestRanking[key].problems[problemOrder[evt.problem.alias]] = {
alias: evt.problem.alias,
penalty: evt.problem.penalty,
points: evt.problem.points,
percent: evt.problem.points,
// If problem appeared in event for than one, it means a problem has
// been solved multiple times
runs: problem ? problem.runs + 1 : 1,
};
originalContestRanking[key].total = evt.total;
});
// Merge original contest scoreboard ranking with virtual contest
for (const ranking of Object.values(originalContestRanking)) {
dataRanking.push(ranking);
}
// Re-sort rank
dataRanking.sort((rank1, rank2) => {
return rank2.total.points - rank1.total.points;
});
// Override ranking
dataRanking.forEach((rank, index) => (rank.place = index + 1));
const mergedScoreboard = data;
mergedScoreboard.ranking = dataRanking;
return { mergedScoreboard, originalContestEvents };
}
export function onVirtualRankingChanged({
scoreboard,
scoreboardEvents,
problems,
contest,
currentUsername,
}: {
scoreboard: types.Scoreboard;
scoreboardEvents: types.ScoreboardEvent[];
problems: types.NavbarProblemsetProblem[];
contest: types.ContestPublicDetails;
currentUsername: string;
}): void {
let rankingChartOptions: Highcharts.Options | null = null;
const { mergedScoreboard, originalContestEvents } = mergeRankings({
scoreboard,
originalScoreboardEvents: scoreboardEvents,
navbarProblems: problems,
});
const rankingInfo = onRankingChanged({
scoreboard: mergedScoreboard,
currentUsername: currentUsername,
navbarProblems: problems,
});
const ranking = rankingInfo.ranking;
const users = rankingInfo.users;
const lastTimeUpdated = rankingInfo.lastTimeUpdated;
rankingStore.commit('updateRanking', ranking);
rankingStore.commit('updateMiniRankingUsers', users);
rankingStore.commit('updateLastTimeUpdated', lastTimeUpdated);
const startTimestamp = contest.start_time.getTime();
const finishTimestamp = Math.min(
contest.finish_time?.getTime() || Infinity,
Date.now(),
);
const { series, navigatorData } = onRankingEvents({
events: scoreboardEvents.concat(originalContestEvents),
currentRanking: rankingInfo.currentRanking,
startTimestamp,
finishTimestamp,
});
if (series.length) {
rankingChartOptions = createChart({
series,
navigatorData,
startTimestamp,
finishTimestamp,
maxPoints: rankingInfo.maxPoints,
});
rankingStore.commit('updateRankingChartOptions', rankingChartOptions);
}
} | the_stack |
import { bigIntToBitcoinVarInt, numberToBinUint32LE } from '../format/numbers';
import { decodeHdPublicKey, deriveHdPath } from '../key/hd-key';
import { bigIntToScriptNumber } from '../vm/instruction-sets/instruction-sets';
import { CompilerDefaults } from './compiler-defaults';
import {
attemptCompilerOperations,
compilerOperationAttemptBytecodeResolution,
compilerOperationHelperAddressIndex,
compilerOperationHelperDeriveHdPrivateNode,
compilerOperationHelperGenerateCoveredBytecode,
compilerOperationHelperUnknownEntity,
compilerOperationRequires,
} from './compiler-operation-helpers';
import { CompilerOperationResult } from './compiler-types';
import { AuthenticationTemplateHdKey } from './template-types';
export const compilerOperationAddressData = compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['bytecode'],
environmentProperties: [],
operation: (identifier, data) => {
const { bytecode } = data;
if (identifier in bytecode) {
return { bytecode: bytecode[identifier], status: 'success' };
}
return {
error: `Identifier "${identifier}" refers to an AddressData, but "${identifier}" was not provided in the CompilationData "bytecode".`,
recoverable: true,
status: 'error',
};
},
});
export const compilerOperationWalletData = compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['bytecode'],
environmentProperties: [],
operation: (identifier, data) => {
const { bytecode } = data;
if (identifier in bytecode) {
return { bytecode: bytecode[identifier], status: 'success' };
}
return {
error: `Identifier "${identifier}" refers to a WalletData, but "${identifier}" was not provided in the CompilationData "bytecode".`,
recoverable: true,
status: 'error',
};
},
});
export const compilerOperationCurrentBlockTime = compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['currentBlockTime'],
environmentProperties: [],
operation: (_, data) => {
return {
bytecode: numberToBinUint32LE(data.currentBlockTime),
status: 'success',
};
},
});
export const compilerOperationCurrentBlockHeight = compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['currentBlockHeight'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: bigIntToScriptNumber(BigInt(data.currentBlockHeight)),
status: 'success',
}),
});
export const compilerOperationSigningSerializationCorrespondingOutput = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) =>
data.transactionContext.correspondingOutput === undefined
? { bytecode: Uint8Array.of(), status: 'success' }
: {
bytecode: data.transactionContext.correspondingOutput,
status: 'success',
},
}
);
export const compilerOperationSigningSerializationCorrespondingOutputHash = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: ['sha256'],
operation: (_, data, environment) =>
data.transactionContext.correspondingOutput === undefined
? { bytecode: Uint8Array.of(), status: 'success' }
: {
bytecode: environment.sha256.hash(
environment.sha256.hash(
data.transactionContext.correspondingOutput
)
),
status: 'success',
},
}
);
const compilerOperationHelperSigningSerializationCoveredBytecode = (
returnLength: boolean
) =>
compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: ['sourceScriptIds', 'unlockingScripts'],
operation: (identifier, data, environment) => {
const { unlockingScripts, sourceScriptIds } = environment;
const result = compilerOperationHelperGenerateCoveredBytecode({
data,
environment,
identifier,
sourceScriptIds,
unlockingScripts,
});
if ('error' in result) {
return result;
}
return {
bytecode: returnLength
? bigIntToBitcoinVarInt(BigInt(result.length))
: result,
status: 'success',
};
},
});
export const compilerOperationSigningSerializationCoveredBytecode = compilerOperationHelperSigningSerializationCoveredBytecode(
false
);
export const compilerOperationSigningSerializationCoveredBytecodeLength = compilerOperationHelperSigningSerializationCoveredBytecode(
true
);
export const compilerOperationSigningSerializationLocktime = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: numberToBinUint32LE(data.transactionContext.locktime),
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationOutpointIndex = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: numberToBinUint32LE(data.transactionContext.outpointIndex),
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationOutpointTransactionHash = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: data.transactionContext.outpointTransactionHash,
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationOutputValue = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: data.transactionContext.outputValue,
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationSequenceNumber = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: numberToBinUint32LE(data.transactionContext.sequenceNumber),
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationTransactionOutpoints = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: data.transactionContext.transactionOutpoints,
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationTransactionOutpointsHash = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: ['sha256'],
operation: (_, data, environment) => ({
bytecode: environment.sha256.hash(
environment.sha256.hash(data.transactionContext.transactionOutpoints)
),
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationTransactionOutputs = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: data.transactionContext.transactionOutputs,
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationTransactionOutputsHash = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: ['sha256'],
operation: (_, data, environment) => ({
bytecode: environment.sha256.hash(
environment.sha256.hash(data.transactionContext.transactionOutputs)
),
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationTransactionSequenceNumbers = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: data.transactionContext.transactionSequenceNumbers,
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationTransactionSequenceNumbersHash = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: ['sha256'],
operation: (_, data, environment) => ({
bytecode: environment.sha256.hash(
environment.sha256.hash(
data.transactionContext.transactionSequenceNumbers
)
),
status: 'success',
}),
}
);
export const compilerOperationSigningSerializationVersion = compilerOperationRequires(
{
canBeSkipped: false,
dataProperties: ['transactionContext'],
environmentProperties: [],
operation: (_, data) => ({
bytecode: numberToBinUint32LE(data.transactionContext.version),
status: 'success',
}),
}
);
export const compilerOperationKeyPublicKeyCommon = attemptCompilerOperations(
[compilerOperationAttemptBytecodeResolution],
compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['keys'],
environmentProperties: ['secp256k1'],
operation: (identifier, data, environment) => {
const { keys } = data;
const { secp256k1 } = environment;
const { privateKeys } = keys;
const [variableId] = identifier.split('.');
if (
privateKeys !== undefined &&
(privateKeys[variableId] as Uint8Array | undefined) !== undefined
) {
return {
bytecode: secp256k1.derivePublicKeyCompressed(
privateKeys[variableId]
),
status: 'success',
};
}
return {
error: `Identifier "${identifier}" refers to a public key, but no public or private keys for "${variableId}" were provided in the compilation data.`,
recoverable: true,
status: 'error',
};
},
})
);
export const compilerOperationHdKeyPublicKeyCommon = attemptCompilerOperations(
[compilerOperationAttemptBytecodeResolution],
compilerOperationRequires({
canBeSkipped: false,
dataProperties: ['hdKeys'],
environmentProperties: [
'entityOwnership',
'ripemd160',
'secp256k1',
'sha256',
'sha512',
'variables',
],
operation:
// eslint-disable-next-line complexity
(identifier, data, environment): CompilerOperationResult => {
const { hdKeys } = data;
const { hdPrivateKeys, addressIndex, hdPublicKeys } = hdKeys;
const [variableId] = identifier.split('.');
const entityId = environment.entityOwnership[variableId] as
| string
| undefined;
if (entityId === undefined) {
return compilerOperationHelperUnknownEntity(identifier, variableId);
}
if (addressIndex === undefined) {
return compilerOperationHelperAddressIndex(identifier);
}
const entityHdPrivateKey =
hdPrivateKeys === undefined ? undefined : hdPrivateKeys[entityId];
/**
* Guaranteed to be an `HdKey` if this method is reached in the compiler.
*/
const hdKey = environment.variables[
variableId
] as AuthenticationTemplateHdKey;
if (entityHdPrivateKey !== undefined) {
const privateResult = compilerOperationHelperDeriveHdPrivateNode({
addressIndex,
entityHdPrivateKey,
entityId,
environment,
hdKey,
identifier,
});
if (privateResult.status === 'error') return privateResult;
return {
bytecode: environment.secp256k1.derivePublicKeyCompressed(
privateResult.bytecode
),
status: 'success',
};
}
const entityHdPublicKey =
hdPublicKeys === undefined ? undefined : hdPublicKeys[entityId];
if (entityHdPublicKey === undefined) {
return {
error: `Identifier "${identifier}" refers to an HdKey owned by "${entityId}", but an HD private key or HD public key for this entity was not provided in the compilation data.`,
recoverable: true,
status: 'error',
};
}
const addressOffset =
hdKey.addressOffset ?? CompilerDefaults.hdKeyAddressOffset;
const privateDerivationPath =
hdKey.privateDerivationPath ??
CompilerDefaults.hdKeyPrivateDerivationPath;
const publicDerivationPath =
hdKey.publicDerivationPath ?? privateDerivationPath.replace('m', 'M');
const validPublicPathWithIndex = /^M(?:\/(?:[0-9]+|i))*$/u;
if (!validPublicPathWithIndex.test(publicDerivationPath)) {
return {
error: `Could not generate ${identifier} – the path "${publicDerivationPath}" is not a valid "publicDerivationPath".`,
status: 'error',
};
}
const i = addressIndex + addressOffset;
const instancePath = publicDerivationPath.replace('i', i.toString());
const masterContents = decodeHdPublicKey(
environment,
entityHdPublicKey
);
if (typeof masterContents === 'string') {
return {
error: `Could not generate "${identifier}" – the HD public key provided for "${entityId}" could not be decoded: ${masterContents}`,
status: 'error',
};
}
const instanceNode = deriveHdPath(
environment,
masterContents.node,
instancePath
);
if (typeof instanceNode === 'string') {
return {
error: `Could not generate "${identifier}" – the path "${instancePath}" could not be derived for entity "${entityId}": ${instanceNode}`,
status: 'error',
};
}
return { bytecode: instanceNode.publicKey, status: 'success' };
},
})
);
/* eslint-disable camelcase, @typescript-eslint/naming-convention */
export const compilerOperationsCommon = {
addressData: compilerOperationAddressData,
currentBlockHeight: compilerOperationCurrentBlockHeight,
currentBlockTime: compilerOperationCurrentBlockTime,
hdKey: {
public_key: compilerOperationHdKeyPublicKeyCommon,
},
key: {
public_key: compilerOperationKeyPublicKeyCommon,
},
signingSerialization: {
corresponding_output: compilerOperationSigningSerializationCorrespondingOutput,
corresponding_output_hash: compilerOperationSigningSerializationCorrespondingOutputHash,
covered_bytecode: compilerOperationSigningSerializationCoveredBytecode,
covered_bytecode_length: compilerOperationSigningSerializationCoveredBytecodeLength,
locktime: compilerOperationSigningSerializationLocktime,
outpoint_index: compilerOperationSigningSerializationOutpointIndex,
outpoint_transaction_hash: compilerOperationSigningSerializationOutpointTransactionHash,
output_value: compilerOperationSigningSerializationOutputValue,
sequence_number: compilerOperationSigningSerializationSequenceNumber,
transaction_outpoints: compilerOperationSigningSerializationTransactionOutpoints,
transaction_outpoints_hash: compilerOperationSigningSerializationTransactionOutpointsHash,
transaction_outputs: compilerOperationSigningSerializationTransactionOutputs,
transaction_outputs_hash: compilerOperationSigningSerializationTransactionOutputsHash,
transaction_sequence_numbers: compilerOperationSigningSerializationTransactionSequenceNumbers,
transaction_sequence_numbers_hash: compilerOperationSigningSerializationTransactionSequenceNumbersHash,
version: compilerOperationSigningSerializationVersion,
},
walletData: compilerOperationWalletData,
};
/* eslint-enable camelcase, @typescript-eslint/naming-convention */ | the_stack |
import { ScriptEnv, scriptenv } from "./scriptenv"
import { rpc, sendMsg } from "./rpc"
import {
WorkerCreateRequestMsg, WorkerCreateResponseMsg,
WorkerMessageMsg, WorkerErrorMsg, WorkerCtrlMsg,
WorkerSetFrameMsg,
} from "../common/messages"
type ScripterWorkerFun = scriptenv.ScripterWorkerFun
type ScripterWorkerError = scriptenv.ScripterWorkerError
type ScripterCreateWorkerOptions = scriptenv.ScripterCreateWorkerOptions
type ScripterTransferable = scriptenv.ScripterTransferable
type ScripterWindowedWorker = scriptenv.ScripterWindowedWorker
interface ScripterWorker extends scriptenv.ScripterWindowedWorker {
_onmessage(msg :WorkerMessageMsg) :void
_onerror(err :ScripterWorkerError) :void
_onclose() :void
_cancel(reason :string) :void // sets error to reason and calls terminate
}
let workerIdGen = 0
// workerMap contains all workers
const workerMap = new Map<string,ScripterWorker>() // workerId => Worker
// called by plugin onmessage dispatch when a worker message is sent from the app
export function handleIncomingMessage(msg :any) {
let workerId = msg.workerId as string
let worker = workerMap.get(workerId)
if (!worker) {
// this happens naturally for close & terminate messages, as close & terminate
// are naturally racey.
dlog(`plugin/worker recv message for non-existing worker#${workerId}:`, msg)
return
}
switch (msg.type) {
case "worker-message":
worker._onmessage(msg as WorkerMessageMsg)
break
case "worker-error": {
let m = msg as WorkerErrorMsg
worker._onerror({
colno: m.error.colno,
error: m.error.error,
filename: m.error.filename,
lineno: m.error.lineno,
message: m.error.message,
})
break
}
case "worker-ctrl": {
let m = msg as WorkerCtrlMsg
if (m.signal == "close") {
// worker closed
worker._onclose()
break
}
console.error("plugin/worker got unexpected control message: " +
JSON.stringify(msg, null, 2))
break
}
default:
console.warn(`plugin/worker recv unexpected message`, msg)
}
}
class _WorkerError extends Error implements ScripterWorkerError {
constructor(init? :ScripterWorkerError) {
super()
if (init) {
for (let k in init) {
;(this as any)[k] = init[k]
}
}
this.name = "ScripterWorkerError"
}
}
const kWorkerId = Symbol("workerId")
// special props on data for implementing script-worker requests
// IMPORTANT: Keep in sync with worker-template.js
const requestIdProp = "__scripterRequestId"
const requestErrProp = "__scripterRequestError"
export function createCreateWorker(env :ScriptEnv, scriptId :string) {
let initialized = false
let scriptEnded = false
function init() {
if (initialized) { return }
initialized = true
env.scripter.addEndCallback(onScriptEnd)
}
function onScriptEnd() {
// when script ends, end all workers
// note: copy values as w.terminate might call workerMap.delete
scriptEnded = true
dlog(`createCreateWorker/onScriptEnd terminating ${workerMap.size} workers`)
for (let w of Array.from(workerMap.values())) {
dlog(`createCreateWorker/onScriptEnd terminate Worker#${w[kWorkerId]}`)
w._cancel("script stopped")
}
workerMap.clear()
}
return function createWorker(
arg0 :ScripterCreateWorkerOptions | undefined | string | ScripterWorkerFun,
arg1? :string | ScripterWorkerFun,
) :ScripterWorker {
if (scriptEnded) {
console.log(`ignoring createWorker call after script has been stopped`)
return Promise.reject(new Error("script stopped")) as any as ScripterWorker
}
init()
let script :string | ScripterWorkerFun = arg1 || (arg0 as string | ScripterWorkerFun)
let opt :ScripterCreateWorkerOptions = (
arg1 && arg0 ? (arg0 as ScripterCreateWorkerOptions) : {}
)
const workerId = scriptId + "." + (workerIdGen++).toString(36)
const eventOrigin = `scripter-worker:${workerId}`
let js = script.toString()
let sendq :{data:any,transfer?:ScripterTransferable[]}[] = []
let recvp :Promise<any>|null = null
let recvr = { resolve: (m:any)=>{}, reject: (reason?:any)=>{} }
let terminated = false
let closed = false
let lastError :ScripterWorkerError|null = null
let requestIdGen = 0
const requests = new Map<string,{ resolve:any, reject:any, timer:any }>()
function checkTerminated() {
if (terminated) {
throw new Error("worker terminated")
}
}
// create ScripterWorker object
let workerPromiseResolve :()=>void
let workerPromiseReject :(reason? :any)=>void
let w = new Promise<void>((resolve, reject) => {
workerPromiseResolve = resolve
workerPromiseReject = reject
}) as any as ScripterWorker
w[kWorkerId] = workerId
w.postMessage = (data :any, transfer?: ScripterTransferable[]) => {
checkTerminated()
sendq.push({ data, transfer })
}
w.send = (data :any, transfer?: ScripterTransferable[]) => {
w.postMessage(data, transfer)
}
w.recv = () :Promise<any> => {
checkTerminated()
if (!recvp) {
recvp = new Promise((resolve, reject) => ( recvr = { resolve, reject } ))
}
return recvp
}
w.request = (data :any, arg1?: number|ScripterTransferable[], arg2? :number) :Promise<any> => {
let transfer: undefined|ScripterTransferable[]
let timeout :number = 0
if (arg2 !== undefined) {
transfer = arg1 as undefined|ScripterTransferable[]
timeout = arg2
} else if (typeof arg1 == "number") {
timeout = arg1 as number
}
return new Promise<any>((resolve, reject) => {
const requestId = scriptId + "." + (requestIdGen++).toString(36)
w.postMessage({ [requestIdProp]: requestId, data }, transfer)
let timer :any = null
if (timeout && timeout > 0) {
timer = setTimeout(() => { reject(new Error("timeout")) }, timeout)
}
dlog(`script send worker request ${requestId}`)
requests.set(requestId, { resolve, reject, timer })
})
}
w.terminate = () => {
dlog("worker/terminate req")
w._onclose()
terminated = true
if (workerMap.delete(workerId)) {
dlog("worker/terminate exec")
dlog(`[worker] terminating worker#${workerId}`)
sendMsg<WorkerCtrlMsg>({
type: "worker-ctrl",
signal: "terminate",
workerId,
})
}
return w
}
// ScripterWindowedWorker methods
if (opt.iframe && typeof opt.iframe == "object" && opt.iframe.visible) {
w.setFrame = (x :number, y :number, width :number, height :number) :void => {
sendMsg<WorkerSetFrameMsg>({ type:"worker-setFrame", workerId, x, y, width, height })
}
w.close = w.terminate
}
// internal methods, exposed for handleIncomingMessage
w._cancel = (reason :string) => {
if (!lastError) {
lastError = new _WorkerError({ message: reason })
}
w.terminate()
}
w._onmessage = (msg :WorkerMessageMsg) => {
if (terminated) {
return
}
if (msg.evtype == "message") {
const data = msg.data
if (data !== null && typeof data == "object") {
const requestId = data[requestIdProp]
if (requestId !== undefined) {
dlog("script got a response from a w.request() call", data, requestId)
const r = requests.get(requestId) // { resolve, reject, timer }
if (r) {
clearTimeout(r.timer)
const err = data[requestErrProp]
if (err) {
r.reject(new Error(String(err)))
} else {
r.resolve(data.data)
}
}
return
}
}
if (w.onmessage) {
;(w as any).onmessage({
type: "message",
data: data,
origin: eventOrigin,
})
}
if (recvp) {
recvp = null
recvr.resolve(msg.data)
}
} else {
if (w.onmessageerror) {
;(w as any).onmessageerror({
type: "messageerror",
data: msg.data,
origin: eventOrigin,
})
}
if (recvp) {
recvp = null
recvr.reject(msg.data)
}
}
}
w._onerror = (err :ScripterWorkerError) => {
lastError = new _WorkerError(err)
if (w.onerror) {
w.onerror(lastError)
}
}
w._onclose = () => {
if (closed) {
dlog(`Worker#${workerId} onclose -- already closed`)
return
}
dlog(`Worker#${workerId} onclose`)
closed = true
terminated = true
if (recvp) {
// reject waiting recv() calls
recvp = null
recvr.reject(lastError || new Error("worker closed"))
}
if (w.onclose) {
w.onclose()
}
if (lastError) {
workerPromiseReject(lastError)
} else {
workerPromiseResolve()
}
}
// register new worker
workerMap.set(workerId, w)
dlog(`script requesting create Worker#${workerId}`)
// sed request to UI
rpc<WorkerCreateRequestMsg, WorkerCreateResponseMsg>(
"worker-create-req", "worker-create-res",
{
workerId,
js,
iframe: opt.iframe,
}).then(res => {
dlog(`Worker#${workerId} created`, res)
if (terminated) {
// worker terminated already
dlog(`[worker] note: worker#${workerId} terminated before it started`)
return
}
if (w.onerror && res.error) {
w.onerror(new _WorkerError(res.error))
w.terminate()
return
}
w.postMessage = (data :any, transfer?: ScripterTransferable[]) => {
checkTerminated()
sendMsg<WorkerMessageMsg>({
type: "worker-message",
evtype: "message",
workerId,
data,
// Note: Figma API does not (yet) support transfer
})
}
// send buffered messages
for (let ent of sendq) {
w.postMessage(ent.data, ent.transfer)
}
sendq = []
}).catch(err => {
console.error(`createWorker: ${err.stack||err}`)
if (w.onerror) {
;(w as any).onerror(new _WorkerError(err))
}
})
return w
}
} | the_stack |
** Copyright (c) 2015 Blackmagic Design
**
** Permission is hereby granted, free of charge, to any person or organization
** obtaining a copy of the software and accompanying documentation covered by
** this license (the "Software") to use, reproduce, display, distribute,
** execute, and transmit the Software, and to prepare derivative works of the
** Software, and to permit third-parties to whom the Software is furnished to
** do so, all subject to the following:
**
** The copyright notices in the Software and this entire statement, including
** the above license grant, this restriction and the following disclaimer,
** must be included in all copies of the Software, in whole or in part, and
** all derivative works of the Software, unless such copies or derivative
** works are solely in the form of machine-executable object code generated by
** a source language processor.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
** DEALINGS IN THE SOFTWARE.
** -LICENSE-END-
*/
/* Enum BMDDisplayMode - Video display modes */
/* SD Modes */
export const bmdModeNTSC : number
export const bmdModeNTSC2398 : number // 3:2 pulldown
export const bmdModePAL : number
export const bmdModeNTSCp : number
export const bmdModePALp : number
/* HD 1080 Modes */
export const bmdModeHD1080p2398 : number
export const bmdModeHD1080p24 : number
export const bmdModeHD1080p25 : number
export const bmdModeHD1080p2997 : number
export const bmdModeHD1080p30 : number
export const bmdModeHD1080i50 : number
export const bmdModeHD1080i5994 : number
export const bmdModeHD1080i6000 : number // N.B. This _really_ is 60.00 Hz.
export const bmdModeHD1080p50 : number
export const bmdModeHD1080p5994 : number
export const bmdModeHD1080p6000 : number // N.B. This _really_ is 60.00 Hz.
/* HD 720 Modes */
export const bmdModeHD720p50 : number
export const bmdModeHD720p5994 : number
export const bmdModeHD720p60 : number
/* 2k Modes */
export const bmdMode2k2398 : number
export const bmdMode2k24 : number
export const bmdMode2k25 : number
/* 2k DCI modes */
export const bmdMode2kDCI2398 : number
export const bmdMode2kDCI24 : number
export const bmdMode2kDCI25 : number
export const bmdMode2kDCI2997 : number
export const bmdMode2kDCI30 : number
export const bmdMode2kDCI50 : number
export const bmdMode2kDCI5994 : number
export const bmdMode2kDCI60 : number
/* 4k UHD Modes */
export const bmdMode4K2160p2398 : number
export const bmdMode4K2160p24 : number
export const bmdMode4K2160p25 : number
export const bmdMode4K2160p2997 : number
export const bmdMode4K2160p30 : number
export const bmdMode4K2160p50 : number
export const bmdMode4K2160p5994 : number
export const bmdMode4K2160p60 : number
/* 4k DCI modes */
export const bmdMode4kDCI2398 : number
export const bmdMode4kDCI24 : number
export const bmdMode4kDCI25 : number
export const bmdMode4kDCI2997 : number
export const bmdMode4kDCI30 : number
export const bmdMode4kDCI50 : number
export const bmdMode4kDCI5994 : number
export const bmdMode4kDCI60 : number
/* 8K UHD Modes */
export const bmdMode8K4320p2398 : number
export const bmdMode8K4320p24 : number
export const bmdMode8K4320p25 : number
export const bmdMode8K4320p2997 : number
export const bmdMode8K4320p30 : number
export const bmdMode8K4320p50 : number
export const bmdMode8K4320p5994 : number
export const bmdMode8K4320p60 : number
/* 8K DCI Modes */
export const bmdMode8kDCI2398 : number
export const bmdMode8kDCI24 : number
export const bmdMode8kDCI25 : number
export const bmdMode8kDCI2997 : number
export const bmdMode8kDCI30 : number
export const bmdMode8kDCI50 : number
export const bmdMode8kDCI5994 : number
export const bmdMode8kDCI60 : number
/* Special Modes */
export const bmdModeUnknown : number
/* Enum BMDFieldDominance - Video field dominance */
export const bmdUnknownFieldDominance : number
export const bmdLowerFieldFirst : number
export const bmdUpperFieldFirst : number
export const bmdProgressiveFrame : number
export const bmdProgressiveSegmentedFrame : number
/* Enum BMDPixelFormat - Video pixel formats supported for output/input */
export const bmdFormat8BitYUV : number
export const bmdFormat10BitYUV : number
export const bmdFormat8BitARGB : number
export const bmdFormat8BitBGRA : number
// Big-endian RGB 10-bit per component with SMPTE video levels (64-960). Packed as 2:10:10:10
export const bmdFormat10BitRGB : number
// Big-endian RGB 12-bit per component with full range (0-4095). Packed as 12-bit per component
export const bmdFormat12BitRGB : number
// Little-endian RGB 12-bit per component with full range (0-4095). Packed as 12-bit per component
export const bmdFormat12BitRGBLE : number
// Little-endian 10-bit RGB with SMPTE video levels (64-940)
export const bmdFormat10BitRGBXLE : number
// Big-endian 10-bit RGB with SMPTE video levels (64-940)
export const bmdFormat10BitRGBX : number
/* Enum BMDDisplayModeFlags - Flags to describe the characteristics of an IDeckLinkDisplayMode. */
export const bmdDisplayModeSupports3D : number
export const bmdDisplayModeColorspaceRec601 : number
export const bmdDisplayModeColorspaceRec709 : number
export const bmdDisplayModeColorspaceRec2020 : number
// Audio parameters
export const bmdAudioSampleRate48kHz : number
export const bmdAudioSampleType16bitInteger : number
export const bmdAudioSampleType32bitInteger : number
// BMDVideo3DPackingFormat
export const bmdVideo3DPackingSidebySideHalf : number // Frames are packed side-by-side as a single stream.
export const bmdVideo3DPackingLinebyLine : number // The two eye frames are packed on alternating lines of the source frame.
export const bmdVideo3DPackingTopAndBottom : number // The two eye frames are packed into the top and bottom half of the source frame.
export const bmdVideo3DPackingFramePacking : number // Frame packing is a standard HDMI 1.4a 3D mode (Top / Bottom full).
export const bmdVideo3DPackingLeftOnly : number // Only the left eye frame is displayed.
export const bmdVideo3DPackingRightOnly : number // Only the right eye frame is displayed.
// BMDDeckLinkCapturePassthroughMode
export const bmdDeckLinkCapturePassthroughModeDisabled : number // Electronic connection - input to output
export const bmdDeckLinkCapturePassthroughModeDirect : number // Uses playout mechanism for clear switch
export const bmdDeckLinkCapturePassthroughModeCleanSwitch : number // No input to output link - use idle mode
// BMDVideoOutputConversionMode
export const bmdNoVideoOutputConversion : number // No video output conversion
export const bmdVideoOutputLetterboxDownconversion : number // Down-converted letterbox SD output
export const bmdVideoOutputAnamorphicDownconversion : number // Down-converted anamorphic SD output
export const bmdVideoOutputHD720toHD1080Conversion : number // HD720 to HD1080 conversion output
export const bmdVideoOutputHardwareLetterboxDownconversion : number // Simultaneous HD and down-converted letterbox SD
export const bmdVideoOutputHardwareAnamorphicDownconversion : number // Simultaneous HD and down-converted anamorphic SD
export const bmdVideoOutputHardwareCenterCutDownconversion : number // Simultaneous HD and center cut SD
export const bmdVideoOutputHardware720p1080pCrossconversion : number // Simultaneous 720p and 1080p cross-conversion
export const bmdVideoOutputHardwareAnamorphic720pUpconversion : number // Simultaneous SD and up-converted anamorphic 720p
export const bmdVideoOutputHardwareAnamorphic1080iUpconversion : number // Simultaneous SD and up-converted anamorphic 1080i
export const bmdVideoOutputHardwareAnamorphic149To720pUpconversion : number // Simultaneous SD and up-converted anamorphic widescreen aspect ratio 14:9 to 720p.
export const bmdVideoOutputHardwareAnamorphic149To1080iUpconversion : number // Simultaneous SD and up-converted anamorphic widescreen aspect ratio 14:9 to 1080i.
export const bmdVideoOutputHardwarePillarbox720pUpconversion : number // Simultaneous SD and up-converted pillarbox 720p
export const bmdVideoOutputHardwarePillarbox1080iUpconversion : number // Simultaneous SD and up-converted pillarbox 1080i
// BMDVideoInputConversionMode
export const bmdNoVideoInputConversion : number // No video input conversion
export const bmdVideoInputLetterboxDownconversionFromHD1080 : number // HD1080 to SD video input down conversion
export const bmdVideoInputAnamorphicDownconversionFromHD1080 : number // Anamorphic from HD1080 to SD video input down conversion
export const bmdVideoInputLetterboxDownconversionFromHD720 : number // Letter box from HD720 to SD video input down conversion
export const bmdVideoInputAnamorphicDownconversionFromHD720 : number // Anamorphic from HD720 to SD video input down conversion
export const bmdVideoInputLetterboxUpconversion : number // Letterbox video input up conversion
export const bmdVideoInputAnamorphicUpconversion : number // Anamorphic video input up conversion
// BMDAnalogVideoFlags
export const bmdAnalogVideoFlagCompositeSetup75 : number // If set, composite black level is 7.5 IRE (USA) rather than 0.0 IRE (Japan)
export const bmdAnalogVideoFlagComponentBetacamLevels : number // IF set, component video color different channels boosted 4/3 for Betacam
// BMDVideoConnection
export const bmdVideoConnectionSDI : number
export const bmdVideoConnectionHDMI : number
export const bmdVideoConnectionOpticalSDI : number
export const bmdVideoConnectionComponent : number
export const bmdVideoConnectionComposite : number
export const bmdVideoConnectionSVideo : number
// BMDAudioConnectionAnalog
export const bmdAudioConnectionEmbedded : number
export const bmdAudioConnectionAESEBU : number
export const bmdAudioConnectionAnalog : number
export const bmdAudioConnectionAnalogXLR : number
export const bmdAudioConnectionAnalogRCA : number
export const bmdAudioConnectionMicrophone : number
export const bmdAudioConnectionHeadphones : number
// BMDLinkConfiguration
export const bmdLinkConfigurationSingleLink : number // A single video stream uses one connector
export const bmdLinkConfigurationDualLink : number // A single video stream uses two connectors
export const bmdLinkConfigurationQuadLink : number // A single video stream uses four connectors
// BMDIdleVideoOutputOperation
export const bmdIdleVideoOutputBlack : number // When not playing video, the device will output black frames
export const bmdIdleVideoOutputLastFrame : number // When not playing video, the device will output the last frame played
// BMDDeckControlConnection
export const bmdDeckControlConnectionRS422Remote1 : number // First RS422 deck control connection
export const bmdDeckControlConnectionRS422Remote2 : number // Second RS422 deck control connection
// BMDDuplexMode
export const bmdDuplexModeFull : number // Configure this sub-device to use two connectors (full-duplex).
export const bmdDuplexModeHalf : number // Configure this sub-device to use a single connector (half-duplex).
// Convert to and from Black Magic codes.
export function intToBMCode(i: number) : string
export function bmCodeToInt(s: string) : number
// Get parameters from modes and formats
export function modeWidth(m: number) : number
export function modeHeight(m: number) : number
/** Returns the duration of a frame as fraction of a second as an array: [<numerator>, <denominator>] */
export function modeGrainDuration(m: number) : number[]
export function modeInterlace(m: number) : boolean
export function formatDepth(f: number) : number
export function formatFourCC(f: number) : number
export function fourCCFormat(fcc: string) : number
export function formatSampling(f: number) : string
export function formatColorimetry(f: number) : string
// access details about the currently connected devices
export function deckLinkVersion() : string
export function getFirstDevice() : string
export function getDeviceInfo() : { [key: string]: unknown }
export type ConfigParams = { [key: string]: unknown }
export function getDeviceConfig(i: number) : ConfigParams
export function setDeviceConfig(config: ConfigParams) : ConfigParams
export type Dominance = 'progressiveFrame' | 'upperFieldFirst' | 'lowerFieldFirst' | 'unknown'
export interface CaptureFrame {
type: 'frame',
video: {
type: 'videoFrame',
width: number,
height: number,
rowBytes: number,
frameTime: number,
frameDuration: number,
data: Buffer,
flipVertical?: boolean
hasNoInputSource?: boolean,
capturedAsPsF?: boolean,
timecode: string,
userbits: number,
hardwareRefFrameTime: number,
hardwareRefFrameDuration: number
}
audio: {
type: 'audioPacket',
packetTime: number,
sampleFrameCount: number,
data: Buffer
}
}
export interface CaptureChannel {
type: 'capture'
displayModeName: string
width: number
height: number
fieldDominance: Dominance
frameRate: number[]
pixelFormat: string
audioEnabled: boolean
/** Wait for the next frames-worth of data */
frame(): Promise<CaptureFrame>
/** Stop the resolution of outstanding frame promises and skip frames on the input */
pause(): undefined
/** Stop the capture and release resources */
stop(): undefined
}
export function capture(params: {
/** Index relative to the 'macadam.getDeviceInfo()' array */
deviceIndex: number, // Index relative to the 'macadam.getDeviceInfo()' array
/** A bmdMode* value to describe the video standard */
displayMode?: number,
/** A bmdFormat* value to describe the video format */
pixelFormat?: number,
/** Enables audio - omit if audio is not required */
channels?: number, // enables audio - omit if audio is not required
/** A bmdAudioSampleRate* value to describe the audio sample rate */
sampleRate?: number,
/** A bmdAudioSampleType* value to describe the audio sample type */
sampleType?: number
}): CaptureChannel
export type PlayoutResult = { [key: string]: unknown }
export interface PlaybackChannel {
type: 'playback'
displayModeName: string
width: number
height: number
rowBytes: number
bufferSize: number
fieldDominance: Dominance
frameRate: number[]
pixelFormat: string
audioEnabled: boolean
rejectTimeout: number
enableKeying: boolean
startTimecode: string | undefined
/**
* For synchronous playback, frame data is sent to the card immediately for display
* at the next possible opportunity using the `displayFrame` method.
* It is up to the user of the synchronous API to make sure that frame data is
* replaced at a suitable frequency to ensure smooth playback.
* The `playback.hardwareTime()` method can be used to help with this.
* @param video A Node.js Buffer containing video data
* @param audio Optional - a Node.js Buffer containing audio data
*/
displayFrame(video: Buffer, audio?: Buffer): Promise<void>
/**
* To playback data using the scheduler, you need to place the frames onto a virtual timeline
* and then start the scheduler's clock.
*/
schedule(params: {
/** Video frame data. Decklink SDK docs have byte packing */
video: Buffer,
/** Relative to `frameRate` in playback object. Hint: Use 1001 for fractional framerates like 59.94 */
time: number,
/** Frames-worth of interleaved audio data */
audio?: Buffer,
/** Optional - otherwise based on buffer length */
sampleFrameCount?: number
}): undefined
/**
* Start the scheduler's clock. You must keep the queue of frames to be played ahead
* of the current playback position by at least a couple of frames.
* The best way to do this is to create a promise that waits for a specific frame to be
* played and use the promise resolution as a trigger to show the next one.
*/
start(params?: {
/**
* Time to start scheduled playback from, measured in units of playback `frameRate`.
* Defaults to `0`.
*/
startTime?: number,
/**
* Relative playback speed. Allows slower or reverse play.
* Defaults to `1.0` for real time forward playback.
*/
playbackSpeed?: number
}): undefined
/** Once playback if finished, call `playback.stop()` to release the associated resources. */
stop(): undefined
/**
* Regulate playback based on played time - latency depends on hw.
* @param time Measured in units of `frameRate` in playback object
* @returns a promise that resolves to an object with details of playout
*/
played(time: number): Promise<PlayoutResult>
/** Get the status of the playback reference */
referenceStatus(): 'ReferenceNotSupportedByHardware' | 'ReferenceLocked' | 'ReferenceNotLocked'
/**
* How many ticks have elapsed from the start time until now.
* In units of the `frameRate` defined for the playback
*/
scheduledTime(): { type: 'scheduledStreamTime', streamTime: number, playbackSpeed: number }
/** Details of the current hardware reference clock */
hardwareTime(): {
type: 'hardwareRefClock',
timeScale: number,
/** Relative value with no specific reference to an external clock but that can be compared between values */
hardwareTime: number,
/** Number of ticks relative to the timescale since the last frame was displayed */
timeInFrame: number,
ticksPerFrame: number
}
/** Number of frames currently buffered for playback */
bufferedFrames(): number
/**
* Number of audio frames (e.g. 1920 _audio frames_ per video frame at 1080i50)
* currently buffered for playback
*/
bufferedAudioFrames(): number
/** Ramp up the key level to `255` over a given number of frames */
rampUp(frameCount: number): undefined
/** Ramp down the key level to `0` over a given number of frames */
rampDown(frameCount: number): undefined
/** Set the overall key level */
setLevel(level: number): undefined
/** Sets a new timecode value based on the given string to be used. Used from the next frame onwards */
setTimecode(tc: string): string
/** Gets the current timecode value - the one to be used for the next frame to be output */
getTimecode(): string
/** Sets the timecode user bits field from a 32-bit integer. These become the user bits to be sent with the next frame */
setTimecodeUserbits(ub: number): undefined
/** Gets the current timecode user bits represented as a 32-bit integer. These are the user bits to be sent with the next frame */
getTimecodeUserbits(): number
}
/** Create a playback channel on a selected device index */
export function playback(params: {
/** Index relative to the 'macadam.getDeviceInfo()' array */
deviceIndex: number,
/** A bmdMode* value to describe the video standard */
displayMode?: number,
/** A bmdFormat* value to describe the video format */
pixelFormat?: number,
/** Enables audio - omit if audio is not required */
channels?: number,
/** A bmdAudioSampleRate* value to describe the audio sample rate */
sampleRate?: number,
/** A bmdAudioSampleType* value to describe the audio sample type */
sampleType?: number,
/** Scheduled playback timeout */
rejectTimeout?: number,
/** Only 8-bit ARGB and BGRA are supported */
enableKeying?: boolean,
/** Default is false for internal keying */
isExternal?: boolean,
/**
* Range between `0` (fully translucent) and `255` (opaque) and a default value of `255`.
* The alpha level in the image key is reduced according to overall level set for the keyer.
*/
level?: number,
/** Leave unset or set to undefined for no timecode */
startTimecode?: string
}): PlaybackChannel; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.