text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { format } from 'date-fns';
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { ReqRes, Collection } from '../../../types';
// ********************************
// * The Redux store is setup in modern Redux Toolkit style
// * https://redux-toolkit.js.org/
// * TODO: should State be in type file?
// ********************************
interface State {
currentTab: string,
reqResArray: ReqRes[],
scheduledReqResArray: ReqRes[],
history: Collection[],
collections: Collection[],
warningMessage: Record<string, unknown>,
newRequestsOpenAPI: {
openapiMetadata: {
info: Record<string, unknown>,
tags: [],
serverUrls: [],
},
openapiReqArray: [],
},
newRequestFields: {
protocol: string,
restUrl: string,
wsUrl: string,
gqlUrl: string,
grpcUrl: string,
webrtcUrl: string,
url: string,
method: string,
graphQL: boolean,
gRPC: boolean,
ws: boolean,
openapi: boolean,
webrtc: boolean,
webhook: boolean,
network: string,
testContent: string,
testResults: [],
openapiReqObj: Record<string, unknown>,
},
newRequestHeaders: {
headersArr: [],
count: number,
},
newRequestStreams: {
streamsArr: [],
count: number,
streamContent: [],
selectedPackage: null,
selectedRequest: null,
selectedService: null,
selectedServiceObj: null,
selectedStreamingType: null,
initialQuery: null,
queryArr: null,
protoPath: null,
services: null,
protoContent: string,
},
newRequestCookies: {
cookiesArr: [],
count: number,
},
newRequestBody: {
bodyContent: string,
bodyVariables: string,
bodyType: string,
rawType: string,
JSONFormatted: boolean,
bodyIsNew: boolean,
},
newRequestSSE: {
isSSE: boolean,
},
newRequestOpenAPIObject: {
request: {
id: number,
enabled: boolean,
reqTags: [],
reqServers: [],
summary: string,
description: string,
operationId: string,
method: string,
endpoint: string,
headers: Record<string, unknown>,
parameters: [],
body: Record<string, unknown>,
urls: [],
},
},
introspectionData: { schemaSDL: null, clientSchema: null },
dataPoints: Record<string, unknown>,
currentResponse: {
request: {
network: string,
},
response: {
source: string,
},
},
};
const initialState: State = {
currentTab: 'First Tab',
reqResArray: [],
scheduledReqResArray: [],
history: [],
collections: [],
warningMessage: {},
newRequestsOpenAPI: {
openapiMetadata: {
info: {},
tags: [],
serverUrls: [],
},
openapiReqArray: [],
},
newRequestFields: {
protocol: '',
restUrl: 'http://',
wsUrl: 'ws://',
gqlUrl: 'https://',
grpcUrl: '',
webrtcUrl: '',
url: 'http://',
method: 'GET',
graphQL: false,
gRPC: false,
ws: false,
openapi: false,
webrtc: false,
webhook: false,
network: 'rest',
testContent: '',
testResults: [],
openapiReqObj: {},
},
newRequestHeaders: {
headersArr: [],
count: 0,
},
newRequestStreams: {
streamsArr: [],
count: 0,
streamContent: [],
selectedPackage: null,
selectedRequest: null,
selectedService: null,
selectedServiceObj: null,
selectedStreamingType: null,
initialQuery: null,
queryArr: null,
protoPath: null,
services: null,
protoContent: '',
},
newRequestCookies: {
cookiesArr: [],
count: 0,
},
newRequestBody: {
bodyContent: '',
bodyVariables: '',
bodyType: 'raw',
rawType: 'text/plain',
JSONFormatted: true,
bodyIsNew: false,
},
newRequestSSE: {
isSSE: false,
},
newRequestOpenAPIObject: {
request: {
id: 0,
enabled: true,
reqTags: [],
reqServers: [],
summary: '',
description: '',
operationId: '',
method: '',
endpoint: '',
headers: {},
parameters: [],
body: {},
urls: [],
},
},
introspectionData: { schemaSDL: null, clientSchema: null },
dataPoints: {},
currentResponse: {
request: {
network: '',
},
response: {
source: ''
},
},
};
const businessSlice = createSlice({
name: 'default',
initialState,
reducers: {
getHistory(state, action: PayloadAction<[]>) {
state.history = action.payload;
},
deleteFromHistory(state, action: PayloadAction<unknown>) {
const deleteId = action.payload.id;
const deleteDate = format(action.payload.createdAt, 'MM/dd/yyyy');
state.history.forEach((obj, i) => {
if (obj.date === deleteDate)
obj.history = obj.history.filter((hist) => hist.id !== deleteId);
if (obj.history.length === 0) {
state.history.splice(i, 1);
}
});
},
clearHistory(state) {
state.history = [];
},
getCollections(state, action: PayloadAction<Collection[]>) {
state.collections = action.payload;
},
deleteFromCollection(state, action: PayloadAction<Collection>) {
const deleteId = action.payload.id;
state.collections.forEach((obj, i) => {
if (obj.id === deleteId) {
state.collections.splice(i, 1);
}
});
},
resetComposerFields(state) {
state.newRequestHeaders = {headersArr: [], count: 0},
state.newRequestCookies = {cookiesArr: [], count: 0},
// should this clear every field or just protocol?
state.newRequestFields= {...state.newRequestFields, protocol: ''},
state.newRequestSSE = {isSSE: false},
state.warningMessage = {}
state.newRequestBody = {
bodyIsNew: state.newRequestBody.bodyIsNew, // why is this state saved?
bodyContent: '',
bodyVariables: '',
bodyType: 'raw',
rawType: 'text/plain',
JSONFormatted: true,
}
},
collectionToReqRes(state, action: PayloadAction<ReqRes[]>) {
state.reqResArray = action.payload;
},
collectionAdd(state, action: PayloadAction<Collection>) {
state.collections.push(action.payload);
},
collectionUpdate(state, action: PayloadAction<Collection>) {
const collectionName = action.payload.name;
state.collections.forEach((obj, i) => {
if (obj.name === collectionName) {
state.collections[i] = action.payload;
}
})
},
reqResClear(state) {
state.reqResArray = [],
state.currentResponse = {request: {network: ''}}
},
reqResAdd(state, action: PayloadAction<ReqRes>) {
state.reqResArray.push(action.payload);
const addDate = format(action.payload.createdAt, 'MM/dd/yyyy');
let updated = false;
state.history.forEach((obj) => {
if (obj.date === addDate) {
obj.history.unshift(action.payload);
updated = true;
}
});
// if there is not history at added date, create new history with new query
if (!updated) {
state.history.unshift({
date: addDate,
history: [action.payload],
});
}
},
reqResDelete(state, action: PayloadAction<ReqRes>) {
const deleteId = action.payload.id;
state.reqResArray = state.reqResArray.filter(
(reqRes) => reqRes.id !== deleteId
);
},
setChecksAndMinis(state, action: PayloadAction<ReqRes[]>) {
state.reqResArray = action.payload;
},
reqResUpdate(state, action: PayloadAction<ReqRes>) {
for (let i = 0; i < state.reqResArray.length; i++) {
if (state.reqResArray[i].id === action.payload.id) {
state.reqResArray[i] = {
...action.payload,
checked: state.reqResArray[i].checked,
minimized: state.reqResArray[i].minimized,
}
break
}
}
},
scheduledReqResUpdate(state, action: PayloadAction<ReqRes>) {
state.scheduledReqResArray.push(action.payload);
},
scheduledReqResDelete(state) {
state.scheduledReqResArray = [];
},
updateGraph(state, action: PayloadAction<ReqRes>) {
const { id } = action.payload; // latest reqRes object
// dataPoints to be used by graph
const data = JSON.parse(JSON.stringify(state.dataPoints));
data.current = id; // more than 8 points and data will shift down an index
if (!data[id]) {
data[id] = [];
} else if (data[id].length > 49) {
data[id] = data[id].slice(1);
}
// check if new object is a closed request with timeSent and timeReceived
if (!data[id].some((elem) => elem.timeSent === action.payload.timeSent)) {
// if a color hasn't been added to this specific request id, add a new one
const color = !data[id][0]?.color
? `${Math.random() * 256}, ${Math.random() * 256}, ${
Math.random() * 256
}`
: data[id][0].color;
// add dataPoint to array connected to its id -and return to state
data[id].push({
reqRes: action.payload,
url: action.payload.url,
timeSent: action.payload.timeSent,
timeReceived: action.payload.timeReceived,
createdAt: action.payload.createdAt,
color,
});
}
state.dataPoints = data
},
clearGraph(state, action: PayloadAction<number>) {
state.dataPoints[action.payload] = [];
},
clearAllGraph(state, action: PayloadAction<Collection>) {
state.dataPoints = {};
},
setComposerWarningMessage(state, action: PayloadAction<Record<string, string>>) {
state.warningMessage = action.payload;
},
setNewRequestFields(state, action: PayloadAction<Record<string, unknown>>) {
state.newRequestFields = action.payload;
},
setNewRequestHeaders(state, action: PayloadAction<Record<string, [] | number>>) {
state.newRequestHeaders = action.payload;
},
setNewRequestStreams(state, action: PayloadAction<Record<string, [] | number | string | null>>) {
state.newRequestStreams = action.payload;
},
setNewRequestBody(state, action: PayloadAction<Record<string, string | boolean>>) {
state.newRequestBody = action.payload;
},
setNewRequestCookies(state, action: PayloadAction<Record<string, [] | number>>) {
state.newRequestCookies = action.payload
},
setNewTestContent(state, action: PayloadAction<string>) {
state.newRequestFields.testContent =action.payload;
},
setNewRequestSSE(state, action: PayloadAction<boolean>) {
state.newRequestSSE = { isSSE: action.payload }
},
setIntrospectionData(state, action: PayloadAction<Record<string, unknown>>) {
state.introspectionData = action.payload;
},
saveCurrentResponseData(state, action: PayloadAction<Record<string, unknown>>) {
state.currentResponse = action.payload;
},
setNewRequestsOpenAPI(state, action: PayloadAction<Record<string, unknown>>) {
state.newRequestsOpenAPI = action.payload
},
// TODO: OpenAPI is not implemented, let's delete yes?
// setOpenAPIServersGlobal(state, action: PayloadAction<[]>) {
// const openapiMetadata = { ...state.openapiMetadata };
// openapiMetadata.serverUrls = [...state.openapiMetadata.serverUrls].filter(
// (_, i) => action.payload.includes(i)
// );
// return {
// ...state,
// newRequestsOpenAPI: openapiMetadata,
// };
// },
// setOpenAPIServers(state, action: PayloadAction<[]>) {
// const { id, serverIds } = action.payload;
// const request = [...state.openapiReqArray]
// .filter(({ request }) => request.id === id)
// .pop();
// request.reqServers = [...state.openapiMetadata.serverUrls].filter(
// (_, i) => serverIds.includes(i)
// );
// const openapiReqArray = [...state.openapiReqArray].push({ request });
// return {
// ...state,
// newRequestsOpenAPI: openapiReqArray,
// };
// },
// setOpenAPIParameter(state, action: PayloadAction<Record<string, unknown>>) {
// const { id, location, name, value } = action.payload;
// const request = [...state.openapiReqArray]
// .filter(({ request }) => request.id === id)
// .pop();
// const urls = [...request.reqServers].map(
// (url) => (url += request.endpoint)
// );
// switch (location) {
// case 'path': {
// urls.map((url) => url.replace(`{${name}}`, value));
// request.urls = urls;
// const openapiReqArray = [...state.openapiReqArray].push({ request });
// return {
// ...state,
// newRequestsOpenAPI: openapiReqArray,
// };
// }
// case 'query': {
// urls.map((url) => {
// if (url.slice(-1) !== '?') url += '?';
// url += `${name}=${value}&`;
// });
// request.urls = urls;
// const openapiReqArray = [...state.openapiReqArray].push({ request });
// return {
// ...state,
// newRequestsOpenAPI: openapiReqArray,
// };
// }
// case 'header': {
// if (['Content-Type', 'Authorization', 'Accepts'].includes(key)) break;
// request.headers.push({ name: value });
// const openapiReqArray = [...state.openapiReqArray].push({ request });
// return {
// ...state,
// newRequestsOpenAPI: openapiReqArray,
// };
// }
// case 'cookie': {
// request.cookies = value;
// const openapiReqArray: [Record<string, unknown>] = [...state.openapiReqArray].push({ request });
// return {
// ...state,
// newRequestsOpenAPI: openapiReqArray,
// };
// }
// default: {
// return state;
// }
// }
// },
// setOpenAPIRequestBody(state, action: PayloadAction<Record<string, unknown>>) {
// const { id, mediaType, requestBody } = action.payload;
// // @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
// const request: Record<string, unknown> = [...state.openapiReqArray]
// .filter(({ request }) => request.id === id)
// .pop();
// const { method } = request;
// if (
// !['get', 'delete', 'head'].includes(method) &&
// requestBody !== undefined
// ) {
// request.body = requestBody;
// request.rawType = mediaType;
// }
// // @ts-expect-error ts-migrate(2339) FIXME: Property 'openapiReqArray' does not exist on type ... Remove this comment to see the full error message
// const openapiReqArray = [...state.openapiReqArray].push({ request });
// return {
// ...state,
// newRequestsOpenAPI: openapiReqArray,
// };
// }
}
})
const { actions, reducer } = businessSlice
export const {
getHistory,
deleteFromHistory,
clearHistory,
getCollections,
deleteFromCollection,
resetComposerFields,
collectionToReqRes,
collectionAdd,
collectionUpdate,
reqResClear,
reqResAdd,
reqResDelete,
setChecksAndMinis,
reqResUpdate,
scheduledReqResUpdate,
scheduledReqResDelete,
updateGraph,
clearGraph,
clearAllGraph,
setComposerWarningMessage,
setNewRequestFields,
setNewRequestHeaders,
setNewRequestStreams,
setNewRequestBody,
setNewRequestCookies,
setNewTestContent,
setNewRequestSSE,
setIntrospectionData,
saveCurrentResponseData,
setNewRequestsOpenAPI
} = actions
export default reducer; | the_stack |
import { BaseApi } from './Base';
import { ExtType, Metadata } from './types';
export interface BufferSetLines {
start?: number;
end?: number;
strictIndexing?: boolean;
}
export interface BufferHighlight {
hlGroup?: string;
line?: number;
colStart?: number;
colEnd?: number;
srcId?: number;
}
export interface BufferClearHighlight {
srcId?: number;
lineStart?: number;
lineEnd?: number;
}
export interface BufferClearNamespace {
nsId?: number;
lineStart?: number;
lineEnd?: number;
}
export type VirtualTextChunk = [string, string];
export const DETACH = Symbol('detachBuffer');
export const ATTACH = Symbol('attachBuffer');
export class Buffer extends BaseApi {
public prefix: string = Metadata[ExtType.Buffer].prefix;
public get isAttached(): boolean {
return this.client.isAttached(this);
}
/**
* Attach to buffer to listen to buffer events
* @param sendBuffer Set to true if the initial notification should contain
* the whole buffer. If so, the first notification will be a
* `nvim_buf_lines_event`. Otherwise, the first notification will be
* a `nvim_buf_changedtick_event`
*/
[ATTACH] = async (sendBuffer = false, options: {} = {}): Promise<boolean> => {
if (this.client.isAttached(this)) return true;
return this.request(`${this.prefix}attach`, [this, sendBuffer, options]);
};
/**
* Detach from buffer to stop listening to buffer events
*/
[DETACH] = () => this.request(`${this.prefix}detach`, [this]);
/**
* Get the bufnr of Buffer
*/
get id(): number {
return this.data as number;
}
/** Total number of lines in buffer */
get length(): Promise<number> {
return this.request(`${this.prefix}line_count`, [this]);
}
/** Get lines in buffer */
get lines(): Promise<string[]> {
return this.getLines();
}
/** Gets a changed tick of a buffer */
get changedtick(): Promise<number> {
return this.request(`${this.prefix}get_changedtick`, [this]);
}
get commands(): Promise<Record<string, any>> {
return this.getCommands();
}
getCommands(options = {}): Promise<Record<string, any>> {
return this.request(`${this.prefix}get_commands`, [this, options]);
}
/** Get specific lines of buffer */
getLines(
{ start, end, strictIndexing } = { start: 0, end: -1, strictIndexing: true }
): Promise<string[]> {
const indexing =
typeof strictIndexing === 'undefined' ? true : strictIndexing;
return this.request(`${this.prefix}get_lines`, [
this,
start,
end,
indexing,
]);
}
/** Set lines of buffer given indeces */
setLines(
_lines: string | string[],
{ start: _start, end: _end, strictIndexing }: BufferSetLines = {
strictIndexing: true,
}
) {
// TODO: Error checking
// if (typeof start === 'undefined' || typeof end === 'undefined') {
// }
const indexing =
typeof strictIndexing === 'undefined' ? true : strictIndexing;
const lines = typeof _lines === 'string' ? [_lines] : _lines;
const end = typeof _end !== 'undefined' ? _end : _start + 1;
return this.request(`${this.prefix}set_lines`, [
this,
_start,
end,
indexing,
lines,
]);
}
/** Insert lines at `start` index */
insert(lines: string[] | string, start: number) {
return this.setLines(lines, {
start,
end: start,
strictIndexing: true,
});
}
/** Replace lines starting at `start` index */
replace(_lines: string[] | string, start: number) {
const lines = typeof _lines === 'string' ? [_lines] : _lines;
return this.setLines(lines, {
start,
end: start + lines.length,
strictIndexing: false,
});
}
/** Remove lines at index */
remove(start: number, end: number, strictIndexing: boolean) {
return this.setLines([], { start, end, strictIndexing });
}
/** Append a string or list of lines to end of buffer */
append(lines: string[] | string) {
return this.setLines(lines, {
start: -1,
end: -1,
strictIndexing: false,
});
}
/** Get buffer name */
get name(): string | Promise<string> {
return this.request(`${this.prefix}get_name`, [this]);
}
/** Set current buffer name */
set name(value: string | Promise<string>) {
this.request(`${this.prefix}set_name`, [this, value]);
}
/** Is current buffer valid */
get valid(): Promise<boolean> {
return this.request(`${this.prefix}is_valid`, [this]);
}
/** Get mark position given mark name */
mark(name: string): Promise<[number, number]> {
return this.request(`${this.prefix}get_mark`, [this, name]);
}
// range(start, end) {
// """Return a `Range` object, which represents part of the Buffer."""
// return Range(this, start, end)
// }
/**
* Gets a list of buffer-local |mapping| definitions.
*/
getKeymap(mode: string): Promise<object[]> {
return this.request(`${this.prefix}get_keymap`, [this, mode]);
}
/**
* Checks if a buffer is valid and loaded. See |api-buffer| for
* more info about unloaded buffers.
*/
get loaded(): Promise<boolean> {
return this.request(`${this.prefix}is_loaded`, [this]);
}
/**
* Returns the byte offset for a line.
*
* Line 1 (index=0) has offset 0. UTF-8 bytes are counted. EOL is
* one byte. 'fileformat' and 'fileencoding' are ignored. The
* line index just after the last line gives the total byte-count
* of the buffer. A final EOL byte is counted if it would be
* written, see 'eol'.
*
* Unlike |line2byte()|, throws error for out-of-bounds indexing.
* Returns -1 for unloaded buffer.
*
* @return {Number} Integer byte offset, or -1 for unloaded buffer.
*/
getOffset(index: number): Promise<number> {
return this.request(`${this.prefix}get_offset`, [this, index]);
}
/**
* Adds a highlight to buffer.
*
* Useful for plugins that dynamically generate highlights to a
* buffer (like a semantic highlighter or linter). The function
* adds a single highlight to a buffer. Unlike |matchaddpos()|
* highlights follow changes to line numbering (as lines are
* inserted/removed above the highlighted line), like signs and
* marks do.
*
* Namespaces are used for batch deletion/updating of a set of
* highlights. To create a namespace, use |nvim_create_namespace|
* which returns a namespace id. Pass it in to this function as
* `ns_id` to add highlights to the namespace. All highlights in
* the same namespace can then be cleared with single call to
* |nvim_buf_clear_namespace|. If the highlight never will be
* deleted by an API call, pass `ns_id = -1`.
*
* As a shorthand, `ns_id = 0` can be used to create a new
* namespace for the highlight, the allocated id is then
* returned. If `hl_group` is the empty string no highlight is
* added, but a new `ns_id` is still returned. This is supported
* for backwards compatibility, new code should use
* |nvim_create_namespace| to create a new empty namespace.
*/
addHighlight({
hlGroup: _hlGroup,
line,
colStart: _start,
colEnd: _end,
srcId: _srcId,
}: BufferHighlight): Promise<number> {
const hlGroup = typeof _hlGroup !== 'undefined' ? _hlGroup : '';
const colEnd = typeof _end !== 'undefined' ? _end : -1;
const colStart = typeof _start !== 'undefined' ? _start : -0;
const srcId = typeof _srcId !== 'undefined' ? _srcId : -1;
return this.request(`${this.prefix}add_highlight`, [
this,
srcId,
hlGroup,
line,
colStart,
colEnd,
]);
}
/**
* Deprecated
*/
clearHighlight(args: BufferClearHighlight = {}) {
// eslint-disable-next-line no-console
console.warn(
'`clearHighlight` is deprecated, use ``clearNamespace()` instead'
);
const defaults = {
srcId: -1,
lineStart: 0,
lineEnd: -1,
};
const { srcId, lineStart, lineEnd } = { ...defaults, ...args };
return this.request(`${this.prefix}clear_highlight`, [
this,
srcId,
lineStart,
lineEnd,
]);
}
/**
* Clears namespaced objects, highlights and virtual text, from a line range
*
* To clear the namespace in the entire buffer, pass in 0 and -1 to line_start and line_end respectively.
*
* @param {Number} nsId Namespace to clear, or -1 to clear all namespaces
* @param {Number} lineStart Start of range of lines to clear
* @param {Number} lineEnd End of range of lines to clear (exclusive) or -1 to clear to end of buffer
*/
clearNamespace(args: BufferClearNamespace): void {
const defaults = {
nsId: -1,
lineStart: 0,
lineEnd: -1,
};
const { nsId, lineStart, lineEnd } = { ...defaults, ...args };
this.request(`${this.prefix}clear_namespace`, [
this,
nsId,
lineStart,
lineEnd,
]);
}
/**
* Set the virtual text (annotation) for a buffer line.
*
* By default (and currently the only option) the text will be
* placed after the buffer text. Virtual text will never cause
* reflow, rather virtual text will be truncated at the end of
* the screen line. The virtual text will begin one cell
* (|lcs-eol| or space) after the ordinary text.
*
* Namespaces are used to support batch deletion/updating of
* virtual text. To create a namespace, use
* |nvim_create_namespace|. Virtual text is cleared using
* |nvim_buf_clear_namespace|. The same `ns_id` can be used for
* both virtual text and highlights added by
* |nvim_buf_add_highlight|, both can then be cleared with a
* single call to |nvim_buf_clear_namespace|. If the virtual text
* never will be cleared by an API call, pass `ns_id = -1`.
*
* As a shorthand, `ns_id = 0` can be used to create a new
* namespace for the virtual text, the allocated id is then
* returned.
*
* @param
* @param {Number} nsId Namespace to use or 0 to create a namespace, or -1 for a ungrouped annotation
* @param {Number} line Line to annotate with virtual text (zero-indexed)
* @param {VirtualTextChunk[]} chunks A list of [text, hl_group] arrays, each
representing a text chunk with specified
highlight. `hl_group` element can be omitted for
no highlight.
* @param {Object} opts Optional parameters. Currently not used.
*/
setVirtualText(
nsId: number,
line: number,
chunks: VirtualTextChunk[],
opts = {}
): Promise<number> {
return this.request(`${this.prefix}set_virtual_text`, [
this,
nsId,
line,
chunks,
opts,
]);
}
/**
* Listens to buffer for events
*/
listen(eventName: string, cb: Function): Function {
if (!this.isAttached) {
this[ATTACH]().then(attached => {
if (!attached) {
this.unlisten(eventName, cb);
}
});
}
this.client.attachBuffer(this, eventName, cb);
return () => {
this.unlisten(eventName, cb);
};
}
unlisten(eventName: string, cb: Function): void {
if (!this.isAttached) return;
const shouldDetach = this.client.detachBuffer(this, eventName, cb);
if (!shouldDetach) return;
this[DETACH]();
}
}
export interface AsyncBuffer extends Buffer, Promise<Buffer> {} | the_stack |
import { expect } from 'chai'
import { DiffParser } from '../../src/lib/diff-parser'
import { DiffLineType } from '../../src/models/diff'
// Atom doesn't like lines with just one space and tries to
// de-indent so when copying- and pasting diff contents the
// space signalling that the line is a context line gets lost.
//
// This function reinstates that space and makes us all
// feel a little bit sad.
function reinstateSpacesAtTheStartOfBlankLines(text: string) {
return text.replace(/\n\n/g, '\n \n')
}
describe('DiffParser', () => {
it('parses changed files', () => {
const diffText = `diff --git a/app/src/lib/diff-parser.ts b/app/src/lib/diff-parser.ts
index e1d4871..3bd3ee0 100644
--- a/app/src/lib/diff-parser.ts
+++ b/app/src/lib/diff-parser.ts
@@ -18,6 +18,7 @@ export function parseRawDiff(lines: ReadonlyArray<string>): Diff {
let numberOfUnifiedDiffLines = 0
+
while (prefixFound) {
// trim any preceding text
@@ -71,12 +72,9 @@ export function parseRawDiff(lines: ReadonlyArray<string>): Diff {
diffSections.push(new DiffSection(range, diffLines, startDiffSection, endDiffSection))
} else {
const diffBody = diffTextBuffer
-
let startDiffSection: number = 0
let endDiffSection: number = 0
-
const diffLines = diffBody.split('\\n')
-
if (diffSections.length === 0) {
startDiffSection = 0
endDiffSection = diffLines.length
@@ -84,10 +82,8 @@ export function parseRawDiff(lines: ReadonlyArray<string>): Diff {
startDiffSection = numberOfUnifiedDiffLines
endDiffSection = startDiffSection + diffLines.length
}
-
diffSections.push(new DiffSection(range, diffLines, startDiffSection, endDiffSection))
}
}
-
return new Diff(diffSections)
}
`
const parser = new DiffParser()
const diff = parser.parse(reinstateSpacesAtTheStartOfBlankLines(diffText))
expect(diff.hunks.length).to.equal(3)
let hunk = diff.hunks[0]
expect(hunk.unifiedDiffStart).to.equal(0)
expect(hunk.unifiedDiffEnd).to.equal(7)
let lines = hunk.lines
expect(lines.length).to.equal(8)
let i = 0
expect(lines[i].text).to.equal(
'@@ -18,6 +18,7 @@ export function parseRawDiff(lines: ReadonlyArray<string>): Diff {'
)
expect(lines[i].type).to.equal(DiffLineType.Hunk)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(null)
i++
expect(lines[i].text).to.equal(' ')
expect(lines[i].type).to.equal(DiffLineType.Context)
expect(lines[i].oldLineNumber).to.equal(18)
expect(lines[i].newLineNumber).to.equal(18)
i++
expect(lines[i].text).to.equal(' let numberOfUnifiedDiffLines = 0')
expect(lines[i].type).to.equal(DiffLineType.Context)
expect(lines[i].oldLineNumber).to.equal(19)
expect(lines[i].newLineNumber).to.equal(19)
i++
expect(lines[i].text).to.equal(' ')
expect(lines[i].type).to.equal(DiffLineType.Context)
expect(lines[i].oldLineNumber).to.equal(20)
expect(lines[i].newLineNumber).to.equal(20)
i++
expect(lines[i].text).to.equal('+')
expect(lines[i].type).to.equal(DiffLineType.Add)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(21)
i++
expect(lines[i].text).to.equal(' while (prefixFound) {')
expect(lines[i].type).to.equal(DiffLineType.Context)
expect(lines[i].oldLineNumber).to.equal(21)
expect(lines[i].newLineNumber).to.equal(22)
i++
hunk = diff.hunks[1]
expect(hunk.unifiedDiffStart).to.equal(8)
expect(hunk.unifiedDiffEnd).to.equal(20)
lines = hunk.lines
expect(lines.length).to.equal(13)
})
it('parses new files', () => {
const diffText = `diff --git a/testste b/testste
new file mode 100644
index 0000000..f13588b
--- /dev/null
+++ b/testste
@@ -0,0 +1 @@
+asdfasdf
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.unifiedDiffStart).to.equal(0)
expect(hunk.unifiedDiffEnd).to.equal(1)
const lines = hunk.lines
expect(lines.length).to.equal(2)
let i = 0
expect(lines[i].text).to.equal('@@ -0,0 +1 @@')
expect(lines[i].type).to.equal(DiffLineType.Hunk)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(null)
i++
expect(lines[i].text).to.equal('+asdfasdf')
expect(lines[i].type).to.equal(DiffLineType.Add)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(1)
i++
})
it('parses files containing @@', () => {
const diffText = `diff --git a/test.txt b/test.txt
index 24219cc..bf711a5 100644
--- a/test.txt
+++ b/test.txt
@@ -1 +1 @@
-foo @@
+@@ foo
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.unifiedDiffStart).to.equal(0)
expect(hunk.unifiedDiffEnd).to.equal(2)
const lines = hunk.lines
expect(lines.length).to.equal(3)
let i = 0
expect(lines[i].text).to.equal('@@ -1 +1 @@')
expect(lines[i].type).to.equal(DiffLineType.Hunk)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(null)
i++
expect(lines[i].text).to.equal('-foo @@')
expect(lines[i].type).to.equal(DiffLineType.Delete)
expect(lines[i].oldLineNumber).to.equal(1)
expect(lines[i].newLineNumber).to.equal(null)
i++
expect(lines[i].text).to.equal('+@@ foo')
expect(lines[i].type).to.equal(DiffLineType.Add)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(1)
i++
})
it('parses new files without a newline at end of file', () => {
const diffText = `diff --git a/test2.txt b/test2.txt
new file mode 100644
index 0000000..faf7da1
--- /dev/null
+++ b/test2.txt
@@ -0,0 +1 @@
+asdasdasd
\\ No newline at end of file
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.unifiedDiffStart).to.equal(0)
expect(hunk.unifiedDiffEnd).to.equal(1)
const lines = hunk.lines
expect(lines.length).to.equal(2)
let i = 0
expect(lines[i].text).to.equal('@@ -0,0 +1 @@')
expect(lines[i].type).to.equal(DiffLineType.Hunk)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(null)
expect(lines[i].noTrailingNewLine).to.be.false
i++
expect(lines[i].text).to.equal('+asdasdasd')
expect(lines[i].type).to.equal(DiffLineType.Add)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(1)
expect(lines[i].noTrailingNewLine).to.be.true
i++
})
it('parses diffs that adds newline to end of file', () => {
const diffText = `diff --git a/test2.txt b/test2.txt
index 1910281..257cc56 100644
--- a/test2.txt
+++ b/test2.txt
@@ -1 +1 @@
-foo
\\ No newline at end of file
+foo
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.unifiedDiffStart).to.equal(0)
expect(hunk.unifiedDiffEnd).to.equal(2)
const lines = hunk.lines
expect(lines.length).to.equal(3)
let i = 0
expect(lines[i].text).to.equal('@@ -1 +1 @@')
expect(lines[i].type).to.equal(DiffLineType.Hunk)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(null)
expect(lines[i].noTrailingNewLine).to.be.false
i++
expect(lines[i].text).to.equal('-foo')
expect(lines[i].type).to.equal(DiffLineType.Delete)
expect(lines[i].oldLineNumber).to.equal(1)
expect(lines[i].newLineNumber).to.equal(null)
expect(lines[i].noTrailingNewLine).to.be.true
i++
expect(lines[i].text).to.equal('+foo')
expect(lines[i].type).to.equal(DiffLineType.Add)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(1)
expect(lines[i].noTrailingNewLine).to.be.false
i++
})
it('parses diffs where neither file version has a trailing newline', () => {
// echo -n 'foo' > test
// git add -A && git commit -m foo
// echo -n 'bar' > test
// git diff test
const diffText = `diff --git a/test b/test
index 1910281..ba0e162 100644
--- a/test
+++ b/test
@@ -1 +1 @@
-foo
\\ No newline at end of file
+bar
\\ No newline at end of file
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.unifiedDiffStart).to.equal(0)
expect(hunk.unifiedDiffEnd).to.equal(2)
const lines = hunk.lines
expect(lines.length).to.equal(3)
let i = 0
expect(lines[i].text).to.equal('@@ -1 +1 @@')
expect(lines[i].type).to.equal(DiffLineType.Hunk)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(null)
expect(lines[i].noTrailingNewLine).to.be.false
i++
expect(lines[i].text).to.equal('-foo')
expect(lines[i].type).to.equal(DiffLineType.Delete)
expect(lines[i].oldLineNumber).to.equal(1)
expect(lines[i].newLineNumber).to.equal(null)
expect(lines[i].noTrailingNewLine).to.be.true
i++
expect(lines[i].text).to.equal('+bar')
expect(lines[i].type).to.equal(DiffLineType.Add)
expect(lines[i].oldLineNumber).to.equal(null)
expect(lines[i].newLineNumber).to.equal(1)
expect(lines[i].noTrailingNewLine).to.be.true
i++
})
it('parses binary diffs', () => {
const diffText = `diff --git a/IMG_2306.CR2 b/IMG_2306.CR2
new file mode 100644
index 0000000..4bf3a64
Binary files /dev/null and b/IMG_2306.CR2 differ
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(0)
expect(diff.isBinary).to.equal(true)
})
it('parses diff of empty file', () => {
// To produce this output, do
// touch foo
// git diff --no-index --patch-with-raw -z -- /dev/null foo
const diffText = `new file mode 100644
index 0000000..e69de29
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(0)
})
it('parses hunk headers with omitted line counts from new file', () => {
const diffText = `diff --git a/testste b/testste
new file mode 100644
index 0000000..f13588b
--- /dev/null
+++ b/testste
@@ -0,0 +1 @@
+asdfasdf
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.header.oldStartLine).to.equal(0)
expect(hunk.header.oldLineCount).to.equal(0)
expect(hunk.header.newStartLine).to.equal(1)
expect(hunk.header.newLineCount).to.equal(1)
})
it('parses hunk headers with omitted line counts from old file', () => {
const diffText = `diff --git a/testste b/testste
new file mode 100644
index 0000000..f13588b
--- /dev/null
+++ b/testste
@@ -1 +0,0 @@
-asdfasdf
`
const parser = new DiffParser()
const diff = parser.parse(diffText)
expect(diff.hunks.length).to.equal(1)
const hunk = diff.hunks[0]
expect(hunk.header.oldStartLine).to.equal(1)
expect(hunk.header.oldLineCount).to.equal(1)
expect(hunk.header.newStartLine).to.equal(0)
expect(hunk.header.newLineCount).to.equal(0)
})
}) | the_stack |
describe('Headers', () => {
it('constructor copies headers', function() {
let original = new Headers();
original.append('Accept', 'application/json');
original.append('Accept', 'text/plain');
original.append('Content-Type', 'text/html');
let headers = new Headers(original);
expect(headers.get('Accept')).toBe('application/json, text/plain');
expect(headers.get('Content-Type')).toBe('text/html');
});
it('constructor works with arrays', function() {
let array = [
['Content-Type', 'text/xml'],
['Breaking-Bad', '<3'],
];
let headers = new Headers(array);
expect(headers.get('Content-Type')).toBe('text/xml');
expect(headers.get('Breaking-Bad')).toBe('<3');
});
it('headers are case insensitive', function() {
let headers = new Headers({ Accept: 'application/json' });
expect(headers.get('ACCEPT')).toBe('application/json');
expect(headers.get('Accept')).toBe('application/json');
expect(headers.get('accept')).toBe('application/json');
});
it('appends to existing', function() {
let headers = new Headers({ Accept: 'application/json' });
expect(headers.has('Content-Type')).toBe(false);
headers.append('Content-Type', 'application/json');
expect(headers.has('Content-Type')).toBe(true);
expect(headers.get('Content-Type')).toBe('application/json');
});
it('appends values to existing header name', function() {
let headers = new Headers({ Accept: 'application/json' });
headers.append('Accept', 'text/plain');
expect(headers.get('Accept')).toBe('application/json, text/plain');
});
it('sets header name and value', function() {
let headers = new Headers();
headers.set('Content-Type', 'application/json');
expect(headers.get('Content-Type')).toBe('application/json');
});
it('returns null on no header found', function() {
let headers = new Headers();
expect(headers.get('Content-Type')).toBe(null);
});
it('has headers that are set', function() {
let headers = new Headers();
headers.set('Content-Type', 'application/json');
expect(headers.has('Content-Type')).toBe(true);
});
it('deletes headers', function() {
let headers = new Headers();
headers.set('Content-Type', 'application/json');
expect(headers.has('Content-Type')).toBe(true);
headers.delete('Content-Type');
expect(headers.has('Content-Type')).toBe(false);
expect(headers.get('Content-Type')).toBe(null);
});
it('converts field name to string on set and get', function() {
let headers = new Headers();
// @ts-ignore
headers.set(1, 'application/json');
expect(headers.has('1')).toBe(true);
// @ts-ignore
expect(headers.get(1)).toBe('application/json');
});
it('converts field value to string on set and get', function() {
let headers = new Headers();
// @ts-ignore
headers.set('Content-Type', 1);
// @ts-ignore
headers.set('X-CSRF-Token', undefined);
expect(headers.get('Content-Type')).toBe('1');
expect(headers.get('X-CSRF-Token')).toBe('undefined');
});
it('throws TypeError on invalid character in field name', function() {
expect(function() {
new Headers({ '[Accept]': 'application/json' });
}).toThrowError(TypeError);
expect(function() {
new Headers({ 'Accept:': 'application/json' });
}).toThrowError(TypeError);
expect(function() {
let headers = new Headers();
// @ts-ignore
headers.set({ field: 'value' }, 'application/json');
}).toThrowError(TypeError);
expect(function() {
new Headers({ '': 'application/json' });
}).toThrowError(TypeError);
});
});
describe('Request', () => {
it('construct with string url', function() {
let request = new Request('https://fetch.spec.whatwg.org/');
expect(request.url).toBe('https://fetch.spec.whatwg.org/');
});
it('construct with non-Request object', function() {
let url = {
toString: function() {
return 'https://fetch.spec.whatwg.org/';
},
};
// @ts-ignore
let request = new Request(url);
expect(request.url).toBe('https://fetch.spec.whatwg.org/');
});
it('construct with Request', function() {
let request1 = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
body: 'I work out',
headers: {
accept: 'application/json',
'Content-Type': 'text/plain',
},
});
let request2 = new Request(request1);
return request2.text().then(function(body2) {
expect(body2).toBe('I work out');
expect(request2.method).toBe('POST');
expect(request2.url).toBe('https://fetch.spec.whatwg.org/');
expect(request2.headers.get('accept')).toBe('application/json');
expect(request2.headers.get('content-type')).toBe('text/plain');
return request1.text().then(
function() {
console.assert(
false,
'original request body should have been consumed'
);
},
function(error) {
console.assert(
error instanceof TypeError,
'expected TypeError for already read body'
);
}
);
});
});
it('construct with Request and override headers', function() {
let request1 = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
body: 'I work out',
headers: {
accept: 'application/json',
'X-Request-ID': '123',
},
});
let request2 = new Request(request1, {
headers: { 'x-it': '42' },
});
// @ts-ignore
expect(request2.headers.get('accept')).toBe(null);
// @ts-ignore
expect(request2.headers.get('x-request-id')).toBe(null);
expect(request2.headers.get('x-it')).toBe('42');
});
it('construct with Request and override body', function() {
let request1 = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
body: 'I work out',
headers: {
'Content-Type': 'text/plain',
},
});
let request2 = new Request(request1, {
body: '{"wiggles": 5}',
headers: { 'Content-Type': 'application/json' },
});
return request2.json().then(function(data) {
expect(data.wiggles).toBe(5);
expect(request2.headers.get('content-type')).toBe('application/json');
});
});
it('construct with used Request body', function() {
let request1 = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
body: 'I work out',
});
return request1.text().then(function() {
expect(function() {
new Request(request1);
}).toThrowError(TypeError);
});
});
it('GET should not have implicit Content-Type', function() {
let req = new Request('https://fetch.spec.whatwg.org/');
expect(req.headers.get('content-type')).toBe(null);
});
it('POST with blank body should not have implicit Content-Type', function() {
let req = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
});
expect(req.headers.get('content-type')).toBe(null);
});
it('construct with string body sets Content-Type header', function() {
let req = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
body: 'I work out',
});
expect(req.headers.get('content-type')).toBe('text/plain;charset=UTF-8');
});
it('construct with body and explicit header uses header', function() {
let req = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
headers: { 'Content-Type': 'image/png' },
body: 'I work out',
});
expect(req.headers.get('content-type')).toBe('image/png');
});
it('construct with unsupported body type', function() {
// @ts-ignore
let req = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
// @ts-ignore
body: {},
});
expect(req.headers.get('content-type')).toBe('text/plain;charset=UTF-8');
return req.text().then((bodyText: string) => {
expect(bodyText).toBe('[object Object]');
});
});
it('construct with null body', function() {
let req = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
});
expect(req.headers.get('content-type')).toBe(null);
return req.text().then(function(bodyText) {
expect(bodyText).toBe('');
});
});
it('clone GET request', function() {
let req = new Request('https://fetch.spec.whatwg.org/', {
headers: { 'content-type': 'text/plain' },
});
let clone = req.clone();
expect(clone.url).toBe(req.url);
expect(clone.method).toBe('GET');
expect(clone.headers.get('content-type')).toBe('text/plain');
expect(clone.headers != req.headers).toBe(true);
expect(req.bodyUsed).toBe(false);
});
it('clone POST request', function() {
let req = new Request('https://fetch.spec.whatwg.org/', {
method: 'post',
headers: { 'content-type': 'text/plain' },
body: 'I work out',
});
let clone = req.clone();
expect(clone.method).toBe('POST');
expect(clone.headers.get('content-type')).toBe('text/plain');
expect(clone.headers != req.headers).toBe(true);
expect(req.bodyUsed).toBe(false);
return Promise.all([clone.text(), req.clone().text()]).then(function(
bodies
) {
expect(bodies).toEqual(['I work out', 'I work out']);
});
});
});
describe('Response', function() {
it('default status is 200 OK', function() {
let res = new Response();
expect(res.status).toBe(200);
expect(res.statusText).toBe('OK');
expect(res.ok).toBe(true);
});
it('default status is 200 OK when an explicit undefined status code is passed', function() {
let res = new Response('', { status: undefined });
expect(res.status).toBe(200);
expect(res.statusText).toBe('OK');
expect(res.ok).toBe(true);
});
it('creates Headers object from raw headers', function() {
let r = new Response('{"foo":"bar"}', {
headers: { 'content-type': 'application/json' },
});
expect(r.headers instanceof Headers).toBe(true);
return r.json().then(function(json) {
expect(json.foo).toBe('bar');
return json;
});
});
it('always creates a new Headers instance', function() {
let headers = new Headers({ 'x-hello': 'world' });
let res = new Response('', { headers: headers });
expect(res.headers.get('x-hello')).toBe('world');
expect(res.headers != headers).toBe(true);
});
it('clone text response', function() {
let res = new Response('{"foo":"bar"}', {
headers: { 'content-type': 'application/json' },
});
let clone = res.clone();
expect(clone.headers != res.headers).toBe(true);
expect(clone.headers.get('content-type')).toBe('application/json');
return Promise.all([clone.json(), res.json()]).then(function(jsons) {
expect(jsons[0]).toEqual(
jsons[1],
'json of cloned object is the same as original'
);
});
});
it('error creates error Response', function() {
let r = Response.error();
console.assert(r instanceof Response);
expect(r.status).toBe(0);
expect(r.statusText).toBe('');
expect(r.type).toBe('error');
});
it('redirect creates redirect Response', function() {
let r = Response.redirect('https://fetch.spec.whatwg.org/', 301);
console.assert(r instanceof Response);
expect(r.status).toBe(301);
expect(r.headers.get('Location')).toBe('https://fetch.spec.whatwg.org/');
});
it('construct with string body sets Content-Type header', function() {
let r = new Response('I work out');
expect(r.headers.get('content-type')).toBe('text/plain;charset=UTF-8');
});
it('construct with body and explicit header uses header', function() {
let r = new Response('I work out', {
headers: {
'Content-Type': 'text/plain',
},
});
expect(r.headers.get('content-type')).toBe('text/plain');
});
it('init object as first argument', function() {
// @ts-ignore
let r = new Response({
// @ts-ignore
status: 201,
headers: {
'Content-Type': 'text/html',
},
});
expect(r.status).toBe(200);
expect(r.headers.get('content-type')).toBe('text/plain;charset=UTF-8');
return r.text().then(function(bodyText: string) {
expect(bodyText).toBe('[object Object]');
});
});
it('null as first argument', function() {
let r = new Response(null);
expect(r.headers.get('content-type')).toBe(null);
return r.text().then(function(bodyText) {
expect(bodyText).toBe('');
});
});
describe('json', () => {
it('parses json response', function() {
return fetch('https://kraken.oss-cn-hangzhou.aliyuncs.com/data/data.json')
.then(function(response) {
return response.json();
})
.then(function(json) {
expect(json.method).toBe('GET');
expect(json.data.userName).toBe('12345');
});
});
it('rejects json promise after body is consumed', function() {
return fetch('/json')
.then(function(response) {
console.assert(response.json, 'Body does not implement json');
expect(response.bodyUsed).toBe(false);
response.text();
expect(response.bodyUsed).toBe(true);
return response.json();
})
.catch(function(error) {
console.assert(
error instanceof Error,
'Promise rejected after body consumed'
);
});
});
});
describe('text', function() {
it('resolves text promise', function() {
return fetch('https://kraken.oss-cn-hangzhou.aliyuncs.com/data/data.json')
.then(function(response) {
return response.text();
})
.then(function(text) {
expect(text.replace(/\s+/g, '')).toBe(
'{"method":"GET","data":{"userName":"12345"}}'
);
});
});
});
}); | the_stack |
import * as React from "react";
import { useRef, useCallback, useEffect, useImperativeHandle, forwardRef, useState, useMemo, useContext, useLayoutEffect } from "react";
import { ISpace, IBoard, getConnections, getCurrentBoard, forEachEventParameter, IEventInstance } from "./boards";
import { BoardType, Space, SpaceSubtype, GameVersion, EventParameterType, isArrayEventParameterType, Action } from "./types";
import { degreesToRadians } from "./utils/number";
import { spaces } from "./spaces";
import { getImage } from "./images";
import { $$hex, $$log, assert } from "./utils/debug";
import { RightClickMenu } from "./rightclick";
import { attachToCanvas, detachFromCanvas } from "./interaction";
import { getEvent } from "./events/events";
import { getDistinctColor } from "./utils/colors";
import { isDebug } from "./debug";
import { takeScreeny } from "./screenshot";
import { getMouseCoordsOnCanvas } from "./utils/canvas";
import { setOverrideBg } from "./app/appControl";
import { useAppSelector, useCurrentBoard } from "./app/hooks";
import { selectCurrentBoard, selectHighlightedSpaceIndices, selectHoveredBoardEventIndex, selectSelectedSpaceIndices, selectSelectionBoxCoords, selectTemporaryConnections, SpaceIndexMap } from "./app/boardState";
import { isEmpty } from "./utils/obj";
import { getEventsInLibrary } from "./events/EventLibrary";
type Canvas = HTMLCanvasElement;
type CanvasContext = CanvasRenderingContext2D;
function _renderConnections(lineCanvas: Canvas, lineCtx: CanvasContext, board: IBoard, clear: boolean = true) {
if (clear)
lineCtx.clearRect(0, 0, lineCanvas.width, lineCanvas.height);
// Draw connecting lines.
const links = board.links;
if (links) {
for (let startSpace in links) {
const x1 = board.spaces[startSpace].x;
const y1 = board.spaces[startSpace].y;
const endLinks = getConnections(parseInt(startSpace), board)!;
let x2, y2;
let bidirectional = false;
for (let i = 0; i < endLinks.length; i++) {
x2 = board.spaces[endLinks[i]].x;
y2 = board.spaces[endLinks[i]].y;
bidirectional = _isConnectedTo(links, endLinks[i], startSpace);
if (bidirectional && parseInt(startSpace) > endLinks[i])
continue;
_drawConnection(lineCtx, x1, y1, x2, y2, bidirectional);
}
}
}
}
function _renderAssociations(
canvas: Canvas,
context: CanvasContext,
board: IBoard,
selectedSpacesIndices?: SpaceIndexMap
) {
context.clearRect(0, 0, canvas.width, canvas.height);
if (!selectedSpacesIndices)
return;
const selectedIndices = Object.keys(selectedSpacesIndices).map(s => parseInt(s, 10));
if (selectedIndices.length !== 1) {
return;
}
const selectedSpaceIndex = selectedIndices[0];
const eventLibrary = getEventsInLibrary();
// Draw associated spaces in event params.
let lastEvent: IEventInstance;
let associationNum = 0;
forEachEventParameter(board, eventLibrary, (parameter, event, eventIndex, space, spaceIndex) => {
if (selectedSpaceIndex !== spaceIndex)
return; // Only draw associations for the selected space.
// Reset coloring for each event.
if (lastEvent !== event) {
associationNum = 0;
}
lastEvent = event;
let spaceIndicesToAssociate: number[] | undefined;
switch (parameter.type) {
case EventParameterType.Space:
const associatedSpaceIndex =
event.parameterValues && event.parameterValues[parameter.name];
if (typeof associatedSpaceIndex === "number") {
spaceIndicesToAssociate = [associatedSpaceIndex];
}
break;
case EventParameterType.SpaceArray:
spaceIndicesToAssociate = event.parameterValues && (event.parameterValues[parameter.name] as number[]);
break;
}
if (spaceIndicesToAssociate) {
spaceIndicesToAssociate.forEach(spaceIndex => {
const associatedSpace = board.spaces[spaceIndex];
if (!associatedSpace)
return; // Probably shouldn't happen.
const dotsColor = `rgba(${getDistinctColor(associationNum).join(", ")}, 0.5)`;
drawAssociation(context, space!.x, space!.y, associatedSpace.x, associatedSpace.y, dotsColor);
associationNum++;
});
}
});
}
function _isConnectedTo(links: any, start: number, end: any) {
let startLinks = links[start];
if (Array.isArray(startLinks))
return startLinks.indexOf(parseInt(end)) >= 0;
else
return startLinks == end; /* eslint-disable-line */ // Can be string vs int?
}
export interface ISpaceRenderOpts {
skipHiddenSpaces?: boolean;
skipBadges?: boolean;
skipCharacters?: boolean;
}
// opts:
// skipHiddenSpaces: true to not render start, invisible spaces
// skipBadges: false to skip event and star badges
function _renderSpaces(spaceCanvas: Canvas, spaceCtx: CanvasContext, board: IBoard, clear: boolean = true, opts: ISpaceRenderOpts = {}) {
if (clear)
spaceCtx.clearRect(0, 0, spaceCanvas.width, spaceCanvas.height);
// Draw spaces
for (let index = 0; index < board.spaces.length; index++) {
let space = board.spaces[index];
if (space === null)
continue;
drawSpace(spaceCtx, board, space, index, opts);
}
}
function drawSpace(spaceCtx: CanvasContext, board: IBoard, space: ISpace, spaceIndex: number, opts: ISpaceRenderOpts = {}) {
const game = board.game || 1;
const boardType = board.type || BoardType.NORMAL;
const x = space.x;
const y = space.y;
const rotation = space.rotation;
const type = space.type;
const subtype = space.subtype;
if (typeof rotation === "number") {
spaceCtx.save();
spaceCtx.translate(x, y);
const adjustedAngleRad = -rotation;
spaceCtx.rotate(degreesToRadians(adjustedAngleRad));
spaceCtx.translate(-x, -y);
}
switch (type) {
case Space.OTHER:
if (opts.skipHiddenSpaces)
break;
if (game === 3)
spaces.drawOther3(spaceCtx, x, y);
else
spaces.drawOther(spaceCtx, x, y);
break;
case Space.BLUE:
if (game === 3)
spaces.drawBlue3(spaceCtx, x, y);
else
spaces.drawBlue(spaceCtx, x, y);
break;
case Space.RED:
if (game === 3)
spaces.drawRed3(spaceCtx, x, y);
else
spaces.drawRed(spaceCtx, x, y);
break;
case Space.MINIGAME:
if (boardType === BoardType.DUEL)
spaces.drawMiniGameDuel3(spaceCtx, x, y);
else
spaces.drawMiniGame(spaceCtx, x, y);
break;
case Space.HAPPENING:
if (game === 3) {
if (boardType === BoardType.DUEL)
spaces.drawHappeningDuel3(spaceCtx, x, y);
else
spaces.drawHappening3(spaceCtx, x, y);
}
else
spaces.drawHappening(spaceCtx, x, y);
break;
case Space.STAR:
if (game === 3)
spaces.drawStar3(spaceCtx, x, y);
else
spaces.drawStar(spaceCtx, x, y);
break;
case Space.CHANCE:
if (game === 3)
spaces.drawChance3(spaceCtx, x, y);
else if (game === 2)
spaces.drawChance2(spaceCtx, x, y);
else
spaces.drawChance(spaceCtx, x, y);
break;
case Space.START:
if (opts.skipHiddenSpaces)
break;
if (game === 3)
spaces.drawStart3(spaceCtx, x, y);
else
spaces.drawStart(spaceCtx, x, y);
break;
case Space.SHROOM:
spaces.drawShroom(spaceCtx, x, y);
break;
case Space.BOWSER:
if (game === 3)
spaces.drawBowser3(spaceCtx, x, y);
else
spaces.drawBowser(spaceCtx, x, y);
break;
case Space.ITEM:
if (game === 3)
spaces.drawItem3(spaceCtx, x, y);
else
spaces.drawItem2(spaceCtx, x, y);
break;
case Space.BATTLE:
if (game === 3)
spaces.drawBattle3(spaceCtx, x, y);
else
spaces.drawBattle2(spaceCtx, x, y);
break;
case Space.BANK:
if (game === 3)
spaces.drawBank3(spaceCtx, x, y);
else
spaces.drawBank2(spaceCtx, x, y);
break;
case Space.ARROW:
spaces.drawArrow(spaceCtx, x, y, game);
break;
case Space.BLACKSTAR:
spaces.drawBlackStar2(spaceCtx, x, y);
break;
case Space.GAMEGUY:
if (boardType === BoardType.DUEL)
spaces.drawGameGuyDuel3(spaceCtx, x, y);
else
spaces.drawGameGuy3(spaceCtx, x, y);
break;
case Space.DUEL_BASIC:
spaces.drawDuelBasic(spaceCtx, x, y);
break;
case Space.DUEL_START_BLUE:
if (opts.skipHiddenSpaces)
break;
spaces.drawStartDuelBlue(spaceCtx, x, y);
break;
case Space.DUEL_START_RED:
if (opts.skipHiddenSpaces)
break;
spaces.drawStartDuelRed(spaceCtx, x, y);
break;
case Space.DUEL_POWERUP:
spaces.drawDuelPowerup(spaceCtx, x, y);
break;
case Space.DUEL_REVERSE:
spaces.drawDuelReverse(spaceCtx, x, y);
break;
default:
spaces.drawUnknown(spaceCtx, x, y);
break;
}
if (typeof rotation === "number") {
spaceCtx.restore();
}
if (!opts.skipCharacters) {
drawCharacters(spaceCtx, x, y, subtype, game);
}
if (!opts.skipBadges) {
let offset = game === 3 ? 5 : 2;
let startOffset = game === 3 ? 16 : 12
if (space.events && space.events.length) {
let iconY = y + offset;
if (type === Space.START)
iconY -= startOffset;
spaceCtx.drawImage(__determineSpaceEventImg(space, board), x + offset, iconY);
}
if (space.star) {
let iconY = y + offset;
if (type === Space.START)
iconY -= startOffset;
spaceCtx.drawImage(getImage("starImg"), x - offset - 9, iconY);
}
if (space.subtype === SpaceSubtype.GATE) {
let iconX = x - offset - 9;
let iconY = y + offset - 5;
spaceCtx.drawImage(getImage("gateImg"), iconX, iconY);
}
}
if (isDebug()) {
// Draw the space's index.
spaceCtx.save();
spaceCtx.fillStyle = "white";
spaceCtx.strokeStyle = "black";
spaceCtx.lineWidth = 2;
spaceCtx.font = "bold 6pt Courier New";
spaceCtx.textAlign = "center";
let text = spaceIndex.toString();
spaceCtx.strokeText(text, x, y - 2);
spaceCtx.fillText(text, x, y - 2);
text = $$hex(spaceIndex);
spaceCtx.strokeText(text, x, y + 8);
spaceCtx.fillText(text, x, y + 8);
spaceCtx.restore();
}
}
function drawCharacters(spaceCtx: CanvasContext, x: number, y: number, subtype: SpaceSubtype | undefined, game: number) {
// Draw the standing Toad.
if (subtype === SpaceSubtype.TOAD) {
if (game === 3)
spaceCtx.drawImage(getImage("mstarImg"), x - 15, y - 22);
else
spaceCtx.drawImage(getImage("toadImg"), x - 9, y - 22);
}
// Draw the standing Bowser.
if (subtype === SpaceSubtype.BOWSER) {
spaceCtx.drawImage(getImage("bowserImg"), x - 27, y - 45);
}
// Draw the standing Koopa Troopa.
if (subtype === SpaceSubtype.KOOPA) {
spaceCtx.drawImage(getImage("koopaImg"), x - 12, y - 22);
}
// Draw the standing Boo.
if (subtype === SpaceSubtype.BOO) {
spaceCtx.drawImage(getImage("booImg"), x - 13, y - 17);
}
// Draw the standing Goomba.
if (subtype === SpaceSubtype.GOOMBA) {
spaceCtx.drawImage(getImage("goombaImg"), x - 8, y - 12);
}
// Draw the bank.
if (subtype === SpaceSubtype.BANK) {
if (game === 2)
spaceCtx.drawImage(getImage("bank2Img"), x - 9, y - 10);
else
spaceCtx.drawImage(getImage("bank3Img"), x - 17, y - 20);
}
// Draw the bank coin.
if (subtype === SpaceSubtype.BANKCOIN) {
spaceCtx.drawImage(getImage("bankcoinImg"), x - 10, y - 9);
}
// Draw the item shop.
if (subtype === SpaceSubtype.ITEMSHOP) {
if (game === 2)
spaceCtx.drawImage(getImage("itemShop2Img"), x - 9, y - 10);
else
spaceCtx.drawImage(getImage("itemShop3Img"), x - 16, y - 20);
}
}
const _PIOver1 = (Math.PI / 1);
function _drawConnection(lineCtx: CanvasContext, x1: number, y1: number, x2: number, y2: number, bidirectional?: boolean) {
lineCtx.save();
lineCtx.beginPath();
lineCtx.strokeStyle = "rgba(255, 185, 105, 0.75)";
lineCtx.lineCap = "round";
lineCtx.lineWidth = 8;
lineCtx.moveTo(x1, y1);
lineCtx.lineTo(x2, y2);
lineCtx.stroke();
// Draw the little triangle arrow on top at halfway.
let midX = (x1 + x2) / 2;
let midY = (y1 + y2) / 2;
lineCtx.translate(midX, midY);
lineCtx.rotate(-Math.atan2(x1 - midX, y1 - midY) + _PIOver1);
lineCtx.fillStyle = "#A15000";
let adjust = bidirectional ? 3 : 0;
lineCtx.moveTo(-4, -2 + adjust);
lineCtx.lineTo(0, 2 + adjust);
lineCtx.lineTo(4, -2 + adjust);
lineCtx.fill();
if (bidirectional) {
lineCtx.moveTo(-4, 2 - adjust);
lineCtx.lineTo(0, -2 - adjust);
lineCtx.lineTo(4, 2 - adjust);
lineCtx.fill();
}
lineCtx.restore();
}
function drawAssociation(lineCtx: CanvasContext,
x1: number, y1: number, x2: number, y2: number,
dotsColor: string
) {
lineCtx.save();
lineCtx.beginPath();
lineCtx.strokeStyle = "rgba(0, 0, 0, 0.5)";
lineCtx.setLineDash([1, 8]);
lineCtx.lineCap = "round";
lineCtx.lineWidth = 6;
lineCtx.moveTo(x1, y1);
lineCtx.lineTo(x2, y2);
lineCtx.stroke();
lineCtx.restore();
lineCtx.save();
lineCtx.beginPath();
lineCtx.strokeStyle = dotsColor;
lineCtx.setLineDash([1, 8]);
lineCtx.lineCap = "round";
lineCtx.lineWidth = 4;
lineCtx.moveTo(x1, y1);
lineCtx.lineTo(x2, y2);
lineCtx.stroke();
lineCtx.restore();
}
/** Adds a glow around the selected spaces in the editor. */
function _renderSelectedSpaces(canvas: Canvas, context: CanvasContext, board: IBoard, spaceIndices: SpaceIndexMap | null) {
context.clearRect(0, 0, canvas.width, canvas.height);
if (!spaceIndices || isEmpty(spaceIndices))
return;
for (const spaceIndex in spaceIndices) {
const space = board.spaces[parseInt(spaceIndex, 10)];
if (space) {
context.save();
context.beginPath();
const radius = getCurrentBoard().game === 3 ? 18 : 12;
context.arc(space.x, space.y, radius, 0, 2 * Math.PI);
context.setLineDash([2, 2]);
context.lineWidth = 2;
context.fillStyle = "rgba(47, 70, 95, 0.35)";
context.strokeStyle = "rgba(47, 70, 95, 1)";
// context.shadowColor = "rgba(225, 225, 225, 1)";
// context.shadowBlur = 2;
// context.fillStyle = "rgba(225, 225, 225, 0.5)";
context.fill();
context.stroke();
context.restore();
}
}
}
/** Does a strong red highlight around some spaces. */
function _highlightSpaces(canvas: Canvas, context: CanvasContext, spaces: number[]) {
const currentBoard = getCurrentBoard();
const radius = currentBoard.game === 3 ? 18 : 12;
for (let i = 0; i < spaces.length; i++) {
const space = currentBoard.spaces[spaces[i]];
if (space) {
context.save();
context.beginPath();
context.arc(space.x, space.y, radius, 0, 2 * Math.PI);
context.shadowColor = "rgba(225, 225, 225, 1)";
context.shadowBlur = 2;
context.fillStyle = "rgba(255, 0, 0, 0.85)";
context.fill();
context.restore();
}
}
}
function _highlightBoardEventSpaces(canvas: Canvas, context: CanvasContext, eventInstance: IEventInstance) {
const currentBoard = getCurrentBoard();
const eventLibrary = getEventsInLibrary();
const radius = currentBoard.game === 3 ? 18 : 12;
const event = getEvent(eventInstance.id, currentBoard, eventLibrary);
assert(!!event);
if (event.parameters) {
let associationNum = 0;
for (const parameter of event.parameters) {
let spacesIndicesToHighlight: number[] | undefined;
switch (parameter.type) {
case EventParameterType.Space:
const spaceIndex = eventInstance.parameterValues?.[parameter.name];
if (typeof spaceIndex === "number") {
spacesIndicesToHighlight = [spaceIndex];
}
break;
case EventParameterType.SpaceArray:
const spaceIndices = eventInstance.parameterValues?.[parameter.name];
if (Array.isArray(spaceIndices)) {
spacesIndicesToHighlight = spaceIndices;
}
break;
}
if (spacesIndicesToHighlight) {
for (const spaceIndex of spacesIndicesToHighlight) {
const space = currentBoard.spaces[spaceIndex];
if (space) {
context.save();
context.beginPath();
context.arc(space.x, space.y, radius, 0, 2 * Math.PI);
context.shadowColor = "rgba(225, 225, 225, 1)";
context.shadowBlur = 2;
context.fillStyle = `rgba(${getDistinctColor(associationNum).join(", ")}, 0.9)`;
context.fill();
context.restore();
associationNum++;
}
}
}
}
}
}
function __determineSpaceEventImg(space: ISpace, board: IBoard) {
if (space.events && space.events.length) {
for (let i = 0; i < space.events.length; i++) {
const spaceEvent = space.events[i];
const event = getEvent(spaceEvent.id, board, getEventsInLibrary());
if (!event)
return getImage("eventErrorImg");
if (event.parameters) {
for (let p = 0; p < event.parameters.length; p++) {
const parameter = event.parameters[p];
if (isArrayEventParameterType(parameter.type)) {
continue;
}
if (!spaceEvent.parameterValues || !spaceEvent.parameterValues.hasOwnProperty(parameter.name)) {
return getImage("eventErrorImg");
}
}
}
}
}
return getImage("eventImg");
}
const BoardBG: React.FC = () => {
const [boardWidth, boardHeight] = useBoardDimensions();
const [editorWidth, editorHeight] = useContext(EditorSizeContext);
const boardBgSrc = useAppSelector(state => selectCurrentBoard(state).bg.src);
const overrideBg = useAppSelector(state => state.app.overrideBg);
const imgEl = useRef<HTMLImageElement | null>(null);
useEffect(() => {
const bgImgEl = imgEl.current!;
const transformStyle = getEditorContentTransform(boardWidth, boardHeight, editorWidth, editorHeight);
bgImgEl.style.transform = transformStyle;
bgImgEl.width = boardWidth;
bgImgEl.height = boardHeight;
}, [boardWidth, boardHeight, editorWidth, editorHeight]);
const imgSrcToUse = overrideBg || boardBgSrc;
return (
<img ref={imgEl} className="editor_bg" alt="Board Background" src={imgSrcToUse} />
);
};
let _animInterval: any;
let _currentFrame = -1;
export function playAnimation() {
if (!_animInterval) {
_animInterval = setInterval(_animationStep, 800);
setOverrideBg(null);
}
}
export function stopAnimation() {
if (_animInterval) {
clearInterval(_animInterval);
}
_animInterval = null;
_currentFrame = -1;
setOverrideBg(null);
}
function _animationStep() {
const board = getCurrentBoard();
const animbgs = board.animbg;
if (!animbgs || !animbgs.length) {
stopAnimation();
return;
}
else if (_currentFrame >= 0 && _currentFrame < animbgs.length) {
setOverrideBg(animbgs[_currentFrame]);
_currentFrame++;
}
else {
_currentFrame = -1;
}
if (_currentFrame === -1) {
setOverrideBg(board.bg.src);
_currentFrame++;
}
}
const BoardLines = () => {
const canvasRef = useRef<Canvas>(null);
const board = useCurrentBoard();
const [boardWidth, boardHeight] = useBoardDimensions();
const tempConnections = useAppSelector(selectTemporaryConnections);
useDimensionsOnCanvas(canvasRef, boardWidth, boardHeight);
useEffect(() => {
// Update lines connecting spaces
const lineCanvas = canvasRef.current!;
const context = lineCanvas.getContext("2d")!;
_renderConnections(lineCanvas, context, board, true);
if (tempConnections) {
for (const tempConnection of tempConnections) {
const [x1, y1, x2, y2] = tempConnection;
_drawConnection(context, x1, y1, x2, y2, false);
}
}
}, [board, tempConnections]);
return (
<canvas ref={canvasRef} className="editor_line_canvas"></canvas>
);
};
const BoardAssociations = () => {
const canvasRef = useRef<Canvas>(null);
const currentBoard = useCurrentBoard();
const [boardWidth, boardHeight] = useBoardDimensions();
const selectedSpaceIndices = useAppSelector(selectSelectedSpaceIndices);
useDimensionsOnCanvas(canvasRef, boardWidth, boardHeight);
useEffect(() => {
// Update space parameter association lines
const assocCanvas = canvasRef.current!;
_renderAssociations(assocCanvas, assocCanvas.getContext("2d")!, currentBoard, selectedSpaceIndices);
}, [currentBoard, selectedSpaceIndices]);
return (
<canvas ref={canvasRef} className="editor_association_canvas"></canvas>
);
};
const BoardSelectedSpaces = () => {
const canvasRef = useRef<Canvas>(null);
const currentBoard = useCurrentBoard();
const [boardWidth, boardHeight] = useBoardDimensions();
const selectedSpaceIndices = useAppSelector(selectSelectedSpaceIndices);
const highlightedSpaceIndices = useAppSelector(selectHighlightedSpaceIndices);
const hoveredBoardEventIndex = useAppSelector(selectHoveredBoardEventIndex);
useDimensionsOnCanvas(canvasRef, boardWidth, boardHeight);
useEffect(() => {
// Update the current space indication
const selectedSpacesCanvas = canvasRef.current!;
const context = selectedSpacesCanvas.getContext("2d")!;
_renderSelectedSpaces(selectedSpacesCanvas, context, currentBoard, selectedSpaceIndices);
if (highlightedSpaceIndices) {
_highlightSpaces(selectedSpacesCanvas, context, highlightedSpaceIndices);
}
if (hoveredBoardEventIndex >= 0) {
const hoveredBoardEvent = currentBoard.boardevents?.[hoveredBoardEventIndex];
if (hoveredBoardEvent) {
_highlightBoardEventSpaces(selectedSpacesCanvas, context, hoveredBoardEvent);
}
}
}, [currentBoard, selectedSpaceIndices, highlightedSpaceIndices, hoveredBoardEventIndex]);
return (
<canvas ref={canvasRef} className="editor_current_space_canvas"></canvas>
);
};
const BoardSpaces = () => {
const canvasRef = useRef<Canvas>(null);
const board = useCurrentBoard();
const [boardWidth, boardHeight] = useBoardDimensions();
const imagesLoaded = useAppSelector(state => state.app.imagesLoaded);
useDimensionsOnCanvas(canvasRef, boardWidth, boardHeight);
useEffect(() => {
// Update spaces
const spaceCanvas = canvasRef.current!;
if (imagesLoaded) {
_renderSpaces(spaceCanvas, spaceCanvas.getContext("2d")!, board);
}
}, [board, imagesLoaded]);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas) {
attachToCanvas(canvas);
return () => detachFromCanvas(canvas);
}
}, []);
return (
<canvas className="editor_space_canvas" tabIndex={-1}
ref={canvasRef}
onDragOver={undefined}></canvas>
);
};
const BoardSelectionBox = () => {
const canvasRef = useRef<Canvas>(null);
const hasBoxDrawn = useRef<boolean>(false);
const selectionBoxCoords = useAppSelector(selectSelectionBoxCoords);
useEffect(() => {
const canvas = canvasRef.current!;
const ctx = canvas.getContext("2d")!;
if (selectionBoxCoords || (!selectionBoxCoords && hasBoxDrawn.current)) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
hasBoxDrawn.current = false;
}
if (selectionBoxCoords) {
const [xs, ys, xf, yf] = selectionBoxCoords;
ctx.save();
ctx.beginPath();
ctx.fillStyle = "rgba(47, 70, 95, 0.5)";
ctx.strokeStyle = "rgba(47, 70, 95, 1)";
ctx.fillRect(Math.min(xs, xf), Math.min(ys, yf), Math.abs(xs - xf), Math.abs(ys - yf));
ctx.strokeRect(Math.min(xs, xf), Math.min(ys, yf), Math.abs(xs - xf), Math.abs(ys - yf));
ctx.restore();
hasBoxDrawn.current = true;
}
}, [selectionBoxCoords]);
const [boardWidth, boardHeight] = useBoardDimensions();
useDimensionsOnCanvas(canvasRef, boardWidth, boardHeight);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas) {
attachToCanvas(canvas);
return () => detachFromCanvas(canvas);
}
}, []);
return (
<canvas className="editor_space_canvas" tabIndex={-1}
ref={canvasRef}
onDragOver={undefined}></canvas>
);
};
const BoardOverlay = forwardRef<BoardOverlayRef>((props, ref) => {
const [rightClickSpace, setRightClickSpace] = useState(-1);
const overlayDiv = useRef<HTMLDivElement>(null);
const [boardWidth, boardHeight] = useBoardDimensions();
const [editorWidth, editorHeight] = useContext(EditorSizeContext);
const renderContent = useCallback(() => {
const overlay = overlayDiv.current!;
const transformStyle = getEditorContentTransform(boardWidth, boardHeight, editorWidth, editorHeight);
overlay.style.transform = transformStyle;
}, [boardWidth, boardHeight, editorWidth, editorHeight]);
const setRightClickMenu = useCallback((spaceIndex: number) => {
setRightClickSpace(spaceIndex);
}, []);
const rightClickOpen = useCallback(() => {
return rightClickSpace >= 0;
}, [rightClickSpace]);
useImperativeHandle(ref, () => ({
renderContent,
setRightClickMenu,
rightClickOpen
}), [renderContent, setRightClickMenu, rightClickOpen]);
useEffect(() => {
renderContent();
});
const currentBoard = useCurrentBoard();
const space = currentBoard.spaces[rightClickSpace] || null;
return (
<div ref={overlayDiv} className="editor_menu_overlay">
{rightClickOpen() && <RightClickMenu space={space} spaceIndex={rightClickSpace} />}
</div>
);
});
const N64_SCREEN_WIDTH = 320;
const N64_SCREEN_HEIGHT = 240;
function getZoomedN64SizeForTelescope(gameVersion: GameVersion) {
let WIDTH_ZOOM_FACTOR = 1;
let HEIGHT_ZOOM_FACTOR = 1;
switch (gameVersion) {
case 1:
case 2:
break;
case 3:
WIDTH_ZOOM_FACTOR = 0.785;
HEIGHT_ZOOM_FACTOR = 0.805;
break;
}
const N64_WIDTH_ZOOMED = (N64_SCREEN_WIDTH * WIDTH_ZOOM_FACTOR);
const N64_HEIGHT_ZOOMED = (N64_SCREEN_HEIGHT * HEIGHT_ZOOM_FACTOR);
return {
N64_WIDTH_ZOOMED,
N64_HEIGHT_ZOOMED
};
}
function addRecommendedBoundaryLine(board: IBoard, canvas: Canvas): void {
const context = canvas.getContext("2d")!;
context.lineWidth = 1;
context.strokeStyle = "rgba(0, 0, 0, 0.5)";
const { width, height} = board.bg;
const { N64_WIDTH_ZOOMED, N64_HEIGHT_ZOOMED } = getZoomedN64SizeForTelescope(board.game);
context.strokeRect(N64_WIDTH_ZOOMED / 2, N64_HEIGHT_ZOOMED / 2, width - N64_WIDTH_ZOOMED, height - N64_HEIGHT_ZOOMED);
}
const TelescopeViewer: React.FC = () => {
const canvasRef = useRef<Canvas | null>(null);
const screenshotCanvasRef = useRef<Canvas | null>(null);
const board = useCurrentBoard();
const [boardWidth, boardHeight] = useBoardDimensions();
useDimensionsOnCanvas(canvasRef, boardWidth, boardHeight);
useEffect(() => {
const canvas = canvasRef.current!;
addRecommendedBoundaryLine(board, canvas);
}, [board]);
useEffect(() => {
(async () => {
const screenshotResult = await takeScreeny({ renderCharacters: true });
screenshotCanvasRef.current = screenshotResult.canvas;
addRecommendedBoundaryLine(board, screenshotCanvasRef.current!);
})();
}, [board]);
const onMouseMove = useCallback((ev: React.MouseEvent<Canvas>) => {
const canvas = canvasRef.current!;
const context = canvas.getContext("2d")!;
const screenshotCanvas = screenshotCanvasRef.current;
if (!screenshotCanvas) {
return;
}
const [clickX, clickY] = getMouseCoordsOnCanvas(canvas, ev.clientX, ev.clientY);
const { width, height } = board.bg;
const { N64_WIDTH_ZOOMED, N64_HEIGHT_ZOOMED } = getZoomedN64SizeForTelescope(board.game);
// The cutout from the board image, bounded like the game camera is.
let sx = Math.max(0, clickX - (N64_WIDTH_ZOOMED / 2));
let sy = Math.max(0, clickY - (N64_HEIGHT_ZOOMED / 2));
const sWidth = N64_WIDTH_ZOOMED;
const sHeight = N64_HEIGHT_ZOOMED;
if (width - sx < N64_WIDTH_ZOOMED) {
sx = width - N64_WIDTH_ZOOMED;
}
if (height - sy < N64_HEIGHT_ZOOMED) {
sy = height - N64_HEIGHT_ZOOMED;
}
$$log(`Viewing (${sx}, ${sy}) - (${sx + sWidth}, ${sy + sHeight})\nMouse: (${clickX}, ${clickY}`);
context.drawImage(
screenshotCanvas,
sx, sy, sWidth, sHeight,
0, 0, width, height
);
// Simulate the black bars the game has, which restrict the viewing area further.
const n64WidthRatio = width / N64_SCREEN_WIDTH;
const n64HeightRatio = height / N64_SCREEN_HEIGHT;
const horzBarHeight = 12 * n64HeightRatio;
const vertBarWidth = 16 * n64WidthRatio;
context.fillStyle = "black";
context.fillRect(0, 0, width, horzBarHeight); // top
context.fillRect(width - vertBarWidth, 0, vertBarWidth, height); // right
context.fillRect(0, height - horzBarHeight, width, horzBarHeight); // bottom
context.fillRect(0, 0, vertBarWidth, height); // left
}, [board]);
const onMouseLeave = useCallback(() => {
const canvas = canvasRef.current!;
const context = canvas.getContext("2d")!;
context.clearRect(0, 0, canvas.width, canvas.height);
addRecommendedBoundaryLine(board, canvas);
}, [board]);
return (
<canvas ref={canvasRef}
className="editor_telescope_viewer"
onMouseMove={onMouseMove}
onMouseLeave={onMouseLeave} />
);
};
interface BoardOverlayRef {
setRightClickMenu(spaceIndex: number): void;
rightClickOpen(): boolean;
}
let _boardOverlay: BoardOverlayRef | null;
const EditorSizeContext = React.createContext([0, 0]);
export const Editor: React.FC = () => {
const editorRef = useRef<HTMLDivElement | null>(null);
const [editorWidth, setEditorWidth] = useState(0);
const [editorHeight, setEditorHeight] = useState(0);
const editorSize = useMemo(() => {
return [editorWidth, editorHeight];
}, [editorWidth, editorHeight]);
const editorWidthChanged = useCallback(() => {
const editorDiv = editorRef.current;
if (editorDiv) {
setEditorWidth(editorDiv.offsetWidth);
setEditorHeight(editorDiv.offsetHeight);
}
}, []);
useEffect(() => {
window.addEventListener("resize", editorWidthChanged, false);
editorWidthChanged();
return () => window.removeEventListener("resize", editorWidthChanged);
}, [editorWidthChanged]);
const telescoping = useAppSelector(state => state.app.currentAction === Action.TELESCOPE);
return (
<div ref={editorRef} className="editor">
<EditorSizeContext.Provider value={editorSize}>
<BoardBG />
<BoardLines />
<BoardAssociations />
<BoardSelectedSpaces />
<BoardSpaces />
<BoardSelectionBox />
<BoardOverlay ref={c => _boardOverlay = c} />
{telescoping && <TelescopeViewer />}
</EditorSizeContext.Provider>
</div>
);
};
export function updateRightClickMenu(spaceIndex: number) {
if (_boardOverlay)
_boardOverlay.setRightClickMenu(spaceIndex);
}
export function rightClickOpen() {
if (_boardOverlay)
return _boardOverlay.rightClickOpen();
return false;
}
export function animationPlaying() {
return !!_animInterval;
}
export const external = {
renderConnections: _renderConnections,
renderSpaces: _renderSpaces
};
function getEditorContentTransform(boardWidth: number, boardHeight: number, editorWidth: number, editorHeight: number): string {
let board_offset_x = Math.floor((editorWidth - boardWidth) / 2);
board_offset_x = Math.max(0, board_offset_x);
let board_offset_y = Math.floor((editorHeight - boardHeight) / 2);
board_offset_y = Math.max(0, board_offset_y);
return `translateX(${board_offset_x}px) translateY(${board_offset_y}px)`;
}
function useDimensionsOnCanvas(canvasRef: React.RefObject<Canvas>, boardWidth: number, boardHeight: number) {
const [editorWidth, editorHeight] = useContext(EditorSizeContext);
useLayoutEffect(() => {
const canvas = canvasRef.current!;
const transformStyle = getEditorContentTransform(boardWidth, boardHeight, editorWidth, editorHeight);
canvas.style.transform = transformStyle;
if (canvas.width !== boardWidth || canvas.height !== boardHeight) {
canvas.width = boardWidth;
canvas.height = boardHeight;
}
}, [canvasRef, boardWidth, boardHeight, editorWidth, editorHeight]);
}
function useBoardDimensions() {
const width = useAppSelector(state => selectCurrentBoard(state).bg.width);
const height = useAppSelector(state => selectCurrentBoard(state).bg.height);
return useMemo(() => [width, height], [width, height]);
} | the_stack |
import { ADMIN } from '@/role'
import { chainSummary, clone } from '@/util'
import { setup as userSetup } from '@/util/testing'
import { append, merge } from 'crdx'
import { createTeam } from './createTeam'
import { redactUser } from './redactUser'
import { TeamAction, TeamSignatureChain } from './types'
describe('chains', () => {
describe('membershipResolver', () => {
const setup = () => {
// 👩🏾 Alice creates a chain
let aChain: TeamSignatureChain = createTeam('Spies Я Us', alice.localContext).chain
// 👩🏾 Alice adds 👨🏻🦲 Bob as admin
aChain = append({
chain: aChain,
action: ADD_BOB_AS_ADMIN,
user: alice.user,
context: alice.chainContext,
})
// 👩🏾 🡒 👨🏻🦲 Alice shares the chain with Bob
let bChain: TeamSignatureChain = clone(aChain)
return { aChain, bChain }
}
it('resolves two chains with no conflicting membership changes', () => {
// 👩🏾 🡒 👨🏻🦲 Alice creates a chain and shares it with Bob
let { aChain, bChain } = setup()
// 🔌❌ Now Alice and Bob are disconnected
// 👨🏻🦲 Bob makes a change
bChain = append({
chain: bChain,
action: ADD_ROLE_MANAGERS,
user: bob.user,
context: bob.chainContext,
})
expect(summary(bChain)).toEqual('ROOT,ADD:bob,ADD:managers')
// 👩🏾 Concurrently,Alice makes a change
aChain = append({
chain: aChain,
action: ADD_CHARLIE,
user: alice.user,
context: alice.chainContext,
})
expect(summary(aChain)).toEqual('ROOT,ADD:bob,ADD:charlie')
// 🔌✔ Alice and Bob reconnect and synchronize chains
// ✅ the result will be one of these two (could be either because timestamps change with each test run)
expectMergedResult(aChain, bChain, [
'ROOT,ADD:bob,ADD:charlie,ADD:managers',
'ROOT,ADD:bob,ADD:managers,ADD:charlie',
])
})
it('discards changes made by a member who is concurrently removed', () => {
// 👩🏾 🡒 👨🏻🦲 Alice creates a chain and shares it with Bob
let { aChain, bChain } = setup()
// 🔌❌ Now Alice and Bob are disconnected
// 👨🏻🦲 Bob adds Charlie to the group
bChain = append({
chain: bChain,
action: ADD_CHARLIE,
user: bob.user,
context: bob.chainContext,
})
expect(summary(bChain)).toEqual('ROOT,ADD:bob,ADD:charlie')
// 👩🏾 but concurrently,Alice removes Bob from the group
aChain = append({
chain: aChain,
action: REMOVE_BOB,
user: alice.user,
context: alice.chainContext,
})
expect(summary(aChain)).toEqual('ROOT,ADD:bob,REMOVE:bob')
// 🔌✔ Alice and Bob reconnect and synchronize chains
// ✅ Bob's change is discarded - Charlie is not added
expectMergedResult(aChain, bChain, 'ROOT,ADD:bob,REMOVE:bob')
})
it('discards changes made by a member who is concurrently demoted', () => {
// 👩🏾 🡒 👨🏻🦲 Alice creates a chain and shares it with Bob
let { aChain, bChain } = setup()
// 🔌❌ Now Alice and Bob are disconnected
// 👨🏻🦲 Bob adds Charlie to the group
bChain = append({
chain: bChain,
action: ADD_CHARLIE,
user: bob.user,
context: bob.chainContext,
})
expect(summary(bChain)).toEqual('ROOT,ADD:bob,ADD:charlie')
// 👩🏾 but concurrently,Alice removes Bob from the admin role
aChain = append({
chain: aChain,
action: DEMOTE_BOB,
user: alice.user,
context: alice.chainContext,
})
expect(summary(aChain)).toEqual('ROOT,ADD:bob,REMOVE:admin:bob')
// 🔌✔ Alice and Bob reconnect and synchronize chains
// ✅ Bob's change is discarded
expectMergedResult(aChain, bChain, 'ROOT,ADD:bob,REMOVE:admin:bob')
})
// TODO: This doesn't really tell us anything since it doesn't cover INVITE_MEMBER, which is how
// members are actually added
it(`doesn't allow a member who is removed to be concurrently added back`, () => {
// 👩🏾 Alice creates a chain and adds Charlie
let { aChain } = setup()
aChain = append({
chain: aChain,
action: ADD_CHARLIE,
user: alice.user,
context: alice.chainContext,
})
// 👩🏾 🡒 👨🏻🦲 Alice shares the chain with Bob
let bChain = clone(aChain)
// 🔌❌ Now Alice and Bob are disconnected
// 👩🏾 Alice removes Charlie
aChain = append({
chain: aChain,
action: REMOVE_CHARLIE,
user: alice.user,
context: alice.chainContext,
})
expect(summary(aChain)).toEqual('ROOT,ADD:bob,ADD:charlie,REMOVE:charlie')
// 👨🏻🦲 Bob removes Charlie then adds him back
bChain = append({
chain: bChain,
action: REMOVE_CHARLIE,
user: bob.user,
context: bob.chainContext,
})
bChain = append({
chain: bChain,
action: ADD_CHARLIE,
user: bob.user,
context: bob.chainContext,
})
expect(summary(bChain)).toEqual('ROOT,ADD:bob,ADD:charlie,REMOVE:charlie,ADD:charlie')
// 🔌✔ Alice and Bob reconnect and synchronize chains
// ✅ Charlie isn't added back
expectMergedResult(aChain, bChain, 'ROOT,ADD:bob,ADD:charlie,REMOVE:charlie,REMOVE:charlie')
})
it('resolves mutual concurrent removals in favor of the team founder', () => {
// 👩🏾 🡒 👨🏻🦲 Alice creates a chain and shares it with Bob
let { aChain, bChain } = setup()
// 🔌❌ Now Alice and Bob are disconnected
// 👨🏻🦲 Bob removes Alice
bChain = append({
chain: bChain,
action: REMOVE_ALICE,
user: bob.user,
context: bob.chainContext,
})
// 👩🏾 Alice removes Bob
aChain = append({
chain: aChain,
action: REMOVE_BOB,
user: alice.user,
context: alice.chainContext,
})
// 🔌✔ Alice and Bob reconnect and synchronize chains
// ✅ Alice created the team; Bob's change is discarded,Alice stays
expectMergedResult(aChain, bChain, 'ROOT,ADD:bob,REMOVE:bob')
})
it('resolves mutual concurrent removals in favor of the senior member', () => {
// 👩🏾 Alice creates a chain and adds Charlie
let { aChain } = setup()
aChain = append({
chain: aChain,
action: ADD_CHARLIE_AS_ADMIN,
user: alice.user,
context: alice.chainContext,
})
// 👩🏾 🡒 👨🏻🦲 👳🏽♂️ Alice shares the chain with Bob and Charlie
let bChain = clone(aChain)
let cChain = clone(aChain)
// 🔌❌ Now Bob and Charlie are disconnected
// 👨🏻🦲 Bob removes Charlie
bChain = append({
chain: bChain,
action: REMOVE_CHARLIE,
user: bob.user,
context: bob.chainContext,
})
// 👳🏽♂️ Charlie removes Bob
cChain = append({
chain: cChain,
action: REMOVE_BOB,
user: charlie.user,
context: charlie.chainContext,
})
// 🔌✔ Bob and Charlie reconnect and synchronize chains
// ✅ Bob was added first; Charlie's change is discarded,Bob stays
expectMergedResult(bChain, cChain, 'ROOT,ADD:bob,ADD:charlie,REMOVE:charlie')
})
it('resolves mutual concurrent demotions in favor of the team founder', () => {
// 👩🏾 🡒 👨🏻🦲 Alice creates a chain and shares it with Bob
let { aChain, bChain } = setup()
// 🔌❌ Now Alice and Bob are disconnected
// 👨🏻🦲 Bob demotes Alice
bChain = append({
chain: bChain,
action: DEMOTE_ALICE,
user: bob.user,
context: bob.chainContext,
})
// 👩🏾 Alice demotes Bob
aChain = append({
chain: aChain,
action: DEMOTE_BOB,
user: alice.user,
context: alice.chainContext,
})
// 🔌✔ Alice and Bob reconnect and synchronize chains
// ✅ Alice created the team; Bob's change is discarded,Alice is still an admin
expectMergedResult(aChain, bChain, 'ROOT,ADD:bob,REMOVE:admin:bob')
})
it('resolves circular mutual concurrent demotions in favor of the team founder', () => {
// 👩🏾 🡒 👨🏻🦲 Alice creates a chain and adds Charlie as admin
let { aChain } = setup()
aChain = append({
chain: aChain,
action: ADD_CHARLIE_AS_ADMIN,
user: alice.user,
context: alice.chainContext,
})
// 👩🏾 🡒 👨🏻🦲 Alice shares the chain with Bob and Charlie
let bChain = clone(aChain)
let cChain = clone(aChain)
// 🔌❌ Now Alice and Bob are disconnected
// 👨🏻🦲 Bob demotes Charlie
bChain = append({
chain: bChain,
action: DEMOTE_CHARLIE,
user: bob.user,
context: bob.chainContext,
})
// 👳🏽♂️ Charlie demotes Alice
cChain = append({
chain: cChain,
action: DEMOTE_ALICE,
user: charlie.user,
context: charlie.chainContext,
})
// 👩🏾 Alice demotes Bob
aChain = append({
chain: aChain,
action: DEMOTE_BOB,
user: alice.user,
context: alice.chainContext,
})
// 🔌✔ All reconnect and synchronize chains
// This could happen three different ways - make sure the result is the same in all cases
const mergedChains = [
merge(aChain, merge(cChain, bChain)),
merge(bChain, merge(cChain, aChain)),
merge(cChain, merge(aChain, bChain)),
]
// ✅ Alice created the team; Bob's change is discarded,Alice is still an admin
const expected = 'ROOT,ADD:bob,ADD:charlie,REMOVE:admin:bob'
for (const chain of mergedChains) expect(summary(chain)).toBe(expected)
})
const expectMergedResult = (
aChain: TeamSignatureChain,
bChain: TeamSignatureChain,
expected: string[] | string
) => {
if (!Array.isArray(expected)) expected = [expected] as string[] // coerce to array
// 👩🏾 ⇄ 👨🏻🦲 They synchronize chains
const mergedChain = merge(aChain, bChain)
// The resolved sequence should match one of the provided options
expect(expected).toContain(summary(mergedChain))
}
const summary = (chain: TeamSignatureChain) =>
chainSummary(chain)
.replace(/_MEMBER/g, '')
.replace(/_ROLE/g, '')
const { alice, bob, charlie } = userSetup('alice', 'bob', 'charlie')
// constant actions
const REMOVE_ALICE = {
type: 'REMOVE_MEMBER',
payload: { userName: 'alice' },
} as TeamAction
const DEMOTE_ALICE = {
type: 'REMOVE_MEMBER_ROLE',
payload: { userName: 'alice', roleName: ADMIN },
} as TeamAction
const ADD_BOB_AS_ADMIN = {
type: 'ADD_MEMBER',
payload: { member: redactUser(bob.user), roles: [ADMIN] },
} as TeamAction
const REMOVE_BOB = {
type: 'REMOVE_MEMBER',
payload: { userName: 'bob' },
} as TeamAction
const DEMOTE_BOB = {
type: 'REMOVE_MEMBER_ROLE',
payload: { userName: 'bob', roleName: ADMIN },
} as TeamAction
const ADD_CHARLIE = {
type: 'ADD_MEMBER',
payload: { member: redactUser(charlie.user) },
} as TeamAction
const ADD_CHARLIE_AS_ADMIN = {
type: 'ADD_MEMBER',
payload: { member: redactUser(charlie.user), roles: [ADMIN] },
} as TeamAction
const REMOVE_CHARLIE = {
type: 'REMOVE_MEMBER',
payload: { userName: 'charlie' },
} as TeamAction
const DEMOTE_CHARLIE = {
type: 'REMOVE_MEMBER_ROLE',
payload: { userName: 'charlie', roleName: ADMIN },
} as TeamAction
const ADD_ROLE_MANAGERS = {
type: 'ADD_ROLE',
payload: { roleName: 'managers' },
} as TeamAction
const ADD_CHARLIE_TO_MANAGERS = {
type: 'ADD_MEMBER_ROLE',
payload: { userName: 'charlie', roleName: 'managers' },
} as TeamAction
/**
TODO simulate this situation from connection.test
20201229 OK. What's happening here is that sometimes (50% of the time?) when we eliminate duplicate
ADD_MEMBERs,we're eliminating one that would have needed to have come BEFORE something else,
in this case the CHANGE_MEMBER_KEYs action that happens after that person is admitted.
Here's an example of a bad chain that you can end up with that way:
👩🏾 ROOT
ADD_MEMBER:👨🦲
<== ADD_MEMBER:👳🏽♂️ was removed from here
INVITE:kPFx4gwGpuWplwa
INVITE:tiKXBLLdMbDndJE
ADMIT:👳🏽♂️
CHANGE_MEMBER_KEYS:{"type":"MEMBER","name":"👳🏽♂️",...} <== we can't do this because 👳🏽♂️ hasn't been added yet
ADD_DEVICE:👳🏽♂️:laptop
ADD_MEMBER:👳🏽♂️
INVITE:dQRE52A+7UGr8X9
ADD_MEMBER:👴
INVITE:j6cC8ZyjyhuojZw
ADMIT:👴
CHANGE_MEMBER_KEYS:{"type":"MEMBER","name":"👴",...}
ADD_DEVICE:👴:laptop
Here's how that chain should have been resolved:
👩🏾 ROOT
ADD_MEMBER:👨🦲
ADD_MEMBER:👳🏽♂️ <== in the bad chain,this ADD_MEMBER was discarded as a duplicate
INVITE:fNpSg0uBcW1vYvf
ADD_MEMBER:👴
INVITE:PkD7SISvUt/3YlJ
ADMIT:👳🏽♂️
CHANGE_MEMBER_KEYS:{"type":"MEMBER","name":"👳🏽♂️",...}
ADD_DEVICE:👳🏽♂️:laptop
<== ADD_MEMBER:👳🏽♂️ was removed from here
INVITE:Pu6NaY6HfbITAf6
INVITE:7vVS0NXz+u15Mx2
ADMIT:👴
CHANGE_MEMBER_KEYS:{"type":"MEMBER","name":"👴",...}
ADD_DEVICE:👴:laptop
*/
})
}) | the_stack |
import type { Linter } from 'eslint'
import { rules as reactPluginRules } from 'eslint-plugin-react'
import { rules as reactHooksPluginRules } from 'eslint-plugin-react-hooks'
import { rules as jsxA11yPluginRules } from 'eslint-plugin-jsx-a11y'
import eslintImportRuleFirst from 'eslint-plugin-import/lib/rules/first'
import eslintImportRuleNoAmd from 'eslint-plugin-import/lib/rules/no-amd'
import eslintImportRuleNoWebpackSyntax from 'eslint-plugin-import/lib/rules/no-webpack-loader-syntax'
const EsLintRecommended: Linter.RulesRecord = {
// Currently on 6.8.0 ruleset: https://github.com/eslint/eslint/blob/v6.8.0/conf/eslint-recommended.js
// This requires manually updating on each release. Urgh.
'constructor-super': 'error',
'for-direction': 'error',
'getter-return': 'error',
'no-async-promise-executor': 'error',
'no-case-declarations': 'error',
'no-class-assign': 'error',
'no-compare-neg-zero': 'error',
'no-cond-assign': 'error',
'no-const-assign': 'error',
'no-constant-condition': 'error',
'no-control-regex': 'error',
'no-debugger': 'error',
'no-delete-var': 'error',
'no-dupe-args': 'error',
'no-dupe-class-members': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-empty': 'error',
'no-empty-character-class': 'error',
'no-empty-pattern': 'error',
'no-ex-assign': 'error',
'no-extra-boolean-cast': 'error',
'no-extra-semi': 'error',
'no-fallthrough': 'error',
'no-func-assign': 'error',
'no-global-assign': 'error',
'no-inner-declarations': 'error',
'no-invalid-regexp': 'error',
'no-irregular-whitespace': 'error',
'no-misleading-character-class': 'error',
'no-mixed-spaces-and-tabs': 'error',
'no-new-symbol': 'error',
'no-obj-calls': 'error',
'no-octal': 'error',
'no-prototype-builtins': 'error',
'no-redeclare': 'error',
'no-regex-spaces': 'error',
'no-self-assign': 'error',
'no-shadow-restricted-names': 'error',
'no-sparse-arrays': 'error',
'no-this-before-super': 'error',
'no-undef': 'error',
'no-unexpected-multiline': 'error',
'no-unreachable': 'error',
'no-unsafe-finally': 'error',
'no-unsafe-negation': 'error',
'no-unused-labels': 'error',
'no-unused-vars': 'warn',
'no-useless-catch': 'error',
'no-useless-escape': 'error',
'no-with': 'error',
'require-yield': 'error',
'use-isnan': 'error',
'valid-typeof': 'error',
}
export const ESLINT_CONFIG: Linter.Config = {
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module',
ecmaFeatures: {
jsx: true,
modules: true,
},
},
env: {
es2020: true,
browser: true,
},
extends: [], // Not supported in browser - to add these, you have to explicitly add them below
plugins: [], // plugin rules are loaded using the CustomUtopiaLinter
globals: {
__DEV__: false,
__dirname: false,
alert: false,
Blob: false,
cancelAnimationFrame: false,
cancelIdleCallback: false,
clearImmediate: true,
clearInterval: false,
clearTimeout: false,
console: false,
escape: false,
Event: false,
EventTarget: false,
exports: false,
fetch: false,
File: false,
FileReader: false,
FormData: false,
global: false,
Map: true,
module: false,
navigator: false,
process: false,
Promise: true,
requestAnimationFrame: true,
requestIdleCallback: true,
require: false,
Set: true,
setImmediate: true,
setInterval: false,
setTimeout: false,
WebSocket: false,
window: false,
XMLHttpRequest: false,
},
rules: {
...EsLintRecommended,
// basic eslint rules
// http://eslint.org/docs/rules/
'array-callback-return': 'warn',
'default-case': ['warn', { commentPattern: '^no default$' }],
'dot-location': ['warn', 'property'],
eqeqeq: ['warn', 'smart'],
'new-parens': 'warn',
'no-array-constructor': 'warn',
'no-caller': 'warn',
'no-cond-assign': ['warn', 'except-parens'],
'no-const-assign': 'warn',
'no-control-regex': 'warn',
'no-delete-var': 'warn',
'no-dupe-args': 'warn',
'no-dupe-class-members': 'warn',
'no-dupe-keys': 'warn',
'no-duplicate-case': 'warn',
'no-empty-character-class': 'warn',
'no-empty-pattern': 'warn',
'no-eval': 'warn',
'no-ex-assign': 'warn',
'no-extend-native': 'warn',
'no-extra-bind': 'warn',
'no-extra-label': 'warn',
'no-fallthrough': 'warn',
'no-func-assign': 'warn',
'no-implied-eval': 'warn',
'no-invalid-regexp': 'warn',
'no-iterator': 'warn',
'no-label-var': 'warn',
'no-labels': ['warn', { allowLoop: true, allowSwitch: false }],
'no-lone-blocks': 'warn',
'no-loop-func': 'warn',
'no-mixed-operators': [
'warn',
{
groups: [
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: false,
},
],
'no-multi-str': 'warn',
'no-native-reassign': 'warn',
'no-negated-in-lhs': 'warn',
'no-new-func': 'warn',
'no-new-object': 'warn',
'no-new-symbol': 'warn',
'no-new-wrappers': 'warn',
'no-obj-calls': 'warn',
'no-octal': 'warn',
'no-octal-escape': 'warn',
'no-regex-spaces': 'warn',
'no-restricted-syntax': ['warn', 'WithStatement'],
'no-script-url': 'warn',
'no-self-assign': 'warn',
'no-self-compare': 'warn',
'no-sequences': 'warn',
'no-shadow-restricted-names': 'warn',
'no-sparse-arrays': 'warn',
'no-template-curly-in-string': 'warn',
'no-this-before-super': 'warn',
'no-throw-literal': 'warn',
'no-undef': 'error',
'no-unreachable': 'warn',
'no-unused-expressions': [
'error',
{
allowShortCircuit: true,
allowTernary: true,
allowTaggedTemplates: true,
},
],
'no-unused-labels': 'warn',
// disabling 'no-unused-vars' because the current ui.js is not working nicely with it
// 'no-unused-vars': [
// 'warn',
// {
// args: 'none',
// ignoreRestSiblings: true,
// },
// ],
'no-use-before-define': [
'error',
{
functions: false,
classes: true,
variables: true,
},
],
'no-useless-computed-key': 'warn',
'no-useless-concat': 'warn',
'no-useless-constructor': 'warn',
'no-useless-escape': 'warn',
'no-useless-rename': [
'warn',
{
ignoreDestructuring: false,
ignoreImport: false,
ignoreExport: false,
},
],
'no-with': 'warn',
'no-whitespace-before-property': 'warn',
'require-yield': 'warn',
'rest-spread-spacing': ['warn', 'never'],
strict: ['warn', 'never'],
'unicode-bom': ['warn', 'never'],
'use-isnan': 'warn',
'valid-typeof': 'warn',
'no-restricted-properties': [
'error',
{
object: 'require',
property: 'ensure',
message:
'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting',
},
{
object: 'System',
property: 'import',
message:
'Please use import() instead. More info: https://facebook.github.io/create-react-app/docs/code-splitting',
},
],
'getter-return': 'warn',
// PLUGINS
// to use a rule from a plugin please add and load them first in EslintPluginRules
// https://github.com/yannickcr/eslint-plugin-react/tree/master/docs/rules
'react/forbid-foreign-prop-types': ['warn', { allowInPropTypes: true }],
'react/jsx-no-comment-textnodes': 'warn',
'react/jsx-no-duplicate-props': 'warn',
'react/jsx-no-target-blank': 'warn',
'react/jsx-no-undef': 'error',
'react/jsx-pascal-case': [
'warn',
{
allowAllCaps: true,
ignore: [],
},
],
'react/jsx-uses-vars': 'warn',
'react/no-danger-with-children': 'warn',
'react/no-deprecated': 'warn',
'react/no-direct-mutation-state': 'warn',
'react/no-is-mounted': 'warn',
'react/no-typos': 'error',
'react/require-render-return': 'error',
'react/style-prop-object': 'warn',
// https://github.com/facebook/react/tree/master/packages/eslint-plugin-react-hooks
'react-hooks/exhaustive-deps': 'warn',
'react-hooks/rules-of-hooks': 'error',
// https://github.com/benmosher/eslint-plugin-import/tree/master/docs/rules
'import/first': 'error',
'import/no-amd': 'error',
'import/no-webpack-loader-syntax': 'error',
// https://github.com/evcohen/eslint-plugin-jsx-a11y/tree/master/docs/rules
'jsx-a11y/accessible-emoji': 'warn',
'jsx-a11y/alt-text': 'warn',
'jsx-a11y/anchor-has-content': 'warn',
'jsx-a11y/anchor-is-valid': [
'warn',
{
aspects: ['noHref', 'invalidHref'],
},
],
'jsx-a11y/aria-activedescendant-has-tabindex': 'warn',
'jsx-a11y/aria-props': 'warn',
'jsx-a11y/aria-proptypes': 'warn',
'jsx-a11y/aria-role': ['warn', { ignoreNonDOM: true }],
'jsx-a11y/aria-unsupported-elements': 'warn',
'jsx-a11y/heading-has-content': 'warn',
'jsx-a11y/iframe-has-title': 'warn',
'jsx-a11y/img-redundant-alt': 'warn',
'jsx-a11y/no-access-key': 'warn',
'jsx-a11y/no-distracting-elements': 'warn',
'jsx-a11y/no-redundant-roles': 'warn',
'jsx-a11y/role-has-required-aria-props': 'warn',
'jsx-a11y/role-supports-aria-props': 'warn',
'jsx-a11y/scope': 'warn',
},
settings: {
react: {
version: '17.0.0-rc.1',
},
},
}
const EslintPluginReactRules = {
'react/jsx-boolean-value': reactPluginRules['jsx-boolean-value'],
'react/jsx-child-element-spacing': reactPluginRules['jsx-child-element-spacing'],
'react/jsx-closing-bracket-location': reactPluginRules['jsx-closing-bracket-location'],
'react/jsx-closing-tag-location': reactPluginRules['jsx-closing-tag-location'],
'react/jsx-curly-brace-presence': reactPluginRules['jsx-curly-brace-presence'],
'react/jsx-curly-newline': reactPluginRules['jsx-curly-newline'],
'react/jsx-curly-spacing': reactPluginRules['jsx-curly-spacing'],
'react/jsx-equals-spacing': reactPluginRules['jsx-equals-spacing'],
'react/jsx-filename-extension': reactPluginRules['jsx-filename-extension'],
'react/jsx-first-prop-new-line': reactPluginRules['jsx-first-prop-new-line'],
'react/jsx-fragments': reactPluginRules['jsx-fragments'],
'react/jsx-handler-names': reactPluginRules['jsx-handler-names'],
'react/jsx-indent': reactPluginRules['jsx-indent'],
'react/jsx-indent-props': reactPluginRules['jsx-indent-props'],
'react/jsx-key': reactPluginRules['jsx-key'],
'react/jsx-max-depth': reactPluginRules['jsx-max-depth'],
'react/jsx-max-props-per-line': reactPluginRules['jsx-max-props-per-line'],
'react/jsx-no-bind': reactPluginRules['jsx-no-bind'],
'react/jsx-no-comment-textnodes': reactPluginRules['jsx-no-comment-textnodes'],
'react/jsx-no-duplicate-props': reactPluginRules['jsx-no-duplicate-props'],
'react/jsx-no-literals': reactPluginRules['jsx-no-literals'],
'react/jsx-no-script-url': reactPluginRules['jsx-no-script-url'],
'react/jsx-no-target-blank': reactPluginRules['jsx-no-target-blank'],
'react/jsx-no-undef': reactPluginRules['jsx-no-undef'],
'react/jsx-no-useless-fragment': reactPluginRules['jsx-no-useless-fragment'],
'react/jsx-one-expression-per-line': reactPluginRules['jsx-one-expression-per-line'],
'react/jsx-pascal-case': reactPluginRules['jsx-pascal-case'],
'react/jsx-props-no-multi-spaces': reactPluginRules['jsx-props-no-multi-spaces'],
'react/jsx-props-no-spreading': reactPluginRules['jsx-props-no-spreading'],
'react/jsx-sort-default-props': reactPluginRules['jsx-sort-default-props'],
'react/jsx-sort-props': reactPluginRules['jsx-sort-props'],
'react/jsx-space-before-closing': reactPluginRules['jsx-space-before-closing'],
'react/jsx-tag-spacing': reactPluginRules['jsx-tag-spacing'],
'react/jsx-uses-vars': reactPluginRules['jsx-uses-vars'],
'react/jsx-wrap-multilines': reactPluginRules['jsx-wrap-multilines'],
'react/boolean-prop-naming': reactPluginRules['boolean-prop-naming'],
'react/button-has-type': reactPluginRules['button-has-type'],
'react/default-props-match-prop-types': reactPluginRules['default-props-match-prop-types'],
'react/destructuring-assignment': reactPluginRules['destructuring-assignment'],
'react/display-name': reactPluginRules['display-name'],
'react/forbid-component-props': reactPluginRules['forbid-component-props'],
'react/forbid-dom-props': reactPluginRules['forbid-dom-props'],
'react/forbid-elements': reactPluginRules['forbid-elements'],
'react/forbid-foreign-prop-types': reactPluginRules['forbid-foreign-prop-types'],
'react/forbid-prop-types': reactPluginRules['forbid-prop-types'],
'react/function-component-definition': reactPluginRules['function-component-definition'],
'react/no-access-state-in-setstate': reactPluginRules['no-access-state-in-setstate'],
'react/no-adjacent-inline-elements': reactPluginRules['no-adjacent-inline-elements'],
'react/no-array-index-key': reactPluginRules['no-array-index-key'],
'react/no-children-prop': reactPluginRules['no-children-prop'],
'react/no-danger': reactPluginRules['no-danger'],
'react/no-danger-with-children': reactPluginRules['no-danger-with-children'],
'react/no-deprecated': reactPluginRules['no-deprecated'],
'react/no-did-mount-set-state': reactPluginRules['no-did-mount-set-state'],
'react/no-did-update-set-state': reactPluginRules['no-did-update-set-state'],
'react/no-direct-mutation-state': reactPluginRules['no-direct-mutation-state'],
'react/no-find-dom-node': reactPluginRules['no-find-dom-node'],
'react/no-is-mounted': reactPluginRules['no-is-mounted'],
'react/no-multi-comp': reactPluginRules['no-multi-comp'],
'react/no-redundant-should-component-update':
reactPluginRules['no-redundant-should-component-update'],
'react/no-render-return-value': reactPluginRules['no-render-return-value'],
'react/no-set-state': reactPluginRules['no-set-state'],
'react/no-string-refs': reactPluginRules['no-string-refs'],
'react/no-this-in-sfc': reactPluginRules['no-this-in-sfc'],
'react/no-typos': reactPluginRules['no-typos'],
'react/no-unescaped-entities': reactPluginRules['no-unescaped-entities'],
'react/no-unknown-property': reactPluginRules['no-unknown-property'],
'react/no-unsafe': reactPluginRules['no-unsafe'],
'react/no-unused-prop-types': reactPluginRules['no-unused-prop-types'],
'react/no-unused-state': reactPluginRules['no-unused-state'],
'react/no-will-update-set-state': reactPluginRules['no-will-update-set-state'],
'react/prefer-es6-class': reactPluginRules['prefer-es6-class'],
'react/prefer-read-only-props': reactPluginRules['prefer-read-only-props'],
'react/prefer-stateless-function': reactPluginRules['prefer-stateless-function'],
'react/prop-types': reactPluginRules['prop-types'],
'react/require-default-props': reactPluginRules['require-default-props'],
'react/require-optimization': reactPluginRules['require-optimization'],
'react/require-render-return': reactPluginRules['require-render-return'],
'react/self-closing-comp': reactPluginRules['self-closing-comp'],
'react/sort-comp': reactPluginRules['sort-comp'],
'react/sort-prop-types': reactPluginRules['sort-prop-types'],
'react/state-in-constructor': reactPluginRules['state-in-constructor'],
'react/static-property-placement': reactPluginRules['static-property-placement'],
'react/style-prop-object': reactPluginRules['style-prop-object'],
'react/void-dom-elements-no-children': reactPluginRules['void-dom-elements-no-children'],
}
const EslintPluginReactHooksRules = {
'react-hooks/exhaustive-deps': reactHooksPluginRules['exhaustive-deps'],
'react-hooks/rules-of-hooks': reactHooksPluginRules['rules-of-hooks'],
}
const EslintPluginImportRules = {
'import/first': eslintImportRuleFirst,
'import/no-amd': eslintImportRuleNoAmd,
'import/no-webpack-loader-syntax': eslintImportRuleNoWebpackSyntax,
}
const EslintPluginJsxA11yRules = {
'jsx-a11y/accessible-emoji': jsxA11yPluginRules['accessible-emoji'],
'jsx-a11y/alt-text': jsxA11yPluginRules['alt-text'],
'jsx-a11y/anchor-has-content': jsxA11yPluginRules['anchor-has-content'],
'jsx-a11y/anchor-is-valid': jsxA11yPluginRules['anchor-is-valid'],
'jsx-a11y/aria-activedescendant-has-tabindex':
jsxA11yPluginRules['aria-activedescendant-has-tabindex'],
'jsx-a11y/aria-props': jsxA11yPluginRules['aria-props'],
'jsx-a11y/aria-proptypes': jsxA11yPluginRules['aria-proptypes'],
'jsx-a11y/aria-role': jsxA11yPluginRules['aria-role'],
'jsx-a11y/aria-unsupported-elements': jsxA11yPluginRules['aria-unsupported-elements'],
'jsx-a11y/heading-has-content': jsxA11yPluginRules['heading-has-content'],
'jsx-a11y/iframe-has-title': jsxA11yPluginRules['iframe-has-title'],
'jsx-a11y/img-redundant-alt': jsxA11yPluginRules['img-redundant-alt'],
'jsx-a11y/no-access-key': jsxA11yPluginRules['no-access-key'],
'jsx-a11y/no-distracting-elements': jsxA11yPluginRules['no-distracting-elements'],
'jsx-a11y/no-redundant-roles': jsxA11yPluginRules['no-redundant-roles'],
'jsx-a11y/role-has-required-aria-props': jsxA11yPluginRules['role-has-required-aria-props'],
'jsx-a11y/role-supports-aria-props': jsxA11yPluginRules['role-supports-aria-props'],
'jsx-a11y/scope': jsxA11yPluginRules['scope'],
}
export const EslintPluginRules = {
...EslintPluginReactRules,
...EslintPluginReactHooksRules,
...EslintPluginImportRules,
...EslintPluginJsxA11yRules,
} | the_stack |
import {
Mutable,
Class,
Proto,
Arrays,
HashCode,
Comparator,
FromAny,
Creatable,
InitType,
Initable,
ObserverType,
Observable,
ObserverMethods,
ObserverParameters,
ConsumerType,
Consumable,
Consumer,
} from "@swim/util";
import {FastenerContext, Fastener, Property, Provider} from "@swim/component";
import {WarpRef, WarpService, WarpProvider, DownlinkFastener} from "@swim/client";
import {ModelContextType, ModelFlags, AnyModel, ModelCreator, Model} from "../model/Model";
import {ModelRelation} from "../model/ModelRelation";
import type {TraitObserver} from "./TraitObserver";
import {TraitRelation} from "./"; // forward import
/** @public */
export type TraitModelType<T extends Trait> = T extends {readonly model: infer M | null} ? M : never;
/** @public */
export type TraitContextType<T extends Trait> = ModelContextType<TraitModelType<T>>;
/** @public */
export type TraitFlags = number;
/** @public */
export type AnyTrait<T extends Trait = Trait> = T | TraitFactory<T> | InitType<T>;
/** @public */
export interface TraitInit {
/** @internal */
uid?: never, // force type ambiguity between Trait and TraitInit
type?: Creatable<Trait>;
key?: string;
traits?: AnyTrait[];
}
/** @public */
export interface TraitFactory<T extends Trait = Trait, U = AnyTrait<T>> extends Creatable<T>, FromAny<T, U> {
fromInit(init: InitType<T>): T;
}
/** @public */
export interface TraitClass<T extends Trait = Trait, U = AnyTrait<T>> extends Function, TraitFactory<T, U> {
readonly prototype: T;
}
/** @public */
export interface TraitConstructor<T extends Trait = Trait, U = AnyTrait<T>> extends TraitClass<T, U> {
new(): T;
}
/** @public */
export type TraitCreator<F extends (abstract new (...args: any) => T) & Creatable<InstanceType<F>>, T extends Trait = Trait> =
(abstract new (...args: any) => InstanceType<F>) & Creatable<InstanceType<F>>;
/** @public */
export abstract class Trait implements HashCode, Initable<TraitInit>, Observable, Consumable, FastenerContext {
constructor() {
this.uid = (this.constructor as typeof Trait).uid();
this.key = void 0;
this.flags = 0;
this.model = null;
this.nextTrait = null;
this.previousTrait = null;
this.fasteners = null;
this.decoherent = null;
this.observers = Arrays.empty;
this.consumers = Arrays.empty;
FastenerContext.init(this);
}
readonly observerType?: Class<TraitObserver>;
/** @override */
readonly consumerType?: Class<Consumer>;
/** @internal */
readonly uid: number;
readonly key: string | undefined;
/** @internal */
setKey(key: string | undefined): void {
(this as Mutable<this>).key = key;
}
/** @internal */
readonly flags: TraitFlags;
setFlags(flags: TraitFlags): void {
(this as Mutable<this>).flags = flags;
}
readonly model: Model | null;
/** @internal */
attachModel(model: Model, nextTrait: Trait | null): void {
// assert(this.model === null);
this.willAttachModel(model);
(this as Mutable<this>).model = model;
let previousTrait: Trait | null;
if (nextTrait !== null) {
previousTrait = nextTrait.previousTrait;
this.setNextTrait(nextTrait);
nextTrait.setPreviousTrait(this);
} else {
previousTrait = model.lastTrait;
model.setLastTrait(this);
}
if (previousTrait !== null) {
previousTrait.setNextTrait(this);
this.setPreviousTrait(previousTrait);
} else {
model.setFirstTrait(this);
}
if (model.mounted) {
this.mountTrait();
}
this.onAttachModel(model);
this.didAttachModel(model);
}
protected willAttachModel(model: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillAttachModel !== void 0) {
observer.traitWillAttachModel(model, this);
}
}
}
protected onAttachModel(model: Model): void {
this.bindModelFasteners(model);
}
protected didAttachModel(model: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidAttachModel !== void 0) {
observer.traitDidAttachModel(model, this);
}
}
}
/** @internal */
detachModel(model: Model): void {
// assert(this.model === model);
this.willDetachModel(model);
if (this.mounted) {
this.unmountTrait();
}
this.onDetachModel(model);
const nextTrait = this.nextTrait;
const previousTrait = this.previousTrait;
if (nextTrait !== null) {
this.setNextTrait(null);
nextTrait.setPreviousTrait(previousTrait);
} else {
model.setLastTrait(previousTrait);
}
if (previousTrait !== null) {
previousTrait.setNextTrait(nextTrait);
this.setPreviousTrait(null);
} else {
model.setFirstTrait(nextTrait);
}
(this as Mutable<this>).model = null;
this.didDetachModel(model);
}
protected willDetachModel(model: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillDetachModel !== void 0) {
observer.traitWillDetachModel(model, this);
}
}
}
protected onDetachModel(model: Model): void {
this.unbindModelFasteners(model);
}
protected didDetachModel(model: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidDetachModel !== void 0) {
observer.traitDidDetachModel(model, this);
}
}
}
get modelFlags(): ModelFlags {
const model = this.model;
return model !== null ? model.flags : 0;
}
setModelFlags(modelFlags: ModelFlags): void {
const model = this.model;
if (model !== null) {
model.setFlags(modelFlags);
} else {
throw new Error("no model");
}
}
remove(): void {
const model = this.model;
if (model !== null) {
model.removeTrait(this);
}
}
get parent(): Model | null {
const model = this.model;
return model !== null ? model.parent : null;
}
/** @protected */
willAttachParent(parent: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillAttachParent !== void 0) {
observer.traitWillAttachParent(parent, this);
}
}
}
/** @protected */
onAttachParent(parent: Model): void {
// hook
}
/** @protected */
didAttachParent(parent: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidAttachParent !== void 0) {
observer.traitDidAttachParent(parent, this);
}
}
}
/** @protected */
willDetachParent(parent: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillDetachParent !== void 0) {
observer.traitWillDetachParent(parent, this);
}
}
}
/** @protected */
onDetachParent(parent: Model): void {
// hook
}
/** @protected */
didDetachParent(parent: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidDetachParent !== void 0) {
observer.traitDidDetachParent(parent, this);
}
}
}
get nextSibling(): Model | null {
const model = this.model;
return model !== null ? model.nextSibling : null;
}
get previousSibling(): Model | null {
const model = this.model;
return model !== null ? model.previousSibling : null;
}
get firstChild(): Model | null {
const model = this.model;
return model !== null ? model.firstChild : null;
}
get lastChild(): Model | null {
const model = this.model;
return model !== null ? model.lastChild : null;
}
forEachChild<T>(callback: (child: Model) => T | void): T | undefined;
forEachChild<T, S>(callback: (this: S, child: Model) => T | void, thisArg: S): T | undefined;
forEachChild<T, S>(callback: (this: S | undefined, child: Model) => T | void, thisArg?: S): T | undefined {
const model = this.model;
return model !== null ? model.forEachChild(callback, thisArg) : void 0;
}
getChild<F extends abstract new (...args: any) => Model>(key: string, childBound: F): InstanceType<F> | null;
getChild(key: string, childBound?: abstract new (...args: any) => Model): Model | null;
getChild(key: string, childBound?: abstract new (...args: any) => Model): Model | null {
const model = this.model;
return model !== null ? model.getChild(key, childBound) : null;
}
setChild<M extends Model>(key: string, newChild: M): Model | null;
setChild<F extends ModelCreator<F>>(key: string, factory: F): Model | null;
setChild(key: string, newChild: AnyModel | null): Model | null;
setChild(key: string, newChild: AnyModel | null): Model | null {
const model = this.model;
if (model !== null) {
return model.setChild(key, newChild);
} else {
throw new Error("no model");
}
}
appendChild<M extends Model>(child: M, key?: string): M;
appendChild<F extends ModelCreator<F>>(factory: F, key?: string): InstanceType<F>;
appendChild(child: AnyModel, key?: string): Model;
appendChild(child: AnyModel, key?: string): Model {
const model = this.model;
if (model !== null) {
return model.appendChild(child, key);
} else {
throw new Error("no model");
}
}
prependChild<M extends Model>(child: M, key?: string): M;
prependChild<F extends ModelCreator<F>>(factory: F, key?: string): InstanceType<F>;
prependChild(child: AnyModel, key?: string): Model;
prependChild(child: AnyModel, key?: string): Model {
const model = this.model;
if (model !== null) {
return model.prependChild(child, key);
} else {
throw new Error("no model");
}
}
insertChild<M extends Model>(child: M, target: Model | null, key?: string): M;
insertChild<F extends ModelCreator<F>>(factory: F, target: Model | null, key?: string): InstanceType<F>;
insertChild(child: AnyModel, target: Model | null, key?: string): Model;
insertChild(child: AnyModel, target: Model | null, key?: string): Model {
const model = this.model;
if (model !== null) {
return model.insertChild(child, target, key);
} else {
throw new Error("no model");
}
}
replaceChild<M extends Model>(newChild: Model, oldChild: M): M;
replaceChild<M extends Model>(newChild: AnyModel, oldChild: M): M;
replaceChild(newChild: AnyModel, oldChild: Model): Model {
const model = this.model;
if (model !== null) {
return model.replaceChild(newChild, oldChild);
} else {
throw new Error("no model");
}
}
get insertChildFlags(): ModelFlags {
return (this.constructor as typeof Trait).InsertChildFlags;
}
/** @protected */
willInsertChild(child: Model, target: Model | null): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillInsertChild !== void 0) {
observer.traitWillInsertChild(child, target, this);
}
}
}
/** @protected */
onInsertChild(child: Model, target: Model | null): void {
this.requireUpdate(this.insertChildFlags);
this.bindChildFasteners(child, target);
}
/** @protected */
didInsertChild(child: Model, target: Model | null): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidInsertChild !== void 0) {
observer.traitDidInsertChild(child, target, this);
}
}
}
removeChild<M extends Model>(child: M): M | null;
removeChild(key: string | Model): Model | null;
removeChild(key: string | Model): Model | null {
const model = this.model;
if (model !== null) {
return model.removeChild(key);
} else {
return null;
}
}
get removeChildFlags(): ModelFlags {
return (this.constructor as typeof Trait).RemoveChildFlags;
}
/** @protected */
willRemoveChild(child: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillRemoveChild !== void 0) {
observer.traitWillRemoveChild(child, this);
}
}
this.requireUpdate(this.removeChildFlags);
}
/** @protected */
onRemoveChild(child: Model): void {
this.unbindChildFasteners(child);
}
/** @protected */
didRemoveChild(child: Model): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidRemoveChild !== void 0) {
observer.traitDidRemoveChild(child, this);
}
}
}
removeChildren(): void {
const model = this.model;
if (model !== null) {
return model.removeChildren();
}
}
sortChildren(comparator: Comparator<Model>): void {
const model = this.model;
if (model !== null) {
return model.sortChildren(comparator);
}
}
getSuper<F extends abstract new (...args: any) => Model>(superBound: F): InstanceType<F> | null {
const model = this.model;
return model !== null ? model.getSuper(superBound) : null;
}
getBase<F extends abstract new (...args: any) => Model>(baseBound: F): InstanceType<F> | null {
const model = this.model;
return model !== null ? model.getBase(baseBound) : null;
}
readonly nextTrait: Trait | null;
/** @internal */
setNextTrait(nextTrait: Trait | null): void {
(this as Mutable<this>).nextTrait = nextTrait;
}
readonly previousTrait: Trait | null;
/** @internal */
setPreviousTrait(previousTrait: Trait | null): void {
(this as Mutable<this>).previousTrait = previousTrait;
}
get firstTrait(): Trait | null {
const model = this.model;
return model !== null ? model.firstTrait : null;
}
get lastTrait(): Trait | null {
const model = this.model;
return model !== null ? model.lastTrait : null;
}
forEachTrait<T>(callback: (trait: Trait) => T | void): T | undefined;
forEachTrait<T, S>(callback: (this: S, trait: Trait) => T | void, thisArg: S): T | undefined;
forEachTrait<T, S>(callback: (this: S | undefined, trait: Trait) => T | void, thisArg?: S): T | undefined {
const model = this.model;
return model !== null ? model.forEachTrait(callback, thisArg) : void 0;
}
getTrait<F extends abstract new (...args: any) => Trait>(key: string, traitBound: F): InstanceType<F> | null;
getTrait(key: string, traitBound?: abstract new (...args: any) => Trait): Trait | null;
getTrait<F extends abstract new (...args: any) => Trait>(traitBound: F): InstanceType<F> | null;
getTrait(key: string | (abstract new (...args: any) => Trait), traitBound?: abstract new (...args: any) => Trait): Trait | null {
const model = this.model;
return model !== null ? model.getTrait(key as string, traitBound) : null;
}
setTrait<T extends Trait>(key: string, newTrait: T): Trait | null;
setTrait<F extends TraitCreator<F>>(key: string, factory: F): Trait | null;
setTrait(key: string, newTrait: AnyTrait | null): Trait | null;
setTrait(key: string, newTrait: AnyTrait | null): Trait | null {
const model = this.model;
if (model !== null) {
return model.setTrait(key, newTrait);
} else {
throw new Error("no model");
}
}
appendTrait<T extends Trait>(trait: T, key?: string): T;
appendTrait<F extends TraitCreator<F>>(factory: F, key?: string): InstanceType<F>;
appendTrait(trait: AnyTrait, key?: string): Trait;
appendTrait(trait: AnyTrait, key?: string): Trait {
const model = this.model;
if (model !== null) {
return model.appendTrait(trait, key);
} else {
throw new Error("no model");
}
}
prependTrait<T extends Trait>(trait: T, key?: string): T;
prependTrait<F extends TraitCreator<F>>(factory: F, key?: string): InstanceType<F>;
prependTrait(trait: AnyTrait, key?: string): Trait;
prependTrait(trait: AnyTrait, key?: string): Trait {
const model = this.model;
if (model !== null) {
return model.prependTrait(trait, key);
} else {
throw new Error("no model");
}
}
insertTrait<T extends Trait>(trait: T, target: Trait | null, key?: string): T;
insertTrait<F extends TraitCreator<F>>(factory: F, target: Trait | null, key?: string): InstanceType<F>;
insertTrait(trait: AnyTrait, target: Trait | null, key?: string): Trait;
insertTrait(trait: AnyTrait, target: Trait | null, key?: string): Trait {
const model = this.model;
if (model !== null) {
return model.insertTrait(trait, target, key);
} else {
throw new Error("no model");
}
}
replaceTraitt<T extends Trait>(newTrait: Trait, oldTrait: T): T;
replaceTraitt<T extends Trait>(newTrait: AnyTrait, oldTrait: T): T;
replaceTraitt(newTrait: AnyTrait, oldTrait: Trait): Trait {
const model = this.model;
if (model !== null) {
return model.replaceTrait(newTrait, oldTrait);
} else {
throw new Error("no model");
}
}
get insertTraitFlags(): ModelFlags {
return (this.constructor as typeof Trait).InsertTraitFlags;
}
/** @protected */
willInsertTrait(trait: Trait, target: Trait | null): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillInsertTrait !== void 0) {
observer.traitWillInsertTrait(trait, target, this);
}
}
}
/** @protected */
onInsertTrait(trait: Trait, target: Trait | null): void {
this.requireUpdate(this.insertTraitFlags);
this.bindTraitFasteners(trait, target);
}
/** @protected */
didInsertTrait(trait: Trait, target: Trait | null): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidInsertTrait !== void 0) {
observer.traitDidInsertTrait(trait, target, this);
}
}
}
removeTrait<T extends Trait>(trait: T): T | null;
removeTrait(key: string | Trait): Trait | null;
removeTrait(key: string | Trait): Trait | null {
const model = this.model;
if (model !== null) {
return model.removeTrait(key);
} else {
return null;
}
}
get removeTraitFlags(): ModelFlags {
return (this.constructor as typeof Trait).RemoveTraitFlags;
}
/** @protected */
willRemoveTrait(trait: Trait): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillRemoveTrait !== void 0) {
observer.traitWillRemoveTrait(trait, this);
}
}
}
/** @protected */
onRemoveTrait(trait: Trait): void {
this.requireUpdate(this.removeTraitFlags);
this.unbindTraitFasteners(trait);
}
/** @protected */
didRemoveTrait(trait: Trait): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidRemoveTrait !== void 0) {
observer.traitDidRemoveTrait(trait, this);
}
}
}
sortTraits(comparator: Comparator<Trait>): void {
const model = this.model;
if (model !== null) {
model.sortTraits(comparator);
}
}
getSuperTrait<F extends abstract new (...args: any) => Trait>(superBound: F): InstanceType<F> | null {
const model = this.model;
return model !== null ? model.getSuperTrait(superBound) : null;
}
getBaseTrait<F extends abstract new (...args: any) => Trait>(baseBound: F): InstanceType<F> | null {
const model = this.model;
return model !== null ? model.getBaseTrait(baseBound) : null;
}
@Provider({
extends: WarpProvider,
type: WarpService,
observes: false,
service: WarpService.global(),
})
readonly warpProvider!: WarpProvider<this>;
@Property({
type: Object,
inherits: true,
value: null,
updateFlags: Model.NeedsReconcile,
})
readonly warpRef!: Property<this, WarpRef | null>;
get mounted(): boolean {
return (this.flags & Trait.MountedFlag) !== 0;
}
get mountFlags(): ModelFlags {
return (this.constructor as typeof Trait).MountFlags;
}
/** @internal */
mountTrait(): void {
if ((this.flags & Trait.MountedFlag) === 0) {
this.setFlags(this.flags | Trait.MountedFlag);
this.willMount();
this.onMount();
this.didMount();
} else {
throw new Error("already mounted");
}
}
protected willMount(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillMount !== void 0) {
observer.traitWillMount(this);
}
}
}
protected onMount(): void {
this.requireUpdate(this.mountFlags);
if (this.decoherent !== null && this.decoherent.length !== 0) {
this.requireUpdate(Model.NeedsMutate);
}
this.mountFasteners();
if (this.consumers.length !== 0) {
this.startConsuming();
}
}
protected didMount(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidMount !== void 0) {
observer.traitDidMount(this);
}
}
}
/** @internal */
unmountTrait(): void {
if ((this.flags & Trait.MountedFlag) !== 0) {
this.setFlags(this.flags & ~Trait.MountedFlag);
this.willUnmount();
this.onUnmount();
this.didUnmount();
} else {
throw new Error("already unmounted");
}
}
protected willUnmount(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillUnmount !== void 0) {
observer.traitWillUnmount(this);
}
}
}
protected onUnmount(): void {
this.stopConsuming();
this.unmountFasteners();
}
protected didUnmount(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidUnmount !== void 0) {
observer.traitDidUnmount(this);
}
}
}
requireUpdate(updateFlags: ModelFlags, immediate: boolean = false): void {
const model = this.model;
if (model !== null) {
model.requireUpdate(updateFlags, immediate);
}
}
/** @protected */
needsUpdate(updateFlags: ModelFlags, immediate: boolean): ModelFlags {
return updateFlags;
}
requestUpdate(target: Model, updateFlags: ModelFlags, immediate: boolean): void {
const model = this.model;
if (model !== null) {
model.requestUpdate(target, updateFlags, immediate);
} else {
throw new TypeError("no model");
}
}
get updating(): boolean {
const model = this.model;
return model !== null && model.updating;
}
get analyzing(): boolean {
const model = this.model;
return model !== null && model.analyzing;
}
/** @protected */
needsAnalyze(analyzeFlags: ModelFlags, modelContext: TraitContextType<this>): ModelFlags {
return analyzeFlags;
}
/** @protected */
willAnalyze(analyzeFlags: ModelFlags, modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
onAnalyze(analyzeFlags: ModelFlags, modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
didAnalyze(analyzeFlags: ModelFlags, modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
willMutate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillMutate !== void 0) {
observer.traitWillMutate(modelContext, this);
}
}
}
/** @protected */
onMutate(modelContext: TraitContextType<this>): void {
this.recohereFasteners(modelContext.updateTime);
}
/** @protected */
didMutate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidMutate !== void 0) {
observer.traitDidMutate(modelContext, this);
}
}
}
/** @protected */
willAggregate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillAggregate !== void 0) {
observer.traitWillAggregate(modelContext, this);
}
}
}
/** @protected */
onAggregate(modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
didAggregate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidAggregate !== void 0) {
observer.traitDidAggregate(modelContext, this);
}
}
}
/** @protected */
willCorrelate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillCorrelate !== void 0) {
observer.traitWillCorrelate(modelContext, this);
}
}
}
/** @protected */
onCorrelate(modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
didCorrelate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidCorrelate !== void 0) {
observer.traitDidCorrelate(modelContext, this);
}
}
}
/** @protected */
analyzeChildren(analyzeFlags: ModelFlags, modelContext: TraitContextType<this>,
analyzeChild: (this: TraitModelType<this>, child: Model, analyzeFlags: ModelFlags,
modelContext: TraitContextType<this>) => void,
analyzeChildren: (this: TraitModelType<this>, analyzeFlags: ModelFlags, modelContext: TraitContextType<this>,
analyzeChild: (this: TraitModelType<this>, child: Model, analyzeFlags: ModelFlags,
modelContext: TraitContextType<this>) => void) => void): void {
analyzeChildren.call(this.model as TraitModelType<this>, analyzeFlags, modelContext, analyzeChild);
}
get refreshing(): boolean {
const model = this.model;
return model !== null && model.refreshing;
}
/** @protected */
needsRefresh(refreshFlags: ModelFlags, modelContext: TraitContextType<this>): ModelFlags {
return refreshFlags;
}
/** @protected */
willRefresh(refreshFlags: ModelFlags, modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
onRefresh(refreshFlags: ModelFlags, modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
didRefresh(refreshFlags: ModelFlags, modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
willValidate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillValidate !== void 0) {
observer.traitWillValidate(modelContext, this);
}
}
}
/** @protected */
onValidate(modelContext: TraitContextType<this>): void {
// hook
}
/** @protected */
didValidate(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidValidate !== void 0) {
observer.traitDidValidate(modelContext, this);
}
}
}
/** @protected */
willReconcile(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillReconcile !== void 0) {
observer.traitWillReconcile(modelContext, this);
}
}
}
/** @protected */
onReconcile(modelContext: TraitContextType<this>): void {
this.recohereDownlinks(modelContext.updateTime);
}
/** @protected */
didReconcile(modelContext: TraitContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidReconcile !== void 0) {
observer.traitDidReconcile(modelContext, this);
}
}
}
/** @protected */
refreshChildren(refreshFlags: ModelFlags, modelContext: TraitContextType<this>,
refreshChild: (this: TraitModelType<this>, child: Model, refreshFlags: ModelFlags,
modelContext: TraitContextType<this>) => void,
refreshChildren: (this: TraitModelType<this>, refreshFlags: ModelFlags, modelContext: TraitContextType<this>,
refreshChild: (this: TraitModelType<this>, child: Model, refreshFlags: ModelFlags,
modelContext: TraitContextType<this>) => void) => void): void {
refreshChildren.call(this.model as TraitModelType<this>, refreshFlags, modelContext, refreshChild);
}
/** @internal */
readonly fasteners: {[fastenerName: string]: Fastener | undefined} | null;
/** @override */
hasFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): boolean {
const fasteners = this.fasteners;
if (fasteners !== null) {
const fastener = fasteners[fastenerName];
if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) {
return true;
}
}
return false;
}
/** @override */
getFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null;
/** @override */
getFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null;
getFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null {
const fasteners = this.fasteners;
if (fasteners !== null) {
const fastener = fasteners[fastenerName];
if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) {
return fastener;
}
}
return null;
}
/** @override */
setFastener(fastenerName: string, newFastener: Fastener | null): void {
const fasteners = this.fasteners;
const oldFastener: Fastener | null | undefined = fasteners !== null ? fasteners[fastenerName] ?? null : null;
if (oldFastener !== newFastener) {
if (oldFastener !== null) {
this.detachFastener(fastenerName, oldFastener);
}
if (newFastener !== null) {
this.attachFastener(fastenerName, newFastener);
}
}
}
/** @internal */
protected attachFastener(fastenerName: string, fastener: Fastener): void {
let fasteners = this.fasteners;
if (fasteners === null) {
fasteners = {};
(this as Mutable<this>).fasteners = fasteners;
}
// assert(fasteners[fastenerName] === void 0);
this.willAttachFastener(fastenerName, fastener);
fasteners[fastenerName] = fastener;
if (this.mounted) {
fastener.mount();
}
this.onAttachFastener(fastenerName, fastener);
this.didAttachFastener(fastenerName, fastener);
}
protected willAttachFastener(fastenerName: string, fastener: Fastener): void {
// hook
}
protected onAttachFastener(fastenerName: string, fastener: Fastener): void {
this.bindFastener(fastener);
}
protected didAttachFastener(fastenerName: string, fastener: Fastener): void {
// hook
}
/** @internal */
protected detachFastener(fastenerName: string, fastener: Fastener): void {
const fasteners = this.fasteners!;
// assert(fasteners !== null);
// assert(fasteners[fastenerName] === fastener);
this.willDetachFastener(fastenerName, fastener);
this.onDetachFastener(fastenerName, fastener);
if (this.mounted) {
fastener.unmount();
}
delete fasteners[fastenerName];
this.didDetachFastener(fastenerName, fastener);
}
protected willDetachFastener(fastenerName: string, fastener: Fastener): void {
// hook
}
protected onDetachFastener(fastenerName: string, fastener: Fastener): void {
// hook
}
protected didDetachFastener(fastenerName: string, fastener: Fastener): void {
// hook
}
/** @override */
getLazyFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null;
/** @override */
getLazyFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null;
getLazyFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null {
return FastenerContext.getLazyFastener(this, fastenerName, fastenerBound);
}
/** @override */
getSuperFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null;
/** @override */
getSuperFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null;
getSuperFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null {
const model = this.model;
if (model === null) {
return null;
} else {
const modelFastener = model.getLazyFastener(fastenerName, fastenerBound);
if (modelFastener !== null) {
return modelFastener;
} else {
return model.getSuperFastener(fastenerName, fastenerBound);
}
}
}
/** @internal */
protected mountFasteners(): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
fastener.mount();
}
}
/** @internal */
protected unmountFasteners(): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
fastener.unmount();
}
}
protected bindFastener(fastener: Fastener): void {
if ((fastener instanceof ModelRelation || fastener instanceof TraitRelation) && fastener.binds) {
this.forEachChild(function (child: Model): void {
fastener.bindModel(child, null);
}, this);
}
if (fastener instanceof TraitRelation && fastener.binds) {
this.forEachTrait(function (trait: Trait): void {
fastener.bindTrait(trait, null);
}, this);
}
if (fastener instanceof DownlinkFastener && fastener.consumed === true && this.consuming) {
fastener.consume(this);
}
}
/** @internal */
protected bindModelFasteners(model: Model): void {
const fasteners = this.fasteners;
model.forEachChild(function (child: Model): void {
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.bindChildFastener(fastener, child, null);
}
}, this);
model.forEachTrait(function (trait: Trait): void {
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.bindTraitFastener(fastener, trait, null);
}
}, this);
}
/** @internal */
protected unbindModelFasteners(model: Model): void {
const fasteners = this.fasteners;
model.forEachTrait(function (trait: Trait): void {
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.unbindTraitFastener(fastener, trait);
}
}, this);
model.forEachChild(function (child: Model): void {
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.unbindChildFastener(fastener, child);
}
}, this);
}
/** @internal */
protected bindChildFasteners(child: Model, target: Model | null): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.bindChildFastener(fastener, child, target);
}
}
/** @internal */
protected bindChildFastener(fastener: Fastener, child: Model, target: Model | null): void {
if (fastener instanceof ModelRelation || fastener instanceof TraitRelation) {
fastener.bindModel(child, target);
}
}
/** @internal */
protected unbindChildFasteners(child: Model): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.unbindChildFastener(fastener, child);
}
}
/** @internal */
protected unbindChildFastener(fastener: Fastener, child: Model): void {
if (fastener instanceof ModelRelation || fastener instanceof TraitRelation) {
fastener.unbindModel(child);
}
}
/** @internal */
protected bindTraitFasteners(trait: Trait, target: Trait | null): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.bindTraitFastener(fastener, trait, target);
}
}
/** @internal */
protected bindTraitFastener(fastener: Fastener, trait: Trait, target: Trait | null): void {
if (fastener instanceof TraitRelation) {
fastener.bindTrait(trait, target);
}
}
/** @internal */
protected unbindTraitFasteners(trait: Trait): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
this.unbindTraitFastener(fastener, trait);
}
}
/** @internal */
protected unbindTraitFastener(fastener: Fastener, trait: Trait): void {
if (fastener instanceof TraitRelation) {
fastener.unbindTrait(trait);
}
}
/** @internal */
readonly decoherent: ReadonlyArray<Fastener> | null;
/** @internal */
decohereFastener(fastener: Fastener): void {
let decoherent = this.decoherent as Fastener[];
if (decoherent === null) {
decoherent = [];
(this as Mutable<this>).decoherent = decoherent;
}
decoherent.push(fastener);
if (fastener instanceof DownlinkFastener) {
this.requireUpdate(Model.NeedsReconcile);
} else {
this.requireUpdate(Model.NeedsMutate);
}
}
/** @internal */
recohereFasteners(t?: number): void {
const decoherent = this.decoherent;
if (decoherent !== null) {
const decoherentCount = decoherent.length;
if (decoherentCount !== 0) {
if (t === void 0) {
t = performance.now();
}
(this as Mutable<this>).decoherent = null;
for (let i = 0; i < decoherentCount; i += 1) {
const fastener = decoherent[i]!;
if (!(fastener instanceof DownlinkFastener)) {
fastener.recohere(t);
} else {
this.decohereFastener(fastener);
}
}
}
}
}
/** @internal */
recohereDownlinks(t: number): void {
const decoherent = this.decoherent;
if (decoherent !== null) {
const decoherentCount = decoherent.length;
if (decoherentCount !== 0) {
(this as Mutable<this>).decoherent = null;
for (let i = 0; i < decoherentCount; i += 1) {
const fastener = decoherent[i]!;
if (fastener instanceof DownlinkFastener) {
fastener.recohere(t);
} else {
this.decohereFastener(fastener);
}
}
}
}
}
/** @internal */
readonly observers: ReadonlyArray<ObserverType<this>>;
/** @override */
observe(observer: ObserverType<this>): void {
const oldObservers = this.observers;
const newObservers = Arrays.inserted(observer, oldObservers);
if (oldObservers !== newObservers) {
this.willObserve(observer);
(this as Mutable<this>).observers = newObservers;
this.onObserve(observer);
this.didObserve(observer);
}
}
protected willObserve(observer: ObserverType<this>): void {
// hook
}
protected onObserve(observer: ObserverType<this>): void {
// hook
}
protected didObserve(observer: ObserverType<this>): void {
// hook
}
/** @override */
unobserve(observer: ObserverType<this>): void {
const oldObservers = this.observers;
const newObservers = Arrays.removed(observer, oldObservers);
if (oldObservers !== newObservers) {
this.willUnobserve(observer);
(this as Mutable<this>).observers = newObservers;
this.onUnobserve(observer);
this.didUnobserve(observer);
}
}
protected willUnobserve(observer: ObserverType<this>): void {
// hook
}
protected onUnobserve(observer: ObserverType<this>): void {
// hook
}
protected didUnobserve(observer: ObserverType<this>): void {
// hook
}
protected forEachObserver<T>(callback: (this: this, observer: ObserverType<this>) => T | void): T | undefined {
let result: T | undefined;
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
result = callback.call(this, observer as ObserverType<this>) as T | undefined;
if (result !== void 0) {
return result;
}
}
return result;
}
callObservers<O, K extends keyof ObserverMethods<O>>(this: this & {readonly observerType?: Class<O>}, key: K, ...args: ObserverParameters<O, K>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]! as ObserverMethods<O>;
const method = observer[key];
if (typeof method === "function") {
method.call(observer, ...args);
}
}
}
/** @internal */
readonly consumers: ReadonlyArray<ConsumerType<this>>;
/** @override */
consume(consumer: ConsumerType<this>): void {
const oldConsumers = this.consumers;
const newConsumers = Arrays.inserted(consumer, oldConsumers);
if (oldConsumers !== newConsumers) {
this.willConsume(consumer);
(this as Mutable<this>).consumers = newConsumers;
this.onConsume(consumer);
this.didConsume(consumer);
if (oldConsumers.length === 0 && this.mounted) {
this.startConsuming();
}
}
}
protected willConsume(consumer: ConsumerType<this>): void {
// hook
}
protected onConsume(consumer: ConsumerType<this>): void {
// hook
}
protected didConsume(consumer: ConsumerType<this>): void {
// hook
}
/** @override */
unconsume(consumer: ConsumerType<this>): void {
const oldConsumers = this.consumers;
const newConsumers = Arrays.removed(consumer, oldConsumers);
if (oldConsumers !== newConsumers) {
this.willUnconsume(consumer);
(this as Mutable<this>).consumers = newConsumers;
this.onUnconsume(consumer);
this.didUnconsume(consumer);
if (newConsumers.length === 0) {
this.stopConsuming();
}
}
}
protected willUnconsume(consumer: ConsumerType<this>): void {
// hook
}
protected onUnconsume(consumer: ConsumerType<this>): void {
// hook
}
protected didUnconsume(consumer: ConsumerType<this>): void {
// hook
}
get consuming(): boolean {
return (this.flags & Trait.ConsumingFlag) !== 0;
}
get startConsumingFlags(): ModelFlags {
return (this.constructor as typeof Trait).StartConsumingFlags;
}
protected startConsuming(): void {
if ((this.flags & Trait.ConsumingFlag) === 0) {
this.willStartConsuming();
this.setFlags(this.flags | Trait.ConsumingFlag);
this.onStartConsuming();
this.didStartConsuming();
}
}
protected willStartConsuming(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillStartConsuming !== void 0) {
observer.traitWillStartConsuming(this);
}
}
}
protected onStartConsuming(): void {
this.requireUpdate(this.startConsumingFlags);
this.startConsumingFasteners();
}
protected didStartConsuming(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidStartConsuming !== void 0) {
observer.traitDidStartConsuming(this);
}
}
}
get stopConsumingFlags(): ModelFlags {
return (this.constructor as typeof Trait).StopConsumingFlags;
}
protected stopConsuming(): void {
if ((this.flags & Trait.ConsumingFlag) !== 0) {
this.willStopConsuming();
this.setFlags(this.flags & ~Trait.ConsumingFlag);
this.onStopConsuming();
this.didStopConsuming();
}
}
protected willStopConsuming(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitWillStopConsuming !== void 0) {
observer.traitWillStopConsuming(this);
}
}
}
protected onStopConsuming(): void {
this.requireUpdate(this.stopConsumingFlags);
this.stopConsumingFasteners();
}
protected didStopConsuming(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.traitDidStopConsuming !== void 0) {
observer.traitDidStopConsuming(this);
}
}
}
/** @internal */
protected startConsumingFasteners(): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
if (fastener instanceof DownlinkFastener && fastener.consumed === true) {
fastener.consume(this);
}
}
}
/** @internal */
protected stopConsumingFasteners(): void {
const fasteners = this.fasteners;
for (const fastenerName in fasteners) {
const fastener = fasteners[fastenerName]!;
if (fastener instanceof DownlinkFastener && fastener.consumed === true) {
fastener.unconsume(this);
}
}
}
get modelContext(): TraitContextType<this> | null {
const model = this.model;
return model !== null ? model.modelContext as TraitContextType<this> : null;
}
/** @override */
equals(that: unknown): boolean {
return this === that;
}
/** @override */
hashCode(): number {
return this.uid;
}
/** @override */
init(init: TraitInit): void {
// hook
}
static create<S extends new () => InstanceType<S>>(this: S): InstanceType<S> {
return new this();
}
static fromInit<S extends abstract new (...args: any) => InstanceType<S>>(this: S, init: InitType<InstanceType<S>>): InstanceType<S> {
let type: Creatable<Trait>;
if ((typeof init === "object" && init !== null || typeof init === "function") && Creatable.is((init as TraitInit).type)) {
type = (init as TraitInit).type!;
} else {
type = this as unknown as Creatable<Trait>;
}
const view = type.create();
view.init(init as TraitInit);
return view as InstanceType<S>;
}
static fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyTrait<InstanceType<S>>): InstanceType<S> {
if (value === void 0 || value === null) {
return value as InstanceType<S>;
} else if (value instanceof Trait) {
if (value instanceof this) {
return value;
} else {
throw new TypeError(value + " not an instance of " + this);
}
} else if (Creatable.is(value)) {
return (value as Creatable<InstanceType<S>>).create();
} else {
return (this as unknown as TraitFactory<InstanceType<S>>).fromInit(value);
}
}
/** @internal */
static uid: () => number = (function () {
let nextId = 1;
return function uid(): number {
const id = ~~nextId;
nextId += 1;
return id;
}
})();
/** @internal */
static readonly MountedFlag: TraitFlags = 1 << 0;
/** @internal */
static readonly ConsumingFlag: TraitFlags = 1 << 1;
/** @internal */
static readonly FlagShift: number = 2;
/** @internal */
static readonly FlagMask: ModelFlags = (1 << Trait.FlagShift) - 1;
static readonly MountFlags: ModelFlags = 0;
static readonly InsertChildFlags: ModelFlags = 0;
static readonly RemoveChildFlags: ModelFlags = 0;
static readonly InsertTraitFlags: ModelFlags = 0;
static readonly RemoveTraitFlags: ModelFlags = 0;
static readonly StartConsumingFlags: TraitFlags = 0;
static readonly StopConsumingFlags: TraitFlags = 0;
} | the_stack |
import { CoreConstants } from '@/core/constants';
import { Component, Input, ViewChild, ElementRef, OnInit, OnDestroy, Optional } from '@angular/core';
import { CoreTabsComponent } from '@components/tabs/tabs';
import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component';
import { CoreCourseContentsPage } from '@features/course/pages/contents/contents';
import { CoreUser } from '@features/user/services/user';
import { IonContent, IonInput } from '@ionic/angular';
import { CoreGroupInfo, CoreGroups } from '@services/groups';
import { CoreNavigator } from '@services/navigator';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreForms } from '@singletons/form';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { AddonModLessonRetakeFinishedInSyncDBRecord } from '../../services/database/lesson';
import { AddonModLessonPrefetchHandler } from '../../services/handlers/prefetch';
import {
AddonModLesson,
AddonModLessonAttemptsOverviewsStudentWSData,
AddonModLessonAttemptsOverviewWSData,
AddonModLessonGetAccessInformationWSResponse,
AddonModLessonLessonWSData,
AddonModLessonPreventAccessReason,
AddonModLessonProvider,
} from '../../services/lesson';
import { AddonModLessonOffline } from '../../services/lesson-offline';
import {
AddonModLessonAutoSyncData,
AddonModLessonSync,
AddonModLessonSyncProvider,
AddonModLessonSyncResult,
} from '../../services/lesson-sync';
import { AddonModLessonModuleHandlerService } from '../../services/handlers/module';
import { CoreTime } from '@singletons/time';
/**
* Component that displays a lesson entry page.
*/
@Component({
selector: 'addon-mod-lesson-index',
templateUrl: 'addon-mod-lesson-index.html',
})
export class AddonModLessonIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, OnDestroy {
@ViewChild(CoreTabsComponent) tabsComponent?: CoreTabsComponent;
@ViewChild('passwordForm') formElement?: ElementRef;
@Input() group = 0; // The group to display.
@Input() action?: string; // The "action" to display first.
component = AddonModLessonProvider.COMPONENT;
moduleName = 'lesson';
lesson?: AddonModLessonLessonWSData; // The lesson.
selectedTab?: number; // The initial selected tab.
askPassword?: boolean; // Whether to ask the password.
canManage?: boolean; // Whether the user can manage the lesson.
canViewReports?: boolean; // Whether the user can view the lesson reports.
showSpinner?: boolean; // Whether to display a spinner.
retakeToReview?: AddonModLessonRetakeFinishedInSyncDBRecord; // A retake to review.
preventReasons: AddonModLessonPreventAccessReason[] = []; // List of reasons that prevent the lesson from being seen.
leftDuringTimed?: boolean; // Whether the user has started and left a retake.
groupInfo?: CoreGroupInfo; // The group info.
reportLoaded?: boolean; // Whether the report data has been loaded.
selectedGroupName?: string; // The name of the selected group.
overview?: AttemptsOverview; // Reports overview data.
finishedOffline?: boolean; // Whether a retake was finished in offline.
avetimeReadable?: string; // Average time in a readable format.
hightimeReadable?: string; // High time in a readable format.
lowtimeReadable?: string; // Low time in a readable format.
protected syncEventName = AddonModLessonSyncProvider.AUTO_SYNCED;
protected accessInfo?: AddonModLessonGetAccessInformationWSResponse; // Lesson access info.
protected password?: string; // The password for the lesson.
protected hasPlayed = false; // Whether the user has gone to the lesson player (attempted).
protected dataSentObserver?: CoreEventObserver; // To detect data sent to server.
protected dataSent = false; // Whether some data was sent to server while playing the lesson.
constructor(
protected content?: IonContent,
@Optional() courseContentsPage?: CoreCourseContentsPage,
) {
super('AddonModLessonIndexComponent', content, courseContentsPage);
}
/**
* Component being initialized.
*/
async ngOnInit(): Promise<void> {
super.ngOnInit();
this.selectedTab = this.action == 'report' ? 1 : 0;
await this.loadContent(false, true);
}
/**
* Change the group displayed.
*
* @param groupId Group ID to display.
* @return Promise resolved when done.
*/
async changeGroup(groupId: number): Promise<void> {
this.reportLoaded = false;
try {
await this.setGroup(groupId);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error getting report.');
} finally {
this.reportLoaded = true;
}
}
/**
* @inheritdoc
*/
protected async fetchContent(refresh?: boolean, sync = false, showErrors = false): Promise<void> {
let lessonReady = true;
this.askPassword = false;
this.lesson = await AddonModLesson.getLesson(this.courseId, this.module.id);
this.dataRetrieved.emit(this.lesson);
this.description = this.lesson.intro; // Show description only if intro is present.
if (sync) {
// Try to synchronize the lesson.
await this.syncActivity(showErrors);
}
this.accessInfo = await AddonModLesson.getAccessInformation(this.lesson.id, { cmId: this.module.id });
this.canManage = this.accessInfo.canmanage;
this.canViewReports = this.accessInfo.canviewreports;
this.preventReasons = [];
const promises: Promise<void>[] = [];
if (AddonModLesson.isLessonOffline(this.lesson)) {
// Handle status.
this.setStatusListener();
promises.push(this.loadOfflineData());
}
if (this.accessInfo.preventaccessreasons.length) {
let preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo, false);
const askPassword = preventReason?.reason == 'passwordprotectedlesson';
if (askPassword) {
try {
// The lesson requires a password. Check if there is one in memory or DB.
const password = this.password ?
this.password :
await AddonModLesson.getStoredPassword(this.lesson.id);
await this.validatePassword(password);
// Now that we have the password, get the access reason again ignoring the password.
preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo, true);
if (preventReason) {
this.preventReasons = [preventReason];
}
} catch {
// No password or the validation failed. Show password form.
this.askPassword = true;
this.preventReasons = [preventReason!];
lessonReady = false;
}
} else {
// Lesson cannot be started.
this.preventReasons = [preventReason!];
lessonReady = false;
}
}
if (this.selectedTab == 1 && this.canViewReports) {
// Only fetch the report data if the tab is selected.
promises.push(this.fetchReportData());
}
await Promise.all(promises);
if (lessonReady) {
// Lesson can be started, don't ask the password and don't show prevent messages.
this.lessonReady();
}
}
/**
* Load offline data for the lesson.
*
* @return Promise resolved when done.
*/
protected async loadOfflineData(): Promise<void> {
if (!this.lesson || !this.accessInfo) {
return;
}
const promises: Promise<unknown>[] = [];
const options = { cmId: this.module.id };
// Check if there is offline data.
promises.push(AddonModLessonSync.hasDataToSync(this.lesson.id, this.accessInfo.attemptscount).then((hasData) => {
this.hasOffline = hasData;
return;
}));
// Check if there is a retake finished in a synchronization.
promises.push(AddonModLessonSync.getRetakeFinishedInSync(this.lesson.id).then((retake) => {
if (retake && retake.retake == this.accessInfo!.attemptscount - 1) {
// The retake finished is still the last retake. Allow reviewing it.
this.retakeToReview = retake;
} else {
this.retakeToReview = undefined;
if (retake) {
AddonModLessonSync.deleteRetakeFinishedInSync(this.lesson!.id);
}
}
return;
}));
// Check if the ser has a finished retake in offline.
promises.push(AddonModLessonOffline.hasFinishedRetake(this.lesson.id).then((finished) => {
this.finishedOffline = finished;
return;
}));
// Update the list of content pages viewed and question attempts.
promises.push(AddonModLesson.getContentPagesViewedOnline(this.lesson.id, this.accessInfo.attemptscount, options));
promises.push(AddonModLesson.getQuestionsAttemptsOnline(this.lesson.id, this.accessInfo.attemptscount, options));
await Promise.all(promises);
}
/**
* Fetch the reports data.
*
* @return Promise resolved when done.
*/
protected async fetchReportData(): Promise<void> {
if (!this.module) {
return;
}
try {
this.groupInfo = await CoreGroups.getActivityGroupInfo(this.module.id);
await this.setGroup(CoreGroups.validateGroupId(this.group, this.groupInfo));
} finally {
this.reportLoaded = true;
}
}
/**
* Checks if sync has succeed from result sync data.
*
* @param result Data returned on the sync function.
* @return If suceed or not.
*/
protected hasSyncSucceed(result: AddonModLessonSyncResult): boolean {
if (result.updated || this.dataSent) {
// Check completion status if something was sent.
this.checkCompletion();
}
this.dataSent = false;
return result.updated;
}
/**
* User entered the page that contains the component.
*/
ionViewDidEnter(): void {
super.ionViewDidEnter();
this.tabsComponent?.ionViewDidEnter();
if (!this.hasPlayed) {
return;
}
// Update data when we come back from the player since the status could have changed.
this.hasPlayed = false;
this.dataSentObserver?.off(); // Stop listening for changes.
this.dataSentObserver = undefined;
// Refresh data.
this.showLoadingAndRefresh(true, false);
}
/**
* User left the page that contains the component.
*/
ionViewDidLeave(): void {
super.ionViewDidLeave();
this.tabsComponent?.ionViewDidLeave();
}
/**
* Perform the invalidate content function.
*
* @return Promise resolved when done.
*/
protected async invalidateContent(): Promise<void> {
const promises: Promise<unknown>[] = [];
promises.push(AddonModLesson.invalidateLessonData(this.courseId));
if (this.lesson) {
promises.push(AddonModLesson.invalidateAccessInformation(this.lesson.id));
promises.push(AddonModLesson.invalidatePages(this.lesson.id));
promises.push(AddonModLesson.invalidateLessonWithPassword(this.lesson.id));
promises.push(AddonModLesson.invalidateTimers(this.lesson.id));
promises.push(AddonModLesson.invalidateContentPagesViewed(this.lesson.id));
promises.push(AddonModLesson.invalidateQuestionsAttempts(this.lesson.id));
promises.push(AddonModLesson.invalidateRetakesOverview(this.lesson.id));
if (this.module) {
promises.push(CoreGroups.invalidateActivityGroupInfo(this.module.id));
}
}
await Promise.all(promises);
}
/**
* Compares sync event data with current data to check if refresh content is needed.
*
* @param syncEventData Data receiven on sync observer.
* @return True if refresh is needed, false otherwise.
*/
protected isRefreshSyncNeeded(syncEventData: AddonModLessonAutoSyncData): boolean {
return !!(this.lesson && syncEventData.lessonId == this.lesson.id);
}
/**
* Function called when the lesson is ready to be seen (no pending prevent access reasons).
*/
protected lessonReady(): void {
this.askPassword = false;
this.leftDuringTimed = this.hasOffline || AddonModLesson.leftDuringTimed(this.accessInfo);
if (this.password) {
// Store the password in DB.
AddonModLesson.storePassword(this.lesson!.id, this.password);
}
}
/**
* @inheritdoc
*/
protected async logActivity(): Promise<void> {
if (!this.lesson || this.preventReasons.length) {
return;
}
await AddonModLesson.logViewLesson(this.lesson.id, this.password, this.lesson.name);
}
/**
* Open the lesson player.
*
* @param continueLast Whether to continue the last retake.
* @return Promise resolved when done.
*/
protected async playLesson(continueLast?: boolean): Promise<void> {
if (!this.lesson || !this.accessInfo) {
return;
}
// Calculate the pageId to load. If there is timelimit, lesson is always restarted from the start.
let pageId: number | undefined;
if (this.hasOffline) {
if (continueLast) {
pageId = await AddonModLesson.getLastPageSeen(this.lesson.id, this.accessInfo.attemptscount, {
cmId: this.module.id,
});
} else {
pageId = this.accessInfo.firstpageid;
}
} else if (this.leftDuringTimed && !this.lesson.timelimit) {
pageId = continueLast ? this.accessInfo.lastpageseen : this.accessInfo.firstpageid;
}
await CoreNavigator.navigateToSitePath(
`${AddonModLessonModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/player`,
{
params: {
pageId: pageId,
password: this.password,
},
},
);
// Detect if anything was sent to server.
this.hasPlayed = true;
this.dataSentObserver?.off();
this.dataSentObserver = CoreEvents.on(AddonModLessonProvider.DATA_SENT_EVENT, (data) => {
// Ignore launch sending because it only affects timers.
if (data.lessonId === this.lesson?.id && data.type != 'launch') {
this.dataSent = true;
}
}, this.siteId);
}
/**
* First tab selected.
*/
indexSelected(): void {
this.selectedTab = 0;
}
/**
* Reports tab selected.
*/
reportsSelected(): void {
this.selectedTab = 1;
if (!this.groupInfo) {
this.fetchReportData().catch((error) => {
CoreDomUtils.showErrorModalDefault(error, 'Error getting report.');
});
}
}
/**
* Review the lesson.
*/
async review(): Promise<void> {
if (!this.retakeToReview || !this.lesson) {
// No retake to review, stop.
return;
}
await CoreNavigator.navigateToSitePath(
`${AddonModLessonModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/player`,
{
params: {
pageId: this.retakeToReview.pageid,
password: this.password,
review: true,
retake: this.retakeToReview.retake,
},
},
);
this.retakeToReview = undefined;
}
/**
* Set a group to view the reports.
*
* @param groupId Group ID.
* @return Promise resolved when done.
*/
async setGroup(groupId: number): Promise<void> {
if (!this.lesson) {
return;
}
this.group = groupId;
this.selectedGroupName = '';
// Search the name of the group if it isn't all participants.
if (groupId && this.groupInfo && this.groupInfo.groups) {
const group = this.groupInfo.groups.find(group => groupId == group.id);
this.selectedGroupName = group?.name || '';
}
// Get the overview of retakes for the group.
const data = await AddonModLesson.getRetakesOverview(this.lesson.id, {
groupId,
cmId: this.lesson.coursemodule,
});
if (!data) {
this.overview = data;
return;
}
const formattedData = <AttemptsOverview> data;
// Format times and grades.
if (formattedData.avetime != null && formattedData.numofattempts) {
formattedData.avetime = Math.floor(formattedData.avetime / formattedData.numofattempts);
this.avetimeReadable = CoreTime.formatTime(formattedData.avetime);
}
if (formattedData.hightime != null) {
this.hightimeReadable = CoreTime.formatTime(formattedData.hightime);
}
if (formattedData.lowtime != null) {
this.lowtimeReadable = CoreTime.formatTime(formattedData.lowtime);
}
if (formattedData.lessonscored) {
if (formattedData.numofattempts && formattedData.avescore != null) {
formattedData.avescore = CoreTextUtils.roundToDecimals(formattedData.avescore, 2);
}
if (formattedData.highscore != null) {
formattedData.highscore = CoreTextUtils.roundToDecimals(formattedData.highscore, 2);
}
if (formattedData.lowscore != null) {
formattedData.lowscore = CoreTextUtils.roundToDecimals(formattedData.lowscore, 2);
}
}
if (formattedData.students) {
// Get the user data for each student returned.
await CoreUtils.allPromises(formattedData.students.map(async (student) => {
student.bestgrade = CoreTextUtils.roundToDecimals(student.bestgrade, 2);
const user = await CoreUtils.ignoreErrors(CoreUser.getProfile(student.id, this.courseId, true));
if (user) {
student.profileimageurl = user.profileimageurl;
}
}));
}
this.overview = formattedData;
}
/**
* @inheritdoc
*/
protected showStatus(status: string): void {
this.showSpinner = status == CoreConstants.DOWNLOADING;
}
/**
* Start the lesson.
*
* @param continueLast Whether to continue the last attempt.
*/
async start(continueLast?: boolean): Promise<void> {
if (this.showSpinner || !this.lesson) {
// Lesson is being downloaded or not retrieved, abort.
return;
}
if (!AddonModLesson.isLessonOffline(this.lesson) || this.currentStatus == CoreConstants.DOWNLOADED) {
// Not downloadable or already downloaded, open it.
this.playLesson(continueLast);
return;
}
// Lesson supports offline and isn't downloaded, download it.
this.showSpinner = true;
try {
await AddonModLessonPrefetchHandler.prefetch(this.module, this.courseId, true);
// Success downloading, open lesson.
this.playLesson(continueLast);
} catch (error) {
if (this.hasOffline) {
// Error downloading but there is something offline, allow continuing it.
this.playLesson(continueLast);
} else {
CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true);
}
} finally {
this.showSpinner = false;
}
}
/**
* Submit password for password protected lessons.
*
* @param e Event.
* @param passwordEl The password input.
*/
async submitPassword(e: Event, passwordEl: IonInput): Promise<void> {
e.preventDefault();
e.stopPropagation();
const password = passwordEl?.value;
if (!password) {
CoreDomUtils.showErrorModal('addon.mod_lesson.emptypassword', true);
return;
}
this.showLoading = true;
try {
await this.validatePassword(<string> password);
// Password validated.
this.lessonReady();
// Now that we have the password, get the access reason again ignoring the password.
const preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo!, true);
this.preventReasons = preventReason ? [preventReason] : [];
// Log view now that we have the password.
this.logActivity();
} catch (error) {
CoreDomUtils.showErrorModal(error);
} finally {
this.showLoading = false;
CoreForms.triggerFormSubmittedEvent(this.formElement, true, this.siteId);
}
}
/**
* Performs the sync of the activity.
*
* @return Promise resolved when done.
*/
protected async sync(): Promise<AddonModLessonSyncResult> {
const result = await AddonModLessonSync.syncLesson(this.lesson!.id, true);
if (!result.updated && this.dataSent && this.isPrefetched()) {
// The user sent data to server, but not in the sync process. Check if we need to fetch data.
await CoreUtils.ignoreErrors(AddonModLessonSync.prefetchAfterUpdate(
AddonModLessonPrefetchHandler.instance,
this.module,
this.courseId,
));
}
return result;
}
/**
* Validate a password and retrieve extra data.
*
* @param password The password to validate.
* @return Promise resolved when done.
*/
protected async validatePassword(password: string): Promise<void> {
try {
this.lesson = await AddonModLesson.getLessonWithPassword(this.lesson!.id, { password, cmId: this.module.id });
this.password = password;
} catch (error) {
this.password = '';
throw error;
}
}
/**
* Open a certain user retake.
*
* @param userId User ID to view.
* @return Promise resolved when done.
*/
async openRetake(userId: number): Promise<void> {
CoreNavigator.navigateToSitePath(
`${AddonModLessonModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/user-retake/${userId}`,
);
}
/**
* Component being destroyed.
*/
ngOnDestroy(): void {
super.ngOnDestroy();
this.dataSentObserver?.off();
}
}
/**
* Overview data including user avatars, calculated in this component.
*/
type AttemptsOverview = Omit<AddonModLessonAttemptsOverviewWSData, 'students'> & {
students?: StudentWithImage[];
};
/**
* Overview student data with the avatar, calculated in this component.
*/
type StudentWithImage = AddonModLessonAttemptsOverviewsStudentWSData & {
profileimageurl?: string;
}; | the_stack |
import type { Color } from "../util/Color";
import type { Pattern } from "../render/patterns/Pattern";
import type { Gradient } from "../render/gradients/Gradient";
import { ISpriteSettings, ISpritePrivate, ISpriteEvents, Sprite } from "./Sprite";
import { IGraphics, BlendMode } from "./backend/Renderer";
import * as $type from "../util/Type";
import * as $array from "../util/Array";
export const visualSettings = ["fill", "fillOpacity", "stroke", "strokeWidth", "strokeOpacity", "fillPattern", "strokePattern", "fillGradient", "strokeGradient", "strokeDasharray", "strokeDashoffset"];
export interface IGraphicsSettings extends ISpriteSettings {
/**
* Fill color.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/} for more information
*/
fill?: Color;
/**
* Stroke (border or line) color.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/} for more information
*/
stroke?: Color;
/**
* Fill pattern.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/patterns/} for more information
*/
fillPattern?: Pattern;
/**
* Stroke (border or line) pattern.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/patterns/} for more information
*/
strokePattern?: Pattern;
/**
* Fill gradient.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/gradients/} for more information
*/
fillGradient?: Gradient;
/**
* Stroke (border or line) gradient.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/gradients/} for more information
*/
strokeGradient?: Gradient;
/**
* Stroke (border or line) dash settings.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/#Dashed_lines} for more information
*/
strokeDasharray?: number[] | number;
/**
* Stroke (border or line) dash offset.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/#Dashed_lines} for more information
*/
strokeDashoffset?: number;
/**
* Opacity of the fill. 0 - fully transparent; 1 - fully opaque.
*/
fillOpacity?: number;
/**
* Opacity of the stroke (border or line). 0 - fully transparent; 1 - fully opaque.
*/
strokeOpacity?: number;
/**
* Width of the stroke (border or line) in pixels.
*/
strokeWidth?: number;
/**
* Drawing function.
*
* Must use renderer (`display` parameter) methods to draw.
*/
draw?: (display: IGraphics, graphics: Graphics) => void;
/**
* Rendering mode.
*
* @default BlendMode.NORMAL ("source-over")
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation} for more information
* @ignore
*/
blendMode?: BlendMode;
/**
* Draw a shape using an SVG path.
*
* @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths} for more information
*/
svgPath?: string;
/**
* Color of the element's shadow.
*
* For this to work at least one of the following needs to be set as well:
* `shadowBlur`, `shadowOffsetX`, `shadowOffsetY`.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/shadows/} for more info
*/
shadowColor?: Color | null;
/**
* Blurriness of the the shadow.
*
* The bigger the number, the more blurry shadow will be.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/shadows/} for more info
*/
shadowBlur?: number;
/**
* Horizontal shadow offset in pixels.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/shadows/} for more info
*/
shadowOffsetX?: number;
/**
* Vertical shadow offset in pixels.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/shadows/} for more info
*/
shadowOffsetY?: number;
/**
* Opacity of the shadow (0-1).
*
* If not set, will use the same as `fillOpacity` of the element.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/colors-gradients-and-patterns/shadows/} for more info
*/
shadowOpacity?: number;
}
export interface IGraphicsPrivate extends ISpritePrivate {
}
export interface IGraphicsEvents extends ISpriteEvents {
}
/**
* Base class used for drawing shapes.
*
* @see {@link https://www.amcharts.com/docs/v5/concepts/common-elements/graphics/} for more info
* @important
*/
export class Graphics extends Sprite {
declare public _settings: IGraphicsSettings;
declare public _privateSettings: IGraphicsPrivate;
declare public _events: IGraphicsEvents;
public _display: IGraphics = this._root._renderer.makeGraphics();
protected _clear = false;
public static className: string = "Graphics";
public static classNames: Array<string> = Sprite.classNames.concat([Graphics.className]);
public _beforeChanged() {
super._beforeChanged();
if (this.isDirty("draw") || this.isDirty("svgPath")) {
this.markDirtyBounds();
}
if (this.isDirty("fill") || this.isDirty("stroke") || this.isDirty("fillGradient") || this.isDirty("strokeGradient") || this.isDirty("fillPattern") || this.isDirty("strokePattern") || this.isDirty("fillOpacity") || this.isDirty("strokeOpacity") || this.isDirty("strokeWidth") || this.isDirty("draw") || this.isDirty("blendMode") || this.isDirty("strokeDasharray") || this.isDirty("strokeDashoffset") || this.isDirty("svgPath") || this.isDirty("shadowColor") || this.isDirty("shadowBlur") || this.isDirty("shadowOffsetX") || this.isDirty("shadowOffsetY")) {
this._clear = true;
}
if (this.isDirty("fillGradient")) {
const gradient = this.get("fillGradient");
if (gradient) {
this._display.isMeasured = true;
const gradientTarget = gradient.get("target");
if (gradientTarget) {
this._disposers.push(gradientTarget.events.on("boundschanged", () => {
this._markDirtyKey("fill");
}))
this._disposers.push(
gradientTarget.events.on("positionchanged", () => {
this._markDirtyKey("fill");
}))
}
}
}
if (this.isDirty("strokeGradient")) {
const gradient = this.get("strokeGradient");
if (gradient) {
this._display.isMeasured = true;
const gradientTarget = gradient.get("target");
if (gradientTarget) {
this._disposers.push(
gradientTarget.events.on("boundschanged", () => {
this._markDirtyKey("stroke");
}))
this._disposers.push(
gradientTarget.events.on("positionchanged", () => {
this._markDirtyKey("stroke");
}))
}
}
}
}
public _changed() {
super._changed();
if (this._clear) {
this.markDirtyLayer();
this._display.clear();
let strokeDasharray = this.get("strokeDasharray");
if ($type.isNumber(strokeDasharray)) {
if (strokeDasharray < 0.5) {
strokeDasharray = [0];
}
else {
strokeDasharray = [strokeDasharray]
}
}
this._display.setLineDash(strokeDasharray as number[]);
const strokeDashoffset = this.get("strokeDashoffset");
if (strokeDashoffset) {
this._display.setLineDashOffset(strokeDashoffset);
}
const blendMode = this.get("blendMode", BlendMode.NORMAL);
this._display.blendMode = blendMode;
const draw = this.get("draw");
if (draw) {
draw(this._display, this);
}
const svgPath = this.get("svgPath");
if (svgPath != null) {
this._display.svgPath(svgPath!);
}
}
}
public _afterChanged() {
super._afterChanged();
if (this._clear) {
const fill = this.get("fill");
const fillGradient = this.get("fillGradient");
const fillPattern = this.get("fillPattern");
const fillOpacity = this.get("fillOpacity");
const stroke = this.get("stroke");
const strokeGradient = this.get("strokeGradient");
const strokePattern = this.get("strokePattern");
const shadowColor = this.get("shadowColor");
const shadowBlur = this.get("shadowBlur");
const shadowOffsetX = this.get("shadowOffsetX");
const shadowOffsetY = this.get("shadowOffsetY");
const shadowOpacity = this.get("shadowOpacity");
//const bounds = this._display.getLocalBounds();
if (shadowColor && (shadowBlur || shadowOffsetX || shadowOffsetY)) {
this._display.shadow(shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY, shadowOpacity);
}
if (fillPattern) {
let changed = false;
if (fill && (!fillPattern.get("fill") || fillPattern.get("fillInherited"))) {
fillPattern.set("fill", fill);
fillPattern.set("fillInherited", true)
changed = true;
}
if (stroke && (!fillPattern.get("color") || fillPattern.get("colorInherited"))) {
fillPattern.set("color", stroke);
fillPattern.set("colorInherited", true)
changed = true;
}
if (changed) {
// @todo: is this OK?
fillPattern._changed();
}
const pattern = fillPattern.pattern;
if (pattern) {
this._display.beginFill(pattern, fillOpacity);
this._display.endFill();
}
}
else if (fillGradient) {
if (fill) {
const stops = fillGradient.get("stops", []);
if (stops.length) {
$array.each(stops, (stop: any) => {
if ((!stop.color || stop.colorInherited) && fill) {
stop.color = fill;
stop.colorInherited = true;
}
if (stop.opacity == null || stop.opacityInherited) {
stop.opacity = fillOpacity;
stop.opacityInherited = true;
}
})
}
}
const gradient = fillGradient.getFill(this);
if (gradient) {
this._display.beginFill(gradient, fillOpacity);
this._display.endFill();
}
}
else if (fill) {
this._display.beginFill(fill, fillOpacity);
this._display.endFill();
}
if (stroke || strokeGradient || strokePattern) {
const strokeOpacity = this.get("strokeOpacity");
const strokeWidth = this.get("strokeWidth", 1);
if (strokePattern) {
let changed = false;
if (stroke && (!strokePattern.get("color") || strokePattern.get("colorInherited"))) {
strokePattern.set("color", stroke);
strokePattern.set("colorInherited", true);
changed = true;
}
if (changed) {
// @todo: is this OK?
strokePattern._changed();
}
const pattern = strokePattern.pattern;
if (pattern) {
this._display.lineStyle(strokeWidth, pattern, strokeOpacity);
this._display.endStroke();
}
}
else if (strokeGradient) {
const stops = strokeGradient.get("stops", []);
if (stops.length) {
$array.each(stops, (stop: any) => {
if ((!stop.color || stop.colorInherited) && stroke) {
stop.color = stroke;
stop.colorInherited = true;
}
if (stop.opacity == null || stop.opacityInherited) {
stop.opacity = strokeOpacity;
stop.opacityInherited = true;
}
})
}
const gradient = strokeGradient.getFill(this);
if (gradient) {
this._display.lineStyle(strokeWidth, gradient, strokeOpacity);
this._display.endStroke();
}
}
else if (stroke) {
this._display.lineStyle(strokeWidth, stroke, strokeOpacity);
this._display.endStroke();
}
}
}
this._clear = false;
}
} | the_stack |
import { expect } from "chai";
import { OAuth2Client } from "google-auth-library";
import * as _ from "lodash";
import * as simple from "simple-mock";
import {
DialogflowEvent,
FacebookEvent,
FacebookPlatform,
GoogleAssistantEvent,
GoogleAssistantPlatform,
VoxaApp,
} from "../../src/";
import { variables } from "../variables";
import { views } from "../views";
/* tslint:disable-next-line:no-var-requires */
const launchIntent = require("../requests/dialogflow/launchIntent.json");
/* tslint:disable-next-line:no-var-requires */
const facebookLaunchIntent = require("../requests/dialogflow/facebookLaunchIntent.json");
/* tslint:disable-next-line:no-var-requires */
const optionIntent = require("../requests/dialogflow/actions.intent.OPTION.json");
/* tslint:disable-next-line:no-var-requires */
const mediaStatusIntent = require("../requests/dialogflow/actions.intent.MEDIA_STATUS.json");
/* tslint:disable-next-line:no-var-requires */
const signinIntent = require("../requests/dialogflow/actions.intent.SIGN_IN.json");
/* tslint:disable-next-line:no-var-requires */
const helpIntent = require("../requests/dialogflow/helpIntent.json");
/* tslint:disable-next-line:no-var-requires */
const permissionIntent = require("../requests/dialogflow/actions.intent.PERMISSION.json");
/* tslint:disable-next-line:no-var-requires */
const datetimeIntent = require("../requests/dialogflow/actions.intent.DATETIME.json");
/* tslint:disable-next-line:no-var-requires */
const placeIntent = require("../requests/dialogflow/actions.intent.PLACE.json");
/* tslint:disable-next-line:no-var-requires */
const confirmationIntent = require("../requests/dialogflow/actions.intent.CONFIRMATION.json");
/* tslint:disable-next-line:no-var-requires */
const slotsIntent = require("../requests/dialogflow/slots.json");
/* tslint:disable-next-line:no-var-requires */
const newSurfaceIntent = require("../requests/dialogflow/actions.intent.NEW_SURFACE.json");
describe("DialogflowEvent", () => {
describe("General Platform Integrations", () => {
it("should get the right userId", async () => {
const event = new DialogflowEvent(launchIntent, {});
/* tslint:disable-next-line:max-line-length */
expect(event.user.id).to.equal(
"ABwppHG14A5zlHSo4Q6CMw3IHD6a3UtYXEtEtcrDrQwBOWKO95VRm-rL-DdhbzDeHXUXiwpDcrDAzY19C8Y",
);
});
it("should return supported capabilities", () => {
const event = new DialogflowEvent(launchIntent, {});
expect(event.supportedInterfaces).to.deep.equal([
"actions.capability.AUDIO_OUTPUT",
"actions.capability.SCREEN_OUTPUT",
"actions.capability.MEDIA_RESPONSE_AUDIO",
"actions.capability.WEB_BROWSER",
]);
});
it("should return undefined for getUserInformation", async () => {
const event = new DialogflowEvent(launchIntent, {});
expect(await event.getUserInformation()).to.be.undefined;
});
it("should return undefined for getUserInformation", () => {
const event = new DialogflowEvent(launchIntent, {});
expect(event.dialogflow.conv.user._id).to.equal(
"ABwppHG14A5zlHSo4Q6CMw3IHD6a3UtYXEtEtcrDrQwBOWKO95VRm-rL-DdhbzDeHXUXiwpDcrDAzY19C8Y",
);
});
});
});
describe("FacebookEvent", () => {
describe("Facebook Messenger", () => {
it("should get the right userId for Facebook Messenger", async () => {
const event = new FacebookEvent(facebookLaunchIntent, {});
expect(event.user.id).to.equal("1234567890");
});
it("should return supported capabilities", () => {
const event = new FacebookEvent(facebookLaunchIntent, {});
expect(event.supportedInterfaces).to.deep.equal([]);
});
});
});
describe("GoogleAssistantEvent", () => {
describe("Google Actions", () => {
it("should format option values", () => {
const event = new GoogleAssistantEvent(optionIntent, {});
expect(event.intent.name).to.equal("actions.intent.OPTION");
expect(event.intent.params).to.deep.equal({
OPTION: "today",
TOUCH: "Today's meditation",
});
});
it("should format dialogflow parms", () => {
const event = new GoogleAssistantEvent(slotsIntent, {});
expect(event.intent.name).to.equal("SleepSingleIntent");
expect(event.intent.params).to.deep.equal({
VOICE: "10 minutes sleep exercise",
length: {
amount: 10,
unit: "min",
},
requestPhrase: "",
text: "10 minutes sleep exercise",
});
});
it("should find users on the session", () => {
const event = new GoogleAssistantEvent(launchIntent, {});
/* tslint:disable-next-line:max-line-length */
expect(event.user.id).to.equal(
"ABwppHG14A5zlHSo4Q6CMw3IHD6a3UtYXEtEtcrDrQwBOWKO95VRm-rL-DdhbzDeHXUXiwpDcrDAzY19C8Y",
);
});
it("should return supported capabilities", () => {
const event = new GoogleAssistantEvent(launchIntent, {});
expect(event.supportedInterfaces).to.deep.equal([
"actions.capability.AUDIO_OUTPUT",
"actions.capability.SCREEN_OUTPUT",
"actions.capability.MEDIA_RESPONSE_AUDIO",
"actions.capability.WEB_BROWSER",
]);
});
it("should return inputs", () => {
const event = new GoogleAssistantEvent(launchIntent, {});
expect(event.intent.name).to.equal("LaunchIntent");
expect(event.intent.params).to.deep.equal({
KEYBOARD: "Talk to my test app",
requestPhrase: "",
});
});
it("should return the MEDIA_STATUS information", () => {
const event = new GoogleAssistantEvent(mediaStatusIntent, {});
expect(event.intent.name).to.equal("MEDIA_STATUS");
expect(event.intent.params).to.deep.equal({
MEDIA_STATUS: {
"@type": "type.googleapis.com/google.actions.v2.MediaStatus",
"status": "FINISHED",
},
});
});
it("should return the SIGN_IN information", () => {
const event = new GoogleAssistantEvent(signinIntent, {});
expect(event.intent.params).to.deep.equal({
SIGN_IN: {
"@type": "type.googleapis.com/google.actions.v2.SignInValue",
"status": "OK",
},
});
});
it("should return the correct intent", () => {
const event = new GoogleAssistantEvent(helpIntent, {});
expect(event.intent.name).to.equal("HelpIntent");
});
it("should extract the session attributes from the context", () => {
const event = new GoogleAssistantEvent(helpIntent, {});
expect(event.session.attributes).to.deep.equal({
key: "value",
});
});
it("should extract the correct parameters from a permissionIntent", () => {
const event = new GoogleAssistantEvent(permissionIntent, {});
expect(event.intent.params).to.deep.equal({
KEYBOARD: "yes",
PERMISSION: true,
});
expect(event.dialogflow.conv.user.permissions).to.deep.equal(["NAME"]);
});
it("should extract the correct parameters from a datetimeIntent", () => {
const event = new GoogleAssistantEvent(datetimeIntent, {});
expect(event.intent.params).to.deep.equal({
DATETIME: {
date: {
day: 8,
month: 6,
year: 2018,
},
time: {
hours: 12,
},
},
KEYBOARD: "noon",
});
});
it("should extract the correct parameters from a confirmationIntent", () => {
const event = new GoogleAssistantEvent(placeIntent, {});
expect(event.intent.params).to.deep.equal({
KEYBOARD: "Query handled by Actions on Google",
PLACE: {
coordinates: {
latitude: 37.1390728,
longitude: -121.6572152,
},
formattedAddress: "Digital Drive, Morgan Hill, CA 95037, USA",
name: "Digital Drive",
placeId: "ChIJF_RbBuogjoAR0BmGuyTKHCY",
},
});
});
it("should extract the NEW_SURFACE confirmationIntent", () => {
const event = new GoogleAssistantEvent(newSurfaceIntent, {});
expect(event.intent.params).to.deep.equal({
NEW_SURFACE: {
"@type": "type.googleapis.com/google.actions.v2.NewSurfaceValue",
"status": "OK",
},
});
});
it("should get the correct userId when present", () => {
const event = new GoogleAssistantEvent(newSurfaceIntent, {});
expect(event.user.id).to.equal("1527283153072");
expect(event.dialogflow.conv.user.storage).to.deep.equal({
voxa: { userId: "1527283153072" },
});
});
it("should generate a new userId when missing", () => {
const event = new GoogleAssistantEvent(confirmationIntent, {});
expect(event.user.id).to.not.be.undefined;
expect(event.dialogflow.conv.user.storage).to.deep.equal({
voxa: { userId: event.user.userId },
});
});
});
describe("Google Sign-In", () => {
let voxaApp: VoxaApp;
let googleAction: GoogleAssistantPlatform;
const googleResponse: any = {
aud: "1234567890-abcdefghijklmnopqrstuvwxyz.apps.googleusercontent.com",
email: "johndoe@example.com",
email_verified: true,
exp: 1542221437,
family_name: "Doe",
given_name: "John",
iat: 1542217837,
iss: "https://accounts.google.com",
jti: "1234567890abcdefghijklmnopqrstuvwxyz",
name: "John Doe",
nbf: 1542217537,
picture:
"https://abc.googleusercontent.com/-abcdefghijok/AAAAAAAAAAI/AAAAAAAACe0/123456789/s96-c/photo.jpg",
sub: "12345678901234567899",
};
beforeEach(() => {
voxaApp = new VoxaApp({ views, variables });
googleAction = new GoogleAssistantPlatform(voxaApp, { clientId: "clientId" });
const userDetailsMocked: any = _.cloneDeep(googleResponse);
simple
.mock(OAuth2Client.prototype, "verifySignedJwtWithCerts")
.returnWith({
getPayload: () => {
return userDetailsMocked;
},
});
});
afterEach(() => {
simple.restore();
});
it("should validate user information", async () => {
const launchIntentWithIdToken = _.cloneDeep(launchIntent);
const pathToIdToken = "originalDetectIntentRequest.payload.user.idToken";
_.set(launchIntentWithIdToken, pathToIdToken, "idToken");
const event = new GoogleAssistantEvent(launchIntentWithIdToken, {});
event.platform = googleAction;
const userInformation = await event.getUserInformation();
const detailsReworked: any = _.cloneDeep(googleResponse);
detailsReworked.emailVerified = detailsReworked.email_verified;
detailsReworked.familyName = detailsReworked.family_name;
detailsReworked.givenName = detailsReworked.given_name;
delete detailsReworked.email_verified;
delete detailsReworked.family_name;
delete detailsReworked.given_name;
expect(userInformation).to.deep.equal(detailsReworked);
});
it("should throw an error when idToken is empty", async () => {
const event = new GoogleAssistantEvent(launchIntent, {});
event.platform = googleAction;
let exceptionWasThrown: boolean = false;
try {
await event.getUserInformation();
} catch (err) {
exceptionWasThrown = true;
expect(err.message).to.equal("conv.user.profile.token is empty");
}
expect(exceptionWasThrown).to.be.true;
});
});
}); | the_stack |
import { ChildProcess, SpawnOptions, spawn } from 'child_process';
import { writeFileSync } from 'fs';
import { CompletionItem, CompletionItemKind, Definition, Disposable, ExtensionContext, Hover, Location, MarkedString, ParameterInformation, Position, Range, SignatureHelp, SignatureInformation, TextDocument, Uri, commands, languages, window, workspace } from 'vscode';
import { fileSync } from 'tmp';
import { Configuration } from '../configuration/Configuration';
import { RustSource } from '../configuration/RustSource';
import { Rustup } from '../configuration/Rustup';
import { getDocumentFilter } from '../configuration/mod';
import { ChildLogger } from '../logging/child_logger';
import { RacerStatusBarItem } from './racer_status_bar_item';
export class CompletionManager {
private configuration: Configuration;
private _rustSource: RustSource;
private _rustup: Rustup | undefined;
private logger: ChildLogger;
private racerDaemon: ChildProcess | undefined;
private commandCallbacks: ((lines: string[]) => void)[];
private linesBuffer: string[];
private dataBuffer: string;
private errorBuffer: string;
private lastCommand: string;
private tmpFile: string;
private providers: Disposable[];
private listeners: Disposable[];
private typeMap: { [type: string]: CompletionItemKind } = {
'Struct': CompletionItemKind.Class,
'Module': CompletionItemKind.Module,
'MatchArm': CompletionItemKind.Variable,
'Function': CompletionItemKind.Function,
'Crate': CompletionItemKind.Module,
'Let': CompletionItemKind.Variable,
'IfLet': CompletionItemKind.Variable,
'WhileLet': CompletionItemKind.Variable,
'For': CompletionItemKind.Variable,
'StructField': CompletionItemKind.Field,
'Impl': CompletionItemKind.Class,
'Enum': CompletionItemKind.Enum,
'EnumVariant': CompletionItemKind.Field,
'Type': CompletionItemKind.Keyword,
'FnArg': CompletionItemKind.Property,
'Trait': CompletionItemKind.Interface,
'Const': CompletionItemKind.Variable,
'Static': CompletionItemKind.Variable
};
private racerStatusBarItem: RacerStatusBarItem;
public constructor(
context: ExtensionContext,
configuration: Configuration,
rustSource: RustSource,
rustup: Rustup | undefined,
logger: ChildLogger
) {
this.configuration = configuration;
this._rustSource = rustSource;
this._rustup = rustup;
this.logger = logger;
this.listeners = [];
const showErrorCommandName = 'rust.racer.show_error';
this.racerStatusBarItem = new RacerStatusBarItem(showErrorCommandName);
context.subscriptions.push(
commands.registerCommand(showErrorCommandName, () => {
this.showErrorBuffer();
})
);
const tmpFile = fileSync();
this.tmpFile = tmpFile.name;
}
public disposable(): Disposable {
return new Disposable(() => {
this.stop();
});
}
/**
* Starts itself at first time.
* Starting fails if a user does not have either racer or Rust's source code
*/
public async initialStart(): Promise<void> {
const logger = this.logger.createChildLogger('initialStart: ');
const pathToRacer: string | undefined = this.configuration.getPathToRacer();
if (!pathToRacer) {
logger.debug('racer is not installed');
return;
}
const isSourceCodeAvailable: boolean = await this.ensureSourceCodeIsAvailable();
if (!isSourceCodeAvailable) {
logger.debug('Rust\'s source is not installed');
return;
}
this.start(pathToRacer);
}
public stop(): void {
this.logger.debug('stop');
this.stopDaemon();
this.racerStatusBarItem.showTurnedOff();
this.stopListeners();
this.clearCommandCallbacks();
}
/**
* Stops the current running instance of racer and starts a new one if a path is defined
* @param pathToRacer A path to the executable of racer
*/
public restart(pathToRacer: string | undefined): void {
this.logger.warning('restart');
this.stop();
if (pathToRacer) {
this.start(pathToRacer);
}
}
/**
* Ensures that Rust's source code is available to use
* @returns flag indicating whether the source code if available or not
*/
private async ensureSourceCodeIsAvailable(): Promise<boolean> {
const logger = this.logger.createChildLogger('ensureSourceCodeIsAvailable: ');
if (this._rustSource.getPath()) {
logger.debug('sources is available');
return true;
}
if (!this._rustup) {
logger.error('rustup is undefined');
return false;
}
// tslint:disable-next-line
const message = 'You are using rustup, but don\'t have installed source code. Do you want to install it?';
const choice = await window.showErrorMessage(message, 'Yes');
if (choice === 'Yes') {
logger.debug('the user agreed to install rust-src');
const rustSrcInstalled = await this._rustup.installRustSrc();
if (rustSrcInstalled) {
logger.debug('rust-src has been installed');
return true;
} else {
logger.error('rust-src has not been installed');
return false;
}
} else {
logger.debug('the user dismissed the dialog');
return false;
}
}
/**
* Starts Racer as a daemon, adds itself as definition, completion, hover, signature provider
* @param pathToRacer A path to the executable of racer which does exist
*/
private start(racerPath: string): void {
const logger = this.logger.createChildLogger('start: ');
logger.debug('enter');
this.commandCallbacks = [];
this.linesBuffer = [];
this.dataBuffer = '';
this.errorBuffer = '';
this.lastCommand = '';
this.providers = [];
logger.debug(`racerPath=${racerPath}`);
this.racerStatusBarItem.showTurnedOn();
const cargoHomePath = this.configuration.getCargoHomePath();
const racerSpawnOptions: SpawnOptions = {
stdio: 'pipe',
env: Object.assign({}, process.env)
};
const rustSourcePath = this._rustSource.getPath();
if (rustSourcePath) {
racerSpawnOptions.env.RUST_SRC_PATH = rustSourcePath;
}
if (cargoHomePath) {
racerSpawnOptions.env.CARGO_HOME = cargoHomePath;
}
logger.debug(`ENV[RUST_SRC_PATH] = ${racerSpawnOptions.env['RUST_SRC_PATH']}`);
this.racerDaemon = spawn(
racerPath,
['--interface=tab-text', 'daemon'],
racerSpawnOptions
);
this.racerDaemon.on('error', (err: NodeJS.ErrnoException) => {
this.logger.error(`racer failed: err = ${err}`);
this.stopDaemon();
if (err.code === 'ENOENT') {
this.racerStatusBarItem.showNotFound();
} else {
this.racerStatusBarItem.showCrashed();
this.scheduleRestart(racerPath);
}
});
this.racerDaemon.on('close', (code: number, signal: string) => {
this.logger.warning(`racer closed: code = ${code}, signal = ${signal}`);
this.stopDaemon();
if (code === 0) {
this.racerStatusBarItem.showTurnedOff();
} else {
this.racerStatusBarItem.showCrashed();
this.scheduleRestart(racerPath);
}
});
this.racerDaemon.stdout.on('data', (data: Buffer) => {
this.dataHandler(data);
});
this.racerDaemon.stderr.on('data', (data: Buffer) => {
this.errorBuffer += data.toString();
});
this.hookCapabilities();
this.listeners.push(workspace.onDidChangeConfiguration(async () => {
await this.configuration.updatePathToRacer();
const newRacerPath: string | undefined = this.configuration.getPathToRacer();
if (racerPath !== newRacerPath) {
this.restart(newRacerPath);
}
}));
}
/**
* Schedules a restart after some time
* @param pathToRacer A path to the executable of racer
*/
private scheduleRestart(racerPath: string): void {
const onTimeout = () => {
this.restart(racerPath);
};
setTimeout(onTimeout, 3000);
}
private stopDaemon(): void {
if (!this.racerDaemon) {
return;
}
this.racerDaemon.kill();
this.racerDaemon = undefined;
this.providers.forEach(disposable => disposable.dispose());
this.providers = [];
}
private stopListeners(): void {
this.listeners.forEach(disposable => disposable.dispose());
this.listeners = [];
}
private clearCommandCallbacks(): void {
this.commandCallbacks.forEach(callback => callback([]));
}
private showErrorBuffer(): void {
const channel = window.createOutputChannel('Racer Error');
channel.clear();
channel.append(`Last command: \n${this.lastCommand}\n`);
channel.append(`Racer Output: \n${this.linesBuffer.join('\n')}\n`);
channel.append(`Racer Error: \n${this.errorBuffer}`);
channel.show(true);
}
private definitionProvider(document: TextDocument, position: Position): Thenable<Definition | undefined> {
const commandArgs = [position.line + 1, position.character, document.fileName, this.tmpFile];
return this.runCommand(document, 'find-definition', commandArgs).then(lines => {
if (lines.length === 0) {
return undefined;
}
const result = lines[0];
const parts = result.split('\t');
const line = Number(parts[2]) - 1;
const character = Number(parts[3]);
const uri = Uri.file(parts[4]);
return new Location(uri, new Position(line, character));
});
}
private hoverProvider(document: TextDocument, position: Position): Thenable<Hover | undefined> | undefined {
// Could potentially use `document.getWordRangeAtPosition`.
const line = document.lineAt(position.line);
const wordStartIndex = line.text.slice(0, position.character + 1).search(/[a-z0-9_]+$/i);
const lastCharIndex = line.text.slice(position.character).search(/[^a-z0-9_]/i);
const wordEndIndex = lastCharIndex === -1 ? 1 + position.character : lastCharIndex + position.character;
const lineTail = line.text.slice(wordEndIndex).trim();
const isFunction = lineTail === '' ? false : lineTail[0] === '(';
const word = line.text.slice(wordStartIndex, wordEndIndex);
if (!word) {
return undefined;
}
// We are using `complete-with-snippet` instead of `find-definition` because it contains
// extra information that is not contained in the `find`definition` command, such as documentation.
const commandArgs = [position.line + 1, wordEndIndex, document.fileName, this.tmpFile];
return this.runCommand(document, 'complete-with-snippet', commandArgs).then(lines => {
if (lines.length <= 1) {
return undefined;
}
const results = lines.slice(1).map(x => x.split('\t'));
const result =
isFunction
? results.find(parts => parts[2].startsWith(word + '(') && parts[6] === 'Function')
: results.find(parts => parts[2] === word);
// We actually found a completion instead of a definition, so we won't show the returned info.
if (!result) {
return undefined;
}
const match = result[2];
const type = result[6];
let definition = type === 'Module' ? 'module ' + match : result[7];
const docs = JSON.parse(result[8].replace(/\\'/g, "'")).split('\n');
const bracketIndex = definition.indexOf('{');
if (bracketIndex !== -1) {
definition = definition.substring(0, bracketIndex);
}
const processedDocs: MarkedString[] = [{
language: 'rust',
value: definition.trim()
}];
let currentBlock: string[] = [];
let codeBlock = false;
let extraIndent = 0;
// The logic to push a block to the processed blocks is a little
// contrived, depending on if we are inside a language block or not,
// as the logic has to be repeated at the end of the for block, I
// preferred to extract it to an inline function.
function pushBlock(): void {
if (codeBlock) {
processedDocs.push({
language: 'rust',
value: currentBlock.join('\n')
});
} else {
processedDocs.push(currentBlock.join('\n'));
}
}
for (let i = 0; i < docs.length; i++) {
const docLine = docs[i];
if (docLine.trim().startsWith('```')) {
if (currentBlock.length) {
pushBlock();
currentBlock = [];
}
codeBlock = !codeBlock;
extraIndent = docLine.indexOf('```');
continue;
}
if (codeBlock) {
if (!docLine.trim().startsWith('# ')) {
currentBlock.push(docLine.slice(extraIndent));
}
continue;
}
// When this was implemented (vscode 1.5.1), the markdown headers
// were a little buggy, with a large margin-botton that pushes the
// next line far down. As an alternative, I replaced the headers
// with links (that lead to nowhere), just so there is some highlight.
//
// The preferred alternative would be to just make the headers a little
// smaller and otherwise draw them as is.
if (docLine.trim().startsWith('#')) {
const headerMarkupEnd = docLine.trim().search(/[^# ]/);
currentBlock.push('[' + docLine.trim().slice(headerMarkupEnd) + ']()');
continue;
}
currentBlock.push(docLine);
}
if (currentBlock.length) {
pushBlock();
}
return new Hover(processedDocs);
});
}
private completionProvider(document: TextDocument, position: Position): Thenable<CompletionItem[]> | undefined {
const commandArgs = [position.line + 1, position.character, document.fileName, this.tmpFile];
const range = new Range(position.line, 0, position.line, position.character);
const text = document.getText(range).trim();
if (text.startsWith('//')) {
return undefined;
}
return this.runCommand(document, 'complete-with-snippet', commandArgs).then(lines => {
lines.shift();
// Split on MATCH, as a definition can span more than one line
lines = lines.map(l => l.trim()).join('').split('MATCH\t').slice(1);
const completions = [];
for (const line of lines) {
const parts = line.split('\t');
const label = parts[0];
const type = parts[5];
let detail = parts[6];
let kind: CompletionItemKind;
if (type in this.typeMap) {
kind = this.typeMap[type];
} else {
console.warn('Kind not mapped: ' + type);
kind = CompletionItemKind.Text;
}
// Remove trailing bracket
if (type !== 'Module' && type !== 'Crate') {
let bracketIndex = detail.indexOf('{');
if (bracketIndex === -1) {
bracketIndex = detail.length;
}
detail = detail.substring(0, bracketIndex).trim();
}
completions.push({ label, kind, detail });
}
return completions;
});
}
private parseParameters(text: string, startingPosition: number): [string[], number, number] {
const stopPosition = text.length;
const parameters = [];
let currentParameter = '';
let currentDepth = 0;
let parameterStart = -1;
let parameterEnd = -1;
for (let i = startingPosition; i < stopPosition; i++) {
const char = text.charAt(i);
if (char === '(') {
if (currentDepth === 0) {
parameterStart = i;
}
currentDepth += 1;
continue;
} else if (char === ')') {
currentDepth -= 1;
if (currentDepth === 0) {
parameterEnd = i;
break;
}
continue;
}
if (currentDepth === 0) {
continue;
}
if (currentDepth === 1 && char === ',') {
parameters.push(currentParameter);
currentParameter = '';
} else {
currentParameter += char;
}
}
parameters.push(currentParameter);
return [parameters, parameterStart, parameterEnd];
}
private parseCall(name: string, args: string[], definition: string, callText: string): SignatureHelp {
const nameEnd = definition.indexOf(name) + name.length;
// tslint:disable-next-line
let [params, paramStart, paramEnd] = this.parseParameters(definition, nameEnd);
const [callParameters] = this.parseParameters(callText, 0);
const currentParameter = callParameters.length - 1;
const nameTemplate = definition.substring(0, paramStart);
// If function is used as a method, ignore the self parameter
if ((args ? args.length : 0) < params.length) {
params = params.slice(1);
}
const result = new SignatureHelp();
result.activeSignature = 0;
result.activeParameter = currentParameter;
const signature = new SignatureInformation(nameTemplate);
signature.label += '(';
params.forEach((param, i) => {
const parameter = new ParameterInformation(param, '');
signature.label += parameter.label;
signature.parameters.push(parameter);
if (i !== params.length - 1) {
signature.label += ', ';
}
});
signature.label += ') ';
let bracketIndex = definition.indexOf('{', paramEnd);
if (bracketIndex === -1) {
bracketIndex = definition.length;
}
// Append return type without possible trailing bracket
signature.label += definition.substring(paramEnd + 1, bracketIndex).trim();
result.signatures.push(signature);
return result;
}
private firstDanglingParen(document: TextDocument, position: Position): Position | undefined {
const text = document.getText();
let offset = document.offsetAt(position) - 1;
let currentDepth = 0;
while (offset > 0) {
const char = text.charAt(offset);
if (char === ')') {
currentDepth += 1;
} else if (char === '(') {
currentDepth -= 1;
} else if (char === '{') {
return undefined; // not inside function call
}
if (currentDepth === -1) {
return document.positionAt(offset);
}
offset--;
}
return undefined;
}
private signatureHelpProvider(document: TextDocument, position: Position): Thenable<SignatureHelp | undefined> | undefined {
// Get the first dangling parenthesis, so we don't stop on a function call used as a previous parameter
const startPos = this.firstDanglingParen(document, position);
if (!startPos) {
return undefined;
}
const name = document.getText(document.getWordRangeAtPosition(startPos));
const commandArgs = [startPos.line + 1, startPos.character - 1, document.fileName, this.tmpFile];
return this.runCommand(document, 'complete-with-snippet', commandArgs).then((lines) => {
lines = lines.map(l => l.trim()).join('').split('MATCH\t').slice(1);
let parts: string[] | undefined = [];
for (const line of lines) {
parts = line.split('\t');
if (parts[0] === name) {
break;
}
}
if (!parts) {
return undefined;
}
const args = parts[1].match(/\${\d+:\w+}/g);
if (!args) {
return undefined;
}
const type = parts[5];
const definition = parts[6];
if (type !== 'Function') {
return null;
}
const callText = document.getText(new Range(startPos, position));
return this.parseCall(name, args, definition, callText);
});
}
private hookCapabilities(): void {
const definitionProvider = { provideDefinition: this.definitionProvider.bind(this) };
this.providers.push(
languages.registerDefinitionProvider(getDocumentFilter(), definitionProvider)
);
const completionProvider = { provideCompletionItems: this.completionProvider.bind(this) };
this.providers.push(
languages.registerCompletionItemProvider(
getDocumentFilter(),
completionProvider,
...['.', ':']
)
);
const signatureProvider = { provideSignatureHelp: this.signatureHelpProvider.bind(this) };
this.providers.push(
languages.registerSignatureHelpProvider(
getDocumentFilter(),
signatureProvider,
...['(', ',']
)
);
const hoverProvider = { provideHover: this.hoverProvider.bind(this) };
this.providers.push(languages.registerHoverProvider(getDocumentFilter(), hoverProvider));
}
private dataHandler(data: Buffer): void {
// Ensure we only start parsing when the whole line has been flushed.
// It can happen that when a line goes over a certain length, racer will
// flush it one part at a time, if we don't wait for the whole line to
// be flushed, we will consider each part of the original line a separate
// line.
const dataStr = data.toString();
if (!/\r?\n$/.test(dataStr)) {
this.dataBuffer += dataStr;
return;
}
const lines = (this.dataBuffer + dataStr).split(/\r?\n/);
this.dataBuffer = '';
for (const line of lines) {
if (line.length === 0) {
continue;
} else if (line.startsWith('END')) {
const callback = this.commandCallbacks.shift();
if (callback !== undefined) {
callback(this.linesBuffer);
}
this.linesBuffer = [];
} else {
this.linesBuffer.push(line);
}
}
}
private updateTmpFile(document: TextDocument): void {
writeFileSync(this.tmpFile, document.getText());
}
private runCommand(document: TextDocument, command: string, args: any[]): Promise<string[]> {
if (!this.racerDaemon) {
return Promise.reject(undefined);
}
this.updateTmpFile(document);
const queryString = [command, ...args].join('\t') + '\n';
this.lastCommand = queryString;
const promise = new Promise(resolve => {
this.commandCallbacks.push(resolve);
});
this.racerDaemon.stdin.write(queryString);
return promise;
}
} | the_stack |
import { bold, green, red, resetColor, yellow } from "../../deps.ts";
import Command from "../Command.ts";
import Option from "../Option.ts";
import { AppDetails, CommandArgument } from "../types/types.ts";
/** Prints success message */
export function success_log(text: string, classicMode: boolean = false): void {
console.log(classicMode ? `${text}` : green(`✅ ${text}`));
}
/** Prints warning message */
export function warning_log(text: string, classicMode: boolean = false): void {
console.log(classicMode ? `${text}` : yellow(`⚠️ ${text}`));
}
/** Prints error message */
export function error_log(text: string, classicMode: boolean = false): void {
console.log(classicMode ? `${text}` : red(`❌ ${text}`));
}
function getUniqueOptions(array: Option[]) {
let options: Option[] = [];
let distinct: any = [];
for (let i = 0; i < array.length; i++) {
if (!distinct.includes(array[i].flags)) {
distinct.push(array[i].flags);
options.push(array[i]);
}
}
return options.sort((a, b) => {
return a.flags.localeCompare(b.flags);
});
}
function calculateSpaceNeeded(args: string[]) {
const lengths = args.map((str) => resetColor(str).length);
const largest = Math.max(...lengths);
return largest + 2;
}
function printFormatted(key: string, value: string, len: number, pad = false) {
let padStr = pad ? " " : "";
let keyStr = key.padEnd(len);
console.log(`${padStr}${keyStr}${value}`);
}
/** The help screen. */
export function printHelp(
app_details: AppDetails,
commands: Array<Command>,
BASE_COMMAND: Command,
) {
console.log();
console.log(green(bold(app_details.app_name)));
console.log(red(bold("v" + app_details.app_version)));
console.log();
console.log(yellow(bold("Description:")));
console.log(app_details.app_description);
console.log();
let commandsList = commands.filter((command) => !command.isDefault);
const maxLen = calculateSpaceNeeded([
...BASE_COMMAND.options.map(({ flags }) => flags),
...commandsList.map(({ value }) => value),
]);
console.log(yellow(bold("Options:")));
BASE_COMMAND.options.forEach((option) => {
printFormatted(option.flags, option.description, maxLen);
});
console.log();
if (commandsList.length) {
console.log(yellow(bold("Commands:")));
commandsList.forEach((command) => {
printFormatted(command.value, command.description, maxLen);
});
console.log();
}
}
/** The help screen. */
export function printHelpClassic(
app_details: AppDetails,
commands: Array<Command>,
BASE_COMMAND: Command,
) {
const defaultCommand = commands.find((command) => command.isDefault);
if (defaultCommand) {
defaultCommand.options = getUniqueOptions([
...BASE_COMMAND.options,
...defaultCommand.options,
]);
printCommandHelpClassic(defaultCommand);
return;
}
console.log(`Usage: ${app_details.app_name}`);
console.log();
console.log(app_details.app_description);
console.log();
let commandsList = commands.filter((command) => !command.isDefault);
const maxLen = calculateSpaceNeeded([
...BASE_COMMAND.options.map(({ flags }) => flags),
...commandsList.map(({ value }) => value),
]);
console.log("Options:");
getUniqueOptions(BASE_COMMAND.options).forEach((option: Option) => {
printFormatted(option.flags, option.description, maxLen, true);
});
console.log();
if (commandsList.length) {
console.log("Commands:");
commandsList.forEach((command) => {
printFormatted(command.value, command.description, maxLen, true);
});
console.log();
}
}
////////////////////////////////////////////////////////////////////////////////
/** Print the help screen for a specific command. */
export function printCommandHelpOld(command: Command, BASE_COMMAND?: Command) {
console.log();
if (command.hasSubCommands()) {
console.log(yellow(bold("Subcommands:")));
command.subCommands.map((subCommand: Command) => {
console.log(subCommand.word_command);
});
console.log();
}
if (command.isSubCommand()) {
console.log(yellow(bold("Parent Command:")));
console.log(command.parentCommand?.word_command);
console.log();
}
if (command.description) {
console.log(yellow(bold("Description:")));
console.log(command.description);
console.log();
}
console.log(yellow(bold(command.isDefault ? "Usage:" : "Command Usage:")));
if (command.hasSubCommands()) {
console.log(command.usage + " {Subcommand}");
} else if (command.hasOptions()) {
console.log(command.usage + " {Options}");
} else {
console.log(command.usage);
}
console.log();
const requiredOptions: Option[] = getUniqueOptions([
...command.requiredOptions,
...(BASE_COMMAND && command.isDefault) ? BASE_COMMAND.requiredOptions : [],
]);
const options: Option[] = getUniqueOptions([
...command.options,
...(BASE_COMMAND && command.isDefault) ? BASE_COMMAND.options : [],
]);
let maxLen = calculateSpaceNeeded([
...command.command_arguments.map(({ value }) => value).filter((val) => val),
...requiredOptions.map(({ flags }) => flags),
...options.map(({ flags }) => flags),
]);
if (command.command_arguments.length > 0) {
console.log(yellow(bold("Arguments:")));
command.command_arguments.forEach((commandArg: CommandArgument) => {
let helpText = green(
`${commandArg.argument}${commandArg.isRequired ? "" : "?"}`,
);
if (commandArg.description) {
helpText = helpText + " \t" + commandArg.description;
}
printFormatted(command.value, command.description, maxLen);
});
console.log();
}
if (command.hasRequiredOptions()) {
console.log(yellow(bold("Required Options:")));
requiredOptions.forEach((option) => {
let extraStr = "";
if (option.hasDefaultValue() || option.choices) {
extraStr += "\t";
}
if (option.hasDefaultValue()) {
extraStr += `(default: ${option.defaultValue})`;
}
if (option.choices) {
extraStr += `(choices: ${option.choices.toString()})`;
}
const valueStr = `${option.description}${extraStr}`;
printFormatted(green(option.flags), valueStr, maxLen);
});
console.log();
}
console.log(yellow(bold("Options:")));
options.forEach((option) => {
if (!option.isRequired) {
let extraStr = "";
if (option.hasDefaultValue() || option.choices) {
extraStr += "\t";
}
if (option.hasDefaultValue()) {
extraStr += `(default: ${option.defaultValue})`;
}
if (option.choices) {
extraStr += `(choices: ${option.choices.toString()})`;
}
const valueStr = `${option.description}${extraStr}`;
printFormatted(green(option.flags), valueStr, maxLen);
}
});
console.log();
if (command.hasAlias()) {
console.log(yellow(bold("Aliases:")));
command.aliases.forEach((alias) => console.log(alias));
}
}
/** Print the help screen for a specific command. */
export function printCommandHelp(command: Command, BASE_COMMAND?: Command) {
let usage = command.usage;
if (command.isDefault) {
usage = usage.replace(/^__DEFAULT__ /, "");
}
if (command.hasSubCommands()) {
usage += " {subcommand}";
} else if (command.hasOptions()) {
usage += " {options}";
}
console.log();
console.log(yellow(bold(command.isDefault ? "Usage:" : "Command Usage:")));
console.log(usage);
console.log();
if (command.description) {
console.log(yellow(bold("Description:")));
console.log(command.description);
console.log();
}
if (command.hasSubCommands()) {
console.log(yellow(bold("Subcommands:")));
command.subCommands.map((subCommand: Command) => {
console.log(subCommand.word_command);
});
console.log();
}
if (command.isSubCommand()) {
console.log(yellow(bold("Parent Command:")));
console.log(command.parentCommand?.word_command);
console.log();
}
const requiredOptions: Option[] = getUniqueOptions([
...command.requiredOptions,
...(BASE_COMMAND && command.isDefault) ? BASE_COMMAND.requiredOptions : [],
]);
const options: Option[] = getUniqueOptions([
...command.options,
...(BASE_COMMAND && command.isDefault) ? BASE_COMMAND.options : [],
]);
let maxLen = calculateSpaceNeeded([
...command.command_arguments.map(({ value }) => value).filter((val) => val),
...requiredOptions.map(({ flags }) => flags),
...options.map(({ flags }) => flags),
]) + 1; // Not sure why it needs the extra 1.
if (command.command_arguments.length > 0) {
const hasRequired = command.command_arguments
.map(({ isRequired }) => isRequired)
.includes(true);
let commandsLen = calculateSpaceNeeded(
command.command_arguments.map(({ argument }) => argument),
);
if (hasRequired) {
commandsLen += 1;
}
maxLen = Math.max(maxLen, commandsLen);
console.log(yellow(bold("Arguments:")));
command.command_arguments.forEach((commandArg: CommandArgument) => {
let helpText = green(
`${commandArg.argument}${commandArg.isRequired ? "" : "?"}`,
);
if (commandArg.description) {
printFormatted(helpText, commandArg.description, maxLen);
} else {
console.log(helpText);
}
});
console.log();
}
if (command.hasRequiredOptions()) {
console.log(yellow(bold("Required Options:")));
requiredOptions.forEach((option) => {
let extraStr = "";
if (option.hasDefaultValue() || option.choices) {
extraStr += "\t";
}
if (option.hasDefaultValue()) {
extraStr += `(default: ${option.defaultValue})`;
}
if (option.choices) {
extraStr += `(choices: ${option.choices.toString()})`;
}
const valueStr = `${option.description}${extraStr}`;
printFormatted(green(option.flags), valueStr, maxLen);
});
console.log();
}
console.log(yellow(bold("Options:")));
options.forEach((option: Option) => {
if (!option.isRequired) {
let extraStr = "";
if (option.hasDefaultValue() || option.choices) {
extraStr += "\t";
}
if (option.hasDefaultValue()) {
extraStr += `(default: ${option.defaultValue})`;
}
if (option.choices) {
extraStr += `(choices: ${option.choices.toString()})`;
}
const valueStr = `${option.description}${extraStr}`;
printFormatted(green(option.flags), valueStr, maxLen);
}
});
console.log();
if (command.hasAlias()) {
console.log(yellow(bold("Aliases:")));
command.aliases.forEach((alias) => {
console.log(alias);
});
}
}
/** Print the help screen for a specific command (Classic). */
export function printCommandHelpClassic(
command: Command,
BASE_COMMAND?: Command,
) {
let usage = command.usage;
// ...BASE_COMMAND.options,
if (command.isDefault) {
usage = usage.replace(/^__DEFAULT__ /, "");
}
if (command.hasSubCommands()) {
usage += " {subcommand}";
} else if (command.hasOptions()) {
usage += " {options}";
}
console.log(`Usage: ${usage}`);
console.log();
if (command.description) {
console.log(command.description);
console.log();
}
if (command.hasSubCommands()) {
console.log("Subcommands:");
command.subCommands.map((subCommand: Command) => {
console.log(" " + subCommand.word_command);
});
console.log();
}
if (command.isSubCommand()) {
console.log("Parent Command:");
console.log(" " + command.parentCommand?.word_command);
console.log();
}
const requiredOptions: Option[] = getUniqueOptions([
...command.requiredOptions,
...(BASE_COMMAND && command.isDefault) ? BASE_COMMAND.requiredOptions : [],
]);
const options: Option[] = getUniqueOptions([
...command.options,
...(BASE_COMMAND && command.isDefault) ? BASE_COMMAND.options : [],
]);
let maxLen = calculateSpaceNeeded([
...requiredOptions.map(({ flags }) => flags),
...options.map(({ flags }) => flags),
]);
if (command.command_arguments.length > 0) {
const hasRequired = command.command_arguments
.map(({ isRequired }) => isRequired)
.includes(true);
let commandsLen = calculateSpaceNeeded(
command.command_arguments.map(({ argument }) => argument),
);
if (hasRequired) {
commandsLen += 1;
}
maxLen = Math.max(maxLen, commandsLen);
console.log("Arguments:");
command.command_arguments.forEach((commandArg: CommandArgument) => {
let helpText = `${commandArg.argument}${
commandArg.isRequired ? "" : "?"
}`;
if (commandArg.description) {
printFormatted(helpText, commandArg.description, maxLen, true);
} else {
console.log(helpText);
}
});
console.log();
}
if (command.hasRequiredOptions()) {
console.log("Required Options:");
requiredOptions.forEach((option) => {
let extraStr = "";
if (option.hasDefaultValue() || option.choices) {
extraStr += "\t";
}
if (option.hasDefaultValue()) {
extraStr += `(default: ${option.defaultValue})`;
}
if (option.choices) {
extraStr += `(choices: ${option.choices.toString()})`;
}
const valueStr = `${option.description}${extraStr}`;
printFormatted(option.flags, valueStr, maxLen, true);
});
console.log();
}
console.log("Options:");
options.forEach((option: Option) => {
if (!option.isRequired) {
let extraStr = "";
if (option.hasDefaultValue() || option.choices) {
extraStr += "\t";
}
if (option.hasDefaultValue()) {
extraStr += `(default: ${option.defaultValue})`;
}
if (option.choices) {
extraStr += `(choices: ${option.choices.toString()})`;
}
const valueStr = `${option.description}${extraStr}`;
printFormatted(option.flags, valueStr, maxLen, true);
}
});
console.log();
if (command.hasAlias()) {
console.log("Aliases:");
command.aliases.forEach((alias) => {
console.log(" " + alias);
});
}
} | the_stack |
import {
print,
TypeMessage,
printSeparator,
} from "../../adapters/messages/console-log";
import * as fs from "fs";
import * as path from "path";
import * as ejs from "ejs";
import { BigNumber } from "bignumber.js";
import antlr4 = require("antlr4/index");
import { ANTLRInputStream, CommonTokenStream } from "antlr4ts";
import { binding_grammarLexer } from "../utils/antlr/binding_grammarLexer";
import { binding_grammarParser } from "../utils/antlr/binding_grammarParser";
import { BindingVisitor } from "../utils/structs/binding-policy-visitor";
import { Policy } from "../utils/structs/policy-info";
const policy2solEJS = fs.readFileSync(
path.join(__dirname, "./../../../templates-ejs/dynamic-access-control") +
"/policy2sol.ejs",
"utf-8"
);
const procesRole2solEJS = fs.readFileSync(
path.join(__dirname, "./../../../templates-ejs/dynamic-access-control") +
"/procesRole2sol.ejs",
"utf-8"
);
const procesRole2ArrsolEJS = fs.readFileSync(
path.join(__dirname, "./../../../templates-ejs/dynamic-access-control") +
"/processRole2solArray.ejs",
"utf-8"
);
let policy2solTemplate = ejs.compile(policy2solEJS);
let procesRole2solTemplate = ejs.compile(procesRole2solEJS);
let procesRole2solArrTemplate = ejs.compile(procesRole2ArrsolEJS);
export let generatePolicy = (policyStr: string, policyName: string) => {
return new Promise<Policy>((resolve, reject) => {
try {
/////////////////////////////////////////////
/// LEXER AND PAXER (ANTLR) ///
////////////////////////////////////////////
let inputStream = new ANTLRInputStream(policyStr);
let lexer = new binding_grammarLexer(inputStream);
let tokenStream = new CommonTokenStream(lexer);
let parser = new binding_grammarParser(tokenStream);
parser.buildParseTree = true;
let tree = parser.binding_policy();
let visitor = new BindingVisitor();
visitor.visit(tree);
let policy = visitor.policy;
/////////////////////////////////////////////
/// CONSISTENCY AND SEMANTIC ANALYSIS ///
////////////////////////////////////////////
// (1) every role must appear as case creator or nominee in some statement.
for (let [key, value] of policy.roleIndexMap) {
let found = false;
if (policy.caseCreator !== key) {
for (let i = 0; i < policy.nominationStatements.length; i++) {
if (policy.nominationStatements[i].nominee == key) {
found = true;
break;
}
}
if (!found)
throw (
"Role [" +
key +
"] cannot be nominated. \n Check that every role in the policy must appear as nominee, or case creator."
);
}
}
// (2) In each statement the nominator and every role in the binding and endorsement constraints must be BOUND before the nominee
// (2.1) Constructing the Nomination Net
// pB will be the index of the role (policy.indexRoleMap[role]), in case of self pU will be policy.indexRoleMap[role] + countRoles
let transitions = [];
let marking = [];
marking[policy.roleIndexMap.get(policy.caseCreator)] = 1;
policy.nominationStatements.forEach((statement) => {
let output = policy.roleIndexMap.get(statement.nominee);
let input = [];
let taken = [];
taken[policy.roleIndexMap.get(statement.nominee)] = 1;
let addArc = (rIndex) => {
if (taken[rIndex] !== 1) {
input.push(rIndex);
taken[rIndex] = 1;
}
};
let updateConstraint = (conjunctionSet) => {
conjunctionSet.forEach((andSet) => {
andSet.roles.forEach((role) => {
addArc(policy.roleIndexMap.get(role));
});
});
};
if (
statement.nominator === statement.nominee ||
statement.nominee === "self"
) {
addArc(
policy.roleIndexMap.get(statement.nominator) + policy.roleCount
);
if (
taken[
policy.roleIndexMap.get(statement.nominator) + policy.roleCount
] !== 1
)
marking[
policy.roleIndexMap.get(statement.nominator) + policy.roleCount
] = 1;
} else addArc(policy.roleIndexMap.get(statement.nominator));
if (statement.bindingConstraint !== undefined)
updateConstraint(statement.bindingConstraint.conjunctionSets);
if (statement.endorsementConstraint !== undefined)
updateConstraint(statement.endorsementConstraint.conjunctionSets);
transitions.push({ input: input, output: output });
});
// (2.2) Validating the precedences (no dead transitions in the nomination net)
let firedTransitions = [];
let firedCount = 0;
let roleOrder = [];
let level = 0;
while (true) {
let toFire = [];
for (let i = 0; i < transitions.length; i++) {
if (firedTransitions[i] !== 1) {
let input = transitions[i].input;
// Validating If enabled
let enabled = true;
for (let j = 0; j < input.length; j++)
if (marking[input[j]] !== 1) {
enabled = false;
break;
}
if (enabled) toFire.push(i);
}
}
// No new enabled transition
if (toFire.length === 0) break;
level++;
// Firing new enabled transitions
toFire.forEach((trIndex) => {
marking[transitions[trIndex].output] = 1;
firedTransitions[trIndex] = 1;
firedCount++;
roleOrder[transitions[trIndex].output] = level;
});
// Every transition already fired, no dead transition
if (firedCount === transitions.length) break;
}
if (firedCount < transitions.length) {
let invalid = "";
for (let [key, value] of policy.roleIndexMap) {
if (marking[value] !== 1) invalid += "[" + key + "] ";
}
throw "Roles " + invalid + "cannot be nominated";
} else {
print("Success: the policy is consistent", TypeMessage.success);
print(" Role Precedence: ", TypeMessage.data);
print(` 0: ${policy.caseCreator}`, TypeMessage.data);
for (let i = 1; i <= level; i++) {
let inLevel = "";
for (let [key, value] of policy.roleIndexMap) {
if (roleOrder[value] === i) inLevel += key + " ";
}
print(` ${i}: ${inLevel}`, TypeMessage.data);
}
printSeparator();
}
/////////////////////////////////////////////
/// SMART CONTRACT GENERATION ///
////////////////////////////////////////////
// (1) BitSet Operations
let bitArrayToInteger = (bitarray) => {
if (bitarray.length > 0) {
let result = "0b";
for (let i = bitarray.length - 1; i >= 0; i--)
result += bitarray[i] ? "1" : "0";
return new BigNumber(result).toFixed();
} else {
return "0";
}
};
let roleMask = (roleId) => {
if (policy.roleIndexMap.has(roleId)) {
let bitarray = [];
bitarray[policy.roleIndexMap.get(roleId)] = 1;
return bitArrayToInteger(bitarray);
} else {
return "0";
}
};
let nominatorMask = (statementList, nominator) => {
let bitarray = [];
statementList.forEach((statement) => {
if (statement.nominator === nominator) {
bitarray[policy.roleIndexMap.get(statement.nominee)] = 1;
}
});
return bitArrayToInteger(bitarray);
};
let disjunctionSetMask = (disjunctionSet) => {
let maskArray = [];
disjunctionSet.conjunctionSets.forEach((andSet) => {
let bitarray = [];
andSet.roles.forEach((role) => {
bitarray[policy.roleIndexMap.get(role)] = 1;
});
maskArray.push(bitArrayToInteger(bitarray));
});
return maskArray;
};
let disjunctionSetJoinMask = (disjunctionSet) => {
let bitarray = [];
disjunctionSet.conjunctionSets.forEach((andSet) => {
andSet.roles.forEach((role) => {
bitarray[policy.roleIndexMap.get(role)] = 1;
});
});
return bitArrayToInteger(bitarray);
};
let statementMask = (statement) => {
let bitarray = [];
bitarray[policy.roleIndexMap.get(statement.nominator)] = 1;
bitarray[policy.roleIndexMap.get(statement.nominee)] = 1;
return bitArrayToInteger(bitarray);
};
let endorsementRequiredMask = (statements) => {
let maskArray = [];
statements.forEach((statement) => {
if (statement.endorsementConstraint !== undefined)
maskArray.push(statementMask(statement));
});
return maskArray;
};
let codeGenerationInfo = {
policyName: policyName,
roleIndex: (roleId) => policy.roleIndexMap.get(roleId),
creatorMask: roleMask(policy.caseCreator),
statementMask: (statement) => statementMask(statement),
nominationStatements: policy.nominationStatements,
nominationMask: (nominator, statements) =>
nominatorMask(statements, nominator),
disjunctionSetJoinMask: (disjunctionSet) =>
disjunctionSetJoinMask(disjunctionSet),
disjunctionSetMask: (disjunctionSet) =>
disjunctionSetMask(disjunctionSet),
endorsementRequiredMask: (statements) =>
endorsementRequiredMask(statements),
releaseStatements: policy.releaseStatements,
};
policy.solidity = policy2solTemplate(codeGenerationInfo);
resolve(policy);
} catch (ex) {
print(`ERROR: ${ex}`, TypeMessage.error);
reject(new Policy());
}
});
};
export let generateRoleTaskContract = (
roleTaskPairs: Array<any>,
contractName: string,
isArray: boolean
) => {
return new Promise<string>((resolve, reject) => {
try {
/////////////////////////////////////////////
/// SMART CONTRACT GENERATION ///
////////////////////////////////////////////
let processData = new Map<string, Array<any>>();
processData.set(contractName, roleTaskPairs);
let sortedMaping: Map<string, Array<number>> = new Map();
if (isArray) {
for (let [key, indexes] of processData) {
let maxTaskInd = 0;
indexes.forEach((index) => {
maxTaskInd =
index.taskIndex > maxTaskInd ? index.taskIndex : maxTaskInd;
});
let sorted: Array<number> = new Array();
for (let i = 0; i <= maxTaskInd; i++) {
let toPush = 0;
indexes.forEach((index) => {
if (index.taskIndex === i) toPush = index.roleIndex;
});
sorted.push(toPush);
}
sortedMaping.set(key, sorted);
}
} else {
sortedMaping = processData;
}
let codeGenerationInfo = {
contractName: contractName,
processData: sortedMaping,
};
let policySolidity = isArray
? procesRole2solArrTemplate(codeGenerationInfo)
: procesRole2solTemplate(codeGenerationInfo);
resolve(policySolidity);
} catch (ex) {
print(`ERROR: ${ex}`, TypeMessage.error);
reject("Error on the contract creation");
}
});
}; | the_stack |
import { fsToProject } from './fsToProject'
import { projectToFs } from './projectToFs'
import * as path from 'path'
import { readDefinition } from './yaml'
import chalk from 'chalk'
import { Args, GraphcoolModule, ProjectDefinition } from '../types/common'
import fs from '../fs'
import { Output } from '../Output/index'
import { Config } from '../Config'
import { GraphcoolDefinition, FunctionDefinition } from 'graphcool-json-schema'
import { flatMap } from 'lodash'
import * as yamlParser from 'yaml-ast-parser'
import * as yaml from 'js-yaml'
import { builtinModules } from './builtin-modules'
const debug = require('debug')('project-definition')
export interface FunctionTuple {
name: string
fn: FunctionDefinition
}
export class ProjectDefinitionClass {
static sanitizeDefinition(definition: ProjectDefinition) {
const modules = definition.modules.map(module => {
const { name, files, externalFiles } = module
let content = module.content
if (module.definition && typeof module.definition === 'object') {
// parse + stringify trims away `undefined` values, which are not accepted by the yaml parser
if (Array.isArray(module.definition.types)) {
module.definition.types = module.definition.types[0]
}
content = yaml.safeDump(JSON.parse(JSON.stringify(module.definition)))
}
return { name, content, files, externalFiles }
})
return { modules }
}
definition: ProjectDefinition | null
out: Output
config: Config
args: Args = {}
constructor(out: Output, config: Config) {
this.out = out
this.config = config
}
public async load(args: Args) {
this.args = args
if (
this.config.definitionPath &&
fs.pathExistsSync(this.config.definitionPath)
) {
this.definition = await fsToProject(
this.config.definitionDir,
this.out,
args,
)
if (process.env.GRAPHCOOL_DUMP_LOADED_DEFINITION) {
const definitionJsonPath = path.join(
this.config.definitionDir,
'loaded-definition.json',
)
fs.writeFileSync(
definitionJsonPath,
JSON.stringify(this.definition, null, 2),
)
}
}
}
public async save(files?: string[], silent?: boolean) {
projectToFs(
this.definition!,
this.config.definitionDir,
this.out,
files,
silent,
)
if (process.env.GRAPHCOOL_DUMP_SAVED_DEFINITION) {
const definitionJsonPath = path.join(
this.config.definitionDir,
'definition.json',
)
fs.writeFileSync(
definitionJsonPath,
JSON.stringify(this.definition, null, 2),
)
}
}
public async saveTypes() {
const definition = await readDefinition(
this.definition!.modules[0]!.content,
this.out,
this.config.definitionPath!,
this.args,
)
const types = this.definition!.modules[0].files[definition.types[0]]
this.out.log(chalk.blue(`Written ${definition.types}`))
fs.writeFileSync(
path.join(this.config.definitionDir, definition.types[0]),
types,
)
}
public set(definition: ProjectDefinition | null) {
this.definition = definition
}
public getFunctionAndModule(
name: string,
): { fn: FunctionDefinition; module: GraphcoolModule } | null {
if (this.definition && this.definition.modules) {
const functions: FunctionDefinition[] = flatMap(
this.definition.modules,
(m: GraphcoolModule) => {
return m.definition && m.definition.functions
? m.definition.functions
: []
},
) as any
const module = this.definition.modules.find(
m =>
(m.definition &&
m.definition.functions &&
Object.keys(m.definition.functions).includes(name)) ||
false,
)
if (module) {
return {
module,
fn: module.definition!.functions![name],
}
}
}
return null
}
public insertModule(moduleName: string, relativePath: string) {
const file = this.definition!.modules[0].content
const insertion = `\n ${moduleName}: ${relativePath}`
return this.insertToDefinition(file, 'modules', insertion)
}
comment(str: string) {
return str
.split('\n')
.map(l => `# ${l}`)
.join('\n')
}
addTemplateNotes(str: string, templateName: string) {
return (
`\n# added by ${templateName} template: (please uncomment)\n` +
str +
'\n\n'
)
}
public mergeDefinition(
newDefinitionYaml: string,
templateName: string,
useComments: boolean = true,
): string {
let newDefinition = this.definition!.modules[0].content
const newYaml = yamlParser.safeLoad(newDefinitionYaml)
const whiteList = ['functions', 'permissions']
newYaml.mappings
.filter(m => whiteList.includes(m.key.value))
.forEach(mapping => {
const key = mapping.key.value
let beginning = this.getBeginningPosition(newDefinition, key)
let values = this.extractValues(
newDefinitionYaml,
newYaml,
key,
beginning > -1,
)
values = useComments ? this.comment(values) : values
values = this.addTemplateNotes(values, templateName)
beginning = beginning === -1 ? newDefinition.length - 1 : beginning
newDefinition =
newDefinition.slice(0, beginning + 1) +
values +
newDefinition.slice(beginning + 1)
})
return newDefinition
}
public mergeTypes(newTypes: string, templateName: string) {
let typesPath = this.definition!.modules[0].definition!.types
typesPath = Array.isArray(typesPath) ? typesPath[0] : typesPath
const oldTypes = this.definition!.modules[0].files[typesPath]
return (
oldTypes + this.addTemplateNotes(this.comment(newTypes), templateName)
)
}
public async checkNodeModules(throwError: boolean) {
if (!this.config.definitionPath) {
this.out.error('Could not find graphcool.yml')
}
const definitionFile = fs.readFileSync(this.config.definitionPath!, 'utf-8')
const json = yaml.safeLoad(definitionFile) as GraphcoolDefinition
const functions = this.extractFunctions(json.functions)
const functionsWithRequire = functions.reduce(
(acc, fn) => {
const src =
typeof fn.fn.handler.code === 'string'
? fn.fn.handler.code
: fn.fn.handler.code!.src
if (!fs.pathExistsSync(src)) {
this.out.error(
`Error for function handler ${chalk.bold(
fn.name,
)}: File ${chalk.bold(src)} doesn't exist.`,
)
}
const file = fs.readFileSync(src, 'utf-8')
const requireRegex = /(?:(?:var|const)\s*([\s\S]*?)\s*=\s*)?require\(['"]([^'"]+)['"](?:, ['"]([^'"]+)['"])?\);?/
const importRegex = /\bimport\s+(?:[\s\S]+\s+from\s+)?[\'"]([^"\']+)["\']/
const statements = file.split('\n').reduce(
(racc, line, index) => {
const requireMatch = requireRegex.exec(line)
const importMatch = importRegex.exec(line)
if (requireMatch || importMatch) {
const srcPath = requireMatch ? requireMatch[1] : importMatch![1]
if (srcPath) {
if (
!builtinModules.includes(srcPath) &&
!srcPath.startsWith('./')
) {
const result = {
line,
index: index + 1,
srcPath,
}
return racc.concat(result)
}
}
}
return racc
},
[] as any
)
if (statements.length > 0) {
return acc.concat({
statements,
fn,
src,
})
}
return acc
},
[] as any,
)
if (functionsWithRequire.length > 0) {
if (
!fs.pathExistsSync(path.join(this.config.definitionDir, 'node_modules'))
) {
const imports = functionsWithRequire
.map(fn => {
return (
`${chalk.bold(fn.fn.name)} (${fn.src}):\n` +
fn.statements
.map(s => ` ${s.index}: ${chalk.dim(s.line)}`)
.join('\n')
)
})
.join('\n')
const text = `You have import/require statements in your functions without a node_modules folder:
${imports}
Please make sure you specified all needed dependencies in your package.json and run npm install.`
if (throwError) {
this.out.error(text)
} else {
this.out.warn(text)
}
}
}
}
private injectEnvironmentToFile(
file: string,
environment: { [envVar: string]: string },
): string {
// get first function line
const lines = file.split('\n')
Object.keys(environment).forEach(key => {
const envVar = environment[key]
lines.splice(0, 0, `process.env['${key}'] = '${envVar}';`)
})
return lines.join('\n')
}
private insertToDefinition(file: string, key: string, insertion: string) {
const obj = yamlParser.safeLoad(file)
const mapping = obj.mappings.find(m => m.key.value === key)
const end = mapping.endPosition
const newFile = file.slice(0, end) + insertion + file.slice(end)
const valueStart = mapping.value.startPosition
const valueEnd = mapping.value.endPosition
if (mapping.value && valueEnd - valueStart < 4) {
return newFile.slice(0, valueStart) + newFile.slice(valueEnd)
}
return file
}
private extractValues(
file: string,
obj: any,
key: string,
valuesOnly: boolean,
) {
const mapping = obj.mappings.find(m => m.key.value === key)
if (!mapping) {
this.out.error(`Could not find mapping for key ${key}`)
}
const start = valuesOnly
? mapping.key.endPosition + 1
: mapping.startPosition
return file.slice(start, mapping.endPosition)
}
private getBeginningPosition(file: string, key: string): number {
const obj = yamlParser.safeLoad(file)
const mapping = obj.mappings.find(m => m.key.value === key)
return mapping ? mapping.key.endPosition + 1 : -1
}
get functions(): FunctionTuple[] {
if (!this.definition) {
return []
}
return this.extractFunctions(
this.definition!.modules[0].definition!.functions,
)
}
private extractFunctions(functions?: { [p: string]: FunctionDefinition }) {
if (!functions) {
return []
} else {
return Object.keys(functions)
.filter(name => functions[name].handler.code)
.map(name => {
return {
name,
fn: functions[name],
}
})
}
}
} | the_stack |
import {
EventEmitter,
programIds,
useConnection,
decodeMetadata,
decodeNameSymbolTuple,
AuctionParser,
decodeEdition,
decodeMasterEdition,
Metadata,
getMultipleAccounts,
cache,
MintParser,
ParsedAccount,
actions,
Edition,
MasterEdition,
NameSymbolTuple,
AuctionData,
SafetyDepositBox,
VaultKey,
decodeSafetyDeposit,
BidderMetadata,
BidderMetadataParser,
BidderPot,
BidderPotParser,
BIDDER_METADATA_LEN,
BIDDER_POT_LEN,
decodeVault,
Vault,
TokenAccount,
useUserAccounts,
} from '@oyster/common';
import { MintInfo } from '@solana/spl-token';
import { Connection, PublicKey, PublicKeyAndAccount } from '@solana/web3.js';
import BN from 'bn.js';
import React, { useContext, useEffect, useState } from 'react';
import {
AuctionManager,
AuctionManagerStatus,
BidRedemptionTicket,
decodeAuctionManager,
decodeBidRedemptionTicket,
getAuctionManagerKey,
getBidderKeys,
MetaplexKey,
} from '../models/metaplex';
const { MetadataKey } = actions;
export interface MetaContextState {
metadata: ParsedAccount<Metadata>[];
metadataByMint: Record<string, ParsedAccount<Metadata>>;
nameSymbolTuples: Record<string, ParsedAccount<NameSymbolTuple>>;
editions: Record<string, ParsedAccount<Edition>>;
masterEditions: Record<string, ParsedAccount<MasterEdition>>;
auctionManagers: Record<string, ParsedAccount<AuctionManager>>;
auctions: Record<string, ParsedAccount<AuctionData>>;
vaults: Record<string, ParsedAccount<Vault>>;
bidderMetadataByAuctionAndBidder: Record<
string,
ParsedAccount<BidderMetadata>
>;
safetyDepositBoxesByVaultAndIndex: Record<
string,
ParsedAccount<SafetyDepositBox>
>;
bidderPotsByAuctionAndBidder: Record<string, ParsedAccount<BidderPot>>;
bidRedemptions: Record<string, ParsedAccount<BidRedemptionTicket>>;
}
const MetaContext = React.createContext<MetaContextState>({
metadata: [],
metadataByMint: {},
nameSymbolTuples: {},
masterEditions: {},
editions: {},
auctionManagers: {},
auctions: {},
vaults: {},
bidderMetadataByAuctionAndBidder: {},
safetyDepositBoxesByVaultAndIndex: {},
bidderPotsByAuctionAndBidder: {},
bidRedemptions: {},
});
export function MetaProvider({ children = null as any }) {
const connection = useConnection();
const { userAccounts } = useUserAccounts();
const accountByMint = userAccounts.reduce((prev, acc) => {
prev.set(acc.info.mint.toBase58(), acc);
return prev;
}, new Map<string, TokenAccount>());
const [metadata, setMetadata] = useState<ParsedAccount<Metadata>[]>([]);
const [metadataByMint, setMetadataByMint] = useState<
Record<string, ParsedAccount<Metadata>>
>({});
const [nameSymbolTuples, setNameSymbolTuples] = useState<
Record<string, ParsedAccount<NameSymbolTuple>>
>({});
const [masterEditions, setMasterEditions] = useState<
Record<string, ParsedAccount<MasterEdition>>
>({});
const [editions, setEditions] = useState<
Record<string, ParsedAccount<Edition>>
>({});
const [auctionManagers, setAuctionManagers] = useState<
Record<string, ParsedAccount<AuctionManager>>
>({});
const [bidRedemptions, setBidRedemptions] = useState<
Record<string, ParsedAccount<BidRedemptionTicket>>
>({});
const [auctions, setAuctions] = useState<
Record<string, ParsedAccount<AuctionData>>
>({});
const [vaults, setVaults] = useState<Record<string, ParsedAccount<Vault>>>(
{},
);
const [
bidderMetadataByAuctionAndBidder,
setBidderMetadataByAuctionAndBidder,
] = useState<Record<string, ParsedAccount<BidderMetadata>>>({});
const [
bidderPotsByAuctionAndBidder,
setBidderPotsByAuctionAndBidder,
] = useState<Record<string, ParsedAccount<BidderPot>>>({});
const [
safetyDepositBoxesByVaultAndIndex,
setSafetyDepositBoxesByVaultAndIndex,
] = useState<Record<string, ParsedAccount<SafetyDepositBox>>>({});
useEffect(() => {
});
useEffect(() => {
let dispose = () => {};
(async () => {
const processAuctions = async (a: PublicKeyAndAccount<Buffer>) => {
try {
const account = cache.add(
a.pubkey,
a.account,
AuctionParser,
) as ParsedAccount<AuctionData>;
account.info.auctionManagerKey = await getAuctionManagerKey(
account.info.resource,
a.pubkey,
);
const payerAcct = accountByMint.get(
account.info.tokenMint.toBase58(),
);
if (payerAcct)
account.info.bidRedemptionKey = (
await getBidderKeys(a.pubkey, payerAcct.pubkey)
).bidRedemption;
setAuctions(e => ({
...e,
[a.pubkey.toBase58()]: account,
}));
} catch {
// ignore errors
// add type as first byte for easier deserialization
}
try {
if (a.account.data.length == BIDDER_METADATA_LEN) {
const account = cache.add(
a.pubkey,
a.account,
BidderMetadataParser,
) as ParsedAccount<BidderMetadata>;
setBidderMetadataByAuctionAndBidder(e => ({
...e,
[account.info.auctionPubkey.toBase58() +
'-' +
account.info.bidderPubkey.toBase58()]: account,
}));
}
} catch {
// ignore errors
// add type as first byte for easier deserialization
}
try {
if (a.account.data.length == BIDDER_POT_LEN) {
const account = cache.add(
a.pubkey,
a.account,
BidderPotParser,
) as ParsedAccount<BidderPot>;
setBidderPotsByAuctionAndBidder(e => ({
...e,
[account.info.auctionAct.toBase58() +
'-' +
account.info.bidderAct.toBase58()]: account,
}));
}
} catch {
// ignore errors
// add type as first byte for easier deserialization
}
};
const accounts = await connection.getProgramAccounts(
programIds().auction,
);
for (let i = 0; i < accounts.length; i++) {
await processAuctions(accounts[i]);
}
let subId = connection.onProgramAccountChange(
programIds().auction,
async info => {
const pubkey =
typeof info.accountId === 'string'
? new PublicKey((info.accountId as unknown) as string)
: info.accountId;
await processAuctions({
pubkey,
account: info.accountInfo,
});
},
);
dispose = () => {
connection.removeProgramAccountChangeListener(subId);
};
})();
return () => {
dispose();
};
}, [connection, setAuctions, userAccounts]);
useEffect(() => {
let dispose = () => {};
(async () => {
const processVaultData = async (a: PublicKeyAndAccount<Buffer>) => {
try {
if (a.account.data[0] == VaultKey.SafetyDepositBoxV1) {
const safetyDeposit = await decodeSafetyDeposit(a.account.data);
const account: ParsedAccount<SafetyDepositBox> = {
pubkey: a.pubkey,
account: a.account,
info: safetyDeposit,
};
setSafetyDepositBoxesByVaultAndIndex(e => ({
...e,
[safetyDeposit.vault.toBase58() +
'-' +
safetyDeposit.order]: account,
}));
} else if (a.account.data[0] == VaultKey.VaultV1) {
const vault = await decodeVault(a.account.data);
const account: ParsedAccount<Vault> = {
pubkey: a.pubkey,
account: a.account,
info: vault,
};
setVaults(e => ({
...e,
[a.pubkey.toBase58()]: account,
}));
}
} catch {
// ignore errors
// add type as first byte for easier deserialization
}
};
const accounts = await connection.getProgramAccounts(programIds().vault);
for (let i = 0; i < accounts.length; i++) {
await processVaultData(accounts[i]);
}
let subId = connection.onProgramAccountChange(
programIds().vault,
async info => {
const pubkey =
typeof info.accountId === 'string'
? new PublicKey((info.accountId as unknown) as string)
: info.accountId;
await processVaultData({
pubkey,
account: info.accountInfo,
});
},
);
dispose = () => {
connection.removeProgramAccountChangeListener(subId);
};
})();
return () => {
dispose();
};
}, [connection, setSafetyDepositBoxesByVaultAndIndex, setVaults]);
useEffect(() => {
let dispose = () => {};
(async () => {
const processAuctionManagers = async (a: PublicKeyAndAccount<Buffer>) => {
try {
if (a.account.data[0] == MetaplexKey.AuctionManagerV1) {
const auctionManager = await decodeAuctionManager(a.account.data);
const account: ParsedAccount<AuctionManager> = {
pubkey: a.pubkey,
account: a.account,
info: auctionManager,
};
setAuctionManagers(e => ({
...e,
[a.pubkey.toBase58()]: account,
}));
} else if (a.account.data[0] == MetaplexKey.BidRedemptionTicketV1) {
const ticket = await decodeBidRedemptionTicket(a.account.data);
const account: ParsedAccount<BidRedemptionTicket> = {
pubkey: a.pubkey,
account: a.account,
info: ticket,
};
setBidRedemptions(e => ({
...e,
[a.pubkey.toBase58()]: account,
}));
}
} catch {
// ignore errors
// add type as first byte for easier deserialization
}
};
const accounts = await connection.getProgramAccounts(
programIds().metaplex,
);
for (let i = 0; i < accounts.length; i++) {
await processAuctionManagers(accounts[i]);
}
let subId = connection.onProgramAccountChange(
programIds().metaplex,
async info => {
const pubkey =
typeof info.accountId === 'string'
? new PublicKey((info.accountId as unknown) as string)
: info.accountId;
await processAuctionManagers({
pubkey,
account: info.accountInfo,
});
},
);
dispose = () => {
connection.removeProgramAccountChangeListener(subId);
};
})();
return () => {
dispose();
};
}, [connection, setAuctionManagers, setBidRedemptions]);
useEffect(() => {
let dispose = () => {};
(async () => {
const processMetaData = async (meta: PublicKeyAndAccount<Buffer>) => {
try {
if (meta.account.data[0] == MetadataKey.MetadataV1) {
const metadata = await decodeMetadata(meta.account.data);
if (
isValidHttpUrl(metadata.uri) &&
metadata.uri.indexOf('arweave') >= 0
) {
const account: ParsedAccount<Metadata> = {
pubkey: meta.pubkey,
account: meta.account,
info: metadata,
};
setMetadataByMint(e => ({
...e,
[metadata.mint.toBase58()]: account,
}));
}
} else if (meta.account.data[0] == MetadataKey.EditionV1) {
const edition = decodeEdition(meta.account.data);
const account: ParsedAccount<Edition> = {
pubkey: meta.pubkey,
account: meta.account,
info: edition,
};
setEditions(e => ({ ...e, [meta.pubkey.toBase58()]: account }));
} else if (meta.account.data[0] == MetadataKey.MasterEditionV1) {
const masterEdition = decodeMasterEdition(meta.account.data);
const account: ParsedAccount<MasterEdition> = {
pubkey: meta.pubkey,
account: meta.account,
info: masterEdition,
};
setMasterEditions(e => ({
...e,
[meta.pubkey.toBase58()]: account,
}));
} else if (meta.account.data[0] == MetadataKey.NameSymbolTupleV1) {
const nameSymbolTuple = decodeNameSymbolTuple(meta.account.data);
const account: ParsedAccount<NameSymbolTuple> = {
pubkey: meta.pubkey,
account: meta.account,
info: nameSymbolTuple,
};
setNameSymbolTuples(e => ({
...e,
[meta.pubkey.toBase58()]: account,
}));
}
} catch {
// ignore errors
// add type as first byte for easier deserialization
}
};
const accounts = await connection.getProgramAccounts(
programIds().metadata,
);
for (let i = 0; i < accounts.length; i++) {
await processMetaData(accounts[i]);
}
setMetadataByMint(latest => {
queryExtendedMetadata(
connection,
setMetadata,
setMetadataByMint,
latest,
);
return latest;
});
let subId = connection.onProgramAccountChange(
programIds().metadata,
async info => {
const pubkey =
typeof info.accountId === 'string'
? new PublicKey((info.accountId as unknown) as string)
: info.accountId;
await processMetaData({
pubkey,
account: info.accountInfo,
});
setMetadataByMint(latest => {
queryExtendedMetadata(
connection,
setMetadata,
setMetadataByMint,
latest,
);
return latest;
});
},
);
dispose = () => {
connection.removeProgramAccountChangeListener(subId);
};
})();
return () => {
dispose();
};
}, [
connection,
setMetadata,
setMasterEditions,
setNameSymbolTuples,
setEditions,
]);
return (
<MetaContext.Provider
value={{
metadata,
editions,
masterEditions,
nameSymbolTuples,
auctionManagers,
auctions,
metadataByMint,
safetyDepositBoxesByVaultAndIndex,
bidderMetadataByAuctionAndBidder,
bidderPotsByAuctionAndBidder,
vaults,
bidRedemptions,
}}
>
{children}
</MetaContext.Provider>
);
}
const queryExtendedMetadata = async (
connection: Connection,
setMetadata: (metadata: ParsedAccount<Metadata>[]) => void,
setMetadataByMint: (
metadata: Record<string, ParsedAccount<Metadata>>,
) => void,
mintToMeta: Record<string, ParsedAccount<Metadata>>,
) => {
const mintToMetadata = { ...mintToMeta };
const extendedMetadataFetch = new Map<string, Promise<any>>();
const mints = await getMultipleAccounts(
connection,
[...Object.keys(mintToMetadata)].filter(k => !cache.get(k)),
'single',
);
mints.keys.forEach((key, index) => {
const mintAccount = mints.array[index];
const mint = cache.add(
key,
mintAccount,
MintParser,
) as ParsedAccount<MintInfo>;
if (mint.info.supply.gt(new BN(1)) || mint.info.decimals !== 0) {
// naive not NFT check
delete mintToMetadata[key];
} else {
const metadata = mintToMetadata[key];
}
});
// await Promise.all([...extendedMetadataFetch.values()]);
setMetadata([...Object.values(mintToMetadata)]);
setMetadataByMint(mintToMetadata);
};
export const useMeta = () => {
const context = useContext(MetaContext);
return context as MetaContextState;
};
function isValidHttpUrl(text: string) {
let url;
try {
url = new URL(text);
} catch (_) {
return false;
}
return url.protocol === 'http:' || url.protocol === 'https:';
} | the_stack |
import HostType from '../types/HostType'
import HAPService2NodeType from '../types/HAPService2NodeType'
import {
Accessory,
Characteristic,
CharacteristicChange,
CharacteristicEventTypes,
CharacteristicGetCallback,
CharacteristicSetCallback,
CharacteristicValue,
Service,
} from 'hap-nodejs'
import HAPService2ConfigType from '../types/HAPService2ConfigType'
import {
HAPConnection,
HAPUsername,
} from 'hap-nodejs/dist/lib/util/eventedhttp'
import { logger } from '@nrchkb/logger'
import { SessionIdentifier } from 'hap-nodejs/dist/types'
import { Storage } from '../Storage'
import NRCHKBError from '../NRCHKBError'
module.exports = function (node: HAPService2NodeType) {
const log = logger('NRCHKB', 'ServiceUtils2', node.config.name, node)
const HapNodeJS = require('hap-nodejs')
const Service = HapNodeJS.Service
const Characteristic = HapNodeJS.Characteristic
const CameraSource = require('../cameraSource').Camera
const NO_RESPONSE_MSG = 'NO_RESPONSE'
type HAPServiceNodeEvent = {
name: CharacteristicEventTypes // Event type
context?: {
callbackID?: string // ID used to update Characteristic value with get event
key?: string // Characteristic key
reason?: string
} & {} // Additional event data provided by event caller
}
type HAPServiceMessage = {
payload?: { [key: string]: any }
hap?: {
oldValue?: any
newValue?: any
event?: HAPServiceNodeEvent
session?: {
sessionID?: SessionIdentifier
username?: HAPUsername
remoteAddress?: string
localAddress?: string
httpPort?: number
}
allChars: { [key: string]: any }
}
name?: string
topic?: string
}
const output = function (
this: Characteristic,
allCharacteristics: Characteristic[],
event: CharacteristicEventTypes | HAPServiceNodeEvent,
{ oldValue, newValue }: any,
connection?: HAPConnection
) {
const eventObject = typeof event === 'object' ? event : { name: event }
log.debug(
`${eventObject.name} event, oldValue: ${oldValue}, newValue: ${newValue}, connection ${connection?.sessionID}`
)
const msg: HAPServiceMessage = {
name: node.name,
topic: node.config.topic ? node.config.topic : node.topic_in,
}
msg.payload = {}
msg.hap = {
newValue,
event: eventObject,
allChars: allCharacteristics.reduce<{ [key: string]: any }>(
(allChars, singleChar) => {
allChars[singleChar.displayName] = singleChar.value
return allChars
},
{}
),
}
if (oldValue !== undefined) {
msg.hap.oldValue = oldValue
}
const key = this.constructor.name
msg.payload[key] = newValue
if (connection) {
msg.hap.session = {
sessionID: connection.sessionID,
username: connection.username,
remoteAddress: connection.remoteAddress,
localAddress: connection.localAddress,
httpPort: connection.remotePort,
}
}
node.setStatus(
{
fill: 'yellow',
shape: 'dot',
text: `[${eventObject.name}] ${key}${
newValue != undefined ? `: ${newValue}` : ''
}`,
},
3000
)
log.debug(
`${node.name} received ${eventObject.name} ${key}: ${newValue}`
)
if (connection || node.hostNode.config.allowMessagePassthrough) {
node.send(msg)
}
}
const onCharacteristicGet = (allCharacteristics: Characteristic[]) =>
function (
this: Characteristic,
callback: CharacteristicGetCallback,
_context: any,
connection?: HAPConnection
) {
const characteristic = this
const oldValue = characteristic.value
const delayedCallback = (value?: any) => {
const newValue = value ?? characteristic.value
if (callback) {
try {
callback(
node.accessory.reachable
? characteristic.statusCode
: new Error(NO_RESPONSE_MSG),
newValue
)
} catch (_) {}
}
output.call(
characteristic,
allCharacteristics,
{
name: CharacteristicEventTypes.GET,
context: { key: this.displayName },
},
{ oldValue, newValue },
connection
)
}
if (node.config.useEventCallback) {
const callbackID = Storage.saveCallback({
event: CharacteristicEventTypes.GET,
callback: delayedCallback,
})
log.debug(
`Registered callback ${callbackID} for Characteristic ${characteristic.displayName}`
)
output.call(
this,
allCharacteristics,
{
name: CharacteristicEventTypes.GET,
context: { callbackID, key: this.displayName },
},
{ oldValue },
connection
)
} else {
delayedCallback()
}
}
// eslint-disable-next-line no-unused-vars
const onCharacteristicSet = (allCharacteristics: Characteristic[]) =>
function (
this: Characteristic,
newValue: CharacteristicValue,
callback: CharacteristicSetCallback,
_context: any,
connection?: HAPConnection
) {
try {
if (callback) {
callback(
node.accessory.reachable
? null
: new Error(NO_RESPONSE_MSG)
)
}
} catch (_) {}
output.call(
this,
allCharacteristics,
{
name: CharacteristicEventTypes.SET,
context: { key: this.displayName },
},
{ newValue },
connection
)
}
const onCharacteristicChange = (allCharacteristics: Characteristic[]) =>
function (this: Characteristic, change: CharacteristicChange) {
const { oldValue, newValue, context, originator, reason } = change
if (oldValue != newValue) {
output.call(
this,
allCharacteristics,
{
name: CharacteristicEventTypes.CHANGE,
context: { reason, key: this.displayName },
},
{ oldValue, newValue, context },
originator
)
}
}
const onInput = function (msg: HAPServiceMessage) {
if (msg.payload) {
// payload must be an object
const type = typeof msg.payload
if (type !== 'object') {
log.error(`Invalid payload type: ${type}`)
return
}
} else {
log.error('Invalid message (payload missing)')
return
}
const topic = node.config.topic ? node.config.topic : node.name
if (node.config.filter && msg.topic !== topic) {
log.debug(
"msg.topic doesn't match configured value and filter is enabled. Dropping message."
)
return
}
let context: any = null
if (msg.payload.Context) {
context = msg.payload.Context
delete msg.payload.Context
}
node.topic_in = msg.topic ?? ''
// iterate over characteristics to be written
// eslint-disable-next-line no-unused-vars
Object.keys(msg.payload).map((key: string) => {
if (node.supported.indexOf(key) < 0) {
if (
node.config.useEventCallback &&
Storage.uuid4Validate(key)
) {
const callbackID = key
const callbackValue = msg.payload?.[key]
const eventCallback = Storage.loadCallback(callbackID)
if (eventCallback) {
log.debug(
`Calling ${eventCallback.event} callback ${callbackID}`
)
eventCallback.callback(callbackValue)
} else {
log.error(`Callback ${callbackID} timeout`)
}
} else {
log.error(
`Instead of ${key} try one of these characteristics: ${node.supported.join(
', '
)}`
)
}
} else {
const value = msg.payload?.[key]
if (
(node.config.isParent &&
node.config.hostType == HostType.BRIDGE) ||
(!node.config.isParent &&
node.hostNode.hostType == HostType.BRIDGE)
) {
// updateReachability is only supported on bridged accessories
node.accessory.updateReachability(value !== NO_RESPONSE_MSG)
}
const characteristic = node.service.getCharacteristic(
Characteristic[key]
)
if (context !== null) {
characteristic.setValue(value, undefined, context)
} else {
characteristic.setValue(value)
}
}
})
}
const onClose = function (removed: boolean, done: () => void) {
const characteristics = node.service.characteristics.concat(
node.service.optionalCharacteristics
)
characteristics.forEach(function (characteristic) {
// cleanup all node specific listeners
characteristic.removeListener('get', node.onCharacteristicGet)
characteristic.removeListener('set', node.onCharacteristicSet)
characteristic.removeListener('change', node.onCharacteristicChange)
})
if (node.config.isParent) {
// remove identify listener to prevent errors with undefined values
node.accessory.removeListener('identify', node.onIdentify)
}
if (removed) {
// This node has been deleted
if (node.config.isParent) {
// remove accessory from bridge
node.hostNode.host.removeBridgedAccessories([node.accessory])
node.accessory.destroy()
} else {
// only remove the service if it is not a parent
node.accessory.removeService(node.service)
node.parentService.removeLinkedService(node.service)
}
}
done()
}
const getOrCreate = function (
accessory: Accessory,
serviceInformation: {
name: string
UUID: string
serviceName: string
config: HAPService2ConfigType
},
parentService: Service
) {
const newService = new Service[serviceInformation.serviceName](
serviceInformation.name,
serviceInformation.UUID
)
log.debug(
`Looking for service with UUID ${serviceInformation.UUID} ...`
)
// search for a service with the same subtype
let service: Service | undefined = accessory.services.find(
(service) => {
return newService.subtype === service.subtype
}
)
if (service && newService.UUID !== service.UUID) {
// if the UUID and therefore the type changed, the whole service
// will be replaced
log.debug('... service type changed! Removing the old service.')
accessory.removeService(service)
service = undefined
}
if (!service) {
// if no matching service was found or the type changed, then a new
// service will be added
log.debug(
`... didn't find it. Adding new ${serviceInformation.serviceName} service.`
)
if (serviceInformation.serviceName === 'CameraControl') {
configureCameraSource(
accessory,
newService,
serviceInformation.config
)
service = newService
} else {
service = accessory.addService(newService)
}
} else {
// if a service with the same UUID and subtype was found it will
// be updated and used
log.debug('... found it! Updating it.')
service
.getCharacteristic(Characteristic.Name)
.setValue(serviceInformation.name)
}
if (parentService) {
if (serviceInformation.serviceName === 'CameraControl') {
//We don't add or link it since configureCameraSource do this already.
log.debug('... and adding service to accessory.')
} else if (service) {
log.debug('... and linking service to parent.')
parentService.addLinkedService(service)
}
}
return service
}
const configureCameraSource = function (
accessory: Accessory,
service: Service,
config: HAPService2ConfigType
) {
if (config.cameraConfigSource) {
log.debug('Configuring Camera Source')
if (!config.cameraConfigVideoProcessor) {
log.error(
'Missing configuration for CameraControl: videoProcessor cannot be empty!'
)
} else {
// Use of deprecated method to be replaced with new Camera API
accessory.configureCameraSource(
new CameraSource(service, config, node)
)
}
} else {
log.error('Missing configuration for CameraControl.')
}
}
const waitForParent = () => {
log.debug('Waiting for Parent Service')
return new Promise((resolve) => {
node.setStatus({
fill: 'blue',
shape: 'dot',
text: 'Waiting for Parent Service',
})
const checkAndWait = () => {
const parentNode: HAPService2NodeType = node.RED.nodes.getNode(
node.config.parentService
) as HAPService2NodeType
if (parentNode && parentNode.configured) {
resolve(parentNode)
} else {
setTimeout(checkAndWait, 1000)
}
}
checkAndWait()
}).catch((error) => {
log.error(`Waiting for Parent Service failed due to: ${error}`)
throw new NRCHKBError(error)
})
}
const handleWaitForSetup = (
config: HAPService2ConfigType,
msg: Record<string, any>,
resolve: (newConfig: HAPService2ConfigType) => void
) => {
if (node.setupDone) {
return
}
if (
msg.hasOwnProperty('payload') &&
msg.payload.hasOwnProperty('nrchkb') &&
msg.payload.nrchkb.hasOwnProperty('setup')
) {
node.setupDone = true
const newConfig = {
...config,
...msg.payload.nrchkb.setup,
}
node.removeListener('input', node.handleWaitForSetup)
resolve(newConfig)
} else {
log.error(
'Invalid message (required {"payload":{"nrchkb":{"setup":{}}}})'
)
}
}
return {
getOrCreate,
onCharacteristicGet,
onCharacteristicSet,
onCharacteristicChange,
onInput,
onClose,
waitForParent,
handleWaitForSetup,
}
} | the_stack |
import {
TOP_BLUR,
TOP_COMPOSITION_START,
TOP_COMPOSITION_END,
TOP_COMPOSITION_UPDATE,
TOP_KEY_DOWN,
TOP_KEY_PRESS,
TOP_KEY_UP,
TOP_MOUSE_DOWN,
TOP_TEXT_INPUT,
TOP_PASTE
} from './DOMTopLevelEventTypes';
import {
getData as FallbackCompositionStateGetData,
initialize as FallbackCompositionStateInitialize,
reset as FallbackCompositionStateReset
} from './FallbackCompositionState';
const canUseDOM: boolean = !!(
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined'
);
const END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
const START_KEYCODE = 229;
const canUseCompositionEvent = canUseDOM && 'CompositionEvent' in window;
let documentMode = null;
if (canUseDOM && 'documentMode' in document) {
documentMode = (document as any).documentMode;
}
// Webkit offers a very useful `textInput` event that can be used to
// directly represent `beforeInput`. The IE `textinput` event is not as
// useful, so we don't use it.
const canUseTextInputEvent = canUseDOM && 'TextEvent' in window && !documentMode;
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. Japanese ideographic
// spaces, for instance (\u3000) are not recorded correctly.
const useFallbackCompositionData = canUseDOM && (!canUseCompositionEvent || (documentMode && documentMode > 8 && documentMode <= 11));
const SPACEBAR_CODE = 32;
const SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE);
// Events and their corresponding property names.
const eventTypes = {
beforeInput: {
phasedRegistrationNames: {
bubbled: 'onBeforeInput',
captured: 'onBeforeInputCapture'
},
dependencies: [TOP_COMPOSITION_END, TOP_KEY_PRESS, TOP_TEXT_INPUT, TOP_PASTE]
}
};
// Track whether we've ever handled a keypress on the space key.
let hasSpaceKeypress = false;
/**
* Return whether a native keypress event is assumed to be a command.
* This is required because Firefox fires `keypress` events for key commands
* (cut, copy, select-all, etc.) even though no character is inserted.
*/
function isKeypressCommand(nativeEvent) {
return (
(nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) &&
// ctrlKey && altKey is equivalent to AltGr, and is not a command.
!(nativeEvent.ctrlKey && nativeEvent.altKey)
);
}
/**
* Does our fallback mode think that this event is the end of composition?
*
*/
function isFallbackCompositionEnd(topLevelType, nativeEvent) {
switch (topLevelType) {
case TOP_KEY_UP:
// Command keys insert or clear IME input.
return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1;
case TOP_KEY_DOWN:
// Expect IME keyCode on each keydown. If we get any other
// code we must have exited earlier.
return nativeEvent.keyCode !== START_KEYCODE;
case TOP_KEY_PRESS:
case TOP_MOUSE_DOWN:
case TOP_BLUR:
// Events are not possible without cancelling IME.
return true;
default:
return false;
}
}
/**
* Google Input Tools provides composition data via a CustomEvent,
* with the `data` property populated in the `detail` object. If this
* is available on the event object, use it. If not, this is a plain
* composition event and we have nothing special to extract.
*
*/
function getDataFromCustomEvent(nativeEvent) {
const detail = nativeEvent.detail;
if (typeof detail === 'object' && 'data' in detail) {
return detail.data;
}
return null;
}
/**
* Check if a composition event was triggered by Korean IME.
* Our fallback mode does not work well with IE's Korean IME,
* so just use native composition events when Korean IME is used.
* Although CompositionEvent.locale property is deprecated,
* it is available in IE, where our fallback mode is enabled.
*
*/
function isUsingKoreanIME(nativeEvent) {
return nativeEvent.locale === 'ko';
}
// Track the current IME composition status, if any.
let isComposing = false;
function getNativeBeforeInputChars(topLevelType: any, nativeEvent) {
switch (topLevelType) {
case TOP_COMPOSITION_END:
return getDataFromCustomEvent(nativeEvent);
case TOP_KEY_PRESS:
/**
* If native `textInput` events are available, our goal is to make
* use of them. However, there is a special case: the spacebar key.
* In Webkit, preventing default on a spacebar `textInput` event
* cancels character insertion, but it *also* causes the browser
* to fall back to its default spacebar behavior of scrolling the
* page.
*
* Tracking at:
* https://code.google.com/p/chromium/issues/detail?id=355103
*
* To avoid this issue, use the keypress event as if no `textInput`
* event is available.
*/
const which = nativeEvent.which;
if (which !== SPACEBAR_CODE) {
return null;
}
hasSpaceKeypress = true;
return SPACEBAR_CHAR;
case TOP_TEXT_INPUT:
// Record the characters to be added to the DOM.
const chars = nativeEvent.data;
// If it's a spacebar character, assume that we have already handled
// it at the keypress level and bail immediately. Android Chrome
// doesn't give us keycodes, so we need to ignore it.
if (chars === SPACEBAR_CHAR && hasSpaceKeypress) {
return null;
}
return chars;
default:
// For other native event types, do nothing.
return null;
}
}
/**
* For browsers that do not provide the `textInput` event, extract the
* appropriate string to use for SyntheticInputEvent.
*
*/
function getFallbackBeforeInputChars(topLevelType: any, nativeEvent) {
// If we are currently composing (IME) and using a fallback to do so,
// try to extract the composed characters from the fallback object.
// If composition event is available, we extract a string only at
// compositionevent, otherwise extract it at fallback events.
if (isComposing) {
if (topLevelType === TOP_COMPOSITION_END || (!canUseCompositionEvent && isFallbackCompositionEnd(topLevelType, nativeEvent))) {
const chars = FallbackCompositionStateGetData();
FallbackCompositionStateReset();
isComposing = false;
return chars;
}
return null;
}
switch (topLevelType) {
case TOP_PASTE:
// If a paste event occurs after a keypress, throw out the input
// chars. Paste events should not lead to BeforeInput events.
return null;
case TOP_KEY_PRESS:
/**
* As of v27, Firefox may fire keypress events even when no character
* will be inserted. A few possibilities:
*
* - `which` is `0`. Arrow keys, Esc key, etc.
*
* - `which` is the pressed key code, but no char is available.
* Ex: 'AltGr + d` in Polish. There is no modified character for
* this key combination and no character is inserted into the
* document, but FF fires the keypress for char code `100` anyway.
* No `input` event will occur.
*
* - `which` is the pressed key code, but a command combination is
* being used. Ex: `Cmd+C`. No character is inserted, and no
* `input` event will occur.
*/
if (!isKeypressCommand(nativeEvent)) {
// IE fires the `keypress` event when a user types an emoji via
// Touch keyboard of Windows. In such a case, the `char` property
// holds an emoji character like `\uD83D\uDE0A`. Because its length
// is 2, the property `which` does not represent an emoji correctly.
// In such a case, we directly return the `char` property instead of
// using `which`.
if (nativeEvent.char && nativeEvent.char.length > 1) {
return nativeEvent.char;
} else if (nativeEvent.which) {
return String.fromCharCode(nativeEvent.which);
}
}
return null;
case TOP_COMPOSITION_END:
return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data;
default:
return null;
}
}
/**
* Extract a SyntheticInputEvent for `beforeInput`, based on either native
* `textInput` or fallback behavior.
*
*/
export function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) {
let chars;
if (canUseTextInputEvent) {
chars = getNativeBeforeInputChars(topLevelType, nativeEvent);
} else {
chars = getFallbackBeforeInputChars(topLevelType, nativeEvent);
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return null;
}
const beforeInputEvent = new BeforeInputEvent();
beforeInputEvent.data = chars;
beforeInputEvent.nativeEvent = nativeEvent;
return beforeInputEvent;
}
/**
* Create an `onBeforeInput` event to match
* http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents.
*
* This event plugin is based on the native `textInput` event
* available in Chrome, Safari, Opera, and IE. This event fires after
* `onKeyPress` and `onCompositionEnd`, but before `onInput`.
*
* `beforeInput` is spec'd but not implemented in any browsers, and
* the `input` event does not provide any useful information about what has
* actually been added, contrary to the spec. Thus, `textInput` is the best
* available event to identify the characters that have actually been inserted
* into the target node.
*
* This plugin is also responsible for emitting `composition` events, thus
* allowing us to share composition fallback code for both `beforeInput` and
* `composition` event types.
*/
const BeforeInputEventPlugin = {
extractEvents: (topLevelType, targetInst, nativeEvent, nativeEventTarget) => {
return extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget);
}
};
export class BeforeInputEvent {
data: string;
nativeEvent: Event;
}
export default BeforeInputEventPlugin; | the_stack |
import { Match, Template } from '@aws-cdk/assertions';
import * as cb from '@aws-cdk/aws-codebuild';
import * as secretsmanager from '@aws-cdk/aws-secretsmanager';
import { Stack } from '@aws-cdk/core';
import { Construct } from 'constructs';
import * as cdkp from '../../lib';
import { CodeBuildStep } from '../../lib';
import { behavior, PIPELINE_ENV, TestApp, LegacyTestGitHubNpmPipeline, ModernTestGitHubNpmPipeline, DockerAssetApp, stringLike } from '../testhelpers';
const secretSynthArn = 'arn:aws:secretsmanager:eu-west-1:0123456789012:secret:synth-012345';
const secretUpdateArn = 'arn:aws:secretsmanager:eu-west-1:0123456789012:secret:update-012345';
const secretPublishArn = 'arn:aws:secretsmanager:eu-west-1:0123456789012:secret:publish-012345';
let app: TestApp;
let pipelineStack: Stack;
let secretSynth: secretsmanager.ISecret;
let secretUpdate: secretsmanager.ISecret;
let secretPublish: secretsmanager.ISecret;
beforeEach(() => {
app = new TestApp();
pipelineStack = new Stack(app, 'PipelineStack', { env: PIPELINE_ENV });
secretSynth = secretsmanager.Secret.fromSecretCompleteArn(pipelineStack, 'Secret1', secretSynthArn);
secretUpdate = secretsmanager.Secret.fromSecretCompleteArn(pipelineStack, 'Secret2', secretUpdateArn);
secretPublish = secretsmanager.Secret.fromSecretCompleteArn(pipelineStack, 'Secret3', secretPublishArn);
});
afterEach(() => {
app.cleanup();
});
behavior('synth action receives install commands and access to relevant credentials', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyPipelineWithCreds(pipelineStack, 'Cdk');
pipeline.addApplicationStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation();
});
suite.modern(() => {
const pipeline = new ModernPipelineWithCreds(pipelineStack, 'Cdk');
pipeline.addStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation();
});
function THEN_codePipelineExpectation() {
const expectedCredsConfig = JSON.stringify({
version: '1.0',
domainCredentials: { 'synth.example.com': { secretsManagerSecretId: secretSynthArn } },
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodeBuild::Project', {
Environment: { Image: 'aws/codebuild/standard:5.0' },
Source: {
BuildSpec: Match.serializedJson(Match.objectLike({
phases: {
pre_build: {
commands: Match.arrayWith([
'mkdir $HOME/.cdk',
`echo '${expectedCredsConfig}' > $HOME/.cdk/cdk-docker-creds.json`,
]),
},
// Prove we're looking at the Synth project
build: {
commands: Match.arrayWith([stringLike('*cdk*synth*')]),
},
},
})),
},
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: Match.arrayWith([{
Action: ['secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret'],
Effect: 'Allow',
Resource: secretSynthArn,
}]),
Version: '2012-10-17',
},
Roles: [{ Ref: stringLike('Cdk*BuildProjectRole*') }],
});
}
});
behavior('synth action receives Windows install commands if a Windows image is detected', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyPipelineWithCreds(pipelineStack, 'Cdk2', {
npmSynthOptions: {
environment: {
buildImage: cb.WindowsBuildImage.WINDOWS_BASE_2_0,
},
},
});
pipeline.addApplicationStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation();
});
suite.modern(() => {
const pipeline = new ModernPipelineWithCreds(pipelineStack, 'Cdk2', {
synth: new CodeBuildStep('Synth', {
commands: ['cdk synth'],
primaryOutputDirectory: 'cdk.out',
input: cdkp.CodePipelineSource.gitHub('test/test', 'main'),
buildEnvironment: {
buildImage: cb.WindowsBuildImage.WINDOWS_BASE_2_0,
computeType: cb.ComputeType.MEDIUM,
},
}),
});
pipeline.addStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation();
});
function THEN_codePipelineExpectation() {
const expectedCredsConfig = JSON.stringify({
version: '1.0',
domainCredentials: { 'synth.example.com': { secretsManagerSecretId: secretSynthArn } },
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodeBuild::Project', {
Environment: { Image: 'aws/codebuild/windows-base:2.0' },
Source: {
BuildSpec: Match.serializedJson(Match.objectLike({
phases: {
pre_build: {
commands: Match.arrayWith([
'mkdir %USERPROFILE%\\.cdk',
`echo '${expectedCredsConfig}' > %USERPROFILE%\\.cdk\\cdk-docker-creds.json`,
]),
},
// Prove we're looking at the Synth project
build: {
commands: Match.arrayWith([stringLike('*cdk*synth*')]),
},
},
})),
},
});
}
});
behavior('self-update receives install commands and access to relevant credentials', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyPipelineWithCreds(pipelineStack, 'Cdk');
pipeline.addApplicationStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation('install');
});
suite.modern(() => {
const pipeline = new ModernPipelineWithCreds(pipelineStack, 'Cdk');
pipeline.addStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation('pre_build');
});
function THEN_codePipelineExpectation(expectedPhase: string) {
const expectedCredsConfig = JSON.stringify({
version: '1.0',
domainCredentials: { 'selfupdate.example.com': { secretsManagerSecretId: secretUpdateArn } },
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodeBuild::Project', {
Environment: { Image: 'aws/codebuild/standard:5.0' },
Source: {
BuildSpec: Match.serializedJson(Match.objectLike({
phases: {
[expectedPhase]: {
commands: Match.arrayWith([
'mkdir $HOME/.cdk',
`echo '${expectedCredsConfig}' > $HOME/.cdk/cdk-docker-creds.json`,
]),
},
// Prove we're looking at the SelfMutate project
build: {
commands: Match.arrayWith([
stringLike('cdk * deploy PipelineStack*'),
]),
},
},
})),
},
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: Match.arrayWith([{
Action: ['secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret'],
Effect: 'Allow',
Resource: secretUpdateArn,
}]),
Version: '2012-10-17',
},
Roles: [{ Ref: stringLike('*SelfMutat*Role*') }],
});
}
});
behavior('asset publishing receives install commands and access to relevant credentials', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyPipelineWithCreds(pipelineStack, 'Cdk');
pipeline.addApplicationStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation('install');
});
suite.modern(() => {
const pipeline = new ModernPipelineWithCreds(pipelineStack, 'Cdk');
pipeline.addStage(new DockerAssetApp(app, 'App1'));
THEN_codePipelineExpectation('pre_build');
});
function THEN_codePipelineExpectation(expectedPhase: string) {
const expectedCredsConfig = JSON.stringify({
version: '1.0',
domainCredentials: { 'publish.example.com': { secretsManagerSecretId: secretPublishArn } },
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodeBuild::Project', {
Environment: { Image: 'aws/codebuild/standard:5.0' },
Source: {
BuildSpec: Match.serializedJson(Match.objectLike({
phases: {
[expectedPhase]: {
commands: Match.arrayWith([
'mkdir $HOME/.cdk',
`echo '${expectedCredsConfig}' > $HOME/.cdk/cdk-docker-creds.json`,
]),
},
// Prove we're looking at the Publishing project
build: {
commands: Match.arrayWith([stringLike('cdk-assets*')]),
},
},
})),
},
});
Template.fromStack(pipelineStack).hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: Match.arrayWith([{
Action: ['secretsmanager:GetSecretValue', 'secretsmanager:DescribeSecret'],
Effect: 'Allow',
Resource: secretPublishArn,
}]),
Version: '2012-10-17',
},
Roles: [{ Ref: 'CdkAssetsDockerRole484B6DD3' }],
});
}
});
class LegacyPipelineWithCreds extends LegacyTestGitHubNpmPipeline {
constructor(scope: Construct, id: string, props?: ConstructorParameters<typeof LegacyTestGitHubNpmPipeline>[2]) {
super(scope, id, {
dockerCredentials: [
cdkp.DockerCredential.customRegistry('synth.example.com', secretSynth, {
usages: [cdkp.DockerCredentialUsage.SYNTH],
}),
cdkp.DockerCredential.customRegistry('selfupdate.example.com', secretUpdate, {
usages: [cdkp.DockerCredentialUsage.SELF_UPDATE],
}),
cdkp.DockerCredential.customRegistry('publish.example.com', secretPublish, {
usages: [cdkp.DockerCredentialUsage.ASSET_PUBLISHING],
}),
],
...props,
});
}
}
class ModernPipelineWithCreds extends ModernTestGitHubNpmPipeline {
constructor(scope: Construct, id: string, props?: ConstructorParameters<typeof ModernTestGitHubNpmPipeline>[2]) {
super(scope, id, {
dockerCredentials: [
cdkp.DockerCredential.customRegistry('synth.example.com', secretSynth, {
usages: [cdkp.DockerCredentialUsage.SYNTH],
}),
cdkp.DockerCredential.customRegistry('selfupdate.example.com', secretUpdate, {
usages: [cdkp.DockerCredentialUsage.SELF_UPDATE],
}),
cdkp.DockerCredential.customRegistry('publish.example.com', secretPublish, {
usages: [cdkp.DockerCredentialUsage.ASSET_PUBLISHING],
}),
],
...props,
});
}
} | the_stack |
import { Action, isObservable, observable, observe, Static } from '../src/index';
// /**
// * observable
// */
test('should return a new observable when no argument is provided', () => {
const dynamicObj = observable();
expect(isObservable(dynamicObj)).toBe(true);
});
test('should return an observable wrapping of an object argument', () => {
const obj = { prop: 'value' };
const dynamicObj = observable(obj);
expect(obj === dynamicObj).not.toBe(true);
expect(isObservable(dynamicObj)).toBe(true);
});
test('should return the argument if test is already an observable', () => {
const dynamicObj1 = observable();
const dynamicObj2 = observable(dynamicObj1);
expect(dynamicObj1 === dynamicObj2).toBe(true);
});
test('should return the same observable wrapper when called repeatedly with the same argument', () => {
const obj = { prop: 'value' };
const dynamicObj1 = observable(obj);
const dynamicObj2 = observable(obj);
expect(dynamicObj1 === dynamicObj2).toBe(true);
});
test('should never modify the underlying plain object', () => {
const obj = {} as any;
const dynamicObj = observable(obj);
obj.nested1 = {};
dynamicObj.nested2 = observable({});
expect(isObservable(obj.nested1)).not.toBe(true);
expect(isObservable(obj.nested2)).not.toBe(true);
});
test('null throw typeError', () => {
expect(() => {
observable(null);
}).toThrow(TypeError);
});
test('undefined not throw', () => {
expect(() => {
observable(undefined);
}).not.toThrow();
});
test('primitive type typeError', () => {
expect(() => {
observable(1);
}).toThrow(TypeError);
});
test('when observable class has constructor', () => {
@observable
class MyCount {
private count1: number;
private count2: number;
constructor(count1: number, count2: number) {
this.count1 = count1;
this.count2 = count2;
}
public getCount1(): number {
return this.count1;
}
public getCount2(): number {
return this.count2;
}
}
const myCount = new MyCount(3, 4);
expect(myCount.getCount1() === 3).toBe(true);
expect(myCount.getCount2() === 4).toBe(true);
});
/**
* isObservable
*/
test('should throw a TypeError on invalid arguments', () => {
expect(isObservable({})).not.toBe(true);
});
test('should return true if an observable is passed as argument', () => {
const dynamicObj = observable();
expect(isObservable(dynamicObj)).toBe(true);
});
test('should return false if a non observable is passed as argument', () => {
const obj1 = { prop: 'value' };
const obj2 = new Proxy({}, {});
expect(isObservable(obj1)).not.toBe(true);
expect(isObservable(obj2)).not.toBe(true);
});
/**
* Action
*/
test('observe run sync', () => {
let data = '';
const dynamicObj = observable({ name: 'b' });
data += 'a';
observe(() => (data += dynamicObj.name));
data += 'c';
return Promise.resolve().then(() => expect(data === 'abc').toBe(true));
});
test('observe run but not used', () => {
let runCount = 0;
const dynamicObj = observable({ name: 'b' });
observe(() => runCount++);
dynamicObj.name = 'c';
return Promise.resolve().then(() => expect(runCount === 1).toBe(true));
});
test('observe run any time', () => {
let runCount = 0;
const dynamicObj = observable({ name: 'b' });
observe(() => {
runCount += 1;
// use it!
// tslint:disable-next-line:no-unused-expression
dynamicObj.name;
});
dynamicObj.name = 'c';
dynamicObj.name = 'd';
return Promise.resolve().then(() => expect(runCount === 3).toBe(true));
});
test('Action', () => {
let runCount = 0;
let count = 0;
const dynamicObj = observable({ number: 1 });
observe(() => {
runCount += 1;
// use it!
count += dynamicObj.number;
});
Action(() => {
dynamicObj.number = 2;
dynamicObj.number = 3;
});
return Promise.resolve()
.then(() => expect(runCount === 2).toBe(true))
.then(() => expect(count === 4).toBe(true)); // 1 + 3, do not use 2
});
/**
* Action
*/
test('Action with Action work', () => {
let runCount = 0;
let data = 0;
const dynamicObj = observable({ counter: 0 });
observe(() => {
runCount++;
data += dynamicObj.counter;
});
class MyAction {
@Action
public run() {
dynamicObj.counter = 1;
dynamicObj.counter = 2;
}
}
new MyAction().run();
return Promise.resolve()
.then(() => expect(runCount === 2).toBe(true))
.then(() => (data = 2)); // 0 + 2, ignore 1
});
test('Action with params', () => {
let runCount = 0;
let data = 0;
const dynamicObj = observable({ counter: 0 });
observe(() => {
runCount++;
data += dynamicObj.counter;
});
class MyAction {
@Action
public run(num: number) {
dynamicObj.counter = num + 1;
dynamicObj.counter = num + 1;
}
}
new MyAction().run(1);
return Promise.resolve()
.then(() => expect(runCount === 2).toBe(true))
.then(() => (data = 3)); // 0 + 3, ignore 2
});
test('Action can get sync return value', () => {
let data = 0;
const dynamicObj = observable({ counter: 0 });
observe(() => {
data += dynamicObj.counter;
});
class MyAction {
@Action
public run(num: number) {
dynamicObj.counter = num + 1;
return dynamicObj.counter;
}
}
const result = new MyAction().run(1);
return Promise.resolve().then(() => expect(result === 2).toBe(true));
});
test('Action can get async return value', async () => {
let data = 0;
const dynamicObj = observable({ counter: 0 });
observe(() => {
data += dynamicObj.counter;
});
class MyAction {
@Action
public async run(num: number) {
dynamicObj.counter = num + 1;
return dynamicObj.counter;
}
}
const result = new MyAction().run(1);
return Promise.resolve().then(() => {
return result.then(value => {
expect(value === 2).toBe(true);
});
});
});
/**
* observe
*/
test('should observe basic properties', () => {
let data = 0;
const dynamicObj = observable({ counter: 0 });
observe(() => (data = dynamicObj.counter));
return Promise.resolve()
.then(() => expect(data === 0).toBe(true))
.then(() => (dynamicObj.counter = 7))
.then(() => expect(data === 7).toBe(true));
});
test('should observe delete operations', () => {
let data = '';
const dynamicObj = observable({ prop: 'value' });
observe(() => (data = dynamicObj.prop));
return Promise.resolve()
.then(() => expect(data === 'value').toBe(true))
.then(() => delete dynamicObj.prop)
.then(() => expect(data === undefined).toBe(true));
});
test('should observe properties on the prototype chain', () => {
let data = 0;
const dynamicObj = observable({ counter: 0 });
const parentDynamicObj = observable({ counter: 2 });
Object.setPrototypeOf(dynamicObj, parentDynamicObj);
observe(() => (data = dynamicObj.counter));
return Promise.resolve()
.then(() => expect(data === 0).toBe(true))
.then(() => delete dynamicObj.counter)
.then(() => expect(data === 2).toBe(true))
.then(() => (parentDynamicObj.counter = 4))
.then(() => expect(data === 4).toBe(true))
.then(() => (dynamicObj.counter = 3))
.then(() => expect(data === 3).toBe(true));
});
test('should observe function call chains', () => {
let data = 0;
const dynamicObj = observable({ counter: 0 });
observe(() => (data = getCounter()));
function getCounter() {
return dynamicObj.counter;
}
return Promise.resolve()
.then(() => expect(data === 0).toBe(true))
.then(() => (dynamicObj.counter = 2))
.then(() => expect(data === 2).toBe(true));
});
test('should observe for of iteration', () => {
let data = '';
const dynamicObj = observable({ array: ['Hello'] });
observe(() => (data = dynamicObj.array.join(' ')));
return Promise.resolve()
.then(() => expect(data === 'Hello').toBe(true))
.then(() => dynamicObj.array.push('World!'))
.then(() => expect(data === 'Hello World!').toBe(true))
.then(() => dynamicObj.array.shift())
.then(() => expect(data === 'World!').toBe(true));
});
// // test('should observe for in iteration', () => {
// // let data = 0
// // const dynamicObj: any = observable({prop: 0})
// // observe(() => {
// // data = 0
// // for (let key in dynamicObj) {
// // data += dynamicObj[key]
// // }
// // })
// //
// // return Promise.resolve()
// // .then(() => expect(data === 0))
// // .then(() => dynamicObj.prop = 1)
// // .then(() => expect(data === 1))
// // .then(() => dynamicObj.prop1 = 1)
// // .then(() => expect(data === 2))
// // .then(() => dynamicObj.prop2 = 3)
// // .then(() => expect(data === 5))
// // .then(() => dynamicObj.prop1 = 6)
// // .then(() => expect(data === 10))
// // })
// // test('should not observe well-known symbols', () => {
// // let data = ''
// // const dynamicObj = observable({[Symbol.toStringTag]: 'myString'})
// // observe(() => data = String(dynamicObj))
// //
// // return Promise.resolve()
// // .then(() => expect(data).to.equal('[object myString]'))
// // .then(() => dynamicObj[Symbol.toStringTag] = 'otherString')
// // .then(() => expect(data).to.equal('[object myString]'))
// // })
test('should not observe set operations without a value change', () => {
let data = '';
const dynamicObj = observable({ prop: 'prop' });
let numOfRuns = 0;
function testObserve() {
data = dynamicObj.prop;
numOfRuns++;
}
observe(testObserve);
return Promise.resolve()
.then(() => expect(data === 'prop').toBe(true))
.then(() => (dynamicObj.prop = 'prop'))
.then(() => {
expect(numOfRuns === 1).toBe(true);
expect(data === 'prop').toBe(true);
})
.then(() => (dynamicObj.prop = 'prop2'))
.then(() => (dynamicObj.prop = 'prop2'))
.then(() => {
expect(numOfRuns === 2).toBe(true);
expect(data === 'prop2').toBe(true);
});
});
test('should run synchronously after registration', () => {
let data = '';
const dynamicObj = observable({ prop: 'prop' });
let numOfRuns = 0;
observe(() => {
data = dynamicObj.prop;
numOfRuns++;
});
expect(numOfRuns === 1).toBe(true);
expect(data === 'prop').toBe(true);
return Promise.resolve()
.then(() => {
expect(numOfRuns === 1).toBe(true);
expect(data === 'prop').toBe(true);
})
.then(() => {
dynamicObj.prop = 'new prop';
})
.then(() => {
expect(numOfRuns === 2).toBe(true);
expect(data === 'new prop').toBe(true);
});
});
test('should rerun maximum once per stack', () => {
let data = 0;
const dynamicObj = observable({ prop1: 0, prop2: 0 });
let numOfRuns = 0;
function testObserve() {
data = dynamicObj.prop1 + dynamicObj.prop2;
numOfRuns++;
}
observe(testObserve);
return Promise.resolve()
.then(() => {
expect(numOfRuns === 1).toBe(true);
expect(data === 0).toBe(true);
})
.then(() => {
Action(() => {
dynamicObj.prop1 = 1;
dynamicObj.prop2 = 3;
dynamicObj.prop1 = 2;
});
})
.then(() => {
expect(numOfRuns === 2).toBe(true);
expect(data === 5).toBe(true);
});
});
test('should avoid infinite loops', () => {
const dynamicObj1 = observable({ prop: 'value1' });
const dynamicObj2 = observable({ prop: 'value2' });
let numOfRuns1 = 0;
let numOfRuns2 = 0;
function test1() {
dynamicObj1.prop = dynamicObj2.prop;
numOfRuns1++;
}
function test2() {
dynamicObj2.prop = dynamicObj1.prop;
numOfRuns2++;
}
observe(test1);
observe(test2);
return Promise.resolve()
.then(() => (dynamicObj1.prop = 'Hello'))
.then(() => expect(dynamicObj2.prop === 'Hello').toBe(true))
.then(() => (dynamicObj1.prop = 'World!'))
.then(() => expect(dynamicObj2.prop === 'World!').toBe(true))
.then(() => {
expect(numOfRuns1 === 3).toBe(true);
expect(numOfRuns2 === 3).toBe(true);
});
});
test('should return an unobserve (object) signal', () => {
let data = 0;
const dynamicObj = observable({ counter: 0 });
const signal = observe(() => (data = dynamicObj.counter));
expect(typeof signal === 'object').toBe(true);
});
/**
* set
*/
test('set should observe string', () => {
let data: boolean;
const dynamicObj = observable(new Set());
observe(() => (data = dynamicObj.has('value')));
return Promise.resolve()
.then(() => expect(data).not.toBe(true))
.then(() => dynamicObj.add('value'))
.then(() => expect(data).toBe(true))
.then(() => dynamicObj.delete('value'))
.then(() => expect(data).not.toBe(true));
});
test('should observe iteration', () => {
let data: number;
const dynamicObj = observable(new Set());
observe(() => {
data = 0;
dynamicObj.forEach(each => {
data += each;
});
});
return Promise.resolve()
.then(() => expect(data === 0).toBe(true))
.then(() => dynamicObj.add(3))
.then(() => expect(data === 3).toBe(true))
.then(() => dynamicObj.add(2))
.then(() => expect(data === 5).toBe(true))
.then(() => dynamicObj.delete(2))
.then(() => expect(data === 3).toBe(true))
.then(() => dynamicObj.clear())
.then(() => expect(data === 0).toBe(true));
});
test('set delete test', () => {
let data: boolean;
let numOfRuns = 0;
const dynamicObj = observable(new Set());
observe(() => {
numOfRuns++;
data = dynamicObj.has('value');
});
return Promise.resolve()
.then(() => {
expect(data).not.toBe(true);
expect(numOfRuns === 1).toBe(true);
})
.then(() => dynamicObj.add('value'))
.then(() => dynamicObj.add('value'))
.then(() => {
expect(data).toBe(true);
expect(numOfRuns === 2).toBe(true);
})
.then(() => dynamicObj.delete('value'))
.then(() => dynamicObj.delete('value'))
.then(() => {
expect(data).not.toBe(true);
expect(numOfRuns === 3).toBe(true);
});
});
test('should observe mutations', () => {
let data: boolean;
const value = {};
const dynamicObj = observable(new Set());
observe(() => (data = dynamicObj.has(value)));
return Promise.resolve()
.then(() => expect(data).not.toBe(true))
.then(() => dynamicObj.add(value))
.then(() => expect(data).toBe(true))
.then(() => dynamicObj.delete(value))
.then(() => expect(data).not.toBe(true));
});
test('should not observe non value changing mutations', () => {
let data: boolean;
const value = {};
let numOfRuns = 0;
const dynamicObj = observable(new Set());
observe(() => {
numOfRuns++;
data = dynamicObj.has(value);
});
return Promise.resolve()
.then(() => {
expect(data).not.toBe(true);
expect(numOfRuns === 1).toBe(true);
})
.then(() => dynamicObj.add(value))
.then(() => dynamicObj.add(value))
.then(() => {
expect(data).toBe(true);
expect(numOfRuns === 2).toBe(true);
})
.then(() => dynamicObj.delete(value))
.then(() => dynamicObj.delete(value))
.then(() => {
expect(data).not.toBe(true);
expect(numOfRuns === 3).toBe(true);
});
});
/**
* WeakSet
*/
test('weakSet should observe object', () => {
let data: boolean;
const value = {};
const dynamicObj = observable(new WeakSet());
observe(() => (data = dynamicObj.has(value)));
return Promise.resolve()
.then(() => expect(data).not.toBe(true))
.then(() => dynamicObj.add(value))
.then(() => expect(data).toBe(true))
.then(() => dynamicObj.delete(value))
.then(() => expect(data).not.toBe(true));
});
/**
* Map
*/
test('weakSet should observe string', () => {
let data: string;
const dynamicObj = observable(new Map());
observe(() => (data = dynamicObj.get('key')));
return Promise.resolve()
.then(() => expect(data === undefined).toBe(true))
.then(() => dynamicObj.set('key', 'value'))
.then(() => expect(data === 'value').toBe(true))
.then(() => dynamicObj.delete('key'))
.then(() => expect(data === undefined).toBe(true));
});
test('should observe iteration', () => {
let data: number;
const dynamicObj = observable(new Map());
observe(() => {
data = 0;
dynamicObj.forEach(each => {
data += each;
});
});
return Promise.resolve()
.then(() => expect(data === 0).toBe(true))
.then(() => dynamicObj.set('key0', 3))
.then(() => expect(data === 3).toBe(true))
.then(() => dynamicObj.set('key1', 2))
.then(() => expect(data === 5).toBe(true))
.then(() => dynamicObj.delete('key0'))
.then(() => expect(data === 2).toBe(true))
.then(() => dynamicObj.clear())
.then(() => expect(data === 0).toBe(true));
});
test('should not observe non value changing mutations', () => {
let data: string;
let numOfRuns = 0;
const dynamicObj = observable(new Map());
observe(() => {
numOfRuns++;
data = dynamicObj.get('key');
});
return Promise.resolve()
.then(() => {
expect(data === undefined).toBe(true);
expect(numOfRuns === 1).toBe(true);
})
.then(() => dynamicObj.set('key', 'value'))
.then(() => dynamicObj.set('key', 'value'))
.then(() => {
expect(data === 'value').toBe(true);
expect(numOfRuns === 2).toBe(true);
})
.then(() => dynamicObj.delete('key'))
.then(() => dynamicObj.delete('key'))
.then(() => {
expect(data === undefined).toBe(true);
expect(numOfRuns === 3).toBe(true);
});
});
test('should observe map array', () => {
let data: number;
const dynamicObj = observable(new Map<string, number[]>([['a', [1, 2, 3]]]));
observe(() => (data = dynamicObj!.get('a')!.length));
return Promise.resolve()
.then(() => expect(data === 3).toBe(true))
.then(() => dynamicObj!.get('a')!.push(4))
.then(() => expect(data === 4).toBe(true));
});
test('should observe map.size', () => {
const map = observable(new Map());
let count = 0;
observe(() => {
count += map.size;
});
map.set('banana', 5);
map.set('apple', 3);
return Promise.resolve().then(() => expect(count === 3).toBe(true));
});
/**
* WeakMap
*/
test('should observe mutations', () => {
let data: string;
const key = {};
const dynamicObj = observable(new WeakMap());
observe(() => (data = dynamicObj.get(key)));
return Promise.resolve()
.then(() => expect(data === undefined).toBe(true))
.then(() => dynamicObj.set(key, 'value'))
.then(() => expect(data === 'value').toBe(true))
.then(() => dynamicObj.delete(key))
.then(() => expect(data === undefined).toBe(true));
});
test('should not observe non value changing mutations', () => {
let data: string;
let numOfRuns = 0;
const key = {};
const dynamicObj = observable(new WeakMap());
observe(() => {
numOfRuns++;
data = dynamicObj.get(key);
});
return Promise.resolve()
.then(() => {
expect(data === undefined).toBe(true);
expect(numOfRuns === 1).toBe(true);
})
.then(() => dynamicObj.set(key, 'value'))
.then(() => dynamicObj.set(key, 'value'))
.then(() => {
expect(data === 'value').toBe(true);
expect(numOfRuns === 2).toBe(true);
})
.then(() => dynamicObj.delete(key))
.then(() => dynamicObj.delete(key))
.then(() => {
expect(data === undefined).toBe(true);
expect(numOfRuns === 3).toBe(true);
});
});
/**
* execution order
*/
test('should run in runner order the first time', () => {
let data = '';
const dynamicObj = observable({ prop1: 'prop1', prop2: 'prop2', prop3: 'prop3' });
observe(() => (data += dynamicObj.prop1));
observe(() => (data += dynamicObj.prop2));
observe(() => (data += dynamicObj.prop3));
dynamicObj.prop3 = 'p3';
dynamicObj.prop1 = 'p1';
dynamicObj.prop2 = 'p2';
return Promise.resolve().then(() => expect(data === 'prop1prop2prop3p3p1p2').toBe(true));
});
/**
* unobserve
*/
test('should unobserve the observed function', () => {
// TODO:
// let data = ""
// const dynamicObj = observable({ prop: "" })
// let numOfRuns = 0
// function testObserve() {
// data = dynamicObj.prop
// numOfRuns++
// }
// const signal = observe(testObserve)
// return Promise.resolve()
// .then(() => dynamicObj.prop = "Hello")
// .then(() => signal.unobserve())
// .then(() => {
// expect(signal.callback === undefined)
// expect(signal.observedKeys === undefined)
// })
// .then(() => dynamicObj.prop = "World")
// .then(() => dynamicObj.prop = "!")
// .then(() => expect(numOfRuns === 2))
});
test('should not unobserve if the function is registered for the stack, because of sync', () => {
let data: number;
const dynamicObj = observable({ prop: 0 });
let numOfRuns = 0;
function testObserve() {
data = dynamicObj.prop;
numOfRuns++;
}
const signal = observe(testObserve);
return Promise.resolve()
.then(() => {
dynamicObj.prop = 2; // but also run
signal.unobserve();
})
.then(() => expect(numOfRuns === 2).toBe(true));
});
test('should unobserve even if the function is registered for the stack, when use Action', () => {
let data: number;
const dynamicObj = observable({ prop: 0 });
let numOfRuns = 0;
function testObserve() {
data = dynamicObj.prop;
numOfRuns++;
}
const signal = observe(testObserve);
return Promise.resolve()
.then(() => {
Action(() => {
dynamicObj.prop = 2; // not run
signal.unobserve();
});
})
.then(() => expect(numOfRuns === 1).toBe(true));
});
test('will trace dependency in anywhere', () => {
let runCount = 0;
const dynamicObj = observable({
a: 0,
b: 1
});
observe(() => {
// use a
// tslint:disable-next-line:no-unused-expression
dynamicObj.a;
runSomeThing();
runCount++;
});
function runSomeThing() {
// use b
// tslint:disable-next-line:no-unused-expression
dynamicObj.b;
}
dynamicObj.a = 2;
dynamicObj.b = 3;
return Promise.resolve().then(() => expect(runCount === 3).toBe(true));
});
test('Action will not trace dependency', () => {
let runCount = 0;
const dynamicObj = observable({
a: 0,
b: 1
});
observe(() => {
// use a
// tslint:disable-next-line:no-unused-expression
dynamicObj.a;
Action(() => {
// tslint:disable-next-line:no-unused-expression
dynamicObj.b;
});
runCount++;
});
dynamicObj.b = 2;
return Promise.resolve().then(() => expect(runCount === 1).toBe(true));
});
/**
* Action handle async
*/
test('Action not handle async function!!', async () => {
let runCount = 0;
let num = 0;
const dynamicObj = observable({
a: 0,
b: 1
});
observe(() => {
// use a
num = dynamicObj.a;
runCount++;
});
Action(async () => {
dynamicObj.a = 1;
dynamicObj.a = 2;
await Promise.resolve();
dynamicObj.a = 3;
dynamicObj.a = 4;
dynamicObj.a = 5;
dynamicObj.a = 6;
});
return Promise.resolve()
.then(() => expect(runCount === 2).toBe(false))
.then(() => expect(num === 2).toBe(false));
});
test('Action handle async function with Action', async () => {
let runCount = 0;
let num = 0;
const dynamicObj = observable({
a: 0,
b: 1
});
observe(() => {
// use a
num = dynamicObj.a;
runCount++;
});
Action(async () => {
dynamicObj.a = 1;
await Promise.resolve();
Action(() => {
dynamicObj.a = 2;
dynamicObj.a = 3;
dynamicObj.a = 4;
dynamicObj.a = 5;
});
});
return Promise.resolve()
.then(() => expect(runCount === 3).toBe(true))
.then(() => expect(num === 5).toBe(true));
});
/**
* Branch judgment
*/
test('branch judgment', () => {
let value = 0;
let runCount = 0;
const dynamicObj = observable({
a: true,
b: 1,
c: 2
});
observe(() => {
runCount++;
// tslint:disable-next-line:prefer-conditional-expression
if (dynamicObj.a) {
value = dynamicObj.b;
} else {
value = dynamicObj.c;
}
});
return Promise.resolve()
.then(() => expect(value === 1).toBe(true))
.then(() => expect(runCount === 1).toBe(true))
.then(() => (dynamicObj.c = 3)) // nothing happend
.then(() => expect(value === 1).toBe(true))
.then(() => expect(runCount === 1).toBe(true))
.then(() => (dynamicObj.a = false))
.then(() => expect(value === 3).toBe(true))
.then(() => expect(runCount === 2).toBe(true))
.then(() => (dynamicObj.c = 4))
.then(() => expect(value === 4).toBe(true))
.then(() => expect(runCount === 3).toBe(true))
.then(() => (dynamicObj.b = 5))
.then(() => expect(value === 4).toBe(true))
.then(() => expect(runCount === 3).toBe(true));
});
/**
* Static
*/
test('Static will not tracking object', () => {
let runCount = 0;
let result = '';
const dynamicObj = observable(Static({ name: 'b' }));
observe(() => {
result = dynamicObj.name;
runCount++;
});
dynamicObj.name = 'c';
return Promise.resolve()
.then(() => expect(runCount === 1).toBe(true))
.then(() => expect(result === 'b').toBe(true));
});
test('Static will not tracking map', () => {
let runCount = 0;
let size = 0;
const dynamicObj = observable(Static(new Map<string, string>()));
observe(() => {
size = dynamicObj.size;
runCount++;
});
dynamicObj.set('a', 'a');
dynamicObj.set('b', 'b');
return Promise.resolve()
.then(() => expect(runCount === 1).toBe(true))
.then(() => expect(size === 0).toBe(true));
});
test('nested observe should eventually run', () => {
const dynamicObj = observable({
a: '1',
b: '2',
c: '3',
d: '4'
});
let str = '';
observe(() => {
str += dynamicObj.a;
observe(() => {
str += 5;
observe(() => {
str += dynamicObj.b;
});
str += 6;
});
observe(() => {
str += 8;
observe(() => {
str += dynamicObj.c;
});
str += 9;
});
str += dynamicObj.d;
});
dynamicObj.a = '2';
return Promise.resolve().then(() => expect(str === '1456289324562893').toBe(true));
});
test('observe in action', () => {
const dynamicObj = observable({
a: 'a'
});
let count = '';
Action(() => {
observe(() => {
count += dynamicObj.a;
});
count += 'b';
});
dynamicObj.a = 'c';
return Promise.resolve().then(() => expect(count === 'bac').toBe(true));
}); | the_stack |
import * as fileSystem from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import { WasmTaskProvider } from './taskProvider';
import { TargetConfigPanel } from './view/TargetConfigPanel';
import { NewProjectPanel } from './view/NewProjectPanel';
import {
WriteIntoFile,
ReadFromFile,
WriteIntoFileAsync,
} from './utilities/directoryUtilities';
import { decorationProvider } from './explorer/decorationProvider';
import { WasmDebugConfigurationProvider } from './debug/debugConfigurationProvider';
let wasmTaskProvider: WasmTaskProvider;
let wasmDebugConfigProvider: WasmDebugConfigurationProvider;
var currentPrjDir = '';
var extensionPath = '';
export async function activate(context: vscode.ExtensionContext) {
var OS_PLATFORM = '',
buildScript = '',
runScript = '',
debugScript = '',
buildScriptFullPath = '',
runScriptFullPath = '',
debugScriptFullPath = '',
typeMap = new Map(),
/* include paths array used for written into config file */
includePathArr = new Array(),
/* exclude files array used for written into config file */
excludeFileArr = new Array(),
scriptMap = new Map();
/**
* Get OS platform information for differ windows and linux execution script
*/
OS_PLATFORM = os.platform();
/**
* Provide Build & Run Task with Task Provider instead of "tasks.json"
*/
/* set relative path of build.bat|sh script */
let scriptPrefix = 'resource/scripts/';
if (OS_PLATFORM === 'win32') {
buildScript = scriptPrefix.concat('build.bat');
runScript = scriptPrefix.concat('run.bat');
debugScript = scriptPrefix.concat('boot_debugger_server.bat');
} else if (OS_PLATFORM === 'linux') {
buildScript = scriptPrefix.concat('build.sh');
runScript = scriptPrefix.concat('run.sh');
debugScript = scriptPrefix.concat('boot_debugger_server.sh');
}
/* get extension's path, and set scripts' absolute path */
extensionPath = context.extensionPath;
buildScriptFullPath = path.join(extensionPath, buildScript);
runScriptFullPath = path.join(extensionPath, runScript);
debugScriptFullPath = path.join(extensionPath, debugScript);
scriptMap.set('buildScript', buildScriptFullPath);
scriptMap.set('runScript', runScriptFullPath);
scriptMap.set('debugScript', debugScriptFullPath);
typeMap.set('Build', 'Build');
typeMap.set('Run', 'Run');
typeMap.set('Debug', 'Debug');
wasmTaskProvider = new WasmTaskProvider(typeMap, scriptMap);
vscode.tasks.registerTaskProvider('wasm', wasmTaskProvider);
/* set current project directory */
if (vscode.workspace.workspaceFolders?.[0]) {
if (OS_PLATFORM === 'win32') {
currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.fsPath as string;
} else if (OS_PLATFORM === 'linux') {
currentPrjDir = vscode.workspace.workspaceFolders?.[0].uri
.path as string;
}
}
/**
* check whether current project opened in vscode workspace is wasm project
* it not, `build`, `run` and `debug` will be disabled
*/
if (currentPrjDir !== '') {
let wamrFolder = fileSystem
.readdirSync(currentPrjDir, {
withFileTypes: true,
})
.filter(folder => folder.isDirectory() && folder.name === '.wamr');
if (wamrFolder.length !== 0) {
vscode.commands.executeCommand(
'setContext',
'ext.isWasmProject',
true
);
}
}
/* register debug configuration */
wasmDebugConfigProvider = new WasmDebugConfigurationProvider();
wasmDebugConfigProvider.setDebugConfig(currentPrjDir, 1234);
vscode.debug.registerDebugConfigurationProvider(
'wamr-debug',
wasmDebugConfigProvider
);
/* update ext.includePaths to show or hide 'Remove' button in menus */
vscode.commands.executeCommand('setContext', 'ext.supportedFileType', [
'.c',
'.cpp',
'.cxx',
]);
if (readFromConfigFile() !== '') {
let configData = JSON.parse(readFromConfigFile());
includePathArr = configData['include_paths'];
excludeFileArr = configData['exclude_files'];
if (Object.keys(configData['build_args']).length !== 0) {
TargetConfigPanel.BUILD_ARGS = configData['build_args'];
}
}
let disposableNewProj = vscode.commands.registerCommand(
'wamride.newProject',
() => {
let _ok = 'Set up now';
let _cancle = 'Maybe later';
let curWorkspace = vscode.workspace
.getConfiguration()
.get('WAMR-IDE.configWorkspace');
/* if user has not set up workspace yet, prompt to set up */
if (curWorkspace === '' || curWorkspace === undefined) {
vscode.window
.showWarningMessage(
'Please setup your workspace firstly.',
_ok,
_cancle
)
.then(item => {
if (item === _ok) {
vscode.commands.executeCommand(
'wamride.changeWorkspace'
);
} else {
return;
}
});
} else {
NewProjectPanel.render(context);
}
}
);
let disposableTargetConfig = vscode.commands.registerCommand(
'wamride.targetConfig',
() => {
if (currentPrjDir !== '') {
TargetConfigPanel.render(context);
} else {
vscode.window.showWarningMessage(
'Please create and open project firstly.',
'OK'
);
}
}
);
let disposableChangeWorkspace = vscode.commands.registerCommand(
'wamride.changeWorkspace',
async () => {
let options: vscode.OpenDialogOptions = {
canSelectFiles: false,
canSelectFolders: true,
openLabel: 'Select Workspace',
};
let Workspace = await vscode.window
.showOpenDialog(options)
.then(res => {
if (res) {
return res[0].fsPath as string;
} else {
return '';
}
});
/* update workspace value to vscode global settings */
await vscode.workspace
.getConfiguration()
.update(
'WAMR-IDE.configWorkspace',
Workspace.trim(),
vscode.ConfigurationTarget.Global
)
.then(
success => {
vscode.window.showInformationMessage(
'Workspace has been set up successfully!'
);
},
error => {
vscode.window.showErrorMessage(
'Set up Workspace failed!'
);
}
);
}
);
let disposableBuild = vscode.commands.registerCommand(
'wamride.build',
() => {
generateCMakeFile(includePathArr, excludeFileArr);
return vscode.commands.executeCommand(
'workbench.action.tasks.runTask',
'Build: Wasm'
);
}
);
let disposableDebug = vscode.commands.registerCommand(
'wamride.debug',
() => {
vscode.commands
.executeCommand('workbench.action.tasks.runTask', 'Debug: Wasm')
.then(() => {
vscode.debug.startDebugging(
undefined,
wasmDebugConfigProvider.getDebugConfig()
);
});
}
);
let disposableRun = vscode.commands.registerCommand('wamride.run', () => {
return vscode.commands.executeCommand(
'workbench.action.tasks.runTask',
'Run: Wasm'
);
});
let disposableToggleIncludePath = vscode.commands.registerCommand(
'wamride.build.toggleStateIncludePath',
fileUri => {
let pathRelative: string;
let path =
fileUri._fsPath !== null && fileUri._fsPath !== undefined
? fileUri._fsPath
: vscode.Uri.parse(fileUri.path as string).fsPath;
pathRelative = path.replace(currentPrjDir, '..');
if (includePathArr.indexOf(pathRelative) > -1) {
/* this folder has been added to include path, remove it */
includePathArr = includePathArr.filter(value => {
return value !== pathRelative;
});
} else {
includePathArr.push(pathRelative);
}
writeIntoConfigFile(
includePathArr,
excludeFileArr,
TargetConfigPanel.BUILD_ARGS
);
decorationProvider.updateDecorationsForSource(fileUri);
}
);
let disposableToggleExcludeFile = vscode.commands.registerCommand(
'wamride.build.toggleStateExclude',
fileUri => {
let pathRelative: string;
let path =
fileUri._fsPath !== null && fileUri._fsPath !== undefined
? fileUri._fsPath
: vscode.Uri.parse(fileUri.path as string).fsPath;
/* replace the current project absolute path with .. to change to relative path */
pathRelative = path.replace(currentPrjDir, '..');
if (excludeFileArr.indexOf(pathRelative) > -1) {
excludeFileArr = excludeFileArr.filter(val => {
return val !== pathRelative;
});
} else {
excludeFileArr.push(pathRelative);
}
writeIntoConfigFile(
includePathArr,
excludeFileArr,
TargetConfigPanel.BUILD_ARGS
);
/* update decoration for this source file */
decorationProvider.updateDecorationsForSource(fileUri);
}
);
let disposableOpenFolder = vscode.commands.registerCommand(
'wamride.openFolder',
() => {
let _ok = 'Set up now';
let _cancle = 'Maybe later';
let curWorkspace = vscode.workspace
.getConfiguration()
.get('WAMR-IDE.configWorkspace') as string;
/* if user has not set up workspace yet, prompt to set up */
if (curWorkspace === '' || curWorkspace === undefined) {
vscode.window
.showWarningMessage(
'Please setup your workspace firstly.',
_ok,
_cancle
)
.then(item => {
if (item === _ok) {
vscode.commands.executeCommand(
'wamride.changeWorkspace'
);
} else {
return;
}
});
} else {
/* get all directories within directory, ignore files */
let directoryArrDirent, directoryArr;
try {
directoryArrDirent = fileSystem.readdirSync(curWorkspace, {
withFileTypes: true,
});
} catch (err) {
vscode.window.showErrorMessage(
'Read from current workspace failed, please check.'
);
}
if (directoryArrDirent !== undefined) {
directoryArr = directoryArrDirent
.filter(dirent => dirent.isDirectory())
.map(dirent => dirent.name);
vscode.window
.showQuickPick(directoryArr, {
title: 'Select project',
placeHolder: 'Please select project',
})
.then(option => {
if (!option) {
return;
}
let _path = curWorkspace.concat(
OS_PLATFORM === 'win32'
? '\\'
: OS_PLATFORM === 'linux'
? '/'
: '',
option
);
openWindoWithSituation(vscode.Uri.file(_path));
});
}
}
}
);
context.subscriptions.push(
disposableNewProj,
disposableTargetConfig,
disposableChangeWorkspace,
disposableBuild,
disposableRun,
disposableToggleIncludePath,
disposableOpenFolder,
disposableToggleExcludeFile,
disposableDebug
);
}
function openWindoWithSituation(uri: vscode.Uri) {
/**
* check if the workspace folder is empty,
* if yes, open new window, else open in current window
*/
let isWorkspaceEmpty: boolean;
isWorkspaceEmpty = !vscode.workspace.workspaceFolders?.[0] ? true : false;
isWorkspaceEmpty === false
? vscode.commands.executeCommand('vscode.openFolder', uri, {
forceNewWindow: true,
})
: vscode.commands.executeCommand('vscode.openFolder', uri);
return;
}
interface BuildArgs {
output_file_name: string;
init_memory_size: string;
max_memory_size: string;
stack_size: string;
exported_symbols: string;
}
/**
* @param: includePathArr
* @param: excludeFileArr
* Get current includePathArr and excludeFileArr from the json string that
* will be written into compilation_config.json
*/
export function writeIntoConfigFile(
includePathArr: string[],
excludeFileArr: string[],
buildArgs?: BuildArgs
) {
let jsonStr = JSON.stringify({
include_paths: includePathArr,
exclude_files: excludeFileArr,
build_args: buildArgs ? buildArgs : '{}',
});
let prjConfigDir = path.join(currentPrjDir, '.wamr');
let configFilePath = path.join(prjConfigDir, 'compilation_config.json');
WriteIntoFile(configFilePath, jsonStr);
}
export function readFromConfigFile(): string {
let prjConfigDir = path.join(currentPrjDir, '.wamr');
let configFilePath = path.join(prjConfigDir, 'compilation_config.json');
return ReadFromFile(configFilePath);
}
/**
* will be triggered when the user clicking `build` button
*/
function generateCMakeFile(
includePathArr: string[],
excludeFileArr: string[]
): void {
// -Wl,--export=${EXPORT_SYMBOLS}
let srcFilePath = path.join(currentPrjDir, 'src');
let prjConfigDir = path.join(currentPrjDir, '.wamr');
let cmakeFilePath = path.join(prjConfigDir, 'project.cmake');
let strIncludeList = 'set (PROJECT_INCLUDES';
let strSrcList = 'set (PROJECT_SRC_LIST';
let strOutputFileName = 'set (OUTPUT_FILE_NAME';
let strInitMemSize = 'set (INIT_MEM_SIZE';
let strMaxMemSize = 'set (MAX_MEM_SIZE';
let strStackSize = 'set (STACK_SIZE';
let strExportedSymbols = 'set (EXPORTED_SYMBOLS';
let fullStr = '';
let i, s, e: number;
/* change the absolute path into relative path */
let _re = currentPrjDir;
let _substr = '${CMAKE_CURRENT_SOURCE_DIR}/..';
let srcPathArr: Array<{ path: string }> | undefined;
/**
* set PROJECT_SRC_LIST
* default ADD every c OR c++ OR cpp under the src/ path
* except the files saved in the exclude_files array
*/
srcPathArr = getAllSrcFiles(srcFilePath);
if (srcPathArr === undefined) {
return;
}
for (s = 0; s < srcPathArr.length; s++) {
if (
excludeFileArr.indexOf(
srcPathArr[s].path.replace(currentPrjDir, '..')
) === -1
) {
/* replace currentPrjDir with ${CMAKE_CURRENT_SOURCE_DIR} */
let _newStr = srcPathArr[s].path
.replace(_re, _substr)
.replace(/\\/g, '/');
strSrcList = strSrcList.concat(' ', _newStr);
}
}
strSrcList = strSrcList.concat(' )');
for (i = 0; i < includePathArr.length; i++) {
let _newStr = includePathArr[i]
.replace(/../, _substr)
.replace(/\\/g, '/');
strIncludeList = strIncludeList.concat(' ', _newStr);
}
strIncludeList = strIncludeList.concat(' )');
/* set up user customized input in configBuildArgs webview */
strOutputFileName = strOutputFileName.concat(
' ',
TargetConfigPanel.BUILD_ARGS.output_file_name + ')'
);
strInitMemSize = strInitMemSize.concat(
' ',
TargetConfigPanel.BUILD_ARGS.init_memory_size + ')'
);
strMaxMemSize = strMaxMemSize.concat(
' ',
TargetConfigPanel.BUILD_ARGS.max_memory_size + ')'
);
strStackSize = strStackSize.concat(
' ',
TargetConfigPanel.BUILD_ARGS.stack_size + ')'
);
let exportedSymbolArr =
TargetConfigPanel.BUILD_ARGS.exported_symbols.split(',');
strExportedSymbols = strExportedSymbols.concat(' "');
for (e = 0; e < exportedSymbolArr.length; e++) {
strExportedSymbols = strExportedSymbols.concat(
' -Wl,',
'--export=',
exportedSymbolArr[e]
);
}
strExportedSymbols = strExportedSymbols.concat('")');
fullStr = strOutputFileName
.concat('\n', strInitMemSize)
.concat('\n', strMaxMemSize)
.concat('\n', strStackSize)
.concat('\n', strExportedSymbols)
.concat('\n', strSrcList)
.concat('\n', strIncludeList);
WriteIntoFile(cmakeFilePath, fullStr);
}
function getAllSrcFiles(_path: string) {
try {
const entries = fileSystem.readdirSync(_path, {
withFileTypes: true,
});
const files = entries
.filter(
/* filter files mismatch .c |.cpp |.cxx */
file =>
!file.isDirectory() && file.name.match('(.c|.cpp|.cxx)$')
)
.map(file => ({
path: path.join(_path, file.name),
}));
const folders = entries.filter(folder => folder.isDirectory());
for (const folder of folders) {
let fileArr = getAllSrcFiles(path.join(_path, folder.name));
fileArr ? files.push(...fileArr) : '';
}
return files;
} catch (error) {
vscode.window.showErrorMessage(error as string);
}
} | the_stack |
import * as moment from "moment";
/**
* Response base.
*/
export interface ResponseBase {
/**
* Polymorphic Discriminator
*/
_type: string;
}
/**
* Defines the identity of a resource.
*/
export interface Identifiable extends ResponseBase {
/**
* A String identifier.
*/
readonly id?: string;
}
/**
* Defines a response. All schemas that return at the root of the response must inherit from this
* object.
*/
export interface Response extends Identifiable {
/**
* The URL that returns this resource. To use the URL, append query parameters as appropriate and
* include the Ocp-Apim-Subscription-Key header.
*/
readonly readLink?: string;
/**
* The URL to Bing's search result for this item.
*/
readonly webSearchUrl?: string;
}
/**
* Defines a thing.
*/
export interface Thing extends Response {
/**
* The name of the thing represented by this object.
*/
readonly name?: string;
/**
* The URL to get more information about the thing represented by this object.
*/
readonly url?: string;
/**
* An image of the item.
*/
readonly image?: ImageObject;
/**
* A short description of the item.
*/
readonly description?: string;
/**
* An alias for the item.
*/
readonly alternateName?: string;
/**
* An ID that uniquely identifies this item.
*/
readonly bingId?: string;
}
/**
* A utility class that serves as the umbrella for a number of 'intangible' things such as
* quantities, structured values, etc.
*/
export interface Intangible extends Thing {
}
export interface StructuredValue extends Intangible {
}
/**
* Defines a 2D point with X and Y coordinates.
*/
export interface Point2D extends StructuredValue {
/**
* The x-coordinate of the point.
*/
x: number;
/**
* The y-coordinate of the point.
*/
y: number;
}
/**
* Defines a region of an image. The region is a convex quadrilateral defined by coordinates of its
* top left, top right, bottom left, and bottom right points. The coordinates are fractional values
* of the original image's width and height in the range 0.0 through 1.0.
*/
export interface NormalizedQuadrilateral extends StructuredValue {
/**
* The top left corner coordinate.
*/
topLeft: Point2D;
/**
* The top right corner coordinate.
*/
topRight: Point2D;
/**
* The bottom right corner coordinate.
*/
bottomRight: Point2D;
/**
* The bottom left corner coordinate.
*/
bottomLeft: Point2D;
}
/**
* Defines an image region relevant to the ImageTag.
*/
export interface ImageTagRegion {
/**
* A rectangle that outlines the area of interest for this tag.
*/
queryRectangle: NormalizedQuadrilateral;
/**
* A recommended rectangle to show to the user.
*/
displayRectangle: NormalizedQuadrilateral;
}
/**
* The most generic kind of creative work, including books, movies, photographs, software programs,
* etc.
*/
export interface CreativeWork extends Thing {
/**
* The URL to a thumbnail of the item.
*/
readonly thumbnailUrl?: string;
/**
* The source of the creative work.
*/
readonly provider?: Thing[];
/**
* The date on which the CreativeWork was published.
*/
readonly datePublished?: string;
/**
* Text content of this creative work.
*/
readonly text?: string;
}
/**
* Defines an action.
*/
export interface Action extends CreativeWork {
/**
* The result produced in the action.
*/
readonly result?: Thing[];
/**
* A display name for the action.
*/
readonly displayName?: string;
/**
* A Boolean representing whether this result is the top action.
*/
readonly isTopAction?: boolean;
/**
* Use this URL to get additional data to determine how to take the appropriate action. For
* example, the serviceUrl might return JSON along with an image URL.
*/
readonly serviceUrl?: string;
}
/**
* Defines an image action.
*/
export interface ImageAction extends Action {
/**
* A string representing the type of action.
*/
readonly actionType?: string;
}
/**
* A visual search tag.
*/
export interface ImageTag extends Thing {
/**
* Display name for this tag. For the default tag, the display name is empty.
*/
readonly displayName?: string;
/**
* The bounding box for this tag. For the default tag, there is no bounding box.
*/
readonly boundingBox?: ImageTagRegion;
/**
* Actions within this tag. The order of the items denotes the default ranking order of these
* actions, with the first action being the most likely user intent.
*/
readonly actions?: ImageAction[];
}
/**
* Defines an organization.
*/
export interface Organization extends Thing {
}
/**
* Defines an item.
*/
export interface PropertiesItem {
/**
* Text representation of an item.
*/
readonly text?: string;
/**
* Polymorphic Discriminator
*/
_type: string;
}
/**
* Defines a rating.
*/
export interface Rating extends PropertiesItem {
/**
* The mean (average) rating. The possible values are 1.0 through 5.0.
*/
ratingValue: number;
/**
* The highest rated review. The possible values are 1.0 through 5.0.
*/
readonly bestRating?: number;
}
/**
* Defines the metrics that indicate how well an item was rated by others.
*/
export interface AggregateRating extends Rating {
/**
* The number of times the recipe has been rated or reviewed.
*/
readonly reviewCount?: number;
}
/**
* Defines a merchant's offer.
*/
export interface Offer extends Thing {
/**
* Seller for this offer.
*/
readonly seller?: Organization;
/**
* The item's price.
*/
readonly price?: number;
/**
* The monetary currency. For example, USD. Possible values include: 'USD', 'CAD', 'GBP', 'EUR',
* 'COP', 'JPY', 'CNY', 'AUD', 'INR', 'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AWG',
* 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD',
* 'BTN', 'BWP', 'BYR', 'BZD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'COU', 'CRC', 'CUC',
* 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'FJD', 'FKP', 'GEL',
* 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS',
* 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD',
* 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT',
* 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK',
* 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD',
* 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP',
* 'STD', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH',
* 'UGX', 'UYU', 'UZS', 'VEF', 'VND', 'VUV', 'WST', 'XAF', 'XCD', 'XOF', 'XPF', 'YER', 'ZAR',
* 'ZMW'
*/
readonly priceCurrency?: string;
/**
* The item's availability. The following are the possible values: Discontinued, InStock,
* InStoreOnly, LimitedAvailability, OnlineOnly, OutOfStock, PreOrder, SoldOut. Possible values
* include: 'Discontinued', 'InStock', 'InStoreOnly', 'LimitedAvailability', 'OnlineOnly',
* 'OutOfStock', 'PreOrder', 'SoldOut'
*/
readonly availability?: string;
/**
* An aggregated rating that indicates how well the product has been rated by others.
*/
readonly aggregateRating?: AggregateRating;
/**
* The last date that the offer was updated. The date is in the form YYYY-MM-DD.
*/
readonly lastUpdated?: string;
}
/**
* Defines a list of offers from merchants that are related to the image.
*/
export interface AggregateOffer extends Offer {
/**
* A list of offers from merchants that have offerings related to the image.
*/
readonly offers?: Offer[];
}
/**
* Defines a count of the number of websites where you can shop or perform other actions related to
* the image.
*/
export interface ImagesImageMetadata {
/**
* The number of websites that sell the products seen in the image.
*/
readonly shoppingSourcesCount?: number;
/**
* The number of websites that offer recipes of the food seen in the image.
*/
readonly recipeSourcesCount?: number;
/**
* A summary of the online offers of products found in the image. For example, if the image is of
* a dress, the offer might identify the lowest price and the number of offers found. Only
* visually similar products insights include this field. The offer includes the following
* fields: Name, AggregateRating, OfferCount, and LowPrice.
*/
readonly aggregateOffer?: AggregateOffer;
}
/**
* Defines a media object.
*/
export interface MediaObject extends CreativeWork {
/**
* Original URL to retrieve the source (file) for the media object (e.g., the source URL for the
* image).
*/
readonly contentUrl?: string;
/**
* URL of the page that hosts the media object.
*/
readonly hostPageUrl?: string;
/**
* Size of the media object content. Use format "value unit" (e.g., "1024 B").
*/
readonly contentSize?: string;
/**
* Encoding format (e.g., png, gif, jpeg, etc).
*/
readonly encodingFormat?: string;
/**
* Display URL of the page that hosts the media object.
*/
readonly hostPageDisplayUrl?: string;
/**
* The width of the media object, in pixels.
*/
readonly width?: number;
/**
* The height of the media object, in pixels.
*/
readonly height?: number;
}
/**
* Defines an image.
*/
export interface ImageObject extends MediaObject {
/**
* The URL to a thumbnail of the image.
*/
readonly thumbnail?: ImageObject;
/**
* The token that you use in a subsequent call to Visual Search API to get additional information
* about the image. For information about using this token, see the imageInsightsToken field
* inside the knowledgeRequest request parameter.
*/
readonly imageInsightsToken?: string;
/**
* A count of the number of websites where you can shop or perform other actions related to the
* image. For example, if the image is of an apple pie, this object includes a count of the
* number of websites where you can buy an apple pie. To indicate the number of offers in your
* UX, include badging such as a shopping cart icon that contains the count. When the user clicks
* on the icon, use imageInisghtsToken in a subsequent Visual Search API call to get the list of
* shopping websites.
*/
readonly insightsMetadata?: ImagesImageMetadata;
/**
* Unique Id for the image.
*/
readonly imageId?: string;
/**
* A three-byte hexadecimal number that represents the color that dominates the image. Use the
* color as the temporary background in your client until the image is loaded.
*/
readonly accentColor?: string;
/**
* For interal use only.
*/
readonly visualWords?: string;
}
/**
* Defines a visual search API response.
*/
export interface ImageKnowledge extends Response {
/**
* A list of visual search tags.
*/
readonly tags?: ImageTag[];
/**
* Image object containing metadata about the requested image.
*/
readonly image?: ImageObject;
}
/**
* Defines the error that occurred.
*/
export interface ErrorModel {
/**
* The error code that identifies the category of error. Possible values include: 'None',
* 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization',
* 'InsufficientAuthorization'
*/
code: string;
/**
* The error code that further helps to identify the error. Possible values include:
* 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing',
* 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing',
* 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired'
*/
readonly subCode?: string;
/**
* A description of the error.
*/
message: string;
/**
* A description that provides additional information about the error.
*/
readonly moreDetails?: string;
/**
* The parameter in the request that caused the error.
*/
readonly parameter?: string;
/**
* The parameter's value in the request that was not valid.
*/
readonly value?: string;
}
/**
* The top-level response that represents a failed request.
*/
export interface ErrorResponse extends Response {
/**
* A list of errors that describe the reasons why the request failed.
*/
errors: ErrorModel[];
}
/**
* Defines a person.
*/
export interface Person extends Thing {
/**
* The person's job title.
*/
readonly jobTitle?: string;
/**
* The URL of the person's twitter profile.
*/
readonly twitterProfile?: string;
}
/**
* Defines an entity action.
*/
export interface ImageEntityAction extends ImageAction {
}
/**
* Defines a list of images.
*/
export interface ImagesModule {
/**
* A list of images.
*/
readonly value?: ImageObject[];
}
/**
* Defines an image list action.
*/
export interface ImageModuleAction extends ImageAction {
/**
* A list of images.
*/
readonly data?: ImagesModule;
}
/**
* Defines a cooking recipe.
*/
export interface Recipe extends CreativeWork {
/**
* The amount of time the food takes to cook. For example, PT25M. For information about the time
* format, see http://en.wikipedia.org/wiki/ISO_8601#Durations.
*/
readonly cookTime?: string;
/**
* The amount of time required to prepare the ingredients. For example, PT15M. For information
* about the time format, see http://en.wikipedia.org/wiki/ISO_8601#Durations.
*/
readonly prepTime?: string;
/**
* The total amount of time it takes to prepare and cook the recipe. For example, PT45M. For
* information about the time format, see http://en.wikipedia.org/wiki/ISO_8601#Durations.
*/
readonly totalTime?: string;
}
/**
* Defines a list of recipes.
*/
export interface RecipesModule {
/**
* A list of recipes.
*/
readonly value?: Recipe[];
}
/**
* Defines an recipe action.
*/
export interface ImageRecipesAction extends ImageAction {
/**
* A list of recipes related to the image.
*/
readonly data?: RecipesModule;
}
/**
* Defines a search query.
*/
export interface Query {
/**
* The query string. Use this string as the query term in a new search request.
*/
text: string;
/**
* The display version of the query term.
*/
readonly displayText?: string;
/**
* The URL that takes the user to the Bing search results page for the query.
*/
readonly webSearchUrl?: string;
/**
* The URL that you use to get the results of the related search. Before using the URL, you must
* append query parameters as appropriate and include the Ocp-Apim-Subscription-Key header. Use
* this URL if you're displaying the results in your own user interface. Otherwise, use the
* webSearchUrl URL.
*/
readonly searchLink?: string;
/**
* The URL to a thumbnail of a related image.
*/
readonly thumbnail?: ImageObject;
}
/**
* Defines a list of related searches.
*/
export interface RelatedSearchesModule {
/**
* A list of related searches.
*/
readonly value?: Query[];
}
/**
* Defines an related search action.
*/
export interface ImageRelatedSearchesAction extends ImageAction {
/**
* A list of queries related to the image.
*/
readonly data?: RelatedSearchesModule;
}
/**
* Defines a shopping sources action.
*/
export interface ImageShoppingSourcesAction extends ImageAction {
/**
* A list of merchants that offer items related to the image.
*/
readonly data?: AggregateOffer;
}
/**
* A JSON object consisting of coordinates specifying the four corners of a cropped rectangle
* within the input image.
*/
export interface CropArea {
/**
* The top coordinate of the region to be cropped. The coordinate is a fractional value of the
* original image's height and is measured from the top edge of the image. Specify the coordinate
* as a value from 0.0 through 1.0.
*/
top: number;
/**
* The bottom coordinate of the region to be cropped. The coordinate is a fractional value of the
* original image's height and is measured from the top edge of the image. Specify the coordinate
* as a value from 0.0 through 1.0.
*/
bottom: number;
/**
* The left coordinate of the region to be cropped. The coordinate is a fractional value of the
* original image's width and is measured from the left edge of the image. Specify the coordinate
* as a value from 0.0 through 1.0.
*/
left: number;
/**
* The right coordinate of the region to be cropped. The coordinate is a fractional value of the
* original image's width and is measured from the left edge of the image. Specify the coordinate
* as a value from 0.0 through 1.0.
*/
right: number;
}
/**
* A JSON object that identities the image to get insights of . It also includes the optional crop
* area that you use to identify the region of interest in the image.
*/
export interface ImageInfo {
/**
* An image insights token. To get the insights token, call one of the Image Search APIs (for
* example, /images/search). In the search results, the
* [Image](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image)
* object's
* [imageInsightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image-imageinsightstoken)
* field contains the token. The imageInsightsToken and url fields mutually exclusive; do not
* specify both. Do not specify an insights token if the request includes the image form data.
*/
imageInsightsToken?: string;
/**
* The URL of the input image. The imageInsightsToken and url fields are mutually exclusive; do
* not specify both. Do not specify the URL if the request includes the image form data.
*/
url?: string;
/**
* A JSON object consisting of coordinates specifying the four corners of a cropped rectangle
* within the input image. Use the crop area to identify the region of interest in the image. You
* can apply the crop area to the images specified using the imageInsightsToken or url fields, or
* an image binary specified in an image form data.
*/
cropArea?: CropArea;
}
/**
* A key-value object consisting of filters that may be specified to limit the results returned by
* the API. Current available filters: site.
*/
export interface Filters {
/**
* The URL of the site to return similar images and similar products from. (e.g., "www.bing.com",
* "bing.com").
*/
site?: string;
}
/**
* A JSON object containing information about the request, such as filters for the resulting
* actions.
*/
export interface KnowledgeRequest {
/**
* A key-value object consisting of filters that may be specified to limit the results returned
* by the API.
*/
filters?: Filters;
}
/**
* A JSON object that contains information about the image to get insights of. Specify this object
* only in a knowledgeRequest form data.
*/
export interface VisualSearchRequest {
/**
* A JSON object that identities the image to get insights of.
*/
imageInfo?: ImageInfo;
/**
* A JSON object containing information about the request, such as filters, or a description.
*/
knowledgeRequest?: KnowledgeRequest;
} | the_stack |
import { getValidDate, getTime } from '../dates';
import { getTypeOf } from '../deps';
import { isSimpleObject } from '../objects';
import { ensureBuffer, isBuffer } from '../buffers';
import { parseJSON } from '../json';
import * as i from './interfaces';
import * as utils from './utils';
import { locked } from '../decorators';
/**
* A wrapper for data that can hold additional metadata properties.
* A DataEntity should be essentially transparent to use within operations.
*
* NOTE: Use `DataEntity.make`, `DataEntity.fromBuffer` and `DataEntity.makeArray`
* in production for potential performance gains
*/
export class DataEntity<
T = Record<string, any>,
M = Record<string, any>
> {
/**
* A utility for safely converting an object a `DataEntity`.
* If the input is a DataEntity it will return it and have no side-effect.
* If you want a create new DataEntity from an existing DataEntity
* either use `new DataEntity` or shallow clone the input before
* passing it to `DataEntity.make`.
*/
static make<T extends DataEntity<any, any>, M = Record<string, any>>(
input: T,
metadata?: M
): T;
static make<T = Record<string, any>, M = Record<string, any>>(
input: Record<string, any>,
metadata?: M
): DataEntity<T, M>;
static make<
T extends Record<string, any>|DataEntity<any, any> = Record<string, any>,
M extends i._DataEntityMetadataType = Record<string, any>
>(input: T, metadata?: M): T|DataEntity<T, M> {
if (DataEntity.isDataEntity(input)) {
if (metadata) {
for (const [key, val] of Object.entries(metadata)) {
input.setMetadata(key, val);
}
}
return input;
}
return new DataEntity(input, metadata);
}
/**
* A utility for safely converting an input of an object,
* or an array of objects, to an array of DataEntities.
* This will detect if passed an already converted input and return it.
*/
static makeArray<T = Record<string, any>, M = Record<string, any>>(
input: DataArrayInput
): DataEntity<T, M>[] {
if (!Array.isArray(input)) {
return [DataEntity.make(input)];
}
if (DataEntity.isDataEntityArray<T, M>(input)) {
return input;
}
return input.map((d) => DataEntity.make(d));
}
/**
* Create a new instance of a DataEntity.
*
* If the second param `withData` is set to `true`
* both the data and metadata will be forked, if set
* to `false` only the metadata will be copied. Defaults
* to `true`
*/
static fork<T extends DataEntity<any, any> = DataEntity>(
input: T,
withData = true
): T {
if (!DataEntity.isDataEntity(input)) {
throw new Error(`Invalid input to fork, expected DataEntity, got ${getTypeOf(input)}`);
}
const { _createTime, ...metadata } = input.getMetadata();
if (withData) {
return DataEntity.make(input, metadata) as T;
}
return DataEntity.make({}, metadata) as T;
}
/**
* A utility for converting a `Buffer` to a `DataEntity`,
* using the DataEntity encoding.
*
* @param input A `Buffer` to parse to JSON
* @param opConfig The operation config used to get the encoding type of the Buffer,
* defaults to "json"
* @param metadata Optionally add any metadata
*/
static fromBuffer<T = Record<string, any>, M = Record<string, any>>(
input: Buffer|string,
opConfig: i.EncodingConfig = {},
metadata?: M
): DataEntity<T, M> {
const { _encoding = i.DataEncoding.JSON } = opConfig || {};
if (_encoding === i.DataEncoding.JSON) {
return DataEntity.make(parseJSON(input), metadata);
}
if (_encoding === i.DataEncoding.RAW) {
const entity = DataEntity.make({}, metadata);
entity.setRawData(input);
return entity;
}
throw new Error(`Unsupported encoding type, got "${_encoding}"`);
}
/**
* Verify that an input is the `DataEntity`
*/
static isDataEntity<T = Record<string, any>, M = Record<string, any>>(
input: unknown
): input is DataEntity<T, M> {
return utils.isDataEntity(input);
}
/**
* Verify that an input is an Array of DataEntities,
*/
static isDataEntityArray<T = Record<string, any>, M = Record<string, any>>(
input: unknown
): input is DataEntity<T, M>[] {
if (input == null) return false;
if (!Array.isArray(input)) return false;
if (input.length === 0) return true;
return utils.isDataEntity(input[0]);
}
/**
* Safely get the metadata from a `DataEntity`.
* If the input is object it will get the property from the object
*
* **DEPRECATED:** Since this isn't recommended to be used, and will
* be removed in future releases.
*
* @deprecated
*/
static getMetadata<V = any>(input: unknown, field?: string): V|undefined {
if (input == null) return undefined;
if (DataEntity.isDataEntity(input)) {
const val = field ? input.getMetadata(field) : input.getMetadata();
return val as V|undefined;
}
return field ? (input as any)[field] : undefined;
}
static [Symbol.hasInstance](instance: unknown): boolean {
// prevent automatically thinking a base DataEntity is
// an instance of a class that extends from a DataEntity
if (this.name !== 'DataEntity' && this.name !== 'Object') {
return false;
}
return utils.isDataEntity(instance);
}
private readonly [i.__ENTITY_METADATA_KEY]: {
metadata: i._DataEntityMetadata<M>;
rawData: Buffer|null;
};
private readonly [i.__IS_DATAENTITY_KEY]: true;
constructor(data: T|null|undefined, metadata?: M) {
if (data && !isSimpleObject(data)) {
throw new Error(`Invalid data source, must be an object, got "${getTypeOf(data)}"`);
}
utils.defineEntityProperties(this);
this[i.__ENTITY_METADATA_KEY].metadata = utils.makeMetadata(metadata);
if (data) {
Object.assign(this, data);
}
}
/**
* Get the metadata for the DataEntity.
* If a field is specified, it will get that property of the metadata
*/
getMetadata(key?: undefined): i._DataEntityMetadata<M>;
getMetadata<K extends i.DataEntityMetadataValue<M>>(key: K): i.EntityMetadataValue<M, K>;
@locked()
getMetadata<K extends i.DataEntityMetadataValue<M>>(key?: K): i.EntityMetadataValue<M, K>|i._DataEntityMetadata<M> {
if (key) {
return this[i.__ENTITY_METADATA_KEY].metadata[key];
}
return this[i.__ENTITY_METADATA_KEY].metadata;
}
/**
* Given a field and value set the metadata on the record
*/
@locked()
setMetadata<K extends i.DataEntityMetadataValue<M>, V extends i.EntityMetadataValue<M, K>>(
field: K,
value: V
): void {
if (field == null || field === '') {
throw new Error('Missing field to set in metadata');
}
if (field === '_createTime') {
throw new Error(`Cannot set readonly metadata property ${field}`);
}
this[i.__ENTITY_METADATA_KEY].metadata[field] = value as any;
}
/**
* Get the unique document `_key` from the metadata.
* If no `_key` is found, an error will be thrown
*/
@locked()
getKey(): string|number {
const key = this[i.__ENTITY_METADATA_KEY].metadata._key;
if (!utils.isValidKey(key)) {
throw new Error('No key has been set in the metadata');
}
return key;
}
/**
* Set the unique document `_key` from the metadata.
* If no `_key` is found, an error will be thrown
*/
@locked()
setKey(key: string|number): void {
if (!utils.isValidKey(key)) {
throw new Error('Invalid key to set in metadata');
}
this[i.__ENTITY_METADATA_KEY].metadata._key = key;
}
/**
* Get the time at which this entity was created.
*/
@locked()
getCreateTime(): Date {
const val = this[i.__ENTITY_METADATA_KEY].metadata._createTime;
const date = getValidDate(val);
if (date === false) {
throw new Error('Missing _createTime');
}
return date;
}
/**
* Get the time at which the data was ingested into the source data
*
* If none is found, `undefined` will be returned.
* If an invalid date is found, `false` will be returned.
*/
@locked()
getIngestTime(): Date|false|undefined {
const val = this[i.__ENTITY_METADATA_KEY].metadata._ingestTime;
if (val == null) return undefined;
return getValidDate(val);
}
/**
* Set the time at which the data was ingested into the source data
*
* If the value is empty it will set the time to now.
* If an invalid date is given, an error will be thrown.
*/
@locked()
setIngestTime(val?: string|number|Date): void {
const unixTime = getTime(val);
if (unixTime === false) {
throw new Error(`Invalid date format, got ${getTypeOf(val)}`);
}
this[i.__ENTITY_METADATA_KEY].metadata._ingestTime = unixTime;
}
/**
* Get the time at which the data was consumed by the reader.
*
* If none is found, `undefined` will be returned.
* If an invalid date is found, `false` will be returned.
*/
@locked()
getProcessTime(): Date|false|undefined {
const val = this[i.__ENTITY_METADATA_KEY].metadata._ingestTime;
if (val == null) return undefined;
return getValidDate(val);
}
/**
* Set the time at which the data was consumed by the reader
*
* If the value is empty it will set the time to now.
* If an invalid date is given, an error will be thrown.
*/
@locked()
setProcessTime(val?: string|number|Date): void {
const unixTime = getTime(val);
if (unixTime === false) {
throw new Error(`Invalid date format, got ${getTypeOf(val)}`);
}
this[i.__ENTITY_METADATA_KEY].metadata._ingestTime = unixTime;
}
/**
* Get time associated from a specific field on source data or message
*
* If none is found, `undefined` will be returned.
* If an invalid date is found, `false` will be returned.
*/
@locked()
getEventTime(): Date|false|undefined {
const val = this[i.__ENTITY_METADATA_KEY].metadata._ingestTime;
if (val == null) return undefined;
return getValidDate(val);
}
/**
* Set time associated from a specific field on source data or message
*
* If the value is empty it will set the time to now.
* If an invalid date is given, an error will be thrown.
*/
@locked()
setEventTime(val?: string|number|Date): void {
const unixTime = getTime(val);
if (unixTime === false) {
throw new Error(`Invalid date format, got ${getTypeOf(val)}`);
}
this[i.__ENTITY_METADATA_KEY].metadata._ingestTime = unixTime;
}
/**
* Get the raw data, usually used for encoding type `raw`.
* If there is no data, an error will be thrown
*/
@locked()
getRawData(): Buffer {
const buf = this[i.__ENTITY_METADATA_KEY].rawData;
if (isBuffer(buf)) return buf;
throw new Error('No data has been set');
}
/**
* Set the raw data, usually used for encoding type `raw`
* If given `null`, it will unset the data
*/
@locked()
setRawData(buf: Buffer|string|null): void {
if (buf === null) {
this[i.__ENTITY_METADATA_KEY].rawData = null;
return;
}
this[i.__ENTITY_METADATA_KEY].rawData = ensureBuffer(buf, 'utf8');
}
/**
* Convert the DataEntity to an encoded buffer
*
* @param opConfig The operation config used to get the encoding type of the buffer,
* @default `json`
*/
@locked()
toBuffer(opConfig: i.EncodingConfig = {}): Buffer {
const { _encoding = i.DataEncoding.JSON } = opConfig;
if (_encoding === i.DataEncoding.JSON) {
return utils.jsonToBuffer(this);
}
if (_encoding === i.DataEncoding.RAW) {
return this.getRawData();
}
throw new Error(`Unsupported encoding type, got "${_encoding}"`);
}
[prop: string]: any;
}
export type DataInput = Record<string, any> | DataEntity;
export type DataArrayInput = DataInput | DataInput[]; | the_stack |
import * as angular from 'angular';
describe('uif-persona', () => {
beforeEach(() => {
angular.mock.module('officeuifabric.core');
angular.mock.module('officeuifabric.components.persona');
});
describe('<uif-persona-text /> directives', () => {
describe('HTML rendering', () => {
let liteElement: angular.IAugmentedJQuery;
let element: JQuery;
let scope: angular.IScope;
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: angular.ICompileService) => {
liteElement = angular.element('<uif-persona-primary-text>Alton Lafferty</uif-persona-primary-text>' +
'<uif-persona-secondary-text>Interior Designer, Contoso</uif-persona-secondary-text>' +
'<uif-persona-tertiary-text>Office: 7/1234</uif-persona-tertiary-text>' +
'<uif-persona-optional-text>Available - Video capable</uif-persona-optional-text>');
scope = $rootScope.$new();
$compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
}));
it('should not replace the markup', () => {
expect(element[0].tagName === 'UIF-PERSONA-PRIMARY-TEXT').toBeTruthy();
expect(element[1].tagName === 'UIF-PERSONA-SECONDARY-TEXT').toBeTruthy();
expect(element[2].tagName === 'UIF-PERSONA-TERTIARY-TEXT').toBeTruthy();
expect(element[3].tagName === 'UIF-PERSONA-OPTIONAL-TEXT').toBeTruthy();
});
it('should render as DIV in directive template', () => {
for (let i: number = 0; i < element.length; i++) {
expect(element.eq(i).children().first()[0].tagName === 'DIV').toBeTruthy();
}
});
it('should have proper CSS applied', () => {
expect(element.eq(0).children('div').first()).toHaveClass('ms-Persona-primaryText');
expect(element.eq(1).children('div').first()).toHaveClass('ms-Persona-secondaryText');
expect(element.eq(2).children('div').first()).toHaveClass('ms-Persona-tertiaryText');
expect(element.eq(3).children('div').first()).toHaveClass('ms-Persona-optionalText');
});
it('should transclude content', () => {
expect(element.eq(0).html()).toContain('Alton Lafferty');
expect(element.eq(1).html()).toContain('Interior Designer, Contoso');
expect(element.eq(2).html()).toContain('Office: 7/1234');
expect(element.eq(3).html()).toContain('Available - Video capable');
});
});
});
describe('<uif-persona-initials /> directive', () => {
describe('HTML rendering', () => {
let liteElement: angular.IAugmentedJQuery;
let element: JQuery;
let scope: angular.IScope;
let _rootScope: angular.IRootScopeService;
let _compile: angular.ICompileService;
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: angular.ICompileService) => {
_rootScope = $rootScope;
_compile = $compile;
liteElement = angular.element('<uif-persona><uif-persona-initials>AL</uif-persona-initials></uif-persona>');
scope = $rootScope.$new();
$compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
}));
it('should not replace the markup', () => {
let initials: JQuery = element.find('uif-persona-initials');
expect(initials.length === 1).toBeTruthy();
});
it('should render as DIV in directive template', () => {
expect(element.eq(0).children().first()[0].tagName === 'DIV').toBeTruthy();
});
it('should have proper CSS applied', () => {
let initials: JQuery = element.find('div.ms-Persona-imageArea').eq(0).find('div').first();
expect(initials).toHaveClass('ms-Persona-initials');
expect(initials).toHaveClass('ms-Persona-initials--blue');
});
it('should transclude content', () => {
expect(element.eq(0).html()).toContain('AL');
});
it('should render proper color for initials', () => {
let expectedClasses: string[] = [
'ms-Persona-initials--lightBlue',
'ms-Persona-initials--blue',
'ms-Persona-initials--darkBlue',
'ms-Persona-initials--teal',
'ms-Persona-initials--lightGreen',
'ms-Persona-initials--green',
'ms-Persona-initials--darkGreen',
'ms-Persona-initials--lightPink',
'ms-Persona-initials--pink',
'ms-Persona-initials--magenta',
'ms-Persona-initials--purple',
'ms-Persona-initials--black',
'ms-Persona-initials--orange',
'ms-Persona-initials--red',
'ms-Persona-initials--darkRed'
];
let initials: angular.IAugmentedJQuery[] = [
angular.element('<uif-persona><uif-persona-initials uif-color="lightBlue">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="blue">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="darkBlue">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="teal">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="lightGreen">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="green">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="darkGreen">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="lightPink">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="pink">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="magenta">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="purple">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="black">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="orange">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="red">AL</uif-persona-initials></uif-persona>'),
angular.element('<uif-persona><uif-persona-initials uif-color="darkRed">AL</uif-persona-initials></uif-persona>')
];
scope = _rootScope.$new();
for (let i: number = 0; i < initials.length; i++) {
_compile(initials[i])(scope);
}
scope.$digest();
let initialsElement: JQuery;
let initialsDiv: JQuery;
for (let i: number = 0; i < initials.length; i++) {
initialsElement = jQuery(initials[i]);
initialsDiv = initialsElement.find('.ms-Persona-initials').first();
expect(initialsDiv).toHaveClass(expectedClasses[i]);
}
});
it('should have blue color if uifColor not specified', () => {
expect(element.find('div.ms-Persona-initials').first()).toHaveClass('ms-Persona-initials--blue');
});
it('should validate initials color', inject(($log: angular.ILogService) => {
liteElement = angular.element('<uif-persona><uif-persona-initials uif-color="invalid">AL</uif-persona-initials></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
let expectedError: string = 'Error [ngOfficeUiFabric] officeuifabric.components.persona - "invalid"' +
' is not a valid value for uifColor.' +
' It should be lightBlue, blue, darkBlue, teal, lightGreen, green,' +
' darkGreen, lightPink, pink, magenta, purple, black, orange, red or darkRed.';
expect($log.error.logs.length === 1).toBeTruthy();
expect($log.error.logs[0]).toContain(expectedError);
}));
});
});
describe('<uif-persona /> directive', () => {
let liteElement: angular.IAugmentedJQuery;
let element: JQuery;
let scope: angular.IScope;
let _rootScope: angular.IRootScopeService;
let _compile: angular.ICompileService;
describe('HTML rendering', () => {
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: angular.ICompileService) => {
_rootScope = $rootScope;
_compile = $compile;
liteElement = angular.element('<uif-persona uif-style="round" uif-size="xlarge"></uif-persona>');
scope = _rootScope.$new();
_compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
}));
it('renders as DIV with proper CSS', () => {
// let personaDiv: JQuery = element.children('div');
expect(element[0].tagName === 'DIV').toBeTruthy();
expect(element).toHaveClass('ms-Persona');
});
it('should have CSS for size', () => {
let personas: angular.IAugmentedJQuery[] = [
angular.element('<uif-persona uif-size="tiny"></uif-persona>'),
angular.element('<uif-persona uif-size="xsmall"></uif-persona>'),
angular.element('<uif-persona uif-size="small"></uif-persona>'),
angular.element('<uif-persona uif-size="large"></uif-persona>'),
angular.element('<uif-persona uif-size="xlarge"></uif-persona>')
];
let expectedClass: string[] = ['ms-Persona--tiny', 'ms-Persona--xs', 'ms-Persona--sm', 'ms-Persona--lg', 'ms-Persona--xl'];
for (let i: number = 0; i < personas.length; i++) {
_compile(personas[i])(scope);
}
scope.$digest();
let persona: JQuery;
// let innerDiv: JQuery;
for (let i: number = 0; i < personas.length; i++) {
persona = jQuery(personas[i]);
// innerDiv = persona.find('div.ms-Persona');
expect(persona).toHaveClass(expectedClass[i]);
}
});
it('should have no CSS for medium size', () => {
liteElement = angular.element('<uif-persona uif-size="medium"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
// let innerDiv: JQuery = element.find('div.ms-Persona');
let notExpectedClasses: string[] = ['ms-Persona--tiny', 'ms-Persona--xs', 'ms-Persona--sm', 'ms-Persona--lg', 'ms-Persona--xl'];
angular.forEach(notExpectedClasses, (className: string) => {
expect(element).not.toHaveClass(className);
});
});
it('should log error when invalid size is used', inject(($log: angular.ILogService) => {
liteElement = angular.element('<uif-persona uif-size="invalid"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
expect($log.error.logs.length === 1).toBeTruthy();
let expectedMessage: string = 'Error [ngOfficeUiFabric] officeuifabric.components.persona - "invalid"' +
' is not a valid value for uifSize. It should be tiny, xsmall, small, medium, large, xlarge.';
expect($log.error.logs[0]).toContain(expectedMessage);
}));
it('should have proper CSS when uif-style is round', () => {
expect(element).not.toHaveClass('ms-Persona--square');
});
it('should have proper CSS when uif-style is square', () => {
liteElement = angular.element('<uif-persona uif-style="square"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
expect(element).toHaveClass('ms-Persona--square');
});
it('should log error when uif-style is incorrect', inject(($log: angular.ILogService) => {
liteElement = angular.element('<uif-persona uif-style="invalid"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
expect($log.error.logs.length === 1).toBeTruthy();
let expectedMessage: string = 'Error [ngOfficeUiFabric] officeuifabric.components.persona - "invalid"' +
' is not a valid value for uifStyle. It should be round or square.';
expect($log.error.logs[0]).toContain(expectedMessage);
}));
it('should have image area with proper CSS', () => {
let imageArea: JQuery = element.children().first();
expect(imageArea.length === 1).toBeTruthy();
expect(imageArea[0].tagName === 'DIV');
expect(imageArea).toHaveClass('ms-Persona-imageArea');
});
it('should have IMG with proper source and CSS', () => {
liteElement = angular.element('<uif-persona uif-image-url="' +
'http://dev.office.com/Modules/DevOffice.Fabric/Fabric/components/persona/Persona.Person2.png"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
let imageArea: JQuery = element.find('div.ms-Persona-imageArea');
let image: JQuery = imageArea.find('img');
expect(image.length === 1).toBeTruthy();
expect(image).toHaveClass('ms-Persona-image');
expect(image).toHaveAttr('src', 'http://dev.office.com/Modules/DevOffice.Fabric/Fabric/components/' +
'persona/Persona.Person2.png');
});
it('should not render IMG tag when picture URL not set', () => {
let image: JQuery = element.find('img');
expect(image.length === 0).toBeTruthy();
});
it('should not render image area when size is tiny', () => {
liteElement = angular.element('<uif-persona uif-size="tiny"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
element = jQuery(liteElement);
let imageArea: JQuery = element.find('div.ms-Persona-imageArea');
expect(imageArea).toHaveClass('ng-hide');
});
it('should have presence DIV with proper CSS', () => {
let presence: JQuery = element.find('div.ms-Persona-presence');
expect(presence.length === 1).toBeTruthy();
let parent: JQuery = presence.parent();
expect(parent).toHaveClass('ms-Persona');
});
it('should have proper CSS class for presence', () => {
let personas: angular.IAugmentedJQuery[] = [
angular.element('<uif-persona uif-presence="available"></uif-persona>'),
angular.element('<uif-persona uif-presence="away"></uif-persona>'),
angular.element('<uif-persona uif-presence="blocked"></uif-persona>'),
angular.element('<uif-persona uif-presence="busy"></uif-persona>'),
angular.element('<uif-persona uif-presence="dnd"></uif-persona>'),
angular.element('<uif-persona uif-presence="offline"></uif-persona>')
];
for (let i: number = 0; i < personas.length; i++) {
_compile(personas[i])(scope);
}
scope.$digest();
let expectedClasses: string[] = [
'ms-Persona--available',
'ms-Persona--away',
'ms-Persona--blocked',
'ms-Persona--busy',
'ms-Persona--dnd',
'ms-Persona--offline'
];
let personaDiv: JQuery;
for (let i: number = 0; i < personas.length; i++) {
personaDiv = jQuery(personas[i]);
// let personaDiv: JQuery = persona.find('div.ms-Persona');
expect(personaDiv.length === 1).toBeTruthy();
expect(personaDiv).toHaveClass(expectedClasses[i]);
}
});
it('should have presence "offline" if uif-presence not set', () => {
// let personaDiv: JQuery = element.find('div.ms-Persona');
// expect(personaDiv.length === 1).toBeTruthy();
expect(element).toHaveClass('ms-Persona--offline');
});
it('should validate presence attribute', inject(($log: angular.ILogService) => {
liteElement = angular.element('<uif-persona uif-presence="invalid"></uif-persona>');
_compile(liteElement)(scope);
scope.$digest();
expect($log.error.logs.length === 1).toBeTruthy();
let expectedMessage: string = 'Error [ngOfficeUiFabric] officeuifabric.components.persona - "invalid"' +
' is not a valid value for uifPresence. It should be available, away, blocked, busy, dnd or offline.';
expect($log.error.logs[0]).toContain(expectedMessage);
}));
it('should have details DIV with proper CSS', () => {
let personaDetails: JQuery = element.find('div.ms-Persona-details');
expect(personaDetails.length === 1).toBeTruthy();
expect(personaDetails.parent()).toHaveClass('ms-Persona');
});
it('should transclude uif-persona-primary-text inside details DIV', () => {
liteElement = angular.element('<uif-persona uif-presence="available">' +
'<uif-persona-primary-text>Alton Lafferty</uif-persona-primary-text>' +
'<uif-persona-secondary-text>Interior Designer, Contoso</uif-persona-secondary-text>' +
'<uif-persona-tertiary-text>Office: 7/1234</uif-persona-tertiary-text>' +
'<uif-persona-optional-text>Available - Video capable</uif-persona-optional-text>' +
'</uif-persona>');
_compile(liteElement)(scope);
element = jQuery(liteElement[0]);
scope.$digest();
let detailsDiv: JQuery = element.find('div.ms-Persona-details');
expect(detailsDiv.children().length === 4).toBeTruthy();
let textDivs: JQuery = detailsDiv.find('div');
expect(textDivs.eq(0)).toHaveClass('ms-Persona-primaryText');
expect(textDivs.eq(1)).toHaveClass('ms-Persona-secondaryText');
expect(textDivs.eq(2)).toHaveClass('ms-Persona-tertiaryText');
expect(textDivs.eq(3)).toHaveClass('ms-Persona-optionalText');
});
it('should transclude uif-persona-initials into image area', () => {
liteElement = angular.element('<uif-persona uif-presence="available">' +
'<uif-persona-initials>AL</uif-persona-initials>' +
'</uif-persona>');
_compile(liteElement)(scope);
element = jQuery(liteElement[0]);
scope.$digest();
let imageArea: JQuery = element.find('div.ms-Persona-imageArea');
let initials: JQuery = imageArea.find('div.ms-Persona-initials');
expect(initials.length === 1).toBeTruthy();
});
});
});
}); | the_stack |
// --------------------------------------------------------------------------
// Shared Type Definitions and Interfaces
// --------------------------------------------------------------------------
/**
* BaseType serves as an alias for the 'minimal' data type which can be selected
* without 'd3-selection' trying to use properties internally which would otherwise not
* be supported.
*/
export type BaseType = Element | EnterElement | Window;
// export type BaseType = any; // Alternative, very permissive BaseType specification for edge cases
export interface ArrayLike<T> {
length: number;
item(index: number): T;
[index: number]: T;
}
export interface EnterElement {
ownerDocument: Document;
namespaceURI: string;
appendChild(newChild: Node): Node;
insertBefore(newChild: Node, refChild: Node): Node;
querySelector(selectors: string): Element;
querySelectorAll(selectors: string): NodeListOf<Element>;
}
/**
* Container element type usable for mouse/touch functions
*/
export type ContainerElement = HTMLElement | SVGSVGElement | SVGGElement;
/**
* Type for optional parameters map, when dispatching custom events
* on a selection
*/
export type CustomEventParameters = {
/**
* If true, the event is dispatched to ancestors in reverse tree order
*/
bubbles: boolean;
/**
* If true, event.preventDefault is allowed
*/
cancelable: boolean;
/**
* Any custom data associated with the event
*/
detail: any;
}
/**
* Callback type for selections and transitions
*/
export type ValueFn<Element, Datum, Result> = (this: Element, datum: Datum, index: number, groups: Array<Element> | ArrayLike<Element>) => Result;
/**
* TransitionLike is a helper interface to represent a quasi-Transition, without specifying the full Transition interface in this file.
* For example, whereever d3-zoom allows a Transition to be passed in as an argument, it internally immediately invokes its `selection()`
* method to retrieve the underlying Selection object before proceeding.
* d3-brush uses a subset of Transition methods internally.
* The use of this interface instead of the full imported Transition interface is [referred] to achieve
* two things:
* (1) the d3-transition module may not be required by a projects use case,
* (2) it avoid avoids possible complications from 'module augmentation' from d3-transition to Selection.
*/
export interface TransitionLike<GElement extends BaseType, Datum> {
selection(): Selection<GElement, Datum, any, any>;
on(type: string, listener: null): TransitionLike<GElement, Datum>;
on(type: string, listener: ValueFn<GElement, Datum, void>): TransitionLike<GElement, Datum>;
tween(name: string, tweenFn: null): TransitionLike<GElement, Datum>;
tween(name: string, tweenFn: ValueFn<GElement, Datum, ((t: number) => void)>): TransitionLike<GElement, Datum>;
}
// --------------------------------------------------------------------------
// All Selection related interfaces and function
// --------------------------------------------------------------------------
// NB: Note that, d3.select does not generate the same parent element, when targeting the same DOM element with string selector
// or node element
export function select<GElement extends BaseType, OldDatum>(selector: string): Selection<GElement, OldDatum, HTMLElement, any>;
export function select<GElement extends BaseType, OldDatum>(node: GElement): Selection<GElement, OldDatum, null, undefined>;
export function selectAll(): Selection<null, undefined, null, undefined>; // _groups are set to empty array, first generic type is set to null by convention
export function selectAll(selector: null): Selection<null, undefined, null, undefined>; // _groups are set to empty array, first generic type is set to null by convention
export function selectAll<GElement extends BaseType, OldDatum>(selector: string): Selection<GElement, OldDatum, HTMLElement, any>;
export function selectAll<GElement extends BaseType, OldDatum>(nodes: GElement[]): Selection<GElement, OldDatum, null, undefined>;
export function selectAll<GElement extends BaseType, OldDatum>(nodes: ArrayLike<GElement>): Selection<GElement, OldDatum, null, undefined>;
interface Selection<GElement extends BaseType, Datum, PElement extends BaseType, PDatum> {
// Sub-selection -------------------------
select<DescElement extends BaseType>(selector: string): Selection<DescElement, Datum, PElement, PDatum>;
select<DescElement extends BaseType>(selector: null): Selection<null, undefined, PElement, PDatum>; // _groups are set to empty array, first generic type is set to null by convention
select<DescElement extends BaseType>(selector: ValueFn<GElement, Datum, DescElement>): Selection<DescElement, Datum, PElement, PDatum>;
selectAll(): Selection<null, undefined, GElement, Datum>; // _groups are set to empty array, first generic type is set to null by convention
selectAll(selector: null): Selection<null, undefined, GElement, Datum>; // _groups are set to empty array, first generic type is set to null by convention
selectAll<DescElement extends BaseType, OldDatum>(selector: string): Selection<DescElement, OldDatum, GElement, Datum>;
selectAll<DescElement extends BaseType, OldDatum>(selector: ValueFn<GElement, Datum, Array<DescElement> | ArrayLike<DescElement>>): Selection<DescElement, OldDatum, GElement, Datum>;
// Modifying -------------------------------
attr(name: string): string;
attr(name: string, value: null): this;
attr(name: string, value: string | number | boolean): this;
attr(name: string, value: ValueFn<GElement, Datum, string | number | boolean>): this;
classed(name: string): boolean;
classed(name: string, value: boolean): this;
classed(name: string, value: ValueFn<GElement, Datum, boolean>): this;
style(name: string): string;
style(name: string, value: null): this;
style(name: string, value: string | number | boolean, priority?: null | 'important'): this;
style(name: string, value: ValueFn<GElement, Datum, string | number | boolean>, priority?: null | 'important'): this;
property(name: string): any;
/**
* Look up a local variable on the first node of this selection. Note that this is not equivalent to `local.get(selection.node())` in that it will not look up locals set on the parent node(s).
*
* @param name The `d3.local` variable to look up.
*/
property<T>(name: Local<T>): T | undefined;
property(name: string, value: ValueFn<GElement, Datum, any>): this;
property(name: string, value: null): this;
property(name: string, value: any): this;
/**
* Store a value in a `d3.local` variable. This is equivalent to `selection.each(function (d, i, g) { name.set(this, value.call(this, d, i, g)); })` but more concise.
*
* @param name A `d3.local` variable
* @param value A callback that returns the value to store
*/
property<T>(name: Local<T>, value: ValueFn<GElement, Datum, T>): this;
/**
* Store a value in a `d3.local` variable for each node in the selection. This is equivalent to `selection.each(function () { name.set(this, value); })` but more concise.
*
* @param name A `d3.local` variable
* @param value A callback that returns the value to store
*/
property<T>(name: Local<T>, value: T): this;
text(): string;
text(value: string | number | boolean): this;
text(value: ValueFn<GElement, Datum, string | number | boolean>): this;
html(): string;
html(value: string): this;
html(value: ValueFn<GElement, Datum, string>): this;
append<ChildElement extends BaseType>(type: string): Selection<ChildElement, Datum, PElement, PDatum>;
append<ChildElement extends BaseType>(type: ValueFn<GElement, Datum, ChildElement>): Selection<ChildElement, Datum, PElement, PDatum>;
insert<ChildElement extends BaseType>(type: string, before: string): Selection<ChildElement, Datum, PElement, PDatum>;
insert<ChildElement extends BaseType>(type: ValueFn<GElement, Datum, ChildElement>, before: string): Selection<ChildElement, Datum, PElement, PDatum>;
insert<ChildElement extends BaseType>(type: string, before: ValueFn<GElement, Datum, BaseType>): Selection<ChildElement, Datum, PElement, PDatum>;
insert<ChildElement extends BaseType>(type: ValueFn<GElement, Datum, ChildElement>, before: ValueFn<GElement, Datum, BaseType>): Selection<ChildElement, Datum, PElement, PDatum>;
/**
* Removes the selected elements from the document.
* Returns this selection (the removed elements) which are now detached from the DOM.
*/
remove(): this;
merge(other: Selection<GElement, Datum, PElement, PDatum>): Selection<GElement, Datum, PElement, PDatum>;
filter(selector: string): this;
filter(selector: ValueFn<GElement, Datum, boolean>): this;
sort(comparator?: (a: Datum, b: Datum) => number): this;
order(): this;
raise(): this;
lower(): this;
// Data Join ---------------------------------
datum(): Datum;
datum(value: null): Selection<GElement, undefined, PElement, PDatum>;
datum<NewDatum>(value: ValueFn<GElement, Datum, NewDatum>): Selection<GElement, NewDatum, PElement, PDatum>;
datum<NewDatum>(value: NewDatum): Selection<GElement, NewDatum, PElement, PDatum>;
data(): Datum[];
data<NewDatum>(data: Array<NewDatum>, key?: ValueFn<GElement | PElement, Datum | NewDatum, string>): Selection<GElement, NewDatum, PElement, PDatum>;
data<NewDatum>(data: ValueFn<PElement, PDatum, Array<NewDatum>>, key?: ValueFn<GElement | PElement, Datum | NewDatum, string>): Selection<GElement, NewDatum, PElement, PDatum>;
enter(): Selection<EnterElement, Datum, PElement, PDatum>;
// The type Datum on the exit items is actually of the type prior to calling data(...), as by definition, no new data of type NewDatum exists for these
// elements. Due to the chaining, .data(...).exit(...), however, the definition would imply that the exit group elements have assumed the NewDatum type.
// This seems to imply the following workaroud: Recast the exit Selection to OldDatum, if needed, or ommit and allow exit group elements to be of type any.
exit<OldDatum>(): Selection<GElement, OldDatum, PElement, PDatum>;
// Event Handling -------------------
on(type: string): ValueFn<GElement, Datum, void>;
on(type: string, listener: null): this;
on(type: string, listener: ValueFn<GElement, Datum, void>, capture?: boolean): this;
dispatch(type: string, parameters?: CustomEventParameters): this;
dispatch(type: string, parameters?: ValueFn<GElement, Datum, CustomEventParameters>): this;
// Control Flow ----------------------
each(valueFn: ValueFn<GElement, Datum, void>): this;
call(func: (selection: Selection<GElement, Datum, PElement, PDatum>, ...args: any[]) => void, ...args: any[]): this;
empty(): boolean;
node(): GElement;
nodes(): Array<GElement>;
size(): number;
}
interface SelectionFn extends Function {
(): Selection<HTMLElement, any, null, undefined>;
}
export var selection: SelectionFn;
// ---------------------------------------------------------------------------
// on.js event and customEvent related
// ---------------------------------------------------------------------------
// See issue #3 (https://github.com/tomwanzek/d3-v4-definitelytyped/issues/3)
interface BaseEvent {
type: string;
sourceEvent?: any; // Could be of all sorts of types, too general: BaseEvent | Event | MouseEvent | TouchEvent | ... | OwnCustomEventType;
}
export var event: any; // Could be of all sorts of types, too general: BaseEvent | Event | MouseEvent | TouchEvent | ... | OwnCustomEventType;
export function customEvent<Context, Result>(event: BaseEvent, listener: (this: Context, ...args: any[]) => Result, that: Context, ...args: any[]): Result;
// ---------------------------------------------------------------------------
// mouse.js related
// ---------------------------------------------------------------------------
/**
* Get (x, y)-coordinates of the current event relative to the specified container element.
* The coordinates are returned as a two-element array of numbers [x, y].
* @param container
*/
export function mouse(container: ContainerElement): [number, number];
// ---------------------------------------------------------------------------
// touch.js and touches.js related
// ---------------------------------------------------------------------------
export function touch(container: ContainerElement, identifier: number): [number, number];
export function touch(container: ContainerElement, touches: TouchList, identifier: number): [number, number];
export function touches(container: ContainerElement, touches?: TouchList): Array<[number, number]>;
// ---------------------------------------------------------------------------
// local.js related
// ---------------------------------------------------------------------------
export interface Local<T> {
/**
* Retrieves a local variable stored on the node (or one of its parents).
*/
get(node: Element): T | undefined;
/**
* Deletes the value associated with the given node. Values stored on ancestors are not affected, meaning that child nodes will still see inherited values.
*
* This function returns true if there was a value stored directly on the node, and false otherwise.
*/
remove(node: Element): boolean;
/**
* Store a value for this local variable. Calling `.get()` on children of this node will also retrieve the variable's value.
*/
set(node: Element, value: T): Element;
/**
* Obtain a string with the internally assigned property name for the local
* which is used to store the value on a node
*/
toString(): string;
}
/**
* Obtain a new local variable
*/
export function local<T>(): Local<T>;
// ---------------------------------------------------------------------------
// namespace.js related
// ---------------------------------------------------------------------------
/**
* Type for object literal containing local name with related fully qualified namespace
*/
export type NamespaceLocalObject = {
/**
* Fully qualified namespace
*/
space: string,
/**
* Name of the local to be namespaced.
*/
local: string
}
/**
* Obtain an object with properties of fully qualified namespace string and
* name of local by parsing a shorthand string "prefix:local". If the prefix
* does not exist in the "namespaces" object provided by d3-selection, then
* the local name is returned as a simple string.
*
* @param prefixedLocal A string composed of the namespace prefix and local
* name separated by colon, e.g. "svg:text".
*/
export function namespace(prefixedLocal: string): NamespaceLocalObject | string;
// ---------------------------------------------------------------------------
// namespaces.js related
// ---------------------------------------------------------------------------
/**
* Type for maps of namespace prefixes to corresponding fully qualified namespace strings
*/
export type NamespaceMap = { [prefix: string]: string };
/**
* Map of namespace prefixes to corresponding fully qualified namespace strings
*/
export var namespaces: NamespaceMap;
// ---------------------------------------------------------------------------
// window.js related
// ---------------------------------------------------------------------------
export function window(DOMNode: Window | Document | Element): Window;
// ---------------------------------------------------------------------------
// creator.js and matcher.js Complex helper closure generating functions
// for explicit bound-context dependent use
// ---------------------------------------------------------------------------
/**
* Returns a closure structure which can be invoked in the 'this' context
* of a group element. Depending on the use of namespacing, the NewGElement can be HTMLElement,
* SVGElement an extension thereof or an element from a different namespace.
*
* @param elementName Name of the element to be added
*/
export function creator<NewGElement extends Element>(elementName: string): (this: BaseType) => NewGElement;
/**
* Returns a closure structure which can be invoked in the 'this' context
* of a group element. Returns true, if the element in the 'this' context matches the selector
*
* @param selector A valid selector string
*/
export function matcher<GElement extends Element>(selector: string): (this: BaseType) => boolean;
// ----------------------------------------------------------------------------
// selector.js and selectorAll.js related functions
// ----------------------------------------------------------------------------
export function selector<DescElement extends Element>(selector: string): (this: BaseType) => DescElement
export function selectorAll<DescElement extends Element>(selector: string): (this: BaseType) => NodeListOf<DescElement>; | the_stack |
import { Gex } from 'gex'
/* $lab:coverage:on$ */
// NOTE: naming convention:
// key : pattern element key name string
// fix : pattern element match value
// val : potential match value
export interface Matcher {
make(key: string, fix: any): MatchValue | undefined
scan(mvs: MatchValue[], opts?: any): ScanResult
}
export interface ScanResult {
complete: boolean,
sound: boolean,
gaps: any[],
overs: any[],
why?: string
}
export interface MatchValue {
match(val: any): boolean
same(mv: MatchValue | undefined): boolean
kind: string
fix: any
meta: any
keymap?: any
}
export class GexMatcher implements Matcher {
constructor() {
}
make(key: string, fix: any) {
if ('string' === typeof fix && fix.match(/[*?]/)) {
let gex = Gex(fix)
return {
kind: 'gex',
match: (val: any) => null != gex.on(val),
fix: fix,
meta: {},
same(mv: MatchValue) {
return null != mv && mv.kind === this.kind && mv.fix === this.fix
}
}
}
else return undefined
}
// TODO: pretty primitive, just looks for '*'
scan(mvs: MatchValue[], opts?: any): ScanResult {
let has_match_any = mvs.filter(mv => '*' === mv.fix).length > 0
return {
complete: has_match_any,
sound: has_match_any,
gaps: [],
overs: [],
why: 'no-star'
}
}
}
// TODO: space joins with &
// TODO: recongnize 'and' 'or'
// TODO: integers: <1, >1&<2, >2 is complete
// TODO: any: * is -Inf>=&&<=+Inf \ intervals - ie. gaps
// TODO: non-Number types: special case
// NOTE: '/' == '\\'
const IntervalRE = new RegExp([
'^/s*', // optional whitespace
'(=*[<>/(/[]?=*)?' + // 1, lenient operator symbol
'/s*' + // optional whitespace
'([-+0-9a-fA-FeEoOxX]+(/.([0-9a-fA-FeEoOxX]+))?)' + // 2,3,4 number
'([/)/]]?)' + // 5, optional interval operator symbol
'(' + // 6, start optional second term
'/s*(,|&+|/|+|/./.)' + // 7, join
'/s*' + // optional whitespace
'(=*[<>]?=*)' + // 8, lenient operator symbol
'/s*' + // optional whitespace
'([-+.0-9a-fA-FeEoOxX]+)' + // 9, number
'/s*' + // optional whitespace
'([/)/]]?)' + // 10, interval operator symbol
')?' + // end optional second term
'/s*$', // optional whitespace
].join('').replace(/\//g, '\\'))
export class IntervalMatcher implements Matcher {
kind = 'interval'
constructor() {
}
// == sames as =, <= same as =<
static normop = (op: string) => null == op ? null :
(((op.match(/([<>\(\)\[\]])/) || [])[1] || '') + ((op.match(/(=)/) || [])[1] || ''))
#and = (lhs: any, rhs?: any) => function and(x: number) {
return lhs(x) && rhs(x)
}
#or = (lhs: any, rhs?: any) => function or(x: number) {
return lhs(x) || rhs(x)
}
#nil = (n: any) => function nil(x: any) { return false }
#err = (n: any) => function err(x: any) { return false }
#mgt = (n: any) => function gt(x: any) { return x > n }
#mgte = (n: any) => function gte(x: any) { return x >= n }
#mlt = (n: any) => function lt(x: any) { return x < n }
#mlte = (n: any) => function lte(x: any) { return x <= n }
#meq = (n: any) => function eq(x: any) { return x === n }
make(key: string, fix: any) {
if ('string' === typeof fix &&
// At least one interval operator is required.
// Exact numbers must be specified as '=X'
fix.match(/[=<>.[()\]]/)) {
let m = fix.match(IntervalRE)
let meta = { jo: 'and', o0: 'err', n0: NaN, o1: 'err', n1: NaN }
let match = (val: any) => false
if (null != m) {
let os0 = IntervalMatcher.normop(m[1]) || IntervalMatcher.normop(m[5])
let os1 = IntervalMatcher.normop(m[8]) || IntervalMatcher.normop(m[10])
let o0 =
'=' === os0 ? this.#meq :
'<' === os0 ? this.#mlt :
')' === os0 ? this.#mlt :
'<=' === os0 ? this.#mlte :
']' === os0 ? this.#mlte :
'>' === os0 ? this.#mgt :
'(' === os0 ? this.#mgt :
'>=' === os0 ? this.#mgte :
'[' === os0 ? this.#mgte :
this.#err
let n0 = Number(m[2])
let n1 = null == m[9] ? NaN : Number(m[9])
let jos = m[7]
let jo = null == jos ? this.#or :
'&' === jos.substring(0, 1) ? this.#and :
',' === jos.substring(0, 1) ? this.#and :
this.#or
if ('..' === jos) {
jo = this.#and
o0 = this.#err === o0 ? this.#mgte : o0
os1 = '' === os1 ? '<=' : os1
}
let o1 =
null == os1 ? this.#nil :
'=' === os1 ? this.#meq :
'<' === os1 ? this.#mlt :
')' === os1 ? this.#mlt :
'<=' === os1 ? this.#mlte :
']' === os1 ? this.#mlte :
'>' === os1 ? this.#mgt :
'>=' === os1 ? this.#mgte :
this.#err
// merge ops if same number
if (n0 === n1) {
if ('=' === os0 && null != os1) {
n1 = NaN
o1 = this.#nil
if (os1.includes('<')) {
o0 = this.#mlte
}
else if (os1.includes('>')) {
o0 = this.#mgte
}
else if (os1.includes('=')) {
o0 = this.#meq
}
else {
o0 = this.#err
}
}
else if ('=' === os1 && null != os0) {
n1 = NaN
o1 = this.#nil
if (os0.includes('<')) {
o0 = this.#mlte
}
else if (os0.includes('>')) {
o0 = this.#mgte
}
else {
o0 = this.#err
}
}
}
// console.log(jo(o0(n0), o1(n1)), o0(n0), o1(n1))
// if one sided interval, add the other side out to infinity
if (this.#err !== o0) {
if (this.#nil === o1) {
if (this.#mlt === o0 || this.#mlte === o0) {
o1 = o0
n1 = n0
o0 = this.#mgte
n0 = Number.NEGATIVE_INFINITY
jo = this.#and
}
else if (this.#mgt === o0 || this.#mgte === o0) {
o1 = this.#mlte
n1 = Number.POSITIVE_INFINITY
jo = this.#and
}
// else this.meq ok as is
}
}
// lower bound is always first so that interval sorting will work
if (!isNaN(n1) && n1 < n0) {
let to = o1
let tn = n1
n1 = n0
n0 = tn
// sensible heuristic: 20..10 means >=10&<=20
if ('..' !== jos) {
o1 = o0
o0 = to
}
}
let o0f = o0(n0)
let o1f = o1(n1)
let check = jo(o0f, o1f)
meta = { jo: check.name, o0: o0f.name, n0, o1: o1f.name, n1 }
match = (val: any) => {
let res = false
let n = parseFloat(val)
if (!isNaN(n)) {
res = check(n)
}
return res
}
return {
kind: 'interval',
fix,
meta,
match,
same(mv: MatchValue) {
return null != mv &&
mv.kind === this.kind &&
mv.meta.jo === this.meta.jo &&
mv.meta.o0 === this.meta.o0 &&
mv.meta.n0 === this.meta.n0 &&
mv.meta.o1 === this.meta.o1 &&
mv.meta.n1 === this.meta.n1
}
}
}
}
}
scan(mvs: MatchValue[], opts?: any): ScanResult {
let scanres = {
complete: false,
sound: false,
gaps: [] as any[],
overs: [] as any[],
lower: null,
upper: null,
}
let bottom = Number.NEGATIVE_INFINITY
let top = Number.POSITIVE_INFINITY
let half_intervals: any[] = this.half_intervals(mvs)
// console.log('H', half_intervals)
half_intervals
.reduce((c, h) => {
// c: accumulated state
// h: current half interval
// console.log('\n\nRED')
// console.dir(c, { depth: null })
// console.dir(h, { depth: null })
let heq = 'eq' === h.o
let hlt = 'lt' === h.o
let hlte = 'lte' === h.o
let hgt = 'gt' === h.o
let hgte = 'gte' === h.o
let hn = h.n
// NOTE: { == (or[or none
if (null == c.lower) {
let b = { n: bottom, o: 'gte' }
c.lower = b
c.upper = h
if (!(bottom == hn && hgte)) {
if (hgt || hgte) {
// {-oo,hn}
c.gaps.push([b, { n: hn, o: hgt ? 'lte' : 'lt', m: 0 }])
}
else if (heq) {
// {-oo,hn)
c.gaps.push([b, { n: hn, o: 'lte', m: 1 }])
}
}
}
else {
let ueq = 'eq' === c.upper.o
let ult = 'lt' === c.upper.o
let ulte = 'lte' === c.upper.o
let ugt = 'gt' === c.upper.o
let ugte = 'hgte' === c.upper.o
let un = c.upper.n
let u = c.upper
if (hn === un) {
// un)[hn} OR {un](hn
if ((ult && (hgte || heq)) ||
((ulte || ueq) && hgt)) {
//c.upper = h
}
else if (ueq || ult || ulte) {
// {un,hn}
c.gaps.push([
{ n: un, o: (ueq || ulte) ? 'gt' : 'gte', m: 2, d: { u, h } },
{ n: hn, o: (heq || hgte) ? 'lt' : 'lte', m: 3 }
])
}
else {
// TODO overlaps
// console.log('OL-a', c, h)
}
}
else if (un < hn) {
if (hlt || hlte) {
// console.log('OL-b', c, h)
/*
// overlap matches boundaries of c.upper.n..h.n
c.overs.push([
{ n: un, o: c.upper.o, m: 8 },
{ n: hn, o: h.o, m: 9 }
])
*/
//c.upper = h
}
else if (ueq || ult || ulte) {
// {un,hn}
c.gaps.push([
{ n: un, o: (ueq || ulte) ? 'gt' : 'gte', m: 4 },
{ n: hn, o: (heq || hgte) ? 'lt' : 'lte', m: 5 }
])
}
}
// hn < un
else {
// console.log('hn < un', hn, un)
c.overs.push([
{ n: hn, o: (heq || hgte) ? 'gte' : 'gt', m: 10 },
{ n: un, o: (ueq || ulte) ? 'lte' : 'lt', m: 11 },
])
}
c.upper = h
}
return c
}, scanres)
let last = 0 < half_intervals.length && half_intervals[half_intervals.length - 1]
// {n,+oo]
if (last && top !== last.n && last.o !== 'gt' && last.o !== 'gte') {
scanres.gaps.push([
{ n: last.n, o: (last.o === 'eq' || last.o === 'lte') ? 'gt' : 'gte', m: 6 },
{ n: top, o: 'lte', m: 7 }
])
}
scanres.complete = 0 === scanres.gaps.length
scanres.sound = 0 === scanres.overs.length
return scanres
}
// NOTE: assumes n0<=n1
half_intervals(mvs: MatchValue[]) {
let half_intervals: any[] = []
for (let mv of mvs) {
half_intervals.push(
[{ n: mv.meta.n0, o: mv.meta.o0 },
{ n: mv.meta.n1, o: mv.meta.o1 }]
)
}
// canonical ordering of operations
var os = ['lt', 'lte', 'eq', 'gte', 'gt']
var hi = half_intervals
.map(hh => [
(isNaN(hh[0].n) || null == hh[0].n) ? null : hh[0],
(isNaN(hh[1].n) || null == hh[1].n) ? null : hh[1]]
.filter(h => null != h))
// sorting on intervals, *not* half intervals
.sort((a, b) => {
// sort by first term numerically
if (a[0].n < b[0].n) {
return -1
}
else if (b[0].n < a[0].n) {
return 1
}
else {
// sort by first term operationally
var a0i = os.indexOf(a[0].o)
var b0i = os.indexOf(b[0].o)
if (a0i < b0i) {
return -1
}
else if (b0i < a0i) {
return 1
}
else {
// sort by second term numerically
if (a[1].n < b[1].n) {
return -1
}
else if (b[1].n < a[1].n) {
return 1
}
else {
// sort by second term operationally
var a1i = os.indexOf(a[1].o)
var b1i = os.indexOf(b[1].o)
return a1i < b1i ? -1 : b1i < a1i ? 1 : 0
}
}
}
})
.reduce((hv, hh) => hv.concat(...hh), [])
// console.log(hi)
return hi
}
} | the_stack |
class DetailsMenuElement extends HTMLElement {
get preload(): boolean {
return this.hasAttribute('preload')
}
set preload(value: boolean) {
if (value) {
this.setAttribute('preload', '')
} else {
this.removeAttribute('preload')
}
}
get src(): string {
return this.getAttribute('src') || ''
}
set src(value: string) {
this.setAttribute('src', value)
}
connectedCallback(): void {
if (!this.hasAttribute('role')) this.setAttribute('role', 'menu')
const details = this.parentElement
if (!details) return
const summary = details.querySelector('summary')
if (summary) {
summary.setAttribute('aria-haspopup', 'menu')
if (!summary.hasAttribute('role')) summary.setAttribute('role', 'button')
}
const subscriptions = [
fromEvent(details, 'compositionstart', e => trackComposition(this, e)),
fromEvent(details, 'compositionend', e => trackComposition(this, e)),
fromEvent(details, 'click', e => shouldCommit(details, e)),
fromEvent(details, 'change', e => shouldCommit(details, e)),
fromEvent(details, 'keydown', e => keydown(details, this, e)),
fromEvent(details, 'toggle', () => loadFragment(details, this), {once: true}),
fromEvent(details, 'toggle', () => closeCurrentMenu(details)),
this.preload
? fromEvent(details, 'mouseover', () => loadFragment(details, this), {once: true})
: NullSubscription,
...focusOnOpen(details)
]
states.set(this, {subscriptions, loaded: false, isComposing: false})
}
disconnectedCallback(): void {
const state = states.get(this)
if (!state) return
states.delete(this)
for (const sub of state.subscriptions) {
sub.unsubscribe()
}
}
}
const states = new WeakMap()
type Subscription = {unsubscribe(): void}
const NullSubscription = {
unsubscribe() {
/* Do nothing */
}
}
function fromEvent(
target: EventTarget,
eventName: string,
onNext: EventListenerOrEventListenerObject,
options: boolean | AddEventListenerOptions = false
): Subscription {
target.addEventListener(eventName, onNext, options)
return {
unsubscribe: () => {
target.removeEventListener(eventName, onNext, options)
}
}
}
function loadFragment(details: Element, menu: DetailsMenuElement) {
const src = menu.getAttribute('src')
if (!src) return
const state = states.get(menu)
if (!state) return
if (state.loaded) return
state.loaded = true
const loader = menu.querySelector('include-fragment')
if (loader && !loader.hasAttribute('src')) {
loader.addEventListener('loadend', () => autofocus(details))
loader.setAttribute('src', src)
}
}
function focusOnOpen(details: Element): Subscription[] {
let isMouse = false
const onmousedown = () => (isMouse = true)
const onkeydown = () => (isMouse = false)
const ontoggle = () => {
if (!details.hasAttribute('open')) return
if (autofocus(details)) return
if (!isMouse) focusFirstItem(details)
}
return [
fromEvent(details, 'mousedown', onmousedown),
fromEvent(details, 'keydown', onkeydown),
fromEvent(details, 'toggle', ontoggle)
]
}
function closeCurrentMenu(details: Element) {
if (!details.hasAttribute('open')) return
for (const menu of document.querySelectorAll('details[open] > details-menu')) {
const opened = menu.closest('details')
if (opened && opened !== details && !opened.contains(details)) {
opened.removeAttribute('open')
}
}
}
function autofocus(details: Element): boolean {
if (!details.hasAttribute('open')) return false
const input = details.querySelector<HTMLElement>('details-menu [autofocus]')
if (input) {
input.focus()
return true
} else {
return false
}
}
// Focus first item unless an item is already focused.
function focusFirstItem(details: Element) {
const selected = document.activeElement
if (selected && isMenuItem(selected) && details.contains(selected)) return
const target = sibling(details, true)
if (target) target.focus()
}
function sibling(details: Element, next: boolean): HTMLElement | null {
const options = Array.from(
details.querySelectorAll<HTMLElement>(
'[role^="menuitem"]:not([hidden]):not([disabled]):not([aria-disabled="true"])'
)
)
const selected = document.activeElement
const index = selected instanceof HTMLElement ? options.indexOf(selected) : -1
const found = next ? options[index + 1] : options[index - 1]
const def = next ? options[0] : options[options.length - 1]
return found || def
}
const ctrlBindings = navigator.userAgent.match(/Macintosh/)
function shouldCommit(details: Element, event: Event) {
const target = event.target
if (!(target instanceof Element)) return
// Ignore clicks from nested details.
if (target.closest('details') !== details) return
if (event.type === 'click') {
const menuitem = target.closest('[role="menuitem"], [role="menuitemradio"]')
if (!menuitem) return
const input = menuitem.querySelector('input')
// Ignore double event caused by inputs nested in labels
// Known issue: This will wrongly ignore a legit click event on an already checked input,
// but inputs are not expected to be visible in the menu items.
// I've found no way to discriminate the legit event from the echo one, and we don't want to trigger the selected event twice.
if (menuitem.tagName === 'LABEL' && target === input) return
// An input inside a label will be committed as a change event (we assume it's a radio input),
// unless the input is already checked, so we need to commit on click (to close the popup)
const onlyCommitOnChangeEvent = menuitem.tagName === 'LABEL' && input && !input.checked
if (!onlyCommitOnChangeEvent) {
commit(menuitem, details)
}
} else if (event.type === 'change') {
const menuitem = target.closest('[role="menuitemradio"], [role="menuitemcheckbox"]')
if (menuitem) commit(menuitem, details)
}
}
function updateChecked(selected: Element, details: Element) {
for (const el of details.querySelectorAll('[role="menuitemradio"], [role="menuitemcheckbox"]')) {
const input = el.querySelector('input[type="radio"], input[type="checkbox"]')
let checkState = (el === selected).toString()
if (input instanceof HTMLInputElement) {
checkState = input.indeterminate ? 'mixed' : input.checked.toString()
}
el.setAttribute('aria-checked', checkState)
}
}
function commit(selected: Element, details: Element) {
if (selected.hasAttribute('disabled') || selected.getAttribute('aria-disabled') === 'true') return
const menu = selected.closest('details-menu')
if (!menu) return
const dispatched = menu.dispatchEvent(
new CustomEvent('details-menu-select', {
cancelable: true,
detail: {relatedTarget: selected}
})
)
if (!dispatched) return
updateLabel(selected, details)
updateChecked(selected, details)
if (selected.getAttribute('role') !== 'menuitemcheckbox') close(details)
menu.dispatchEvent(
new CustomEvent('details-menu-selected', {
detail: {relatedTarget: selected}
})
)
}
function keydown(details: Element, menu: DetailsMenuElement, event: Event) {
if (!(event instanceof KeyboardEvent)) return
// Ignore key presses from nested details.
if (details.querySelector('details[open]')) return
const state = states.get(menu)
if (!state || state.isComposing) return
const isSummaryFocused = event.target instanceof Element && event.target.tagName === 'SUMMARY'
switch (event.key) {
case 'Escape':
if (details.hasAttribute('open')) {
close(details)
event.preventDefault()
event.stopPropagation()
}
break
case 'ArrowDown':
{
if (isSummaryFocused && !details.hasAttribute('open')) {
details.setAttribute('open', '')
}
const target = sibling(details, true)
if (target) target.focus()
event.preventDefault()
}
break
case 'ArrowUp':
{
if (isSummaryFocused && !details.hasAttribute('open')) {
details.setAttribute('open', '')
}
const target = sibling(details, false)
if (target) target.focus()
event.preventDefault()
}
break
case 'n':
{
if (ctrlBindings && event.ctrlKey) {
const target = sibling(details, true)
if (target) target.focus()
event.preventDefault()
}
}
break
case 'p':
{
if (ctrlBindings && event.ctrlKey) {
const target = sibling(details, false)
if (target) target.focus()
event.preventDefault()
}
}
break
case ' ':
case 'Enter':
{
const selected = document.activeElement
if (selected instanceof HTMLElement && isMenuItem(selected) && selected.closest('details') === details) {
event.preventDefault()
event.stopPropagation()
selected.click()
}
}
break
}
}
function isMenuItem(el: Element): boolean {
const role = el.getAttribute('role')
return role === 'menuitem' || role === 'menuitemcheckbox' || role === 'menuitemradio'
}
function close(details: Element) {
const wasOpen = details.hasAttribute('open')
if (!wasOpen) return
details.removeAttribute('open')
const summary = details.querySelector('summary')
if (summary) summary.focus()
}
function updateLabel(item: Element, details: Element) {
const button = details.querySelector('[data-menu-button]')
if (!button) return
const text = labelText(item)
if (text) {
button.textContent = text
} else {
const html = labelHTML(item)
if (html) button.innerHTML = html
}
}
function labelText(el: Element | null): string | null {
if (!el) return null
const textEl = el.hasAttribute('data-menu-button-text') ? el : el.querySelector('[data-menu-button-text]')
if (!textEl) return null
return textEl.getAttribute('data-menu-button-text') || textEl.textContent
}
function labelHTML(el: Element | null): string | null {
if (!el) return null
const contentsEl = el.hasAttribute('data-menu-button-contents') ? el : el.querySelector('[data-menu-button-contents]')
return contentsEl ? contentsEl.innerHTML : null
}
function trackComposition(menu: Element, event: Event) {
const state = states.get(menu)
if (!state) return
state.isComposing = event.type === 'compositionstart'
}
declare global {
interface Window {
DetailsMenuElement: typeof DetailsMenuElement
}
interface HTMLElementTagNameMap {
'details-menu': DetailsMenuElement
}
}
export default DetailsMenuElement
if (!window.customElements.get('details-menu')) {
window.DetailsMenuElement = DetailsMenuElement
window.customElements.define('details-menu', DetailsMenuElement)
} | the_stack |
import {expectRevert} from '@statechannels/devtools';
import {Contract, constants, BigNumber} from 'ethers';
import {Allocation, AllocationType} from '@statechannels/exit-format';
import {
getTestProvider,
randomChannelId,
randomExternalDestination,
replaceAddressesAndBigNumberify,
setupContract,
AssetOutcomeShortHand,
} from '../../test-helpers';
import {TESTNitroAdjudicator} from '../../../typechain/TESTNitroAdjudicator';
// eslint-disable-next-line import/order
import TESTNitroAdjudicatorArtifact from '../../../artifacts/contracts/test/TESTNitroAdjudicator.sol/TESTNitroAdjudicator.json';
import {
channelDataToStatus,
convertBytes32ToAddress,
encodeOutcome,
hashOutcome,
Outcome,
} from '../../../src';
import {MAGIC_ADDRESS_INDICATING_ETH} from '../../../src/transactions';
import {encodeGuaranteeData} from '../../../src/contract/outcome';
const provider = getTestProvider();
const testNitroAdjudicator: TESTNitroAdjudicator & Contract = (setupContract(
provider,
TESTNitroAdjudicatorArtifact,
process.env.TEST_NITRO_ADJUDICATOR_ADDRESS
) as unknown) as TESTNitroAdjudicator & Contract;
const addresses = {
// Channels
t: undefined, // Target
g: undefined, // Guarantor
x: undefined, // Application
// Externals
I: randomExternalDestination(),
A: randomExternalDestination(),
B: randomExternalDestination(),
};
const reason5 = 'Channel not finalized';
const reason6 = 'targetAsset != guaranteeAsset';
const names = {
1: ' 1. straight-through guarantee, 3 destinations', // 1. claim G1 (step 1 of figure 23 of nitro paper)
2: ' 2. swap guarantee, 2 destinations', // 2. claim G2 (step 2 of figure 23 of nitro paper)
3: ' 3. swap guarantee, 3 destinations', // 3. claim G1 (step 1 of alternative in figure 23 of nitro paper)
4: ' 4. straight-through guarantee, 2 destinations', // 4. claim G2 (step 2 of alternative of figure 23 of nitro paper)
5: ' 5. allocation not on chain',
6: ' 6. guarantee not on chain',
7: ' 7. swap guarantee, overfunded, 2 destinations',
8: ' 8. underspecified guarantee, overfunded ',
9: ' 9. (all) straight-through guarantee, 3 destinations',
10: '10. (all) swap guarantee, 2 destinations',
11: '11. (all) swap guarantee, 3 destinations',
12: '12. (all) straight-through guarantee, 2 destinations',
13: '13. (all) allocation not on chain',
14: '14. (all) guarantee not on chain',
15: '15. (all) swap guarantee, overfunded, 2 destinations',
16: '16. (all) underspecified guarantee, overfunded ',
17: '17. guarantee and target assets do not match',
18: '18. guarantee includes destination missing in target outcome, indices=[], lowest priority is a channel',
19: '19. guarantee includes destination missing in target outcome, indices=[1], lowest priority is a channel',
20: '20. guarantee includes destination missing in target outcome, indices=[], lowest priority is an external destination', // this guarantee is typical of the virtual funding construction
21: '21. guarantee includes destination missing in target outcome, indices=[1], lowest priority is an external destination', // this guarantee is typical of the virtual funding construction
};
// Amounts are valueString representations of wei
describe('claim', () => {
it.each`
name | heldBefore | guaranteeDestinations | tOutcomeBefore | indices | tOutcomeAfter | heldAfter | payouts | reason
${names[1]} | ${{g: 5}} | ${['I', 'A', 'B']} | ${{I: 5, A: 5, B: 5}} | ${[0]} | ${{I: 0, A: 5, B: 5}} | ${{g: 0}} | ${{I: 5}} | ${undefined}
${names[2]} | ${{g: 5}} | ${['B', 'A']} | ${{A: 5, B: 5}} | ${[1]} | ${{A: 5, B: 0}} | ${{g: 0}} | ${{B: 5}} | ${undefined}
${names[3]} | ${{g: 5}} | ${['I', 'B', 'A']} | ${{I: 5, A: 5, B: 5}} | ${[0]} | ${{I: 0, A: 5, B: 5}} | ${{g: 0}} | ${{I: 5}} | ${undefined}
${names[4]} | ${{g: 5}} | ${['A', 'B']} | ${{A: 5, B: 5}} | ${[0]} | ${{A: 0, B: 5}} | ${{g: 0}} | ${{A: 5}} | ${undefined}
${names[5]} | ${{g: 5}} | ${['B', 'A']} | ${{}} | ${[0]} | ${{A: 5}} | ${{g: 0}} | ${{B: 5}} | ${reason5}
${names[6]} | ${{g: 5}} | ${[]} | ${{A: 5, B: 5}} | ${[1]} | ${{A: 5}} | ${{g: 0}} | ${{B: 5}} | ${reason5}
${names[7]} | ${{g: 12}} | ${['B', 'A']} | ${{A: 5, B: 5}} | ${[1]} | ${{A: 5, B: 0}} | ${{g: 7}} | ${{B: 5}} | ${undefined}
${names[8]} | ${{g: 12}} | ${['B']} | ${{A: 5, B: 5}} | ${[1]} | ${{A: 5, B: 0}} | ${{g: 7}} | ${{B: 5}} | ${undefined}
${names[9]} | ${{g: 5}} | ${['I', 'A', 'B']} | ${{I: 5, A: 5, B: 5}} | ${[]} | ${{I: 0, A: 5, B: 5}} | ${{g: 0}} | ${{I: 5}} | ${undefined}
${names[10]} | ${{g: 5}} | ${['B', 'A']} | ${{A: 5, B: 5}} | ${[]} | ${{A: 5, B: 0}} | ${{g: 0}} | ${{B: 5}} | ${undefined}
${names[11]} | ${{g: 5}} | ${['I', 'B', 'A']} | ${{I: 5, A: 5, B: 5}} | ${[]} | ${{I: 0, A: 5, B: 5}} | ${{g: 0}} | ${{I: 5}} | ${undefined}
${names[12]} | ${{g: 5}} | ${['A', 'B']} | ${{A: 5, B: 5}} | ${[]} | ${{A: 0, B: 5}} | ${{g: 0}} | ${{A: 5}} | ${undefined}
${names[13]} | ${{g: 5}} | ${['B', 'A']} | ${{}} | ${[]} | ${{}} | ${{g: 0}} | ${{B: 5}} | ${reason5}
${names[14]} | ${{g: 5}} | ${[]} | ${{A: 5, B: 5}} | ${[]} | ${{A: 5, B: 5}} | ${{g: 0}} | ${{B: 5}} | ${reason5}
${names[15]} | ${{g: 12}} | ${['B', 'A']} | ${{A: 5, B: 5}} | ${[]} | ${{A: 0, B: 0}} | ${{g: 2}} | ${{A: 5, B: 5}} | ${undefined}
${names[16]} | ${{g: 12}} | ${['B']} | ${{A: 5, B: 5}} | ${[]} | ${{A: 5, B: 0}} | ${{g: 7}} | ${{B: 5}} | ${undefined}
${names[17]} | ${{g: 1}} | ${['A', 'B']} | ${{A: 5, B: 5}} | ${[1]} | ${{A: 4, B: 5}} | ${{g: 0}} | ${{A: 1}} | ${reason6}
${names[18]} | ${{g: 10}} | ${['A', 'I', 'x']} | ${{x: 10, I: 10}} | ${[]} | ${{x: 10, I: 0}} | ${{g: 0}} | ${{I: 10}} | ${undefined}
${names[19]} | ${{g: 10}} | ${['A', 'I', 'x']} | ${{x: 10, I: 10}} | ${[1]} | ${{x: 10, I: 0}} | ${{g: 0}} | ${{I: 10}} | ${undefined}
${names[20]} | ${{g: 10}} | ${['A', 'x', 'I']} | ${{x: 10, I: 10}} | ${[]} | ${{x: 0, I: 10}} | ${{g: 0, x: 10}} | ${{}} | ${undefined}
${names[21]} | ${{g: 10}} | ${['A', 'x', 'I']} | ${{x: 10, I: 10}} | ${[0]} | ${{x: 0, I: 10}} | ${{g: 0, x: 10}} | ${{}} | ${undefined}
`(
'$name',
async ({
heldBefore,
guaranteeDestinations,
tOutcomeBefore,
indices: targetAllocationIndicesToPayout,
tOutcomeAfter,
heldAfter,
payouts,
reason,
}: {
heldBefore: AssetOutcomeShortHand;
guaranteeDestinations;
tOutcomeBefore: AssetOutcomeShortHand;
indices: number[];
tOutcomeAfter: AssetOutcomeShortHand;
heldAfter: AssetOutcomeShortHand;
payouts: AssetOutcomeShortHand;
reason;
}) => {
// Compute channelIds
const targetId = randomChannelId();
const sourceChannelId = randomChannelId();
const applicationChannelId = randomChannelId();
addresses.t = targetId;
addresses.g = sourceChannelId;
addresses.x = applicationChannelId;
// Transform input data (unpack addresses and BigNumber amounts)
[heldBefore, tOutcomeBefore, tOutcomeAfter, heldAfter, payouts] = [
heldBefore,
tOutcomeBefore,
tOutcomeAfter,
heldAfter,
payouts,
].map(object => replaceAddressesAndBigNumberify(object, addresses) as AssetOutcomeShortHand);
guaranteeDestinations = guaranteeDestinations.map(x => addresses[x]);
// Deposit into channels
await Promise.all(
Object.keys(heldBefore).map(async key => {
// Key must be either in heldBefore or heldAfter or both
const amount = heldBefore[key];
await (
await testNitroAdjudicator.deposit(MAGIC_ADDRESS_INDICATING_ETH, key, 0, amount, {
value: amount,
})
).wait();
expect(
(await testNitroAdjudicator.holdings(MAGIC_ADDRESS_INDICATING_ETH, key)).eq(amount)
).toBe(true);
})
);
// Compute an appropriate allocation.
const allocations: Allocation[] = [];
Object.keys(tOutcomeBefore).forEach(key =>
allocations.push({
destination: key,
amount: tOutcomeBefore[key].toString(),
metadata: '0x',
allocationType: AllocationType.simple,
})
);
const outcome: Outcome = [{asset: MAGIC_ADDRESS_INDICATING_ETH, allocations, metadata: '0x'}];
const outcomeHash = hashOutcome(outcome);
const targetOutcomeBytes = encodeOutcome(outcome);
// Set adjudicator status
const stateHash = constants.HashZero; // not realistic, but OK for purpose of this test
const finalizesAt = 42;
const turnNumRecord = 7;
if (reason != reason5) {
await (
await testNitroAdjudicator.setStatusFromChannelData(targetId, {
turnNumRecord,
finalizesAt,
stateHash,
outcomeHash,
})
).wait();
}
// Compute an appropriate guarantee
const encodedGuaranteeData = encodeGuaranteeData(guaranteeDestinations);
const guaranteeOutcome: Outcome = [
{
metadata: '0x',
allocations: [
{
allocationType: AllocationType.guarantee,
amount: heldBefore[addresses.g].toString(),
destination: targetId,
metadata: encodedGuaranteeData,
},
],
asset:
reason === reason6 // test case for mismatched source and target assets
? '0xdac17f958d2ee523a2206206994597c13d831ec7' // USDT
: MAGIC_ADDRESS_INDICATING_ETH,
},
];
const sourceOutcomeBytes = encodeOutcome(guaranteeOutcome);
const guarantorOutcomeHash = hashOutcome(guaranteeOutcome);
// Set status for guarantor
if (guaranteeDestinations.length > 0) {
await (
await testNitroAdjudicator.setStatusFromChannelData(sourceChannelId, {
turnNumRecord,
finalizesAt,
stateHash,
outcomeHash: guarantorOutcomeHash,
})
).wait();
}
// record eth balances before the transaction so we can check payouts later
const ethBalancesBefore = {};
await Promise.all(
Object.keys(payouts).map(async destination => {
const address = convertBytes32ToAddress(destination);
ethBalancesBefore[address] = await provider.getBalance(address);
})
);
const tx = testNitroAdjudicator.claim({
sourceChannelId,
sourceStateHash: stateHash,
sourceOutcomeBytes,
sourceAssetIndex: 0, // TODO: introduce test cases with multiple-asset Source and Targets
indexOfTargetInSource: 0,
targetStateHash: stateHash,
targetOutcomeBytes,
targetAssetIndex: 0,
targetAllocationIndicesToPayout,
});
// Call method in a slightly different way if expecting a revert
if (reason) {
await expectRevert(() => tx, reason);
} else {
// Extract logs
const {events: eventsFromTx} = await (await tx).wait();
// Check new holdings
const heldAfterChecks = Object.keys(heldAfter).map(async g => {
return expect(
await testNitroAdjudicator.holdings(MAGIC_ADDRESS_INDICATING_ETH, g)
).toEqual(heldAfter[g]);
});
await Promise.all(heldAfterChecks);
// Check new outcomeHash
const allocationAfter: Allocation[] = [];
Object.keys(tOutcomeAfter).forEach(key => {
allocationAfter.push({
destination: key,
amount: tOutcomeAfter[key].toString(),
metadata: '0x',
allocationType: AllocationType.simple,
});
});
const outcomeAfter: Outcome = [
{asset: MAGIC_ADDRESS_INDICATING_ETH, allocations: allocationAfter, metadata: '0x'},
];
const expectedStatusAfter = channelDataToStatus({
turnNumRecord,
finalizesAt,
// stateHash will be set to HashZero by this helper fn
// if state property of this object is undefined
outcome: outcomeAfter,
});
expect(await testNitroAdjudicator.statusOf(targetId)).toEqual(expectedStatusAfter);
// Compile event expectations
const expectedEvents = [
{
event: 'AllocationUpdated',
args: {
channelId: sourceChannelId,
assetIndex: BigNumber.from(0),
initialHoldings: heldBefore[addresses.g],
},
},
{
event: 'AllocationUpdated',
args: {
channelId: targetId,
assetIndex: BigNumber.from(0),
initialHoldings: heldBefore[addresses.g],
},
},
];
// Check that each expectedEvent is contained as a subset of the properies of each *corresponding* event: i.e. the order matters!
expect(eventsFromTx).toMatchObject(expectedEvents);
// check payouts
await Promise.all(
Object.keys(payouts).map(async destination => {
const address = convertBytes32ToAddress(destination);
const balanceAfter = await provider.getBalance(address);
const expectedBalanceAfter = ethBalancesBefore[address].add(payouts[destination]);
expect(balanceAfter).toEqual(expectedBalanceAfter);
})
);
}
}
);
}); | the_stack |
import "jest";
import { createLocalVue } from "@vue/test-utils";
import { inMemory } from "@hickory/in-memory";
import { createRouter, prepareRoutes } from "@curi/router";
import { CuriPlugin } from "@curi/vue";
describe("<curi-async-link>", () => {
let Vue, node, router, wrapper;
let routes = prepareRoutes([
{ name: "Place", path: "place/:name" },
{ name: "Catch All", path: "(.*)" }
]);
beforeEach(() => {
node = document.createElement("div");
document.body.appendChild(node);
router = createRouter(inMemory, routes);
Vue = createLocalVue();
Vue.use(CuriPlugin, { router });
});
afterEach(() => {
wrapper.$destroy();
document.body.innerHTML = "";
});
describe("rendering", () => {
it("renders an anchor element", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Aruba' }">
<template slot-scope="{ navigating }">
{{navigating}}
</template>
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(a.tagName).toBe("A");
});
it("is initially rendered with navigating = false", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Aruba' }">
<template slot-scope="{ navigating }">{{navigating}}</template>
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(a.textContent).toEqual("false");
});
it("computes the expected href using the props", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link
name="Place"
:params="{ name: 'Jamaica' }"
hash="island-life"
query="two=2"
>
2
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(a.getAttribute("href")).toBe("/place/Jamaica?two=2#island-life");
});
it("has no pathname component if name is not provided", () => {
let Vue = createLocalVue();
let router = createRouter(inMemory, routes, {
history: {
locations: [{ url: "/place/somewhere" }]
}
});
Vue.use(CuriPlugin, { router });
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link hash="test">somewhere</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(a.getAttribute("href")).toBe("#test");
});
it("sets the slots as the link's children", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Kokomo' }">
<span>Kokomo</span>
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(a.textContent).toBe("Kokomo");
});
it("spreads additional props onto anchor", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link
name="Place"
:params="{ name: 'Aruba' }"
class="hooray"
>
Aruba
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(a.classList.contains("hooray")).toBe(true);
});
});
describe("clicking a <curi-async-link>", () => {
let mockNavigate;
beforeEach(() => {
mockNavigate = jest.fn();
router.history.navigate = mockNavigate;
});
afterEach(() => {
mockNavigate.mockReset();
});
it("navigates to expected location when clicked", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link
name="Place"
:params="{ name: 'Bermuda' }"
hash="beach-boys"
query="name=Bermuda"
>
Bermuda
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(mockNavigate.mock.calls.length).toBe(0);
a.dispatchEvent(
new MouseEvent("click", {
button: 0
})
);
expect(mockNavigate.mock.calls.length).toBe(1);
expect(mockNavigate.mock.calls[0][0]).toMatchObject({
url: "/place/Bermuda?name=Bermuda#beach-boys"
});
});
describe("navigating", () => {
let routes = prepareRoutes([
{
name: "Test",
path: "test",
resolve() {
return new Promise(resolve => {
setTimeout(() => {
resolve("done");
}, 100);
});
}
},
{ name: "Catch All", path: "(.*)" }
]);
it("navigating = true after clicking", done => {
let router = createRouter(inMemory, routes);
let Vue = createLocalVue();
Vue.use(CuriPlugin, { router });
// if a link has no on methods, finished will be called almost
// immediately (although this style should only be used for routes
// with on methods)
let LoadChecker = {
props: ["navigating"],
render(h) {
return h("div", this.navigating);
},
updated() {
expect(this.navigating).toBe(true);
done();
}
};
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Test" id="after-click">
<template slot-scope="{ navigating }">
<LoadChecker :navigating="navigating" />
</template>
</curi-async-link>
</div>
`,
components: {
LoadChecker
}
});
let a = document.querySelector("#after-click");
a.dispatchEvent(
new MouseEvent("click", {
button: 0
})
);
});
it("navigating = false after navigation completes", done => {
let router = createRouter(inMemory, routes);
let Vue = createLocalVue();
Vue.use(CuriPlugin, { router });
// if a link has no on methods, finished will be called almost
// immediately (although this style should only be used for routes
// with on methods)
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Test" id="nav-complete">
<template slot-scope="{ navigating }">
{{navigating}}
</template>
</curi-async-link>
</div>
`
});
let a = document.querySelector("#nav-complete");
a.dispatchEvent(
new MouseEvent("click", {
button: 0
})
);
router.once(
() => {
// navigation is complete, wait for Vue to re-render
Vue.nextTick(() => {
expect(a.textContent.trim()).toBe("false");
done();
});
},
{ initial: false }
);
});
it("navigating = false after navigation is cancelled", done => {
let routes = prepareRoutes([
{
name: "Slow",
path: "slow",
resolve() {
return new Promise(resolve => {
setTimeout(() => {
resolve("slow");
}, 100);
});
}
},
{
name: "Fast",
path: "fast",
resolve() {
return Promise.resolve("fast");
}
},
{ name: "Catch All", path: "(.*)" }
]);
let router = createRouter(inMemory, routes);
let Vue = createLocalVue();
Vue.use(CuriPlugin, { router });
// if a link has no on methods, finished will be called almost
// immediately (although this style should only be used for routes
// with on methods)
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Slow" id="slow">
<template slot-scope="{ navigating }">
{{navigating}}
</template>
</curi-async-link>
<curi-async-link name="Fast" id="fast">
<template slot-scope="{ navigating }">
{{navigating}}
</template>
</curi-async-link>
</div>
`
});
let slowLink = document.querySelector("#slow");
let fastLink = document.querySelector("#slow");
expect(slowLink.textContent.trim()).toBe("false");
slowLink.dispatchEvent(
new MouseEvent("click", {
button: 0
})
);
Vue.nextTick(() => {
expect(slowLink.textContent.trim()).toBe("true");
fastLink.dispatchEvent(
new MouseEvent("click", {
button: 0
})
);
router.once(
() => {
// navigation is cancelled, wait for Vue to re-render
Vue.nextTick(() => {
expect(slowLink.textContent.trim()).toBe("false");
done();
});
},
{ initial: false }
);
});
});
});
it("does not navigate if event.defaultPrevented is true", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Bahamas' }" :click="click">
Bahamas
</curi-async-link>
</div>
`,
data: {
click: function(e) {
e.preventDefault();
}
}
});
let a = document.querySelector("a");
expect(mockNavigate.mock.calls.length).toBe(0);
let event = new MouseEvent("click", {
button: 0,
cancelable: true
});
a.dispatchEvent(event);
expect(mockNavigate.mock.calls.length).toBe(0);
});
it("does not navigate if a modifier key is held while clicking", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Key Largo' }">
Key Largo
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(mockNavigate.mock.calls.length).toBe(0);
let modifiers = ["metaKey", "altKey", "ctrlKey", "shiftKey"];
modifiers.forEach(m => {
let event = new MouseEvent("click", {
[m]: true,
button: 0
});
a.dispatchEvent(event);
expect(mockNavigate.mock.calls.length).toBe(0);
});
});
it("does not navigate for non left mouse button clicks", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Montego' }">
Montego
</curi-async-link>
</div>
`
});
let a = document.querySelector("a");
expect(mockNavigate.mock.calls.length).toBe(0);
let event = new MouseEvent("click", {
button: 1
});
a.dispatchEvent(event);
expect(mockNavigate.mock.calls.length).toBe(0);
});
describe("click prop", () => {
it("will be called prior to navigation", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Montego' }" :click="click">
Montego
</curi-async-link>
</div>
`,
data: {
click: function() {
expect(mockNavigate.mock.calls.length).toBe(0);
}
}
});
let a = document.querySelector("a");
let event = new MouseEvent("click", {
button: 0
});
a.dispatchEvent(event);
expect(mockNavigate.mock.calls.length).toBe(1);
});
it("calling event.preventDefault() in click fn will stop navigation", () => {
wrapper = new Vue({
el: node,
template: `
<div>
<curi-async-link name="Place" :params="{ name: 'Montego' }" :click="click">
Montego
</curi-async-link>
</div>
`,
data: {
click: function(event) {
event.preventDefault();
}
}
});
let a = document.querySelector("a");
let event = new MouseEvent("click", {
button: 0,
cancelable: true
});
a.dispatchEvent(event);
expect(mockNavigate.mock.calls.length).toBe(0);
});
});
});
}); | the_stack |
import { inject, injectable, } from 'inversify';
import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
import * as ESTree from 'estree';
import { TInitialData } from '../../types/TInitialData';
import { TNodeWithLexicalScopeStatements } from '../../types/node/TNodeWithLexicalScopeStatements';
import { TStatement } from '../../types/node/TStatement';
import { TStringArrayScopeCallsWrappersDataByEncoding } from '../../types/node-transformers/string-array-transformers/TStringArrayScopeCallsWrappersDataByEncoding';
import { TStringArrayCustomNodeFactory } from '../../types/container/custom-nodes/TStringArrayCustomNodeFactory';
import { ICustomNode } from '../../interfaces/custom-nodes/ICustomNode';
import { IOptions } from '../../interfaces/options/IOptions';
import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
import { IStringArrayScopeCallsWrapperData } from '../../interfaces/node-transformers/string-array-transformers/IStringArrayScopeCallsWrapperData';
import { IStringArrayScopeCallsWrappersData } from '../../interfaces/node-transformers/string-array-transformers/IStringArrayScopeCallsWrappersData';
import { IStringArrayScopeCallsWrappersDataStorage } from '../../interfaces/storages/string-array-transformers/IStringArrayScopeCallsWrappersDataStorage';
import { IStringArrayStorage } from '../../interfaces/storages/string-array-transformers/IStringArrayStorage';
import { IVisitedLexicalScopeNodesStackStorage } from '../../interfaces/storages/string-array-transformers/IVisitedLexicalScopeNodesStackStorage';
import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
import { NodeTransformer } from '../../enums/node-transformers/NodeTransformer';
import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage';
import { StringArrayCustomNode } from '../../enums/custom-nodes/StringArrayCustomNode';
import { StringArrayWrappersType } from '../../enums/node-transformers/string-array-transformers/StringArrayWrappersType';
import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
import { NodeAppender } from '../../node/NodeAppender';
import { NodeGuards } from '../../node/NodeGuards';
import { StringArrayScopeCallsWrapperFunctionNode } from '../../custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperFunctionNode';
import { StringArrayScopeCallsWrapperVariableNode } from '../../custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperVariableNode';
@injectable()
export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransformer {
/**
* @type {NodeTransformer[]}
*/
public override readonly runAfter: NodeTransformer[] = [
NodeTransformer.StringArrayRotateFunctionTransformer
];
/**
* @type {IStringArrayStorage}
*/
private readonly stringArrayStorage: IStringArrayStorage;
/**
* @type {IStringArrayScopeCallsWrappersDataStorage}
*/
private readonly stringArrayScopeCallsWrappersDataStorage: IStringArrayScopeCallsWrappersDataStorage;
/**
* @type {TStringArrayCustomNodeFactory}
*/
private readonly stringArrayTransformerCustomNodeFactory: TStringArrayCustomNodeFactory;
/**
* @type {IVisitedLexicalScopeNodesStackStorage}
*/
private readonly visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage;
/**
* @param {IRandomGenerator} randomGenerator
* @param {IOptions} options
* @param {IVisitedLexicalScopeNodesStackStorage} visitedLexicalScopeNodesStackStorage
* @param {IStringArrayStorage} stringArrayStorage
* @param {IStringArrayScopeCallsWrappersDataStorage} stringArrayScopeCallsWrappersDataStorage
* @param {TStringArrayCustomNodeFactory} stringArrayTransformerCustomNodeFactory
*/
public constructor (
@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
@inject(ServiceIdentifiers.IOptions) options: IOptions,
@inject(ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage) visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage,
@inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage,
@inject(ServiceIdentifiers.IStringArrayScopeCallsWrappersDataStorage) stringArrayScopeCallsWrappersDataStorage: IStringArrayScopeCallsWrappersDataStorage,
@inject(ServiceIdentifiers.Factory__IStringArrayCustomNode)
stringArrayTransformerCustomNodeFactory: TStringArrayCustomNodeFactory
) {
super(randomGenerator, options);
this.visitedLexicalScopeNodesStackStorage = visitedLexicalScopeNodesStackStorage;
this.stringArrayStorage = stringArrayStorage;
this.stringArrayScopeCallsWrappersDataStorage = stringArrayScopeCallsWrappersDataStorage;
this.stringArrayTransformerCustomNodeFactory = stringArrayTransformerCustomNodeFactory;
}
/**
* @param {NodeTransformationStage} nodeTransformationStage
* @returns {IVisitor | null}
*/
public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null {
if (!this.options.stringArrayWrappersCount) {
return null;
}
switch (nodeTransformationStage) {
case NodeTransformationStage.StringArray:
return {
enter: (node: ESTree.Node, parentNode: ESTree.Node | null): void => {
if (parentNode && NodeGuards.isNodeWithLexicalScopeStatements(node, parentNode)) {
this.onLexicalScopeNodeEnter(node);
}
},
leave: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => {
if (parentNode && NodeGuards.isNodeWithLexicalScopeStatements(node, parentNode)) {
this.onLexicalScopeNodeLeave();
return this.transformNode(node);
}
}
};
default:
return null;
}
}
/**
* @param {TNodeWithLexicalScopeStatements} lexicalScopeBodyNode
* @returns {TNodeWithLexicalScopeStatements}
*/
public transformNode (
lexicalScopeBodyNode: TNodeWithLexicalScopeStatements
): TNodeWithLexicalScopeStatements {
const stringArrayScopeCallsWrappersDataByEncoding: TStringArrayScopeCallsWrappersDataByEncoding | null =
this.stringArrayScopeCallsWrappersDataStorage.get(lexicalScopeBodyNode) ?? null;
if (!stringArrayScopeCallsWrappersDataByEncoding) {
return lexicalScopeBodyNode;
}
const stringArrayScopeCallsWrappersDataList: (IStringArrayScopeCallsWrappersData | undefined)[] =
Object.values(stringArrayScopeCallsWrappersDataByEncoding);
// iterates over data for each encoding type
for (const stringArrayScopeCallsWrappersData of stringArrayScopeCallsWrappersDataList) {
if (!stringArrayScopeCallsWrappersData) {
continue;
}
const {scopeCallsWrappersData} = stringArrayScopeCallsWrappersData;
const scopeCallsWrappersDataLength: number = scopeCallsWrappersData.length;
/**
* Iterates over each name of scope wrapper name
* Reverse iteration appends wrappers at index `0` at the correct order
*/
for (let i = scopeCallsWrappersDataLength - 1; i >= 0; i--) {
const stringArrayScopeCallsWrapperData = scopeCallsWrappersData[i];
const upperStringArrayCallsWrapperData =
this.getUpperStringArrayCallsWrapperData(stringArrayScopeCallsWrappersData);
this.getAndAppendStringArrayScopeCallsWrapperNode(
lexicalScopeBodyNode,
stringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData
);
}
}
return lexicalScopeBodyNode;
}
/**
* @param {IStringArrayScopeCallsWrappersData} stringArrayScopeCallsWrappersData
* @returns {IStringArrayScopeCallsWrapperData}
*/
private getRootStringArrayCallsWrapperData (
stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrappersData,
): IStringArrayScopeCallsWrapperData {
const {encoding} = stringArrayScopeCallsWrappersData;
return {
name: this.stringArrayStorage.getStorageCallsWrapperName(encoding),
index: 0,
parameterIndexesData: null
};
}
/**
* @param {IStringArrayScopeCallsWrappersData} stringArrayScopeCallsWrappersData
* @returns {IStringArrayScopeCallsWrapperData}
*/
private getUpperStringArrayCallsWrapperData (
stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrappersData,
): IStringArrayScopeCallsWrapperData {
const {encoding} = stringArrayScopeCallsWrappersData;
const rootStringArrayCallsWrapperData =
this.getRootStringArrayCallsWrapperData(stringArrayScopeCallsWrappersData);
if (!this.options.stringArrayWrappersChainedCalls) {
return rootStringArrayCallsWrapperData;
}
const parentLexicalScopeBodyNode: TNodeWithLexicalScopeStatements | null =
this.visitedLexicalScopeNodesStackStorage.getLastElement()
?? null;
if (!parentLexicalScopeBodyNode) {
return rootStringArrayCallsWrapperData;
}
const parentLexicalScopeCallsWrappersDataByEncoding: TStringArrayScopeCallsWrappersDataByEncoding | null =
this.stringArrayScopeCallsWrappersDataStorage
.get(parentLexicalScopeBodyNode) ?? null;
const parentScopeCallsWrappersData: IStringArrayScopeCallsWrapperData[] | null =
parentLexicalScopeCallsWrappersDataByEncoding?.[encoding]?.scopeCallsWrappersData ?? null;
if (!parentScopeCallsWrappersData?.length) {
return rootStringArrayCallsWrapperData;
}
return this.randomGenerator
.getRandomGenerator()
.pickone(parentScopeCallsWrappersData);
}
/**
* @param {TNodeWithLexicalScopeStatements} lexicalScopeBodyNode
* @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData
* @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData
*/
private getAndAppendStringArrayScopeCallsWrapperNode (
lexicalScopeBodyNode: TNodeWithLexicalScopeStatements,
stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData,
): void {
let stringArrayScopeCallsWrapperNode: TStatement[];
switch (this.options.stringArrayWrappersType) {
case StringArrayWrappersType.Function: {
const randomIndex: number = this.randomGenerator.getRandomInteger(
0,
lexicalScopeBodyNode.body.length - 1
);
stringArrayScopeCallsWrapperNode = this.getStringArrayScopeCallsWrapperFunctionNode(
stringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData,
);
NodeAppender.insertAtIndex(
lexicalScopeBodyNode,
stringArrayScopeCallsWrapperNode,
randomIndex
);
break;
}
case StringArrayWrappersType.Variable:
default: {
stringArrayScopeCallsWrapperNode = this.getStringArrayScopeCallsWrapperVariableNode(
stringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData
);
NodeAppender.prepend(
lexicalScopeBodyNode,
stringArrayScopeCallsWrapperNode
);
}
}
}
/**
* @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData
* @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData
* @returns {TStatement[]}
*/
private getStringArrayScopeCallsWrapperVariableNode (
stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData
): TStatement[] {
const stringArrayScopeCallsWrapperVariableNode: ICustomNode<TInitialData<StringArrayScopeCallsWrapperVariableNode>> =
this.stringArrayTransformerCustomNodeFactory(
StringArrayCustomNode.StringArrayScopeCallsWrapperVariableNode
);
stringArrayScopeCallsWrapperVariableNode.initialize(
stringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData
);
return stringArrayScopeCallsWrapperVariableNode.getNode();
}
/**
* @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData
* @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData
* @returns {TStatement[]}
*/
private getStringArrayScopeCallsWrapperFunctionNode (
stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData,
): TStatement[] {
const stringArrayScopeCallsWrapperFunctionNode: ICustomNode<TInitialData<StringArrayScopeCallsWrapperFunctionNode>> =
this.stringArrayTransformerCustomNodeFactory(
StringArrayCustomNode.StringArrayScopeCallsWrapperFunctionNode
);
stringArrayScopeCallsWrapperFunctionNode.initialize(
stringArrayScopeCallsWrapperData,
upperStringArrayCallsWrapperData
);
return stringArrayScopeCallsWrapperFunctionNode.getNode();
}
/**
* @param {TNodeWithLexicalScopeStatements} lexicalScopeBodyNode
*/
private onLexicalScopeNodeEnter (lexicalScopeBodyNode: TNodeWithLexicalScopeStatements): void {
this.visitedLexicalScopeNodesStackStorage.push(lexicalScopeBodyNode);
}
private onLexicalScopeNodeLeave (): void {
this.visitedLexicalScopeNodesStackStorage.pop();
}
} | the_stack |
import ClientBase from '../client-base';
import * as chat1 from '../types/chat1';
/** A function to call when a message is received. */
export declare type OnMessage = (message: chat1.MsgSummary) => void | Promise<void>;
/** A function to call when an error occurs. */
export declare type OnError = (error: Error) => void | Promise<void>;
/** A function to call when the bot is added to a new conversation. */
export declare type OnConv = (channel: chat1.ConvSummary) => void | Promise<void>;
/**
* Options for the `list` method of the chat module.
*/
export interface ChatListOptions {
failOffline?: boolean;
showErrors?: boolean;
topicType?: chat1.TopicType;
unreadOnly?: boolean;
}
/**
* Options for the `listChannels` method of the chat module.
*/
export interface ChatListChannelsOptions {
topicType?: chat1.TopicType;
membersType?: chat1.ConversationMembersType;
}
/**
* Options for the `read` method of the chat module.
*/
export interface ChatReadOptions {
failOffline?: boolean;
pagination?: chat1.Pagination;
peek?: boolean;
unreadOnly?: boolean;
}
/**
* Options for the `send` method of the chat module.
*/
export interface ChatSendOptions {
nonblock?: boolean;
membersType?: chat1.ConversationMembersType;
confirmLumenSend?: boolean;
replyTo?: chat1.MessageID;
explodingLifetime?: number;
}
/**
* Options for the `attach` method of the chat module.
*/
export interface ChatAttachOptions {
title?: string;
preview?: string;
explodingLifetime?: number;
}
/**
* Options for the `download` method of the chat module.
*/
export interface ChatDownloadOptions {
preview?: string;
noStream?: boolean;
}
/**
* Options for the methods in the chat module that listen for new messages.
* Local messages are ones sent by your device. Including them in the output is
* useful for applications such as logging conversations, monitoring own flips
* and building tools that seamlessly integrate with a running client used by
* the user. If onNewConvo is set, it will be called when the bot is added to a new conversation.
*/
export interface ListenOptions {
hideExploding: boolean;
showLocal: boolean;
}
export interface Advertisement {
alias?: string;
advertisements: chat1.AdvertiseCommandAPIParam[];
}
export interface AdvertisementsLookup {
channel: chat1.ChatChannel;
conversationID?: string;
}
export interface ReadResult {
messages: chat1.MsgSummary[];
pagination: chat1.Pagination;
}
/** The chat module of your Keybase bot. For more info about the API this module uses, you may want to check out `keybase chat api`. */
declare class Chat extends ClientBase {
/**
* Lists your chats, with info on which ones have unread messages.
* @memberof Chat
* @param options - An object of options that can be passed to the method.
* @returns - An array of chat conversations. If there are no conversations, the array is empty.
* @example
* const chatConversations = await bot.chat.list({unreadOnly: true})
* console.log(chatConversations)
*/
list(options?: ChatListOptions): Promise<chat1.ConvSummary[]>;
/**
* Lists conversation channels in a team
* @memberof Chat
* @param name - Name of the team
* @param options - An object of options that can be passed to the method.
* @returns - An array of chat conversations. If there are no conversations, the array is empty.
* @example
* bot.chat.listChannels('team_name').then(chatConversations => console.log(chatConversations))
*/
listChannels(name: string, options?: ChatListChannelsOptions): Promise<chat1.ConvSummary[]>;
private getChannelOrConversationId;
/**
* Reads the messages in a channel. You can read with or without marking as read.
* @memberof Chat
* @param channel - The chat channel to read messages in.
* @param options - An object of options that can be passed to the method.
* @returns - A summary of data about a message, including who send it, when, the content of the message, etc. If there are no messages in your channel, then an error is thrown.
* @example
* alice.chat.read(channel).then(messages => console.log(messages))
*/
read(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, options?: ChatReadOptions): Promise<ReadResult>;
/**
* Joins a team conversation.
* @param channel - The team chat channel to join.
* @example
* bot.chat.listConvsOnName('team_name').then(async teamConversations => {
* for (const conversation of teamConversations) {
* if (conversation.memberStatus !== 'active') {
* await bot.chat.join(conversation.channel)
* console.log('Joined team channel', conversation.channel)
* }
* }
* })
*/
joinChannel(channel: chat1.ChatChannel): Promise<void>;
/**
* Leaves a team conversation.
* @param channel - The team chat channel to leave.
* @example
* bot.chat.listConvsOnName('team_name').then(async teamConversations => {
* for (const conversation of teamConversations) {
* if (conversation.memberStatus === 'active') {
* await bot.chat.leave(conversation.channel)
* console.log('Left team channel', conversation.channel)
* }
* }
* })
*/
leaveChannel(channel: chat1.ChatChannel): Promise<void>;
/**
* Send a message to a certain channel.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param message - The chat message to send.
* @example
* const channel = {name: 'kbot,' + bot.myInfo().username, public: false, topicType: 'chat'}
* const message = {body: 'Hello kbot!'}
* bot.chat.send(channel, message).then(() => console.log('message sent!'))
*/
send(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, message: chat1.ChatMessage, options?: ChatSendOptions): Promise<chat1.SendRes>;
/**
* Creates a new blank conversation.
* @memberof Chat
* @param channel - The chat channel to create.
* @example
* bot.chat.createChannel(channel).then(() => console.log('conversation created'))
*/
createChannel(channel: chat1.ChatChannel): Promise<void>;
/**
* Send a file to a channel.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param filename - The absolute path of the file to send.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.attach(channel, '/Users/nathan/my_picture.png').then(() => console.log('Sent a picture!'))
*/
attach(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, filename: string, options?: ChatAttachOptions): Promise<chat1.SendRes>;
/**
* Download a file send via Keybase chat.
* @memberof Chat
* @param channel - The chat channel that the desired attacment to download is in.
* @param messageId - The message id of the attached file.
* @param output - The absolute path of where the file should be downloaded to.
* @param options - An object of options that can be passed to the method
* @example
* bot.chat.download(channel, 325, '/Users/nathan/Downloads/file.png')
*/
download(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, messageId: number, output: string, options?: ChatDownloadOptions): Promise<void>;
/**
* Reacts to a given message in a channel. Messages have messageId's associated with
* them, which you can learn in `bot.chat.read`.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param messageId - The id of the message to react to.
* @param reaction - The reaction emoji, in colon form.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.react(channel, 314, ':+1:').then(() => console.log('Thumbs up!'))
*/
react(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, messageId: number, reaction: string): Promise<chat1.SendRes>;
/**
* Deletes a message in a channel. Messages have messageId's associated with
* them, which you can learn in `bot.chat.read`. Known bug: the GUI has a cache,
* and deleting from the CLI may not become apparent immediately.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param messageId - The id of the message to delete.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.delete(channel, 314).then(() => console.log('message deleted!'))
*/
delete(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, messageId: number): Promise<void>;
/**
* Gets current unfurling settings
* @example
* bot.chat.getUnfurlSettings().then((mode) => console.log(mode))
*/
getUnfurlSettings(): Promise<chat1.UnfurlSettings>;
/**
* Sets the unfurling mode
* In Keybase, unfurling means generating previews for links that you're sending
* in chat messages. If the mode is set to always or the domain in the URL is
* present on the whitelist, the Keybase service will automatically send a preview
* to the message recipient in a background chat channel.
* @param mode - the new unfurl mode
* @example
* bot.chat.setUnfurlMode({
* "mode": "always",
* }).then((mode) => console.log('mode updated!'))
*/
setUnfurlSettings(mode: chat1.UnfurlSettings): Promise<void>;
/**
* Gets device information for a given username.
* This method allows you to see device name, description, type (desktop
* or mobile), and creation time for all active devices of a given username.
* @param username - the Keybase username to get devices for
* @example
* bot.chat.getDeviceInfo(username).then((devices) => console.log(devices))
*/
getDeviceInfo(username: string): Promise<chat1.GetDeviceInfoRes>;
/**
* Loads a flip's details
* @param conversationID - conversation ID received in API listen.
* @param flipConversationID - flipConvID from the message summary.
* @param messageID - ID of the message in the conversation.
* @param gameID - gameID from the flip message contents.
* @example
* // check demos/es7/poker-hands.js
*/
loadFlip(conversationID: string, flipConversationID: string, messageID: number, gameID: string): Promise<chat1.UICoinFlipStatus>;
/**
* Publishes a commands advertisement which is shown in the "!" chat autocomplete.
* @param advertisement - details of the advertisement
* @example
* await bot.chat.advertiseCommands({
* advertisements: [
* {
* type: 'public',
* commands: [
* {
* name: '!echo',
* description: 'Sends out your message to the current channel.',
* usage: '[your text]',
* },
* ]
* }
* ],
* })
*/
advertiseCommands(advertisement: Advertisement): Promise<void>;
/**
* Clears all published commands advertisements.
* @param advertisement - advertisement parameters
* @example
* await bot.chat.clearCommands()
*/
clearCommands(): Promise<void>;
/**
* Let's a conversation partner back in after they've reset their account. You can
* get a list of such candidates with getResetConvMembers()
* @param username - the username of the user who has reset
* @param conversationId
* @example
* await bot.chat.addResetConvMember({username: "chris", conversationId: "abc1234567"})
*/
addResetConvMember(param: chat1.ResetConvMemberAPI): Promise<chat1.GetResetConvMembersRes>;
/**
* Lists all the direct (non-team) conversations your bot has, in
* which their partner has "reset" their account and needs to be let back in
* @example
* await bot.chat.getResetConvMembers()
*/
getResetConvMembers(): Promise<chat1.GetResetConvMembersRes>;
/**
* Lists all commands advertised in a channel.
* @param lookup - either conversation id or channel
* @example
* const commandsList = await bot.chat.listCommands({
* channel: channel,
* })
* console.log(commandsList)
* // prints out something like:
* // {
* // commands: [
* // {
* // name: '!helloworld',
* // description: 'sample description',
* // usage: '[command arguments]',
* // username: 'userwhopublished',
* // }
* // ]
* // }
*/
listCommands(lookup: AdvertisementsLookup): Promise<{
commands: chat1.UserBotCommandOutput[];
}>;
/**
* Listens for new chat messages on a specified channel. The `onMessage` function is called for every message your bot receives. This is pretty similar to `watchAllChannelsForNewMessages`, except it specifically checks one channel. Note that it receives messages your own bot posts, but from other devices. You can filter out your own messages by looking at a message's sender object.
* Hides exploding messages by default.
* @memberof Chat
* @param channel - The chat channel to watch.
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param options - Options for the listen method.
* @example
* // Reply to all messages between you and `kbot` with 'thanks!'
* const channel = {name: 'kbot,' + bot.myInfo().username, public: false, topicType: 'chat'}
* const onMessage = message => {
* const channel = message.channel
* bot.chat.send(channel, {body: 'thanks!!!'})
* }
* bot.chat.watchChannelForNewMessages(channel, onMessage)
*/
watchChannelForNewMessages(channel: chat1.ChatChannel, onMessage: OnMessage, onError?: OnError, options?: ListenOptions): Promise<void>;
/**
* This function will put your bot into full-read mode, where it reads
* everything it can and every new message it finds it will pass to you, so
* you can do what you want with it. For example, if you want to write a
* Keybase bot that talks shit at anyone who dares approach it, this is the
* function to use. Note that it receives messages your own bot posts, but from other devices.
* You can filter out your own messages by looking at a message's sender object.
* Hides exploding messages by default.
* @memberof Chat
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param options - Options for the listen method.
* @example
* // Reply to incoming traffic on all channels with 'thanks!'
* const onMessage = message => {
* const channel = message.channel
* bot.chat.send(channel, {body: 'thanks!!!'})
* }
* bot.chat.watchAllChannelsForNewMessages(onMessage)
*
*/
watchAllChannelsForNewMessages(onMessage: OnMessage, onError?: OnError, options?: ListenOptions): Promise<void>;
/**
* This function watches for new conversations your bot is added into. This gives your bot a chance to say hi when it's added/installed into a conversation.
* @param onConv - A callback that is triggered when the bot is added into a conversation.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @example
* // Say hi
* const onConv = conv => {
* const channel = conv.channel
* bot.chat.send(channel, {body: 'Hi!'})
* }
* bot.chat.watchForNewConversation(onConv)
*
*/
watchForNewConversation(onConv: OnConv, onError?: OnError): Promise<void>;
private _spawnChatListenChild;
private _getChatListenArgs;
/**
* Spawns the chat listen process and handles the calling of onMessage, onError, and filtering for a specific channel.
* @memberof Chat
* @ignore
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param channel - The chat channel to watch.
* @param options - Options for the listen method.
* @example
* this._chatListenMessage(onMessage, onError)
*/
private _chatListenMessage;
/**
* Spawns the chat listen process for new channels and handles the calling of onConv, and onError.
* @memberof Chat
* @ignore
* @param onConv - A callback that is triggered on every new channel your bot is added to.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @example
* this._chatListenConvs(onConv, onError)
*/
private _chatListenConvs;
}
export default Chat; | the_stack |
import test from 'tape-promise/tape';
import {fixture} from 'test/setup';
import GL from '@luma.gl/constants';
import {isWebGL2} from '@luma.gl/gltools';
import {Buffer, Texture2D, getKey, readPixelsToArray} from '@luma.gl/gltools';
type WebGLTextureInfo = {
dataFormat: number;
types: number[];
gl2?: boolean;
gl1?: boolean | string;
compressed?: boolean;
}
const WEBGL_TEXTURE_FORMATS: Record<string, WebGLTextureInfo> = {
// Unsized texture format - more performance
[GL.RGB]: {dataFormat: GL.RGB, types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_5_6_5]},
// TODO: format: GL.RGBA type: GL.FLOAT is supported in WebGL1 when 'OES_texure_float' is suported
// we need to update this table structure to specify extensions (gl1ext: 'OES_texure_float', gl2ext: false) for each type.
[GL.RGBA]: {
dataFormat: GL.RGBA,
types: [GL.UNSIGNED_BYTE, GL.UNSIGNED_SHORT_4_4_4_4, GL.UNSIGNED_SHORT_5_5_5_1]
},
// 32 bit floats
// [GL.R32F]: {dataFormat: GL.RED, types: [GL.FLOAT], gl2: true},
// [GL.RG32F]: {dataFormat: GL.RG, types: [GL.FLOAT], gl2: true},
// [GL.RGB32F]: {dataFormat: GL.RGB, types: [GL.FLOAT], gl2: true},
// [GL.RGBA32F]: {dataFormat: GL.RGBA, types: [GL.FLOAT], gl2: true}
};
export const SAMPLER_PARAMETERS = {
[GL.TEXTURE_MIN_FILTER]: {
[GL.LINEAR]: 'interpolated texel',
[GL.NEAREST]: 'nearest texel',
[GL.NEAREST_MIPMAP_NEAREST]: 'nearest texel in closest mipmap',
[GL.LINEAR_MIPMAP_NEAREST]: 'interpolated texel in closest mipmap',
[GL.NEAREST_MIPMAP_LINEAR]: 'average texel from two closest mipmaps',
[GL.LINEAR_MIPMAP_LINEAR]: 'interpolated texel from two closest mipmaps'
},
[GL.TEXTURE_MAG_FILTER]: {
[GL.LINEAR]: 'interpolated texel',
[GL.NEAREST]: 'nearest texel'
},
[GL.TEXTURE_WRAP_S]: {
[GL.REPEAT]: 'use fractional part of texture coordinates',
[GL.CLAMP_TO_EDGE]: 'clamp texture coordinates',
[GL.MIRRORED_REPEAT]:
'use fractional part of texture coordinate if integer part is odd, otherwise `1 - frac'
},
[GL.TEXTURE_WRAP_T]: {
[GL.REPEAT]: 'use fractional part of texture coordinates',
[GL.CLAMP_TO_EDGE]: 'clamp texture coordinates',
[GL.MIRRORED_REPEAT]:
'use fractional part of texture coordinate if integer part is odd, otherwise `1 - frac'
}
};
export const SAMPLER_PARAMETERS_WEBGL2 = {
[GL.TEXTURE_WRAP_R]: {
[GL.REPEAT]: 'use fractional part of texture coordinates',
[GL.CLAMP_TO_EDGE]: 'clamp texture coordinates',
[GL.MIRRORED_REPEAT]:
'use fractional part of texture coordinate if integer part is odd, otherwise `1 - frac'
},
[GL.TEXTURE_COMPARE_MODE]: {
[GL.NONE]: 'no comparison of `r` coordinate is performed',
[GL.COMPARE_REF_TO_TEXTURE]:
'interpolated and clamped `r` texture coordinate is compared to currently bound depth texture, result is assigned to the red channel'
},
[GL.TEXTURE_COMPARE_FUNC]: {
[GL.LEQUAL]: 'result = 1.0 0.0, r <= D t r > D t',
[GL.GEQUAL]: 'result = 1.0 0.0, r >= D t r < D t',
[GL.LESS]: 'result = 1.0 0.0, r < D t r >= D t',
[GL.GREATER]: 'result = 1.0 0.0, r > D t r <= D t',
[GL.EQUAL]: 'result = 1.0 0.0, r = D t r ≠ D t',
[GL.NOTEQUAL]: 'result = 1.0 0.0, r ≠ D t r = D t',
[GL.ALWAYS]: 'result = 1.0',
[GL.NEVER]: 'result = 0.0'
}
};
test('WebGL#Texture2D construct/delete', (t) => {
const {gl} = fixture;
t.throws(
// @ts-expect-error
() => new Texture2D(),
/.*WebGLRenderingContext.*/,
'Texture2D throws on missing gl context'
);
const texture = new Texture2D(gl);
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
t.comment(JSON.stringify(texture.getParameters({keys: true})));
texture.delete();
t.ok(texture instanceof Texture2D, 'Texture2D delete successful');
texture.delete();
t.ok(texture instanceof Texture2D, 'Texture2D repeated delete successful');
t.end();
});
function isFormatSupported(format, glContext) {
format = Number(format);
const opts = Object.assign({format}, WEBGL_TEXTURE_FORMATS[format]);
if (!Texture2D.isSupported(glContext, {format}) || (!isWebGL2(glContext) && opts.compressed)) {
return false;
}
return true;
}
test('WebGL#Texture2D check formats', (t) => {
const {gl, gl2} = fixture;
const WEBGL1_FORMATS = [GL.RGB, GL.RGBA];
const WEBGL2_FORMATS = [GL.R32F, GL.RG32F, GL.RGB32F, GL.RGBA32F];
let unSupportedFormats = [];
WEBGL1_FORMATS.forEach((format) => {
if (!isFormatSupported(format, gl)) {
unSupportedFormats.push(format);
}
});
t.deepEqual(unSupportedFormats, [], 'All WebGL1 formats are supported');
if (gl2) {
const gl2Formats = WEBGL1_FORMATS.concat(WEBGL2_FORMATS);
unSupportedFormats = [];
gl2Formats.forEach((format) => {
if (!isFormatSupported(format, gl2)) {
unSupportedFormats.push(format);
}
});
t.deepEqual(unSupportedFormats, [], 'All WebGL2 formats are supported');
} else {
t.comment('WebGL2 not available, skipping tests');
}
t.end();
});
const DEFAULT_TEXTURE_DATA = new Uint8Array([
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]);
const DATA = [1, 0.5, 0.25, 0.125];
const UINT8_DATA = new Uint8Array(DATA);
const UINT16_DATA = new Uint16Array(DATA);
const FLOAT_DATA = new Float32Array(DATA);
const TEXTURE_DATA = {
[GL.UNSIGNED_BYTE]: UINT8_DATA, // RGB_TO[GL.UNSIGNED_BYTE](DATA)),
[GL.UNSIGNED_SHORT_5_6_5]: UINT16_DATA, // RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA))
[GL.UNSIGNED_SHORT_4_4_4_4]: UINT16_DATA, // RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA))
[GL.UNSIGNED_SHORT_5_5_5_1]: UINT16_DATA, // RGB_TO[GL.UNSIGNED_SHORT_5_6_5](DATA))
[GL.FLOAT]: FLOAT_DATA
};
// const RGB_TO = {
// [GL.UNSIGNED_BYTE]: (r, g, b) => [r * 256, g * 256, b * 256],
// [GL.UNSIGNED_SHORT_5_6_5]: (r, g, b) => r * 32 << 11 + g * 64 << 6 + b * 32
// };
// const RGB_FROM = {
// [GL.UNSIGNED_BYTE]: v => [v[0] / 256, v[1] / 256, v[2] / 256],
// [GL.UNSIGNED_SHORT_5_6_5]: v => [v >> 11 / 32, v >> 6 % 64 / 64, v % 32 * 32]
// };
function testFormatCreation(t, glContext, withData = false) {
for (const formatName in WEBGL_TEXTURE_FORMATS) {
const formatInfo = WEBGL_TEXTURE_FORMATS[formatName];
for (let type of formatInfo.types) {
const format = Number(formatName);
type = Number(type);
const data = withData ? TEXTURE_DATA[type] || DEFAULT_TEXTURE_DATA : null;
const options = Object.assign({}, formatInfo, {
data,
format,
type,
mipmaps: format !== GL.RGB32F, // TODO: for some reason mipmap generation failing for RGB32F format
width: 1,
height: 1
});
if (Texture2D.isSupported(glContext, {format})) {
const texture = new Texture2D(glContext, options);
t.ok(
texture,
`Texture2D({format: ${getKey(GL, texture.format)}, type: ${getKey(
GL,
type
)}, dataFormat: ${getKey(GL, options.dataFormat)}) created`
);
// t.equals(
// texture.format,
// format,
// `Texture2D({format: ${getKey(GL, format)}, type: ${getKey(
// GL,
// type
// )}, dataFormat: ${getKey(GL, options.dataFormat)}) created`
// );
texture.delete();
}
}
}
}
function testFormatDeduction(t, glContext) {
for (const format in WEBGL_TEXTURE_FORMATS) {
const formatInfo = WEBGL_TEXTURE_FORMATS[format];
const expectedType = formatInfo.types[0];
const expectedDataFormat = formatInfo.dataFormat;
const options = {
format: Number(format),
height: 1,
width: 1,
mipmaps: Number(format) !== GL.RGB32F
};
if (Texture2D.isSupported(glContext, {format: Number(format)})) {
const texture = new Texture2D(glContext, options);
const msg = `Texture2D({format: ${getKey(GL, format)}}) created`;
t.equals(texture.format, Number(format), msg);
t.equals(texture.type, expectedType, msg);
t.equals(texture.dataFormat, expectedDataFormat, msg);
texture.delete();
}
}
}
test('WebGL#Texture2D format deduction', (t) => {
const {gl, gl2} = fixture;
testFormatDeduction(t, gl);
if (gl2) {
testFormatDeduction(t, gl2);
} else {
t.comment('WebGL2 not available, skipping tests');
}
t.end();
});
test('WebGL#Texture2D format creation', (t) => {
const {gl, gl2} = fixture;
testFormatCreation(t, gl);
if (gl2) {
// testFormatCreation(t, gl2);
} else {
t.comment('WebGL2 not available, skipping tests');
}
t.end();
});
test('WebGL#Texture2D format creation with data', (t) => {
const {gl, gl2} = fixture;
if (gl2) {
testFormatCreation(t, gl2, true);
} else {
t.comment('WebGL2 not available, skipping tests');
}
testFormatCreation(t, gl, true);
t.end();
});
/*
test('WebGL#Texture2D WebGL1 extension format creation', t => {
const {gl} = fixture;
for (const format of WEBGL_TEXTURE_FORMATS) {
}
let texture = new Texture2D(gl, {});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
texture = texture.delete();
t.ok(texture instanceof Texture2D, 'Texture2D delete successful');
t.end();
});
test('WebGL#Texture2D WebGL2 format creation', t => {
const {gl} = fixture;
for (const format in WEBGL_TEXTURE_FORMATS) {
if (!WEBGL1_FORMATS.indexOf(format)) {
}
}
let texture = new Texture2D(gl, {});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
texture = texture.delete();
t.ok(texture instanceof Texture2D, 'Texture2D delete successful');
t.end();
});
*/
test('WebGL#Texture2D setParameters', (t) => {
const {gl} = fixture;
let texture = new Texture2D(gl, {});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
testSamplerParameters({t, texture, parameters: SAMPLER_PARAMETERS});
/*
// Bad tests
const parameter = GL.TEXTURE_MAG_FILTER;
const value = GL.LINEAR_MIPMAP_LINEAR;
texture.setParameters({
[parameter]: value
});
const newValue = texture.getParameter(GL.TEXTURE_MAG_FILTER);
t.equals(newValue, value,
`Texture2D.setParameters({[${getKey(GL, parameter)}]: ${getKey(GL, value)}})`);
*/
texture = texture.delete();
t.ok(texture instanceof Texture2D, 'Texture2D delete successful');
t.end();
});
test('WebGL2#Texture2D setParameters', (t) => {
const {gl2} = fixture;
if (!gl2) {
t.comment('WebGL2 not available, skipping tests');
t.end();
return;
}
let texture = new Texture2D(gl2, {});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
testSamplerParameters({t, texture, parameters: SAMPLER_PARAMETERS_WEBGL2});
texture = texture.delete();
t.ok(texture instanceof Texture2D, 'Texture2D delete successful');
t.end();
});
test('WebGL#Texture2D NPOT Workaround: texture creation', (t) => {
const {gl} = fixture;
// Create NPOT texture with no parameters
let texture = new Texture2D(gl, {data: null, width: 500, height: 512});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
// Default parameters should be changed to supported NPOT parameters.
let minFilter = texture.getParameter(GL.TEXTURE_MIN_FILTER);
t.equals(minFilter, GL.LINEAR, 'NPOT texture min filter is set to LINEAR');
let wrapS = texture.getParameter(GL.TEXTURE_WRAP_S);
t.equals(wrapS, GL.CLAMP_TO_EDGE, 'NPOT texture wrap_s is set to CLAMP_TO_EDGE');
let wrapT = texture.getParameter(GL.TEXTURE_WRAP_T);
t.equals(wrapT, GL.CLAMP_TO_EDGE, 'NPOT texture wrap_t is set to CLAMP_TO_EDGE');
const parameters = {
[GL.TEXTURE_MIN_FILTER]: GL.NEAREST,
[GL.TEXTURE_WRAP_S]: GL.REPEAT,
[GL.TEXTURE_WRAP_T]: GL.MIRRORED_REPEAT
};
// Create NPOT texture with parameters
texture = new Texture2D(gl, {
data: null,
width: 512,
height: 600,
parameters
});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
// Above parameters should be changed to supported NPOT parameters.
minFilter = texture.getParameter(GL.TEXTURE_MIN_FILTER);
t.equals(minFilter, GL.NEAREST, 'NPOT texture min filter is set to NEAREST');
wrapS = texture.getParameter(GL.TEXTURE_WRAP_S);
t.equals(wrapS, GL.CLAMP_TO_EDGE, 'NPOT texture wrap_s is set to CLAMP_TO_EDGE');
wrapT = texture.getParameter(GL.TEXTURE_WRAP_T);
t.equals(wrapT, GL.CLAMP_TO_EDGE, 'NPOT texture wrap_t is set to CLAMP_TO_EDGE');
t.end();
});
test('WebGL#Texture2D NPOT Workaround: setParameters', (t) => {
const {gl} = fixture;
// Create NPOT texture
const texture = new Texture2D(gl, {data: null, width: 100, height: 100});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
const invalidNPOTParameters = {
[GL.TEXTURE_MIN_FILTER]: GL.LINEAR_MIPMAP_NEAREST,
[GL.TEXTURE_WRAP_S]: GL.MIRRORED_REPEAT,
[GL.TEXTURE_WRAP_T]: GL.REPEAT
};
texture.setParameters(invalidNPOTParameters);
// Above parameters should be changed to supported NPOT parameters.
const minFilter = texture.getParameter(GL.TEXTURE_MIN_FILTER);
t.equals(minFilter, GL.LINEAR, 'NPOT texture min filter is set to LINEAR');
const wrapS = texture.getParameter(GL.TEXTURE_WRAP_S);
t.equals(wrapS, GL.CLAMP_TO_EDGE, 'NPOT texture wrap_s is set to CLAMP_TO_EDGE');
const wrapT = texture.getParameter(GL.TEXTURE_WRAP_T);
t.equals(wrapT, GL.CLAMP_TO_EDGE, 'NPOT texture wrap_t is set to CLAMP_TO_EDGE');
t.end();
});
test('WebGL2#Texture2D NPOT Workaround: texture creation', (t) => {
// WebGL2 supports NPOT texture hence, texture parameters should not be changed.
const {gl2} = fixture;
if (!gl2) {
t.comment('WebGL2 not available, skipping tests');
t.end();
return;
}
// Create NPOT texture with no parameters
let texture = new Texture2D(gl2, {data: null, width: 500, height: 512});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
// Default values are un-changed.
let minFilter = texture.getParameter(GL.TEXTURE_MIN_FILTER);
t.equals(
minFilter,
GL.NEAREST_MIPMAP_LINEAR,
'NPOT texture min filter is set to NEAREST_MIPMAP_LINEAR'
);
let wrapS = texture.getParameter(GL.TEXTURE_WRAP_S);
t.equals(wrapS, GL.REPEAT, 'NPOT texture wrap_s is set to REPEAT');
let wrapT = texture.getParameter(GL.TEXTURE_WRAP_T);
t.equals(wrapT, GL.REPEAT, 'NPOT texture wrap_t is set to REPEAT');
const parameters = {
[GL.TEXTURE_MIN_FILTER]: GL.NEAREST,
[GL.TEXTURE_WRAP_S]: GL.REPEAT,
[GL.TEXTURE_WRAP_T]: GL.MIRRORED_REPEAT
};
// Create NPOT texture with parameters
texture = new Texture2D(gl2, {
data: null,
width: 512,
height: 600,
parameters
});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
minFilter = texture.getParameter(GL.TEXTURE_MIN_FILTER);
t.equals(minFilter, GL.NEAREST, 'NPOT texture min filter is set to NEAREST');
wrapS = texture.getParameter(GL.TEXTURE_WRAP_S);
t.equals(wrapS, GL.REPEAT, 'NPOT texture wrap_s is set to REPEAT');
wrapT = texture.getParameter(GL.TEXTURE_WRAP_T);
t.equals(wrapT, GL.MIRRORED_REPEAT, 'NPOT texture wrap_t is set to MIRRORED_REPEAT');
t.end();
});
test('WebGL2#Texture2D NPOT Workaround: setParameters', (t) => {
const {gl2} = fixture;
if (!gl2) {
t.comment('WebGL2 not available, skipping tests');
t.end();
return;
}
// Create NPOT texture
const texture = new Texture2D(gl2, {data: null, width: 100, height: 100});
t.ok(texture instanceof Texture2D, 'Texture2D construction successful');
const invalidNPOTParameters = {
[GL.TEXTURE_MIN_FILTER]: GL.LINEAR_MIPMAP_NEAREST,
[GL.TEXTURE_WRAP_S]: GL.MIRRORED_REPEAT,
[GL.TEXTURE_WRAP_T]: GL.REPEAT
};
texture.setParameters(invalidNPOTParameters);
// Above parameters are not changed for NPOT texture when using WebGL2 context.
const minFilter = texture.getParameter(GL.TEXTURE_MIN_FILTER);
t.equals(
minFilter,
GL.LINEAR_MIPMAP_NEAREST,
'NPOT texture min filter is set to LINEAR_MIPMAP_NEAREST'
);
const wrapS = texture.getParameter(GL.TEXTURE_WRAP_S);
t.equals(wrapS, GL.MIRRORED_REPEAT, 'NPOT texture wrap_s is set to MIRRORED_REPEAT');
const wrapT = texture.getParameter(GL.TEXTURE_WRAP_T);
t.equals(wrapT, GL.REPEAT, 'NPOT texture wrap_t is set to REPEAT');
t.end();
});
test('WebGL1#Texture2D setImageData', (t) => {
const {gl} = fixture;
// data: null
const texture = new Texture2D(gl, {data: null, width: 2, height: 1, mipmaps: false});
t.deepEquals(readPixelsToArray(texture), new Float32Array(8), 'Pixels are empty');
// data: typed array
const data = new Uint8Array([0, 1, 2, 3, 128, 201, 255, 255]);
texture.setImageData({data});
t.deepEquals(readPixelsToArray(texture), data, 'Pixels are set correctly');
// data: canvas
if (typeof document !== 'undefined') {
const canvas = document.createElement('canvas');
canvas.width = 2;
canvas.height = 1;
const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, 2, 1);
imageData.data[2] = 128;
imageData.data[3] = 255;
imageData.data[7] = 1;
ctx.putImageData(imageData, 0, 0);
texture.setImageData({data: canvas});
t.deepEquals(
readPixelsToArray(texture),
new Uint8Array([0, 0, 128, 255, 0, 0, 0, 1]),
'Pixels are set correctly'
);
}
t.end();
});
test('WebGL2#Texture2D setImageData', (t) => {
const {gl2} = fixture;
if (!gl2) {
t.comment('WebGL2 not available, skipping tests');
t.end();
return;
}
let data;
// data: null
const texture = new Texture2D(gl2, {
data: null,
width: 2,
height: 1,
format: GL.RGBA32F,
type: GL.FLOAT,
mipmaps: false
});
t.deepEquals(readPixelsToArray(texture), new Float32Array(8), 'Pixels are empty');
// data: typed array
data = new Float32Array([0.1, 0.2, -3, -2, 0, 0.5, 128, 255]);
texture.setImageData({data});
t.deepEquals(readPixelsToArray(texture), data, 'Pixels are set correctly');
// data: buffer
data = new Float32Array([21, 0.82, 0, 1, 0, 255, 128, 3.333]);
const buffer = new Buffer(gl2, {data, accessor: {size: 4, type: GL.FLOAT}});
texture.setImageData({data: buffer});
t.deepEquals(readPixelsToArray(texture), data, 'Pixels are set correctly');
// data: canvas
if (typeof document !== 'undefined') {
const canvas = document.createElement('canvas');
canvas.width = 2;
canvas.height = 1;
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 2, 1);
texture.setImageData({data: canvas});
t.deepEquals(
readPixelsToArray(texture),
new Float32Array([0, 0, 0, 1, 0, 0, 0, 1]),
'Pixels are set correctly'
);
}
t.end();
});
test('WebGL1#Texture2D setSubImageData', (t) => {
const {gl} = fixture;
// data: null
const texture = new Texture2D(gl, {data: null, width: 2, height: 1, mipmaps: false});
t.deepEquals(readPixelsToArray(texture), new Uint8Array(8), 'Pixels are empty');
// data: typed array
const data = new Uint8Array([1, 2, 3, 4]);
texture.setSubImageData({data, x: 0, y: 0, width: 1, height: 1});
t.deepEquals(
readPixelsToArray(texture),
new Uint8Array([1, 2, 3, 4, 0, 0, 0, 0]),
'Pixels are set correctly'
);
// data: canvas
if (typeof document !== 'undefined') {
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 1, 1);
texture.setSubImageData({data: canvas, x: 1, y: 0, width: 1, height: 1});
t.deepEquals(
readPixelsToArray(texture),
new Uint8Array([1, 2, 3, 4, 0, 0, 0, 255]),
'Pixels are set correctly'
);
}
t.end();
});
test('WebGL2#Texture2D setSubImageData', (t) => {
const {gl2} = fixture;
if (!gl2) {
t.comment('WebGL2 not available, skipping tests');
t.end();
return;
}
let data;
// data: null
const texture = new Texture2D(gl2, {
data: null,
width: 2,
height: 1,
format: GL.RGBA32F,
type: GL.FLOAT,
mipmaps: false
});
t.deepEquals(readPixelsToArray(texture), new Float32Array(8), 'Pixels are empty');
// data: typed array
data = new Float32Array([0.1, 0.2, -3, -2]);
texture.setSubImageData({data, x: 0, y: 0, width: 1, height: 1});
t.deepEquals(
readPixelsToArray(texture),
new Float32Array([0.1, 0.2, -3, -2, 0, 0, 0, 0]),
'Pixels are set correctly'
);
// data: buffer
data = new Float32Array([-3, 255, 128, 3.333]);
const buffer = new Buffer(gl2, {data, accessor: {size: 4, type: GL.FLOAT}});
texture.setSubImageData({data: buffer, x: 1, y: 0, width: 1, height: 1});
t.deepEquals(
readPixelsToArray(texture),
new Float32Array([0.1, 0.2, -3, -2, -3, 255, 128, 3.333]),
'Pixels are set correctly'
);
// data: canvas
if (typeof document !== 'undefined') {
const canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = 1;
const ctx = canvas.getContext('2d');
ctx.fillRect(0, 0, 1, 1);
texture.setSubImageData({data: canvas, x: 1, y: 0, width: 1, height: 1});
t.deepEquals(
readPixelsToArray(texture),
new Float32Array([0.1, 0.2, -3, -2, 0, 0, 0, 1]),
'Pixels are set correctly'
);
}
t.end();
});
test('WebGL2#Texture2D resize', (t) => {
const {gl} = fixture;
let texture = new Texture2D(gl, {
data: null,
width: 2,
height: 2,
mipmaps: true
});
texture.resize({
width: 4,
height: 4,
mipmaps: true
});
t.ok(texture.mipmaps, 'mipmaps should set to true for POT.');
texture.resize({
width: 3,
height: 3,
mipmaps: true
});
t.notOk(texture.mipmaps, 'mipmaps should set to false when resizing to NPOT.');
texture = new Texture2D(gl, {
data: null,
width: 2,
height: 2,
mipmaps: true
});
texture.resize({
width: 4,
height: 4
});
t.notOk(texture.mipmaps, 'mipmaps should set to false when resizing.');
t.end();
});
test('WebGL2#Texture2D generateMipmap', (t) => {
const {gl} = fixture;
let texture = new Texture2D(gl, {
data: null,
width: 3,
height: 3,
mipmaps: false
});
texture.generateMipmap();
t.notOk(texture.mipmaps, 'Should not turn on mipmaps for NPOT.');
texture = new Texture2D(gl, {
data: null,
width: 2,
height: 2,
mipmaps: false
});
texture.generateMipmap();
t.ok(texture.mipmaps, 'Should turn on mipmaps for POT.');
t.end();
});
// Shared with texture*.spec.js
export function testSamplerParameters({t, texture, parameters}) {
for (const parameterName in parameters) {
const values = parameters[parameterName];
const parameter = Number(parameterName);
for (const valueName in values) {
const value = Number(valueName);
texture.setParameters({
[parameter]: value
});
const name = texture.constructor.name;
const newValue = texture.getParameter(parameter);
t.equals(
newValue,
value,
`${name}.setParameters({[${getKey(GL, parameter)}]: ${getKey(GL, value)}}) read back OK`
);
}
}
} | the_stack |
import { ParseTree } from "antlr4ts/tree/ParseTree";
export class DuplicateSymbolError extends Error { }
export enum MemberVisibility {
Invalid = -1,
Public = 0,
Protected,
Private,
Library,
}
export enum TypeKind {
Integer,
Float,
String,
Boolean,
Date,
Class,
Array,
Alias,
}
export enum ReferenceKind {
Irrelevant,
Pointer, // Default for most languages for dynamically allocated memory ("Type*" in C++).
Reference, // "Type&" in C++
Instance, // "Type" as such and default for all value types.
}
// The root type interface. Used for typed symbols and type aliases.
export interface Type {
name: string;
// The super type of this type or empty if this is a fundamental type.
// Also used as the target type for type aliases.
baseTypes: Type[];
kind: TypeKind;
reference: ReferenceKind;
}
export interface SymbolTableOptions {
allowDuplicateSymbols?: boolean;
}
// A single class for all fundamental types. They are distinguished via the kind field.
export class FundamentalType implements Type {
public static readonly integerType = new FundamentalType("int", TypeKind.Integer, ReferenceKind.Instance);
public static readonly floatType = new FundamentalType("float", TypeKind.Float, ReferenceKind.Instance);
public static readonly stringType = new FundamentalType("string", TypeKind.String, ReferenceKind.Instance);
public static readonly boolType = new FundamentalType("bool", TypeKind.Boolean, ReferenceKind.Instance);
public static readonly dateType = new FundamentalType("date", TypeKind.Date, ReferenceKind.Instance);
public name: string;
private typeKind: TypeKind;
private referenceKind: ReferenceKind;
public constructor(name: string, typeKind: TypeKind, referenceKind: ReferenceKind) {
this.name = name;
this.typeKind = typeKind;
this.referenceKind = referenceKind;
}
public get baseTypes(): Type[] {
return [];
}
public get kind(): TypeKind {
return this.typeKind;
}
public get reference(): ReferenceKind {
return this.referenceKind;
}
}
// The root of the symbol table class hierarchy: a symbol can be any manageable entity (like a block), not only
// things like variables or classes.
// We are using a class hierarchy here, instead of an enum or similar, to allow for easy extension and certain
// symbols can so provide additional APIs for simpler access to their sub elements, if needed.
export class Symbol {
public name = ""; // The name of the scope or empty if anonymous.
public context?: ParseTree; // Reference to the parse tree which contains this symbol.
private theParent?: Symbol;
public constructor(name = "") {
this.name = name;
}
/**
* The parent is usually a scoped symbol as only those can have children, but we allow
* any symbol here for special scenarios.
* This is rather an internal method and should rarely be used by external code.
*
* @param parent The new parent to use.
*/
public setParent(parent: Symbol | undefined): void {
this.theParent = parent;
}
public get parent(): Symbol | undefined {
return this.theParent;
}
public get firstSibling(): Symbol {
if (this.theParent instanceof ScopedSymbol) {
return this.theParent.firstChild!;
}
return this;
}
/**
* @returns the symbol before this symbol in its scope.
*/
public get previousSibling(): Symbol | undefined {
if (!(this.theParent instanceof ScopedSymbol)) {
return this;
}
return this.theParent.previousSiblingOf(this);
}
/**
* @returns the symbol following this symbol in its scope.
*/
public get nextSibling(): Symbol | undefined {
if (!(this.theParent instanceof ScopedSymbol)) {
return this;
}
return this.theParent.nextSiblingOf(this);
}
public get lastSibling(): Symbol {
if (this.theParent instanceof ScopedSymbol) {
return this.theParent.lastChild!;
}
return this;
}
/**
* @returns the next symbol in definition order, regardless of the scope.
*/
public get next(): Symbol | undefined {
if (this.theParent instanceof ScopedSymbol) {
return this.theParent.nextOf(this);
}
return undefined;
}
public removeFromParent(): void {
if (this.theParent instanceof ScopedSymbol) {
this.theParent.removeSymbol(this);
this.theParent = undefined;
}
}
/**
*
* @param name The name of the symbol to find.
* @param localOnly If true only child symbols are returned, otherwise also symbols from the parent of this symbol
* (recursively).
* @returns the first symbol with a given name, in the order of appearance in this scope
* or any of the parent scopes (conditionally).
*/
public async resolve(name: string, localOnly = false): Promise<Symbol | undefined> {
if (this.theParent instanceof ScopedSymbol) {
return this.theParent.resolve(name, localOnly);
}
return Promise.resolve(undefined);
}
/**
* @returns the outermost entity (below the symbol table) that holds us.
*/
public get root(): Symbol | undefined {
let run = this.theParent;
while (run) {
if (!run.theParent || (run.theParent instanceof SymbolTable)) {
return run;
}
run = run.theParent;
}
return run;
}
/**
* @returns the symbol table we belong too or undefined if we are not yet assigned.
*/
public get symbolTable(): SymbolTable | undefined {
if (this instanceof SymbolTable) {
return this;
}
let run = this.theParent;
while (run) {
if (run instanceof SymbolTable) { return run; }
run = run.theParent;
}
return undefined;
}
/**
* @param t The type of objects to return.
* @returns the next enclosing parent of the given type.
*/
public getParentOfType<T extends Symbol>(t: new (...args: any[]) => T): T | undefined {
let run = this.theParent;
while (run) {
if (run instanceof t) { return run; }
run = run.theParent;
}
return undefined;
}
/**
* @returns the list of symbols from this one up to root.
*/
public get symbolPath(): Symbol[] {
const result: Symbol[] = [];
// eslint-disable-next-line @typescript-eslint/no-this-alias
let run: Symbol = this;
while (run) {
result.push(run);
if (!run.theParent) { break; }
run = run.theParent;
}
return result;
}
/**
* Creates a qualified identifier from this symbol and its parent.
* If `full` is true then all parents are traversed in addition to this instance.
*
* @param separator The string to be used between the parts.
* @param full A flag indicating if the full path is to be returned.
* @param includeAnonymous Use a special string for empty scope names.
* @returns the constructed qualified identifier.
*/
public qualifiedName(separator = ".", full = false, includeAnonymous = false): string {
if (!includeAnonymous && this.name.length === 0) {
return "";
}
let result: string = this.name.length === 0 ? "<anonymous>" : this.name;
let run = this.theParent;
while (run) {
if (includeAnonymous || run.name.length > 0) {
result = (run.name.length === 0 ? "<anonymous>" : run.name) + separator + result;
}
if (!full || !run.theParent) {
break;
}
run = run.theParent;
}
return result;
}
}
// A symbol with an attached type (variables, fields etc.).
export class TypedSymbol extends Symbol {
public type: Type | undefined;
public constructor(name: string, type?: Type) {
super(name);
this.type = type;
}
}
// An alias for another type.
export class TypeAlias extends Symbol implements Type {
public get baseTypes(): Type[] { return [this.targetType]; }
public get kind(): TypeKind { return TypeKind.Alias; }
public get reference(): ReferenceKind { return ReferenceKind.Irrelevant; }
private targetType: Type;
public constructor(name: string, target: Type) {
super(name);
this.targetType = target;
}
}
// A symbol with a scope (so it can have child symbols).
export class ScopedSymbol extends Symbol {
private _children: Symbol[] = []; // All child symbols in definition order.
public constructor(name = "") {
super(name);
}
public get children(): Symbol[] {
// eslint-disable-next-line no-underscore-dangle
return this._children;
}
public clear(): void {
// eslint-disable-next-line no-underscore-dangle
this._children = [];
}
/**
* Adds the given symbol to this scope. If it belongs already to a different scope
* it is removed from that before adding it here.
*
* @param symbol The symbol to add as a child.
*/
public addSymbol(symbol: Symbol): void {
symbol.removeFromParent();
// Check for duplicates first.
const symbolTable = this.symbolTable;
if (!symbolTable || !symbolTable.options.allowDuplicateSymbols) {
this.children.forEach((child) => {
if (child === symbol || (symbol.name.length > 0 && child.name === symbol.name)) {
let name = symbol.name;
if (name.length === 0) {
name = "<anonymous>";
}
throw new DuplicateSymbolError("Attempt to add duplicate symbol '" + name + "'");
}
});
}
this.children.push(symbol);
symbol.setParent(this);
}
public removeSymbol(symbol: Symbol): void {
const index = this.children.indexOf(symbol);
if (index > -1) {
this.children.splice(index, 1);
symbol.setParent(undefined);
}
}
/**
* @param t The type of of the objects to return.
* @returns A promise resolving to all (nested) children of the given type.
*/
public async getNestedSymbolsOfType<T extends Symbol>(t: new (...args: any[]) => T): Promise<T[]> {
const result: T[] = [];
const childPromises: Array<Promise<T[]>> = [];
this.children.forEach((child) => {
if (child instanceof t) {
result.push(child);
}
if (child instanceof ScopedSymbol) {
childPromises.push(child.getNestedSymbolsOfType(t));
}
});
const childSymbols = await Promise.all(childPromises);
childSymbols.forEach((entry) => {
result.push(...entry);
});
return result;
}
/**
* @param name If given only returns symbols with that name.
* @returns A promise resolving to symbols from this and all nested scopes in the order they were defined.
*/
public async getAllNestedSymbols(name?: string): Promise<Symbol[]> {
const result: Symbol[] = [];
const childPromises: Array<Promise<Symbol[]>> = [];
this.children.forEach((child) => {
if (!name || child.name === name) {
result.push(child);
}
if (child instanceof ScopedSymbol) {
childPromises.push(child.getAllNestedSymbols(name));
}
});
const childSymbols = await Promise.all(childPromises);
childSymbols.forEach((entry) => {
result.push(...entry);
});
return result;
}
/**
* @param t The type of of the objects to return.
* @returns A promise resolving to direct children of a given type.
*/
public getSymbolsOfType<T extends Symbol>(t: new (...args: any[]) => T): Promise<T[]> {
return new Promise((resolve) => {
const result: T[] = [];
this.children.forEach((child) => {
if (child instanceof t) {
result.push(child);
}
});
resolve(result);
});
}
/**
* TODO: add optional position dependency (only symbols defined before a given caret pos are viable).
*
* @param t The type of the objects to return.
* @param localOnly If true only child symbols are returned, otherwise also symbols from the parent of this symbol
* (recursively).
* @returns A promise resolving to all symbols of the the given type, accessible from this scope (if localOnly is
* false), within the owning symbol table.
*/
public async getAllSymbols<T extends Symbol>(t: new (...args: any[]) => T,
localOnly = false): Promise<T[]> {
const result: T[] = [];
// Special handling for namespaces, which act like grouping symbols in this scope,
// so we show them as available in this scope.
for (const child of this.children) {
if (child instanceof t) {
result.push(child);
}
if (child instanceof NamespaceSymbol) {
const childSymbols = await child.getAllSymbols(t, true);
result.push(...childSymbols);
}
}
if (!localOnly) {
if (this.parent instanceof ScopedSymbol) {
const childSymbols = await this.getAllSymbols(t, true);
result.push(...childSymbols);
}
}
return result;
}
/**
* @param name The name of the symbol to resolve.
* @param localOnly If true only child symbols are returned, otherwise also symbols from the parent of this symbol
* (recursively).
* @returns the first symbol with a given name, in the order of appearance in this scope
* or any of the parent scopes (conditionally).
*/
public async resolve(name: string, localOnly = false): Promise<Symbol | undefined> {
return new Promise((resolve, reject) => {
for (const child of this.children) {
if (child.name === name) {
resolve(child);
return;
}
}
// Nothing found locally. Let the parent continue.
if (!localOnly) {
if (this.parent instanceof ScopedSymbol) {
resolve(this.parent.resolve(name, false));
return;
}
}
resolve(undefined);
});
}
/**
* @param localOnly If true only child symbols are returned, otherwise also symbols from the parent of this symbol
* (recursively).
* @returns all accessible symbols that have a type assigned.
*/
public getTypedSymbols(localOnly = true): TypedSymbol[] {
const result: TypedSymbol[] = [];
for (const child of this.children) {
if (child instanceof TypedSymbol) {
result.push(child);
}
}
if (!localOnly) {
if (this.parent instanceof ScopedSymbol) {
const localList = this.parent.getTypedSymbols(true);
result.push(...localList);
}
}
return result;
}
/**
* The names of all accessible symbols with a type.
*
* @param localOnly If true only child symbols are returned, otherwise also symbols from the parent of this symbol
* (recursively).
* @returns A list of names.
*/
public getTypedSymbolNames(localOnly = true): string[] {
const result: string[] = [];
for (const child of this.children) {
if (child instanceof TypedSymbol) {
result.push(child.name);
}
}
if (!localOnly) {
if (this.parent instanceof ScopedSymbol) {
const localList = (this.parent).getTypedSymbolNames(true);
result.push(...localList);
}
}
return result;
}
/**
* @returns A promise resolving to all direct child symbols with a scope (e.g. classes in a module).
*/
public get directScopes(): Promise<ScopedSymbol[]> {
return this.getSymbolsOfType(ScopedSymbol);
}
/**
* @returns the symbol located at the given path through the symbol hierarchy.
* @param path The path consisting of symbol names separator by `separator`.
* @param separator The character to separate path segments.
*/
public symbolFromPath(path: string, separator = "."): Symbol | undefined {
const elements = path.split(separator);
let index = 0;
if (elements[0] === this.name || elements[0].length === 0) {
++index;
}
// eslint-disable-next-line @typescript-eslint/no-this-alias
let result: Symbol = this;
while (index < elements.length) {
if (!(result instanceof ScopedSymbol)) {
return undefined;
}
// eslint-disable-next-line no-loop-func
const child = result.children.find((candidate) => candidate.name === elements[index]);
if (!child) {
return undefined;
}
result = child;
++index;
}
return result;
}
/**
* @param child The child to search for.
* @returns the index of the given child symbol in the child list or -1 if it couldn't be found.
*/
public indexOfChild(child: Symbol): number {
return this.children.findIndex((value: Symbol, index: number) => value === child);
}
/**
* @param child The reference node.
* @returns the sibling symbol after the given child symbol, if one exists.
*/
public nextSiblingOf(child: Symbol): Symbol | undefined {
const index = this.indexOfChild(child);
if (index === -1 || index >= this.children.length - 1) {
return;
}
return this.children[index + 1];
}
/**
* @param child The reference node.
* @returns the sibling symbol before the given child symbol, if one exists.
*/
public previousSiblingOf(child: Symbol): Symbol | undefined {
const index = this.indexOfChild(child);
if (index < 1) {
return;
}
return this.children[index - 1];
}
public get firstChild(): Symbol | undefined {
if (this.children.length > 0) {
return this.children[0];
}
return undefined;
}
public get lastChild(): Symbol | undefined {
if (this.children.length > 0) {
return this.children[this.children.length - 1];
}
return undefined;
}
/**
* @param child The reference node.
* @returns the next symbol in definition order, regardless of the scope.
*/
public nextOf(child: Symbol): Symbol | undefined {
if (!(child.parent instanceof ScopedSymbol)) {
return;
}
if (child.parent !== this) {
return child.parent.nextOf(child);
}
if (child instanceof ScopedSymbol && child.children.length > 0) {
return child.children[0];
}
const sibling = this.nextSiblingOf(child);
if (sibling) {
return sibling;
}
return (this.parent as ScopedSymbol).nextOf(this);
}
}
export class NamespaceSymbol extends ScopedSymbol {
}
export class BlockSymbol extends ScopedSymbol {
}
export class VariableSymbol extends TypedSymbol {
public value: any;
public constructor(name: string, value: any, type?: Type) {
super(name, type);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.value = value;
}
}
export class LiteralSymbol extends TypedSymbol {
public readonly value: any;
public constructor(name: string, value: any, type?: Type) {
super(name, type);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
this.value = value;
}
}
export class ParameterSymbol extends VariableSymbol { }
// A standalone function/procedure/rule.
export class RoutineSymbol extends ScopedSymbol {
private returnType?: Type; // Can be null if result is void.
public constructor(name: string, returnType: Type) {
super(name);
this.returnType = returnType;
}
public getVariables(localOnly = true): Promise<VariableSymbol[]> {
return this.getSymbolsOfType(VariableSymbol);
}
public getParameters(localOnly = true): Promise<ParameterSymbol[]> {
return this.getSymbolsOfType(ParameterSymbol);
}
}
export enum MethodFlags {
None = 0,
Virtual = 1,
Const = 2,
Overwritten = 4,
SetterOrGetter = 8, // Distinguished by the return type.
Explicit = 16, // Special flag used e.g. in C++ for explicit c-tors.
}
// A routine which belongs to a class or other outer container structure.
export class MethodSymbol extends RoutineSymbol {
public methodFlags = MethodFlags.None;
public visibility = MemberVisibility.Invalid;
}
export class FieldSymbol extends VariableSymbol {
public visibility = MemberVisibility.Invalid;
public setter?: MethodSymbol;
public getter?: MethodSymbol;
}
// Classes and structs.
export class ClassSymbol extends ScopedSymbol implements Type {
public get baseTypes(): Type[] { return this.superClasses; }
public get kind(): TypeKind { return TypeKind.Class; }
public get reference(): ReferenceKind { return this.referenceKind; }
public isStruct = false;
/**
* Usually only one member, unless the language supports multiple inheritance.
*/
public readonly superClasses: ClassSymbol[] = [];
private referenceKind: ReferenceKind;
public constructor(name: string, referenceKind: ReferenceKind, ...superClass: ClassSymbol[]) {
super(name);
this.referenceKind = referenceKind;
this.superClasses.push(...superClass); // Standard case: a single super class.
}
/**
* @param includeInherited Not used.
* @returns a list of all methods.
*/
public getMethods(includeInherited = false): Promise<MethodSymbol[]> {
return this.getSymbolsOfType(MethodSymbol);
}
/**
* @param includeInherited Not used.
* @returns all fields.
*/
public getFields(includeInherited = false): Promise<FieldSymbol[]> {
return this.getSymbolsOfType(FieldSymbol);
}
}
export class ArrayType extends Symbol implements Type {
public get baseTypes(): Type[] { return []; }
public get kind(): TypeKind { return TypeKind.Array; }
public get reference(): ReferenceKind { return this.referenceKind; }
public readonly elementType: Type;
public readonly size: number; // > 0 if fixed length.
private referenceKind: ReferenceKind;
public constructor(name: string, referenceKind: ReferenceKind, elemType: Type, size = 0) {
super(name);
this.referenceKind = referenceKind;
this.elementType = elemType;
this.size = size;
}
}
// The main class managing all the symbols for a top level entity like a file, library or similar.
export class SymbolTable extends ScopedSymbol {
// Other symbol information available to this instance.
protected dependencies: Set<SymbolTable> = new Set();
public constructor(name: string, public readonly options: SymbolTableOptions) {
super(name);
}
public clear() {
super.clear();
this.dependencies.clear();
}
public addDependencies(...tables: SymbolTable[]) {
tables.forEach((value, key) => {
this.dependencies.add(value);
});
}
public removeDependency(table: SymbolTable) {
if (this.dependencies.has(table)) {
this.dependencies.delete(table);
}
}
/**
* @returns instance information, mostly relevant for unit testing.
*/
public get info() {
return {
dependencyCount: this.dependencies.size,
symbolCount: this.children.length,
};
}
public addNewSymbolOfType<T extends Symbol>(t: new (...args: any[]) => T,
parent: ScopedSymbol | undefined, ...args: any[]): T {
const result = new t(...args);
if (!parent || parent === this) {
this.addSymbol(result);
} else {
parent.addSymbol(result);
}
return result;
}
/**
* Adds a new namespace to the symbol table or the given parent. The path parameter specifies a single namespace
* name or a chain of namespaces (which can be e.g. "outer.intermittent.inner.final").
* If any of the parent namespaces is missing they are created implicitly. The final part must not exist however
* or you'll get a duplicate symbol error.
*
* @param parent The parent to add the namespace to.
* @param path The namespace path.
* @param delimiter The delimiter used in the path.
* @returns The new symbol.
*/
public async addNewNamespaceFromPath(parent: ScopedSymbol | undefined, path: string,
delimiter = "."): Promise<NamespaceSymbol> {
const parts = path.split(delimiter);
let i = 0;
let currentParent = (parent === undefined) ? this : parent;
while (i < parts.length - 1) {
let namespace = await currentParent.resolve(parts[i], true) as NamespaceSymbol;
if (namespace === undefined) {
namespace = this.addNewSymbolOfType(NamespaceSymbol, currentParent, parts[i]);
}
currentParent = namespace;
++i;
}
return this.addNewSymbolOfType(NamespaceSymbol, currentParent, parts[parts.length - 1]);
}
public async getAllSymbols<T extends Symbol>(t: new (...args: any[]) => T, localOnly = false): Promise<T[]> {
const result: T[] = await super.getAllSymbols(t, localOnly);
if (!localOnly) {
const dependencyResults = await Promise.all([...this.dependencies].map((dependency) => (
dependency.getAllSymbols(t, localOnly)
)));
dependencyResults.forEach((value) => {
result.push(...value);
});
}
return result;
}
/**
* Looks for a symbol which is connected with a given parse tree context.
*
* @param context The context to search for.
* @returns A promise resolving to the found symbol or undefined.
*/
public async symbolWithContext(context: ParseTree): Promise<Symbol | undefined> {
/**
* Local function to find a symbol recursively.
*
* @param symbol The symbol to search through.
* @returns The symbol with the given context, if found.
*/
const findRecursive = (symbol: Symbol): Symbol | undefined => {
if (symbol.context === context) {
return symbol;
}
if (symbol instanceof ScopedSymbol) {
for (const child of symbol.children) {
const result = findRecursive(child);
if (result) {
return result;
}
}
}
};
let symbols = await this.getAllSymbols(Symbol);
for (const symbol of symbols) {
const result = findRecursive(symbol);
if (result) {
return result;
}
}
for (const dependency of this.dependencies) {
symbols = await dependency.getAllSymbols(Symbol);
for (const symbol of symbols) {
const result = findRecursive(symbol);
if (result) {
result;
}
}
}
}
/**
* Resolves a name to a symbol.
*
* @param name The name of the symbol to find.
* @param localOnly A flag indicating if only this symbol table should be used or also its dependencies.
* @returns The found symbol or undefined.
*/
public async resolve(name: string, localOnly = false): Promise<Symbol | undefined> {
let result = await super.resolve(name, localOnly);
if (!result && !localOnly) {
for (const dependency of this.dependencies) {
result = await dependency.resolve(name, false);
if (result) {
return result;
}
}
}
return result;
}
} | the_stack |
export var inspect: any;
/** object */
export var HEAP8: any;
/** object */
export var HEAP16: any;
/** object */
export var HEAP32: any;
/** object */
export var HEAPU8: any;
/** object */
export var HEAPU16: any;
/** object */
export var HEAPU32: any;
/** object */
export var HEAPF32: any;
/** object */
export var HEAPF64: any;
/** object */
export var preloadedImages: any;
/** object */
export var preloadedAudios: any;
/** object */
export var asm: any;
/** function */
export var requestFullscreen: any;
/** function */
export var requestAnimationFrame: any;
/** function */
export var setCanvasSize: any;
/** function */
export var pauseMainLoop: any;
/** function */
export var resumeMainLoop: any;
/** function */
export var getUserMedia: any;
/** function */
export var createContext: any;
/** function */
export var FS_createFolder: any;
/** function */
export var FS_createPath: any;
/** function */
export var FS_createDataFile: any;
/** function */
export var FS_createPreloadedFile: any;
/** function */
export var FS_createLazyFile: any;
/** function */
export var FS_createLink: any;
/** function */
export var FS_createDevice: any;
/** function */
export var FS_unlink: any;
/** function */
export var InternalError: any;
/** function */
export var BindingError: any;
/** function */
export var getInheritedInstanceCount: any;
/** function */
export var getLiveInheritedInstances: any;
/** function */
export var flushPendingDeletes: any;
/** function */
export var setDelayFunction: any;
/** function */
export var UnboundTypeError: any;
/** function */
export var count_emval_handles: any;
/** function */
export var get_first_emval: any;
/** function */
export var __ZSt18uncaught_exceptionv: any;
/** function */
export var ___cxa_can_catch: any;
/** function */
export var ___cxa_demangle: any;
/** function */
export var ___cxa_is_pointer_type: any;
/** function */
export var ___embind_register_native_and_builtin_types: any;
/** function */
export var ___errno_location: any;
/** function */
export var ___getTypeName: any;
/** function */
export var __get_environ: any;
/** function */
export var _emscripten_get_sbrk_ptr: any;
/** undefined */
export var _emscripten_replace_memory: any;
/** function */
export var _free: any;
/** function */
export var _llvm_bswap_i32: any;
/** function */
export var _malloc: any;
/** function */
export var _memcpy: any;
/** function */
export var _memmove: any;
/** function */
export var _memset: any;
/** function */
export var _rintf: any;
/** function */
export var establishStackSpace: any;
/** function */
export var globalCtors: any;
/** function */
export var stackAlloc: any;
/** function */
export var stackRestore: any;
/** function */
export var stackSave: any;
/** function */
export var dynCall_di: any;
/** function */
export var dynCall_dii: any;
/** function */
export var dynCall_diiddi: any;
/** function */
export var dynCall_diii: any;
/** function */
export var dynCall_diiid: any;
/** function */
export var dynCall_diiiddi: any;
/** function */
export var dynCall_diiii: any;
/** function */
export var dynCall_diiiid: any;
/** function */
export var dynCall_diiiii: any;
/** function */
export var dynCall_diiiiii: any;
/** function */
export var dynCall_diiiiiii: any;
/** function */
export var dynCall_diiiiiiii: any;
/** function */
export var dynCall_diiiiiiiiii: any;
/** function */
export var dynCall_diiiiiiiiiii: any;
/** function */
export var dynCall_diiiiiiiiiiii: any;
/** function */
export var dynCall_diiiiiiiiiiiii: any;
/** function */
export var dynCall_fi: any;
/** function */
export var dynCall_fii: any;
/** function */
export var dynCall_fiii: any;
/** function */
export var dynCall_fiiii: any;
/** function */
export var dynCall_fiiiii: any;
/** function */
export var dynCall_i: any;
/** function */
export var dynCall_ii: any;
/** function */
export var dynCall_iid: any;
/** function */
export var dynCall_iidi: any;
/** function */
export var dynCall_iidiiii: any;
/** function */
export var dynCall_iif: any;
/** function */
export var dynCall_iiff: any;
/** function */
export var dynCall_iifff: any;
/** function */
export var dynCall_iiffff: any;
/** function */
export var dynCall_iii: any;
/** function */
export var dynCall_iiid: any;
/** function */
export var dynCall_iiidd: any;
/** function */
export var dynCall_iiiddi: any;
/** function */
export var dynCall_iiiddii: any;
/** function */
export var dynCall_iiiddiid: any;
/** function */
export var dynCall_iiiddiiid: any;
/** function */
export var dynCall_iiidi: any;
/** function */
export var dynCall_iiidii: any;
/** function */
export var dynCall_iiidiii: any;
/** function */
export var dynCall_iiidiiii: any;
/** function */
export var dynCall_iiidiiiii: any;
/** function */
export var dynCall_iiif: any;
/** function */
export var dynCall_iiifi: any;
/** function */
export var dynCall_iiifii: any;
/** function */
export var dynCall_iiifiii: any;
/** function */
export var dynCall_iiifiiii: any;
/** function */
export var dynCall_iiifiiiii: any;
/** function */
export var dynCall_iiifiiiiii: any;
/** function */
export var dynCall_iiifiiiiiii: any;
/** function */
export var dynCall_iiii: any;
/** function */
export var dynCall_iiiid: any;
/** function */
export var dynCall_iiiif: any;
/** function */
export var dynCall_iiiiff: any;
/** function */
export var dynCall_iiiiffi: any;
/** function */
export var dynCall_iiiifi: any;
/** function */
export var dynCall_iiiifii: any;
/** function */
export var dynCall_iiiifiii: any;
/** function */
export var dynCall_iiiii: any;
/** function */
export var dynCall_iiiiid: any;
/** function */
export var dynCall_iiiiidd: any;
/** function */
export var dynCall_iiiiiddi: any;
/** function */
export var dynCall_iiiiiddid: any;
/** function */
export var dynCall_iiiiiddidd: any;
/** function */
export var dynCall_iiiiiddiddi: any;
/** function */
export var dynCall_iiiiidi: any;
/** function */
export var dynCall_iiiiidii: any;
/** function */
export var dynCall_iiiiidiid: any;
/** function */
export var dynCall_iiiiif: any;
/** function */
export var dynCall_iiiiifi: any;
/** function */
export var dynCall_iiiiifii: any;
/** function */
export var dynCall_iiiiifiii: any;
/** function */
export var dynCall_iiiiii: any;
/** function */
export var dynCall_iiiiiid: any;
/** function */
export var dynCall_iiiiiidi: any;
/** function */
export var dynCall_iiiiiidid: any;
/** function */
export var dynCall_iiiiiididi: any;
/** function */
export var dynCall_iiiiiiff: any;
/** function */
export var dynCall_iiiiiiffi: any;
/** function */
export var dynCall_iiiiiifiididiii: any;
/** function */
export var dynCall_iiiiiii: any;
/** function */
export var dynCall_iiiiiiii: any;
/** function */
export var dynCall_iiiiiiiididiii: any;
/** function */
export var dynCall_iiiiiiiii: any;
/** function */
export var dynCall_iiiiiiiiii: any;
/** function */
export var dynCall_iiiiiiiiiiiii: any;
/** function */
export var dynCall_iiiiij: any;
/** function */
export var dynCall_ji: any;
/** function */
export var dynCall_jii: any;
/** function */
export var dynCall_jiii: any;
/** function */
export var dynCall_jiiii: any;
/** function */
export var dynCall_jiji: any;
/** function */
export var dynCall_v: any;
/** function */
export var dynCall_vdii: any;
/** function */
export var dynCall_vdiii: any;
/** function */
export var dynCall_vi: any;
/** function */
export var dynCall_vid: any;
/** function */
export var dynCall_vidi: any;
/** function */
export var dynCall_vididdi: any;
/** function */
export var dynCall_vididdii: any;
/** function */
export var dynCall_vidii: any;
/** function */
export var dynCall_vidiii: any;
/** function */
export var dynCall_vif: any;
/** function */
export var dynCall_viff: any;
/** function */
export var dynCall_vifff: any;
/** function */
export var dynCall_viffff: any;
/** function */
export var dynCall_vifi: any;
/** function */
export var dynCall_vii: any;
/** function */
export var dynCall_viid: any;
/** function */
export var dynCall_viidd: any;
/** function */
export var dynCall_viiddi: any;
/** function */
export var dynCall_viiddid: any;
/** function */
export var dynCall_viiddidd: any;
/** function */
export var dynCall_viiddiddd: any;
/** function */
export var dynCall_viiddidddd: any;
/** function */
export var dynCall_viiddii: any;
/** function */
export var dynCall_viiddiid: any;
/** function */
export var dynCall_viiddiii: any;
/** function */
export var dynCall_viiddiiid: any;
/** function */
export var dynCall_viidi: any;
/** function */
export var dynCall_viididdi: any;
/** function */
export var dynCall_viididdii: any;
/** function */
export var dynCall_viididi: any;
/** function */
export var dynCall_viididii: any;
/** function */
export var dynCall_viidii: any;
/** function */
export var dynCall_viidiii: any;
/** function */
export var dynCall_viidiiid: any;
/** function */
export var dynCall_viidiiii: any;
/** function */
export var dynCall_viidiiiii: any;
/** function */
export var dynCall_viif: any;
/** function */
export var dynCall_viifi: any;
/** function */
export var dynCall_viifii: any;
/** function */
export var dynCall_viifiii: any;
/** function */
export var dynCall_viifiiii: any;
/** function */
export var dynCall_viifiiiii: any;
/** function */
export var dynCall_viifiiiiii: any;
/** function */
export var dynCall_viifiiiiiii: any;
/** function */
export var dynCall_viii: any;
/** function */
export var dynCall_viiid: any;
/** function */
export var dynCall_viiidd: any;
/** function */
export var dynCall_viiiddd: any;
/** function */
export var dynCall_viiidddd: any;
/** function */
export var dynCall_viiiddddi: any;
/** function */
export var dynCall_viiiddddii: any;
/** function */
export var dynCall_viiidddi: any;
/** function */
export var dynCall_viiidddii: any;
/** function */
export var dynCall_viiidddiii: any;
/** function */
export var dynCall_viiidddiiii: any;
/** function */
export var dynCall_viiiddi: any;
/** function */
export var dynCall_viiiddid: any;
/** function */
export var dynCall_viiiddidd: any;
/** function */
export var dynCall_viiiddiddd: any;
/** function */
export var dynCall_viiiddidddd: any;
/** function */
export var dynCall_viiiddii: any;
/** function */
export var dynCall_viiiddiii: any;
/** function */
export var dynCall_viiiddiiid: any;
/** function */
export var dynCall_viiiddiiii: any;
/** function */
export var dynCall_viiiddiiiid: any;
/** function */
export var dynCall_viiidi: any;
/** function */
export var dynCall_viiididi: any;
/** function */
export var dynCall_viiididii: any;
/** function */
export var dynCall_viiidii: any;
/** function */
export var dynCall_viiidiiddi: any;
/** function */
export var dynCall_viiidiii: any;
/** function */
export var dynCall_viiidiiid: any;
/** function */
export var dynCall_viiidiiii: any;
/** function */
export var dynCall_viiidiiiidi: any;
/** function */
export var dynCall_viiif: any;
/** function */
export var dynCall_viiiff: any;
/** function */
export var dynCall_viiiffi: any;
/** function */
export var dynCall_viiifi: any;
/** function */
export var dynCall_viiifii: any;
/** function */
export var dynCall_viiifiii: any;
/** function */
export var dynCall_viiii: any;
/** function */
export var dynCall_viiiid: any;
/** function */
export var dynCall_viiiidd: any;
/** function */
export var dynCall_viiiiddd: any;
/** function */
export var dynCall_viiiidddd: any;
/** function */
export var dynCall_viiiiddddi: any;
/** function */
export var dynCall_viiiiddddii: any;
/** function */
export var dynCall_viiiidddi: any;
/** function */
export var dynCall_viiiidddii: any;
/** function */
export var dynCall_viiiidddiii: any;
/** function */
export var dynCall_viiiidddiiii: any;
/** function */
export var dynCall_viiiiddi: any;
/** function */
export var dynCall_viiiiddid: any;
/** function */
export var dynCall_viiiiddidd: any;
/** function */
export var dynCall_viiiiddiddi: any;
/** function */
export var dynCall_viiiiddii: any;
/** function */
export var dynCall_viiiiddiii: any;
/** function */
export var dynCall_viiiiddiiid: any;
/** function */
export var dynCall_viiiiddiiii: any;
/** function */
export var dynCall_viiiiddiiiid: any;
/** function */
export var dynCall_viiiidi: any;
/** function */
export var dynCall_viiiidii: any;
/** function */
export var dynCall_viiiidiid: any;
/** function */
export var dynCall_viiiidiidd: any;
/** function */
export var dynCall_viiiidiiddi: any;
/** function */
export var dynCall_viiiidiii: any;
/** function */
export var dynCall_viiiidiiii: any;
/** function */
export var dynCall_viiiidiiiidi: any;
/** function */
export var dynCall_viiiif: any;
/** function */
export var dynCall_viiiifi: any;
/** function */
export var dynCall_viiiifii: any;
/** function */
export var dynCall_viiiifiii: any;
/** function */
export var dynCall_viiiii: any;
/** function */
export var dynCall_viiiiid: any;
/** function */
export var dynCall_viiiiidd: any;
/** function */
export var dynCall_viiiiiddi: any;
/** function */
export var dynCall_viiiiidi: any;
/** function */
export var dynCall_viiiiidid: any;
/** function */
export var dynCall_viiiiididi: any;
/** function */
export var dynCall_viiiiidii: any;
/** function */
export var dynCall_viiiiidiid: any;
/** function */
export var dynCall_viiiiidiidd: any;
/** function */
export var dynCall_viiiiidiiddi: any;
/** function */
export var dynCall_viiiiidiii: any;
/** function */
export var dynCall_viiiiidiiii: any;
/** function */
export var dynCall_viiiiidiiiii: any;
/** function */
export var dynCall_viiiiif: any;
/** function */
export var dynCall_viiiiiff: any;
/** function */
export var dynCall_viiiiiffi: any;
/** function */
export var dynCall_viiiiifi: any;
/** function */
export var dynCall_viiiiifii: any;
/** function */
export var dynCall_viiiiii: any;
/** function */
export var dynCall_viiiiiid: any;
/** function */
export var dynCall_viiiiiidd: any;
/** function */
export var dynCall_viiiiiiddi: any;
/** function */
export var dynCall_viiiiiidi: any;
/** function */
export var dynCall_viiiiiidii: any;
/** function */
export var dynCall_viiiiiidiii: any;
/** function */
export var dynCall_viiiiiidiiii: any;
/** function */
export var dynCall_viiiiiidiiiii: any;
/** function */
export var dynCall_viiiiiif: any;
/** function */
export var dynCall_viiiiiifi: any;
/** function */
export var dynCall_viiiiiii: any;
/** function */
export var dynCall_viiiiiiid: any;
/** function */
export var dynCall_viiiiiiidd: any;
/** function */
export var dynCall_viiiiiiiddi: any;
/** function */
export var dynCall_viiiiiiidi: any;
/** function */
export var dynCall_viiiiiiii: any;
/** function */
export var dynCall_viiiiiiiii: any;
/** function */
export var dynCall_viiiiiiiiidd: any;
/** function */
export var dynCall_viiiiiiiiii: any;
/** function */
export var dynCall_viiiiiiiiiid: any;
/** function */
export var dynCall_viiiiiiiiiiddi: any;
/** function */
export var dynCall_viiiiiiiiiii: any;
/** function */
export var dynCall_viiiiiiiiiiid: any;
/** function */
export var dynCall_viiiij: any;
/** function */
export var dynCall_viiij: any;
/** function */
export var dynCall_viijii: any;
/** function */
export var dynCall_vij: any;
/** function */
export var dynCall_viji: any;
/** function */
export var getMemory: any;
/** function */
export var addRunDependency: any;
/** function */
export var removeRunDependency: any;
export var calledRun: boolean;
/** function */
export var then: any;
/** function */
export var run: any;
/** undefined */
export var stdin: any;
/** undefined */
export var stdout: any;
/** undefined */
export var stderr: any;
/** function */
export var IntVector: any;
/** function */
export var FloatVector: any;
/** function */
export var DoubleVector: any;
/** function */
export var PointVector: any;
/** function */
export var MatVector: any;
/** function */
export var RectVector: any;
/** function */
export var KeyPointVector: any;
/** function */
export var DMatchVector: any;
/** function */
export var DMatchVectorVector: any;
/** function */
export var Mat: any;
/** function */
export var rotatedRectPoints: any;
/** function */
export var rotatedRectBoundingRect: any;
/** function */
export var rotatedRectBoundingRect2f: any;
/** function */
export var exceptionFromPtr: any;
/** function */
export var minEnclosingCircle: any;
/** function */
export var floodFill: any;
/** function */
export var minMaxLoc: any;
/** function */
export var morphologyDefaultBorderValue: any;
/** function */
export var CV_MAT_DEPTH: any;
/** function */
export var CamShift: any;
/** function */
export var meanShift: any;
/** function */
export var getBuildInformation: any;
export var CV_8UC1: number;
export var CV_8UC2: number;
export var CV_8UC3: number;
export var CV_8UC4: number;
export var CV_8SC1: number;
export var CV_8SC2: number;
export var CV_8SC3: number;
export var CV_8SC4: number;
export var CV_16UC1: number;
export var CV_16UC2: number;
export var CV_16UC3: number;
export var CV_16UC4: number;
export var CV_16SC1: number;
export var CV_16SC2: number;
export var CV_16SC3: number;
export var CV_16SC4: number;
export var CV_32SC1: number;
export var CV_32SC2: number;
export var CV_32SC3: number;
export var CV_32SC4: number;
export var CV_32FC1: number;
export var CV_32FC2: number;
export var CV_32FC3: number;
export var CV_32FC4: number;
export var CV_64FC1: number;
export var CV_64FC2: number;
export var CV_64FC3: number;
export var CV_64FC4: number;
export var CV_8U: number;
export var CV_8S: number;
export var CV_16U: number;
export var CV_16S: number;
export var CV_32S: number;
export var CV_32F: number;
export var CV_64F: number;
export var INT_MIN: number;
export var INT_MAX: number;
/** function */
export var Canny: any;
/** function */
export var Canny1: any;
/** function */
export var GaussianBlur: any;
/** function */
export var HoughCircles: any;
/** function */
export var HoughLines: any;
/** function */
export var HoughLinesP: any;
/** function */
export var Laplacian: any;
/** function */
export var Rodrigues: any;
/** function */
export var Scharr: any;
/** function */
export var Sobel: any;
/** function */
export var absdiff: any;
/** function */
export var adaptiveThreshold: any;
/** function */
export var add: any;
/** function */
export var addWeighted: any;
/** function */
export var approxPolyDP: any;
/** function */
export var arcLength: any;
/** function */
export var bilateralFilter: any;
/** function */
export var bitwise_and: any;
/** function */
export var bitwise_not: any;
/** function */
export var bitwise_or: any;
/** function */
export var bitwise_xor: any;
/** function */
export var blur: any;
/** function */
export var boundingRect: any;
/** function */
export var boxFilter: any;
/** function */
export var calcBackProject: any;
/** function */
export var calcHist: any;
/** function */
export var calcOpticalFlowFarneback: any;
/** function */
export var calcOpticalFlowPyrLK: any;
/** function */
export var calibrateCameraExtended: any;
/** function */
export var cartToPolar: any;
/** function */
export var circle: any;
/** function */
export var compare: any;
/** function */
export var compareHist: any;
/** function */
export var connectedComponents: any;
/** function */
export var connectedComponentsWithStats: any;
/** function */
export var contourArea: any;
/** function */
export var convertScaleAbs: any;
/** function */
export var convexHull: any;
/** function */
export var convexityDefects: any;
/** function */
export var copyMakeBorder: any;
/** function */
export var cornerHarris: any;
/** function */
export var cornerMinEigenVal: any;
/** function */
export var countNonZero: any;
/** function */
export var cvtColor: any;
/** function */
export var demosaicing: any;
/** function */
export var determinant: any;
/** function */
export var dft: any;
/** function */
export var dilate: any;
/** function */
export var distanceTransform: any;
/** function */
export var distanceTransformWithLabels: any;
/** function */
export var divide: any;
/** function */
export var divide1: any;
/** function */
export var drawContours: any;
/** function */
export var drawFrameAxes: any;
/** function */
export var drawKeypoints: any;
/** function */
export var drawMatches: any;
/** function */
export var drawMatchesKnn: any;
/** function */
export var eigen: any;
/** function */
export var ellipse: any;
/** function */
export var ellipse1: any;
/** function */
export var ellipse2Poly: any;
/** function */
export var equalizeHist: any;
/** function */
export var erode: any;
/** function */
export var estimateAffine2D: any;
/** function */
export var exp: any;
/** function */
export var fillConvexPoly: any;
/** function */
export var fillPoly: any;
/** function */
export var filter2D: any;
/** function */
export var findContours: any;
/** function */
export var findHomography: any;
/** function */
export var findTransformECC: any;
/** function */
export var fitEllipse: any;
/** function */
export var fitLine: any;
/** function */
export var flip: any;
/** function */
export var gemm: any;
/** function */
export var getAffineTransform: any;
/** function */
export var getDefaultNewCameraMatrix: any;
/** function */
export var getOptimalDFTSize: any;
/** function */
export var getPerspectiveTransform: any;
/** function */
export var getRotationMatrix2D: any;
/** function */
export var getStructuringElement: any;
/** function */
export var goodFeaturesToTrack: any;
/** function */
export var goodFeaturesToTrack1: any;
/** function */
export var grabCut: any;
/** function */
export var groupRectangles: any;
/** function */
export var hconcat: any;
/** function */
export var inRange: any;
/** function */
export var initUndistortRectifyMap: any;
/** function */
export var inpaint: any;
/** function */
export var integral: any;
/** function */
export var integral2: any;
/** function */
export var invert: any;
/** function */
export var isContourConvex: any;
/** function */
export var kmeans: any;
/** function */
export var line: any;
/** function */
export var log: any;
/** function */
export var magnitude: any;
/** function */
export var matchShapes: any;
/** function */
export var matchTemplate: any;
/** function */
export var max: any;
/** function */
export var mean: any;
/** function */
export var meanStdDev: any;
/** function */
export var medianBlur: any;
/** function */
export var merge: any;
/** function */
export var min: any;
/** function */
export var minAreaRect: any;
/** function */
export var mixChannels: any;
/** function */
export var moments: any;
/** function */
export var morphologyEx: any;
/** function */
export var multiply: any;
/** function */
export var norm: any;
/** function */
export var norm1: any;
/** function */
export var normalize: any;
/** function */
export var perspectiveTransform: any;
/** function */
export var pointPolygonTest: any;
/** function */
export var polarToCart: any;
/** function */
export var pow: any;
/** function */
export var putText: any;
/** function */
export var pyrDown: any;
/** function */
export var pyrUp: any;
/** function */
export var randn: any;
/** function */
export var randu: any;
/** function */
export var rectangle: any;
/** function */
export var rectangle1: any;
/** function */
export var reduce: any;
/** function */
export var remap: any;
/** function */
export var repeat: any;
/** function */
export var resize: any;
/** function */
export var rotate: any;
/** function */
export var sepFilter2D: any;
/** function */
export var setIdentity: any;
/** function */
export var setRNGSeed: any;
/** function */
export var solve: any;
/** function */
export var solvePoly: any;
/** function */
export var split: any;
/** function */
export var sqrt: any;
/** function */
export var subtract: any;
/** function */
export var threshold: any;
/** function */
export var trace: any;
/** function */
export var transform: any;
/** function */
export var transpose: any;
/** function */
export var undistort: any;
/** function */
export var vconcat: any;
/** function */
export var warpAffine: any;
/** function */
export var warpPerspective: any;
/** function */
export var warpPolar: any;
/** function */
export var watershed: any;
/** function */
export var blobFromImage: any;
/** function */
export var readNet: any;
/** function */
export var readNet1: any;
/** function */
export var readNetFromCaffe: any;
/** function */
export var readNetFromCaffe1: any;
/** function */
export var readNetFromDarknet: any;
/** function */
export var readNetFromDarknet1: any;
/** function */
export var readNetFromONNX: any;
/** function */
export var readNetFromONNX1: any;
/** function */
export var readNetFromTensorflow: any;
/** function */
export var readNetFromTensorflow1: any;
/** function */
export var readNetFromTorch: any;
/** function */
export var MergeMertens: any;
/** function */
export var CalibrateRobertson: any;
/** function */
export var dnn_Net: any;
/** function */
export var MergeDebevec: any;
/** function */
export var BackgroundSubtractor: any;
/** function */
export var AlignMTB: any;
/** function */
export var HOGDescriptor: any;
/** function */
export var KAZE: any;
/** function */
export var BackgroundSubtractorMOG2: any;
/** function */
export var TonemapMantiuk: any;
/** function */
export var Tonemap: any;
/** function */
export var CLAHE: any;
/** function */
export var CalibrateCRF: any;
/** function */
export var AKAZE: any;
/** function */
export var MergeExposures: any;
/** function */
export var CalibrateDebevec: any;
/** function */
export var Algorithm: any;
/** function */
export var Feature2D: any;
/** function */
export var MergeRobertson: any;
/** function */
export var GFTTDetector: any;
/** function */
export var DescriptorMatcher: any;
/** function */
export var MSER: any;
/** function */
export var BFMatcher: any;
/** function */
export var FastFeatureDetector: any;
/** function */
export var AgastFeatureDetector: any;
/** function */
export var CascadeClassifier: any;
/** function */
export var TonemapReinhard: any;
/** function */
export var TonemapDrago: any;
/** function */
export var ORB: any;
/** function */
export var BRISK: any;
export var ACCESS_FAST: number;
export var ACCESS_MASK: number;
export var ACCESS_READ: number;
export var ACCESS_RW: number;
export var ACCESS_WRITE: number;
export var ADAPTIVE_THRESH_GAUSSIAN_C: number;
export var ADAPTIVE_THRESH_MEAN_C: number;
export var AKAZE_DESCRIPTOR_KAZE: number;
export var AKAZE_DESCRIPTOR_KAZE_UPRIGHT: number;
export var AKAZE_DESCRIPTOR_MLDB: number;
export var AKAZE_DESCRIPTOR_MLDB_UPRIGHT: number;
export var AgastFeatureDetector_AGAST_5_8: number;
export var AgastFeatureDetector_AGAST_7_12d: number;
export var AgastFeatureDetector_AGAST_7_12s: number;
export var AgastFeatureDetector_NONMAX_SUPPRESSION: number;
export var AgastFeatureDetector_OAST_9_16: number;
export var AgastFeatureDetector_THRESHOLD: number;
export var BORDER_CONSTANT: number;
export var BORDER_DEFAULT: number;
export var BORDER_ISOLATED: number;
export var BORDER_REFLECT: number;
export var BORDER_REFLECT101: number;
export var BORDER_REFLECT_101: number;
export var BORDER_REPLICATE: number;
export var BORDER_TRANSPARENT: number;
export var BORDER_WRAP: number;
export var CALIB_CB_ACCURACY: number;
export var CALIB_CB_ADAPTIVE_THRESH: number;
export var CALIB_CB_ASYMMETRIC_GRID: number;
export var CALIB_CB_CLUSTERING: number;
export var CALIB_CB_EXHAUSTIVE: number;
export var CALIB_CB_FAST_CHECK: number;
export var CALIB_CB_FILTER_QUADS: number;
export var CALIB_CB_LARGER: number;
export var CALIB_CB_MARKER: number;
export var CALIB_CB_NORMALIZE_IMAGE: number;
export var CALIB_CB_SYMMETRIC_GRID: number;
export var CALIB_FIX_ASPECT_RATIO: number;
export var CALIB_FIX_FOCAL_LENGTH: number;
export var CALIB_FIX_INTRINSIC: number;
export var CALIB_FIX_K1: number;
export var CALIB_FIX_K2: number;
export var CALIB_FIX_K3: number;
export var CALIB_FIX_K4: number;
export var CALIB_FIX_K5: number;
export var CALIB_FIX_K6: number;
export var CALIB_FIX_PRINCIPAL_POINT: number;
export var CALIB_FIX_S1_S2_S3_S4: number;
export var CALIB_FIX_TANGENT_DIST: number;
export var CALIB_FIX_TAUX_TAUY: number;
export var CALIB_HAND_EYE_ANDREFF: number;
export var CALIB_HAND_EYE_DANIILIDIS: number;
export var CALIB_HAND_EYE_HORAUD: number;
export var CALIB_HAND_EYE_PARK: number;
export var CALIB_HAND_EYE_TSAI: number;
export var CALIB_NINTRINSIC: number;
export var CALIB_RATIONAL_MODEL: number;
export var CALIB_SAME_FOCAL_LENGTH: number;
export var CALIB_THIN_PRISM_MODEL: number;
export var CALIB_TILTED_MODEL: number;
export var CALIB_USE_EXTRINSIC_GUESS: number;
export var CALIB_USE_INTRINSIC_GUESS: number;
export var CALIB_USE_LU: number;
export var CALIB_USE_QR: number;
export var CALIB_ZERO_DISPARITY: number;
export var CALIB_ZERO_TANGENT_DIST: number;
export var CASCADE_DO_CANNY_PRUNING: number;
export var CASCADE_DO_ROUGH_SEARCH: number;
export var CASCADE_FIND_BIGGEST_OBJECT: number;
export var CASCADE_SCALE_IMAGE: number;
export var CCL_DEFAULT: number;
export var CCL_GRANA: number;
export var CCL_WU: number;
export var CC_STAT_AREA: number;
export var CC_STAT_HEIGHT: number;
export var CC_STAT_LEFT: number;
export var CC_STAT_MAX: number;
export var CC_STAT_TOP: number;
export var CC_STAT_WIDTH: number;
export var CHAIN_APPROX_NONE: number;
export var CHAIN_APPROX_SIMPLE: number;
export var CHAIN_APPROX_TC89_KCOS: number;
export var CHAIN_APPROX_TC89_L1: number;
export var CMP_EQ: number;
export var CMP_GE: number;
export var CMP_GT: number;
export var CMP_LE: number;
export var CMP_LT: number;
export var CMP_NE: number;
export var COLORMAP_AUTUMN: number;
export var COLORMAP_BONE: number;
export var COLORMAP_CIVIDIS: number;
export var COLORMAP_COOL: number;
export var COLORMAP_HOT: number;
export var COLORMAP_HSV: number;
export var COLORMAP_INFERNO: number;
export var COLORMAP_JET: number;
export var COLORMAP_MAGMA: number;
export var COLORMAP_OCEAN: number;
export var COLORMAP_PARULA: number;
export var COLORMAP_PINK: number;
export var COLORMAP_PLASMA: number;
export var COLORMAP_RAINBOW: number;
export var COLORMAP_SPRING: number;
export var COLORMAP_SUMMER: number;
export var COLORMAP_TURBO: number;
export var COLORMAP_TWILIGHT: number;
export var COLORMAP_TWILIGHT_SHIFTED: number;
export var COLORMAP_VIRIDIS: number;
export var COLORMAP_WINTER: number;
export var COLOR_BGR2BGR555: number;
export var COLOR_BGR2BGR565: number;
export var COLOR_BGR2BGRA: number;
export var COLOR_BGR2GRAY: number;
export var COLOR_BGR2HLS: number;
export var COLOR_BGR2HLS_FULL: number;
export var COLOR_BGR2HSV: number;
export var COLOR_BGR2HSV_FULL: number;
export var COLOR_BGR2Lab: number;
export var COLOR_BGR2Luv: number;
export var COLOR_BGR2RGB: number;
export var COLOR_BGR2RGBA: number;
export var COLOR_BGR2XYZ: number;
export var COLOR_BGR2YCrCb: number;
export var COLOR_BGR2YUV: number;
export var COLOR_BGR2YUV_I420: number;
export var COLOR_BGR2YUV_IYUV: number;
export var COLOR_BGR2YUV_YV12: number;
export var COLOR_BGR5552BGR: number;
export var COLOR_BGR5552BGRA: number;
export var COLOR_BGR5552GRAY: number;
export var COLOR_BGR5552RGB: number;
export var COLOR_BGR5552RGBA: number;
export var COLOR_BGR5652BGR: number;
export var COLOR_BGR5652BGRA: number;
export var COLOR_BGR5652GRAY: number;
export var COLOR_BGR5652RGB: number;
export var COLOR_BGR5652RGBA: number;
export var COLOR_BGRA2BGR: number;
export var COLOR_BGRA2BGR555: number;
export var COLOR_BGRA2BGR565: number;
export var COLOR_BGRA2GRAY: number;
export var COLOR_BGRA2RGB: number;
export var COLOR_BGRA2RGBA: number;
export var COLOR_BGRA2YUV_I420: number;
export var COLOR_BGRA2YUV_IYUV: number;
export var COLOR_BGRA2YUV_YV12: number;
export var COLOR_BayerBG2BGR: number;
export var COLOR_BayerBG2BGRA: number;
export var COLOR_BayerBG2BGR_EA: number;
export var COLOR_BayerBG2BGR_VNG: number;
export var COLOR_BayerBG2GRAY: number;
export var COLOR_BayerBG2RGB: number;
export var COLOR_BayerBG2RGBA: number;
export var COLOR_BayerBG2RGB_EA: number;
export var COLOR_BayerBG2RGB_VNG: number;
export var COLOR_BayerGB2BGR: number;
export var COLOR_BayerGB2BGRA: number;
export var COLOR_BayerGB2BGR_EA: number;
export var COLOR_BayerGB2BGR_VNG: number;
export var COLOR_BayerGB2GRAY: number;
export var COLOR_BayerGB2RGB: number;
export var COLOR_BayerGB2RGBA: number;
export var COLOR_BayerGB2RGB_EA: number;
export var COLOR_BayerGB2RGB_VNG: number;
export var COLOR_BayerGR2BGR: number;
export var COLOR_BayerGR2BGRA: number;
export var COLOR_BayerGR2BGR_EA: number;
export var COLOR_BayerGR2BGR_VNG: number;
export var COLOR_BayerGR2GRAY: number;
export var COLOR_BayerGR2RGB: number;
export var COLOR_BayerGR2RGBA: number;
export var COLOR_BayerGR2RGB_EA: number;
export var COLOR_BayerGR2RGB_VNG: number;
export var COLOR_BayerRG2BGR: number;
export var COLOR_BayerRG2BGRA: number;
export var COLOR_BayerRG2BGR_EA: number;
export var COLOR_BayerRG2BGR_VNG: number;
export var COLOR_BayerRG2GRAY: number;
export var COLOR_BayerRG2RGB: number;
export var COLOR_BayerRG2RGBA: number;
export var COLOR_BayerRG2RGB_EA: number;
export var COLOR_BayerRG2RGB_VNG: number;
export var COLOR_COLORCVT_MAX: number;
export var COLOR_GRAY2BGR: number;
export var COLOR_GRAY2BGR555: number;
export var COLOR_GRAY2BGR565: number;
export var COLOR_GRAY2BGRA: number;
export var COLOR_GRAY2RGB: number;
export var COLOR_GRAY2RGBA: number;
export var COLOR_HLS2BGR: number;
export var COLOR_HLS2BGR_FULL: number;
export var COLOR_HLS2RGB: number;
export var COLOR_HLS2RGB_FULL: number;
export var COLOR_HSV2BGR: number;
export var COLOR_HSV2BGR_FULL: number;
export var COLOR_HSV2RGB: number;
export var COLOR_HSV2RGB_FULL: number;
export var COLOR_LBGR2Lab: number;
export var COLOR_LBGR2Luv: number;
export var COLOR_LRGB2Lab: number;
export var COLOR_LRGB2Luv: number;
export var COLOR_Lab2BGR: number;
export var COLOR_Lab2LBGR: number;
export var COLOR_Lab2LRGB: number;
export var COLOR_Lab2RGB: number;
export var COLOR_Luv2BGR: number;
export var COLOR_Luv2LBGR: number;
export var COLOR_Luv2LRGB: number;
export var COLOR_Luv2RGB: number;
export var COLOR_RGB2BGR: number;
export var COLOR_RGB2BGR555: number;
export var COLOR_RGB2BGR565: number;
export var COLOR_RGB2BGRA: number;
export var COLOR_RGB2GRAY: number;
export var COLOR_RGB2HLS: number;
export var COLOR_RGB2HLS_FULL: number;
export var COLOR_RGB2HSV: number;
export var COLOR_RGB2HSV_FULL: number;
export var COLOR_RGB2Lab: number;
export var COLOR_RGB2Luv: number;
export var COLOR_RGB2RGBA: number;
export var COLOR_RGB2XYZ: number;
export var COLOR_RGB2YCrCb: number;
export var COLOR_RGB2YUV: number;
export var COLOR_RGB2YUV_I420: number;
export var COLOR_RGB2YUV_IYUV: number;
export var COLOR_RGB2YUV_YV12: number;
export var COLOR_RGBA2BGR: number;
export var COLOR_RGBA2BGR555: number;
export var COLOR_RGBA2BGR565: number;
export var COLOR_RGBA2BGRA: number;
export var COLOR_RGBA2GRAY: number;
export var COLOR_RGBA2RGB: number;
export var COLOR_RGBA2YUV_I420: number;
export var COLOR_RGBA2YUV_IYUV: number;
export var COLOR_RGBA2YUV_YV12: number;
export var COLOR_RGBA2mRGBA: number;
export var COLOR_XYZ2BGR: number;
export var COLOR_XYZ2RGB: number;
export var COLOR_YCrCb2BGR: number;
export var COLOR_YCrCb2RGB: number;
export var COLOR_YUV2BGR: number;
export var COLOR_YUV2BGRA_I420: number;
export var COLOR_YUV2BGRA_IYUV: number;
export var COLOR_YUV2BGRA_NV12: number;
export var COLOR_YUV2BGRA_NV21: number;
export var COLOR_YUV2BGRA_UYNV: number;
export var COLOR_YUV2BGRA_UYVY: number;
export var COLOR_YUV2BGRA_Y422: number;
export var COLOR_YUV2BGRA_YUNV: number;
export var COLOR_YUV2BGRA_YUY2: number;
export var COLOR_YUV2BGRA_YUYV: number;
export var COLOR_YUV2BGRA_YV12: number;
export var COLOR_YUV2BGRA_YVYU: number;
export var COLOR_YUV2BGR_I420: number;
export var COLOR_YUV2BGR_IYUV: number;
export var COLOR_YUV2BGR_NV12: number;
export var COLOR_YUV2BGR_NV21: number;
export var COLOR_YUV2BGR_UYNV: number;
export var COLOR_YUV2BGR_UYVY: number;
export var COLOR_YUV2BGR_Y422: number;
export var COLOR_YUV2BGR_YUNV: number;
export var COLOR_YUV2BGR_YUY2: number;
export var COLOR_YUV2BGR_YUYV: number;
export var COLOR_YUV2BGR_YV12: number;
export var COLOR_YUV2BGR_YVYU: number;
export var COLOR_YUV2GRAY_420: number;
export var COLOR_YUV2GRAY_I420: number;
export var COLOR_YUV2GRAY_IYUV: number;
export var COLOR_YUV2GRAY_NV12: number;
export var COLOR_YUV2GRAY_NV21: number;
export var COLOR_YUV2GRAY_UYNV: number;
export var COLOR_YUV2GRAY_UYVY: number;
export var COLOR_YUV2GRAY_Y422: number;
export var COLOR_YUV2GRAY_YUNV: number;
export var COLOR_YUV2GRAY_YUY2: number;
export var COLOR_YUV2GRAY_YUYV: number;
export var COLOR_YUV2GRAY_YV12: number;
export var COLOR_YUV2GRAY_YVYU: number;
export var COLOR_YUV2RGB: number;
export var COLOR_YUV2RGBA_I420: number;
export var COLOR_YUV2RGBA_IYUV: number;
export var COLOR_YUV2RGBA_NV12: number;
export var COLOR_YUV2RGBA_NV21: number;
export var COLOR_YUV2RGBA_UYNV: number;
export var COLOR_YUV2RGBA_UYVY: number;
export var COLOR_YUV2RGBA_Y422: number;
export var COLOR_YUV2RGBA_YUNV: number;
export var COLOR_YUV2RGBA_YUY2: number;
export var COLOR_YUV2RGBA_YUYV: number;
export var COLOR_YUV2RGBA_YV12: number;
export var COLOR_YUV2RGBA_YVYU: number;
export var COLOR_YUV2RGB_I420: number;
export var COLOR_YUV2RGB_IYUV: number;
export var COLOR_YUV2RGB_NV12: number;
export var COLOR_YUV2RGB_NV21: number;
export var COLOR_YUV2RGB_UYNV: number;
export var COLOR_YUV2RGB_UYVY: number;
export var COLOR_YUV2RGB_Y422: number;
export var COLOR_YUV2RGB_YUNV: number;
export var COLOR_YUV2RGB_YUY2: number;
export var COLOR_YUV2RGB_YUYV: number;
export var COLOR_YUV2RGB_YV12: number;
export var COLOR_YUV2RGB_YVYU: number;
export var COLOR_YUV420p2BGR: number;
export var COLOR_YUV420p2BGRA: number;
export var COLOR_YUV420p2GRAY: number;
export var COLOR_YUV420p2RGB: number;
export var COLOR_YUV420p2RGBA: number;
export var COLOR_YUV420sp2BGR: number;
export var COLOR_YUV420sp2BGRA: number;
export var COLOR_YUV420sp2GRAY: number;
export var COLOR_YUV420sp2RGB: number;
export var COLOR_YUV420sp2RGBA: number;
export var COLOR_mRGBA2RGBA: number;
export var CONTOURS_MATCH_I1: number;
export var CONTOURS_MATCH_I2: number;
export var CONTOURS_MATCH_I3: number;
export var COVAR_COLS: number;
export var COVAR_NORMAL: number;
export var COVAR_ROWS: number;
export var COVAR_SCALE: number;
export var COVAR_SCRAMBLED: number;
export var COVAR_USE_AVG: number;
export var CirclesGridFinderParameters_ASYMMETRIC_GRID: number;
export var CirclesGridFinderParameters_SYMMETRIC_GRID: number;
export var DCT_INVERSE: number;
export var DCT_ROWS: number;
export var DECOMP_CHOLESKY: number;
export var DECOMP_EIG: number;
export var DECOMP_LU: number;
export var DECOMP_NORMAL: number;
export var DECOMP_QR: number;
export var DECOMP_SVD: number;
export var DFT_COMPLEX_INPUT: number;
export var DFT_COMPLEX_OUTPUT: number;
export var DFT_INVERSE: number;
export var DFT_REAL_OUTPUT: number;
export var DFT_ROWS: number;
export var DFT_SCALE: number;
export var DISOpticalFlow_PRESET_FAST: number;
export var DISOpticalFlow_PRESET_MEDIUM: number;
export var DISOpticalFlow_PRESET_ULTRAFAST: number;
export var DIST_C: number;
export var DIST_FAIR: number;
export var DIST_HUBER: number;
export var DIST_L1: number;
export var DIST_L12: number;
export var DIST_L2: number;
export var DIST_LABEL_CCOMP: number;
export var DIST_LABEL_PIXEL: number;
export var DIST_MASK_3: number;
export var DIST_MASK_5: number;
export var DIST_MASK_PRECISE: number;
export var DIST_USER: number;
export var DIST_WELSCH: number;
export var DescriptorMatcher_BRUTEFORCE: number;
export var DescriptorMatcher_BRUTEFORCE_HAMMING: number;
export var DescriptorMatcher_BRUTEFORCE_HAMMINGLUT: number;
export var DescriptorMatcher_BRUTEFORCE_L1: number;
export var DescriptorMatcher_BRUTEFORCE_SL2: number;
export var DescriptorMatcher_FLANNBASED: number;
export var DrawMatchesFlags_DEFAULT: number;
export var DrawMatchesFlags_DRAW_OVER_OUTIMG: number;
export var DrawMatchesFlags_DRAW_RICH_KEYPOINTS: number;
export var DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS: number;
export var FILLED: number;
export var FILTER_SCHARR: number;
export var FLOODFILL_FIXED_RANGE: number;
export var FLOODFILL_MASK_ONLY: number;
export var FM_7POINT: number;
export var FM_8POINT: number;
export var FM_LMEDS: number;
export var FM_RANSAC: number;
export var FONT_HERSHEY_COMPLEX: number;
export var FONT_HERSHEY_COMPLEX_SMALL: number;
export var FONT_HERSHEY_DUPLEX: number;
export var FONT_HERSHEY_PLAIN: number;
export var FONT_HERSHEY_SCRIPT_COMPLEX: number;
export var FONT_HERSHEY_SCRIPT_SIMPLEX: number;
export var FONT_HERSHEY_SIMPLEX: number;
export var FONT_HERSHEY_TRIPLEX: number;
export var FONT_ITALIC: number;
export var FastFeatureDetector_FAST_N: number;
export var FastFeatureDetector_NONMAX_SUPPRESSION: number;
export var FastFeatureDetector_THRESHOLD: number;
export var FastFeatureDetector_TYPE_5_8: number;
export var FastFeatureDetector_TYPE_7_12: number;
export var FastFeatureDetector_TYPE_9_16: number;
export var FileNode_EMPTY: number;
export var FileNode_FLOAT: number;
export var FileNode_FLOW: number;
export var FileNode_INT: number;
export var FileNode_MAP: number;
export var FileNode_NAMED: number;
export var FileNode_NONE: number;
export var FileNode_REAL: number;
export var FileNode_SEQ: number;
export var FileNode_STR: number;
export var FileNode_STRING: number;
export var FileNode_TYPE_MASK: number;
export var FileNode_UNIFORM: number;
export var FileStorage_APPEND: number;
export var FileStorage_BASE64: number;
export var FileStorage_FORMAT_AUTO: number;
export var FileStorage_FORMAT_JSON: number;
export var FileStorage_FORMAT_MASK: number;
export var FileStorage_FORMAT_XML: number;
export var FileStorage_FORMAT_YAML: number;
export var FileStorage_INSIDE_MAP: number;
export var FileStorage_MEMORY: number;
export var FileStorage_NAME_EXPECTED: number;
export var FileStorage_READ: number;
export var FileStorage_UNDEFINED: number;
export var FileStorage_VALUE_EXPECTED: number;
export var FileStorage_WRITE: number;
export var FileStorage_WRITE_BASE64: number;
export var Formatter_FMT_C: number;
export var Formatter_FMT_CSV: number;
export var Formatter_FMT_DEFAULT: number;
export var Formatter_FMT_MATLAB: number;
export var Formatter_FMT_NUMPY: number;
export var Formatter_FMT_PYTHON: number;
export var GC_BGD: number;
export var GC_EVAL: number;
export var GC_EVAL_FREEZE_MODEL: number;
export var GC_FGD: number;
export var GC_INIT_WITH_MASK: number;
export var GC_INIT_WITH_RECT: number;
export var GC_PR_BGD: number;
export var GC_PR_FGD: number;
export var GEMM_1_T: number;
export var GEMM_2_T: number;
export var GEMM_3_T: number;
export var HISTCMP_BHATTACHARYYA: number;
export var HISTCMP_CHISQR: number;
export var HISTCMP_CHISQR_ALT: number;
export var HISTCMP_CORREL: number;
export var HISTCMP_HELLINGER: number;
export var HISTCMP_INTERSECT: number;
export var HISTCMP_KL_DIV: number;
export var HOGDescriptor_DEFAULT_NLEVELS: number;
export var HOGDescriptor_DESCR_FORMAT_COL_BY_COL: number;
export var HOGDescriptor_DESCR_FORMAT_ROW_BY_ROW: number;
export var HOGDescriptor_L2Hys: number;
export var HOUGH_GRADIENT: number;
export var HOUGH_GRADIENT_ALT: number;
export var HOUGH_MULTI_SCALE: number;
export var HOUGH_PROBABILISTIC: number;
export var HOUGH_STANDARD: number;
export var INPAINT_NS: number;
export var INPAINT_TELEA: number;
export var INTERSECT_FULL: number;
export var INTERSECT_NONE: number;
export var INTERSECT_PARTIAL: number;
export var INTER_AREA: number;
export var INTER_BITS: number;
export var INTER_BITS2: number;
export var INTER_CUBIC: number;
export var INTER_LANCZOS4: number;
export var INTER_LINEAR: number;
export var INTER_LINEAR_EXACT: number;
export var INTER_MAX: number;
export var INTER_NEAREST: number;
export var INTER_TAB_SIZE: number;
export var INTER_TAB_SIZE2: number;
export var KAZE_DIFF_CHARBONNIER: number;
export var KAZE_DIFF_PM_G1: number;
export var KAZE_DIFF_PM_G2: number;
export var KAZE_DIFF_WEICKERT: number;
export var KMEANS_PP_CENTERS: number;
export var KMEANS_RANDOM_CENTERS: number;
export var KMEANS_USE_INITIAL_LABELS: number;
export var LDR_SIZE: number;
export var LINE_4: number;
export var LINE_8: number;
export var LINE_AA: number;
export var LMEDS: number;
export var LSD_REFINE_ADV: number;
export var LSD_REFINE_NONE: number;
export var LSD_REFINE_STD: number;
export var MARKER_CROSS: number;
export var MARKER_DIAMOND: number;
export var MARKER_SQUARE: number;
export var MARKER_STAR: number;
export var MARKER_TILTED_CROSS: number;
export var MARKER_TRIANGLE_DOWN: number;
export var MARKER_TRIANGLE_UP: number;
export var MIXED_CLONE: number;
export var MONOCHROME_TRANSFER: number;
export var MORPH_BLACKHAT: number;
export var MORPH_CLOSE: number;
export var MORPH_CROSS: number;
export var MORPH_DILATE: number;
export var MORPH_ELLIPSE: number;
export var MORPH_ERODE: number;
export var MORPH_GRADIENT: number;
export var MORPH_HITMISS: number;
export var MORPH_OPEN: number;
export var MORPH_RECT: number;
export var MORPH_TOPHAT: number;
export var MOTION_AFFINE: number;
export var MOTION_EUCLIDEAN: number;
export var MOTION_HOMOGRAPHY: number;
export var MOTION_TRANSLATION: number;
export var Mat_AUTO_STEP: number;
export var Mat_CONTINUOUS_FLAG: number;
export var Mat_DEPTH_MASK: number;
export var Mat_MAGIC_MASK: number;
export var Mat_MAGIC_VAL: number;
export var Mat_SUBMATRIX_FLAG: number;
export var Mat_TYPE_MASK: number;
export var NORMAL_CLONE: number;
export var NORMCONV_FILTER: number;
export var NORM_HAMMING: number;
export var NORM_HAMMING2: number;
export var NORM_INF: number;
export var NORM_L1: number;
export var NORM_L2: number;
export var NORM_L2SQR: number;
export var NORM_MINMAX: number;
export var NORM_RELATIVE: number;
export var NORM_TYPE_MASK: number;
export var OPTFLOW_FARNEBACK_GAUSSIAN: number;
export var OPTFLOW_LK_GET_MIN_EIGENVALS: number;
export var OPTFLOW_USE_INITIAL_FLOW: number;
export var ORB_FAST_SCORE: number;
export var ORB_HARRIS_SCORE: number;
export var PCA_DATA_AS_COL: number;
export var PCA_DATA_AS_ROW: number;
export var PCA_USE_AVG: number;
export var PROJ_SPHERICAL_EQRECT: number;
export var PROJ_SPHERICAL_ORTHO: number;
export var Param_ALGORITHM: number;
export var Param_BOOLEAN: number;
export var Param_FLOAT: number;
export var Param_INT: number;
export var Param_MAT: number;
export var Param_MAT_VECTOR: number;
export var Param_REAL: number;
export var Param_SCALAR: number;
export var Param_STRING: number;
export var Param_UCHAR: number;
export var Param_UINT64: number;
export var Param_UNSIGNED_INT: number;
export var RANSAC: number;
export var RECURS_FILTER: number;
export var REDUCE_AVG: number;
export var REDUCE_MAX: number;
export var REDUCE_MIN: number;
export var REDUCE_SUM: number;
export var RETR_CCOMP: number;
export var RETR_EXTERNAL: number;
export var RETR_FLOODFILL: number;
export var RETR_LIST: number;
export var RETR_TREE: number;
export var RHO: number;
export var RNG_NORMAL: number;
export var RNG_UNIFORM: number;
export var ROTATE_180: number;
export var ROTATE_90_CLOCKWISE: number;
export var ROTATE_90_COUNTERCLOCKWISE: number;
export var SOLVELP_MULTI: number;
export var SOLVELP_SINGLE: number;
export var SOLVELP_UNBOUNDED: number;
export var SOLVELP_UNFEASIBLE: number;
export var SOLVEPNP_AP3P: number;
export var SOLVEPNP_DLS: number;
export var SOLVEPNP_EPNP: number;
export var SOLVEPNP_IPPE: number;
export var SOLVEPNP_IPPE_SQUARE: number;
export var SOLVEPNP_ITERATIVE: number;
export var SOLVEPNP_MAX_COUNT: number;
export var SOLVEPNP_P3P: number;
export var SOLVEPNP_UPNP: number;
export var SORT_ASCENDING: number;
export var SORT_DESCENDING: number;
export var SORT_EVERY_COLUMN: number;
export var SORT_EVERY_ROW: number;
export var SVD_FULL_UV: number;
export var SVD_MODIFY_A: number;
export var SVD_NO_UV: number;
export var SparseMat_HASH_BIT: number;
export var SparseMat_HASH_SCALE: number;
export var SparseMat_MAGIC_VAL: number;
export var SparseMat_MAX_DIM: number;
export var StereoBM_PREFILTER_NORMALIZED_RESPONSE: number;
export var StereoBM_PREFILTER_XSOBEL: number;
export var StereoMatcher_DISP_SCALE: number;
export var StereoMatcher_DISP_SHIFT: number;
export var StereoSGBM_MODE_HH: number;
export var StereoSGBM_MODE_HH4: number;
export var StereoSGBM_MODE_SGBM: number;
export var StereoSGBM_MODE_SGBM_3WAY: number;
export var Subdiv2D_NEXT_AROUND_DST: number;
export var Subdiv2D_NEXT_AROUND_LEFT: number;
export var Subdiv2D_NEXT_AROUND_ORG: number;
export var Subdiv2D_NEXT_AROUND_RIGHT: number;
export var Subdiv2D_PREV_AROUND_DST: number;
export var Subdiv2D_PREV_AROUND_LEFT: number;
export var Subdiv2D_PREV_AROUND_ORG: number;
export var Subdiv2D_PREV_AROUND_RIGHT: number;
export var Subdiv2D_PTLOC_ERROR: number;
export var Subdiv2D_PTLOC_INSIDE: number;
export var Subdiv2D_PTLOC_ON_EDGE: number;
export var Subdiv2D_PTLOC_OUTSIDE_RECT: number;
export var Subdiv2D_PTLOC_VERTEX: number;
export var THRESH_BINARY: number;
export var THRESH_BINARY_INV: number;
export var THRESH_MASK: number;
export var THRESH_OTSU: number;
export var THRESH_TOZERO: number;
export var THRESH_TOZERO_INV: number;
export var THRESH_TRIANGLE: number;
export var THRESH_TRUNC: number;
export var TM_CCOEFF: number;
export var TM_CCOEFF_NORMED: number;
export var TM_CCORR: number;
export var TM_CCORR_NORMED: number;
export var TM_SQDIFF: number;
export var TM_SQDIFF_NORMED: number;
export var TermCriteria_COUNT: number;
export var TermCriteria_EPS: number;
export var TermCriteria_MAX_ITER: number;
export var UMatData_ASYNC_CLEANUP: number;
export var UMatData_COPY_ON_MAP: number;
export var UMatData_DEVICE_COPY_OBSOLETE: number;
export var UMatData_DEVICE_MEM_MAPPED: number;
export var UMatData_HOST_COPY_OBSOLETE: number;
export var UMatData_TEMP_COPIED_UMAT: number;
export var UMatData_TEMP_UMAT: number;
export var UMatData_USER_ALLOCATED: number;
export var UMat_AUTO_STEP: number;
export var UMat_CONTINUOUS_FLAG: number;
export var UMat_DEPTH_MASK: number;
export var UMat_MAGIC_MASK: number;
export var UMat_MAGIC_VAL: number;
export var UMat_SUBMATRIX_FLAG: number;
export var UMat_TYPE_MASK: number;
export var USAGE_ALLOCATE_DEVICE_MEMORY: number;
export var USAGE_ALLOCATE_HOST_MEMORY: number;
export var USAGE_ALLOCATE_SHARED_MEMORY: number;
export var USAGE_DEFAULT: number;
export var WARP_FILL_OUTLIERS: number;
export var WARP_INVERSE_MAP: number;
export var WARP_POLAR_LINEAR: number;
export var WARP_POLAR_LOG: number;
export var _InputArray_CUDA_GPU_MAT: number;
export var _InputArray_CUDA_HOST_MEM: number;
export var _InputArray_EXPR: number;
export var _InputArray_FIXED_SIZE: number;
export var _InputArray_FIXED_TYPE: number;
export var _InputArray_KIND_MASK: number;
export var _InputArray_KIND_SHIFT: number;
export var _InputArray_MAT: number;
export var _InputArray_MATX: number;
export var _InputArray_NONE: number;
export var _InputArray_OPENGL_BUFFER: number;
export var _InputArray_STD_ARRAY: number;
export var _InputArray_STD_ARRAY_MAT: number;
export var _InputArray_STD_BOOL_VECTOR: number;
export var _InputArray_STD_VECTOR: number;
export var _InputArray_STD_VECTOR_CUDA_GPU_MAT: number;
export var _InputArray_STD_VECTOR_MAT: number;
export var _InputArray_STD_VECTOR_UMAT: number;
export var _InputArray_STD_VECTOR_VECTOR: number;
export var _InputArray_UMAT: number;
export var _OutputArray_DEPTH_MASK_16F: number;
export var _OutputArray_DEPTH_MASK_16S: number;
export var _OutputArray_DEPTH_MASK_16U: number;
export var _OutputArray_DEPTH_MASK_32F: number;
export var _OutputArray_DEPTH_MASK_32S: number;
export var _OutputArray_DEPTH_MASK_64F: number;
export var _OutputArray_DEPTH_MASK_8S: number;
export var _OutputArray_DEPTH_MASK_8U: number;
export var _OutputArray_DEPTH_MASK_ALL: number;
export var _OutputArray_DEPTH_MASK_ALL_16F: number;
export var _OutputArray_DEPTH_MASK_ALL_BUT_8S: number;
export var _OutputArray_DEPTH_MASK_FLT: number;
export var __UMAT_USAGE_FLAGS_32BIT: number;
export var BadAlign: number;
export var BadAlphaChannel: number;
export var BadCOI: number;
export var BadCallBack: number;
export var BadDataPtr: number;
export var BadDepth: number;
export var BadImageSize: number;
export var BadModelOrChSeq: number;
export var BadNumChannel1U: number;
export var BadNumChannels: number;
export var BadOffset: number;
export var BadOrder: number;
export var BadOrigin: number;
export var BadROISize: number;
export var BadStep: number;
export var BadTileSize: number;
export var GpuApiCallError: number;
export var GpuNotSupported: number;
export var HeaderIsNull: number;
export var MaskIsTiled: number;
export var OpenCLApiCallError: number;
export var OpenCLDoubleNotSupported: number;
export var OpenCLInitError: number;
export var OpenCLNoAMDBlasFft: number;
export var OpenGlApiCallError: number;
export var OpenGlNotSupported: number;
export var StsAssert: number;
export var StsAutoTrace: number;
export var StsBackTrace: number;
export var StsBadArg: number;
export var StsBadFlag: number;
export var StsBadFunc: number;
export var StsBadMask: number;
export var StsBadMemBlock: number;
export var StsBadPoint: number;
export var StsBadSize: number;
export var StsDivByZero: number;
export var StsError: number;
export var StsFilterOffsetErr: number;
export var StsFilterStructContentErr: number;
export var StsInplaceNotSupported: number;
export var StsInternal: number;
export var StsKernelStructContentErr: number;
export var StsNoConv: number;
export var StsNoMem: number;
export var StsNotImplemented: number;
export var StsNullPtr: number;
export var StsObjectNotFound: number;
export var StsOk: number;
export var StsOutOfRange: number;
export var StsParseError: number;
export var StsUnmatchedFormats: number;
export var StsUnmatchedSizes: number;
export var StsUnsupportedFormat: number;
export var StsVecLengthErr: number;
export var TEST_CUSTOM: number;
export var TEST_EQ: number;
export var TEST_GE: number;
export var TEST_GT: number;
export var TEST_LE: number;
export var TEST_LT: number;
export var TEST_NE: number;
export var DNN_BACKEND_CUDA: number;
export var DNN_BACKEND_DEFAULT: number;
export var DNN_BACKEND_HALIDE: number;
export var DNN_BACKEND_INFERENCE_ENGINE: number;
export var DNN_BACKEND_OPENCV: number;
export var DNN_BACKEND_VKCOM: number;
export var DNN_TARGET_CPU: number;
export var DNN_TARGET_CUDA: number;
export var DNN_TARGET_CUDA_FP16: number;
export var DNN_TARGET_FPGA: number;
export var DNN_TARGET_MYRIAD: number;
export var DNN_TARGET_OPENCL: number;
export var DNN_TARGET_OPENCL_FP16: number;
export var DNN_TARGET_VULKAN: number;
export var CALIB_CHECK_COND: number;
export var CALIB_FIX_SKEW: number;
export var CALIB_RECOMPUTE_EXTRINSIC: number;
/** object */
export var FS: any;
/** function */
export var imread: any;
/** function */
export var imshow: any;
/** function */
export var VideoCapture: any;
/** function */
export var Range: any;
/** function */
export var Point: any;
/** function */
export var Size: any;
/** function */
export var Rect: any;
/** function */
export var RotatedRect: any;
/** function */
export var Scalar: any;
/** function */
export var MinMaxLoc: any;
/** function */
export var Circle: any;
/** function */
export var TermCriteria: any;
/** function */
export var matFromArray: any;
/** function */
export var matFromImageData: any; | the_stack |
import { expect } from "chai";
import { Timeline } from "./Timeline";
interface StateTimelineEvent {
state: string;
time: number;
}
interface TimelineNameEvent {
name: string;
time: number;
}
interface TimelineValueEvent {
time: number;
value: any;
}
describe("Timeline", () => {
it("can be created and disposed", () => {
const sched = new Timeline();
sched.dispose();
});
it("accepts events into the timeline", () => {
const sched = new Timeline<StateTimelineEvent>();
sched.add({
state: "A",
time: 0,
});
sched.add({
state: "B",
time: 1,
});
sched.add({
state: "C",
time: 2,
});
sched.dispose();
});
it("can insert events in the timeline in the right order", () => {
const sched = new Timeline();
sched.add({
time: 0,
});
sched.add({
time: 2,
});
sched.add({
time: 1,
});
let index = 0;
const eventTimes = [0, 1, 2];
sched.forEach((event) => {
expect(event.time).to.equal(eventTimes[index++]);
});
sched.dispose();
});
it("can get the length of the timeline", () => {
const sched = new Timeline();
expect(sched.length).to.equal(0);
sched.add({
time: 0,
});
expect(sched.length).to.equal(1);
sched.dispose();
});
it("can remove items from the timeline", () => {
const sched = new Timeline();
const obj = { time: 0 };
sched.add(obj);
sched.add({
time: 2,
});
expect(sched.length).to.equal(2);
sched.remove(obj);
expect(sched.length).to.equal(1);
sched.dispose();
});
it("has no effect to remove an object which is not there", () => {
const sched = new Timeline();
sched.add({
time: 2,
});
sched.remove({ time: 1 });
expect(sched.length).to.equal(1);
sched.forEach((event) => {
sched.remove({ time: 4 });
});
expect(sched.length).to.equal(1);
sched.dispose();
});
it("can search for events in the timeline by time", () => {
const sched = new Timeline();
sched.add({
time: 0,
});
sched.add({
time: 2,
});
sched.add({
time: 1,
});
// expect(sched._search(0)).to.equal(0);
// expect(sched._search(0.01)).to.equal(0);
// expect(sched._search(1)).to.equal(1);
// expect(sched._search(1.01)).to.equal(1);
// expect(sched._search(2)).to.equal(2);
// expect(sched._search(20000)).to.equal(2);
// expect(sched._search(-1)).to.equal(-1);
sched.dispose();
});
it("can get a previous event", () => {
const sched = new Timeline();
const event0 = {
time: 0,
};
const event1 = {
time: 1,
};
sched.add(event0);
sched.add(event1);
expect(sched.previousEvent(event1)).to.equal(event0);
expect(sched.previousEvent(event0)).to.equal(null);
sched.dispose();
});
it("can get the scheduled event at the given time", () => {
const sched = new Timeline<StateTimelineEvent>();
sched.add({
state: "A",
time: 2,
});
sched.add({
state: "C",
time: 9.4,
});
sched.add({
state: "B",
time: 6,
});
expect(sched.get(0)).is.null;
const e1 = sched.get(2);
const e2 = sched.get(5.9);
const e3 = sched.get(6.1);
const e4 = sched.get(12);
if (e1 && e2 && e3 && e4) {
expect(e1.state).is.equal("A");
expect(e2.state).is.equal("A");
expect(e3.state).is.equal("B");
expect(e4.state).is.equal("C");
} else {
throw new Error("expected 4 events");
}
sched.dispose();
});
it("puts the second scheduled event after if two events are scheduled at the same time", () => {
const sched = new Timeline<TimelineNameEvent>();
sched.add({
name: "A",
time: 0,
});
sched.add({
name: "B",
time: 0,
});
const firstEvent0 = sched.get(0);
if (firstEvent0) {
expect(firstEvent0.name).is.equal("B");
}
sched.add({
name: "C",
time: 0,
});
const firstEvent1 = sched.get(0);
if (firstEvent1) {
expect(firstEvent1.name).is.equal("C");
}
sched.dispose();
});
it("can the next event after the given time", () => {
const sched = new Timeline<StateTimelineEvent>();
expect(sched.getAfter(0)).is.null;
sched.add({
state: "A",
time: 0.1,
});
sched.add({
state: "B",
time: 1.1,
});
sched.add({
state: "C",
time: 2.1,
});
const firstEvent = sched.getAfter(0);
const secondEvent = sched.getAfter(1);
if (firstEvent && secondEvent) {
expect(firstEvent.state).is.equal("A");
expect(secondEvent.state).is.equal("B");
} else {
throw new Error("should have 2 events");
}
expect(sched.getAfter(3)).is.null;
sched.dispose();
});
it("can the event before the event before the given time", () => {
const sched = new Timeline<StateTimelineEvent>();
expect(sched.getBefore(0)).is.null;
sched.add({
state: "A",
time: 0.1,
});
sched.add({
state: "B",
time: 1.1,
});
sched.add({
state: "C",
time: 2.1,
});
expect(sched.getBefore(0)).is.null;
const firstEvent = sched.getBefore(1.1);
const secondEvent = sched.getBefore(2.1);
const thirdEvent = sched.getBefore(3);
if (firstEvent && secondEvent && thirdEvent) {
expect(firstEvent.state).is.equal("A");
expect(secondEvent.state).is.equal("B");
expect(thirdEvent.state).is.equal("C");
} else {
throw new Error("should have 3 events");
}
sched.dispose();
});
it("can cancel an item", () => {
const sched = new Timeline();
sched.add({ time: 3 });
sched.add({ time: 5 });
sched.add({ time: 4 });
sched.add({ time: 8 });
sched.add({ time: 5 });
expect(sched.length).to.equal(5);
sched.cancel(10);
expect(sched.length).to.equal(5);
sched.cancel(5);
expect(sched.length).to.equal(2);
sched.cancel(3);
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can cancel items after the given time", () => {
const sched = new Timeline();
for (let i = 0; i < 100; i++) {
sched.add({ time: 100 - i });
}
sched.cancel(10);
expect(sched.length).to.equal(9);
sched.cancel(5);
expect(sched.length).to.equal(4);
sched.cancel(0);
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can cancel items before the given time", () => {
const sched = new Timeline();
for (let i = 0; i < 100; i++) {
sched.add({ time: i });
}
sched.cancelBefore(9);
expect(sched.length).to.equal(90);
sched.cancelBefore(10.1);
expect(sched.length).to.equal(89);
sched.cancelBefore(100);
expect(sched.length).to.equal(0);
sched.dispose();
});
it("has no problem with many items", () => {
const sched = new Timeline();
for (let i = 0; i < 10000; i++) {
sched.add({
time: i,
});
}
for (let j = 0; j < 1000; j++) {
const val = sched.get(j);
if (val) {
expect(val.time).to.equal(j);
}
}
sched.dispose();
});
it("inforces increasing time", () => {
const sched = new Timeline({
increasing: true,
});
expect(() => {
sched.add({ time: 1 });
sched.add({ time: 0 });
}).to.throw(Error);
sched.dispose();
});
it("the same time value is allowed to be added", () => {
const sched = new Timeline({
increasing: true,
});
sched.add({ time: 1 });
sched.add({ time: 1 });
sched.add({ time: 1 });
sched.dispose();
});
it("can constrain the length of the timeline", () => {
const sched = new Timeline(4);
for (let i = 0; i < 10000; i++) {
sched.add({
time: i,
});
}
expect(sched.length).to.equal(4);
sched.dispose();
});
it("can peek and shift off the first element", () => {
const timeline = new Timeline<TimelineValueEvent>();
timeline.add({
time: 0,
value: "a",
});
timeline.add({
time: 1,
value: "b",
});
timeline.add({
time: 2,
value: "c",
});
expect(timeline.length).to.equal(3);
const peekValue = timeline.peek();
if (peekValue) {
expect(peekValue.value).to.equal("a");
} else {
throw new Error("should have value");
}
expect(timeline.length).to.equal(3);
const shiftValue = timeline.shift();
if (shiftValue) {
expect(shiftValue.value).to.equal("a");
} else {
throw new Error("should have value");
}
expect(timeline.length).to.equal(2);
const peekValue2 = timeline.peek();
if (peekValue2) {
expect(peekValue2.value).to.equal("b");
} else {
throw new Error("should have value");
}
const shiftValue2 = timeline.shift();
if (shiftValue2) {
expect(shiftValue2.value).to.equal("b");
} else {
throw new Error("should have value");
}
expect(timeline.length).to.equal(1);
timeline.dispose();
});
context("Iterators", () => {
it("iterates over all items and returns and item", () => {
const sched = new Timeline();
sched.add({ time: 0 });
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEach((event) => {
expect(event).to.be.an("object");
count++;
});
expect(count).to.equal(5);
sched.dispose();
});
it("iterates over all items before the given time", () => {
const sched = new Timeline();
sched.add({ time: 0 });
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachBefore(0.3, (event) => {
expect(event).to.be.an("object");
expect(event.time).to.be.at.most(0.3);
count++;
});
expect(count).to.equal(4);
sched.dispose();
});
it("handles time ranges before the available objects", () => {
const sched = new Timeline();
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachBefore(0, () => {
count++;
});
expect(count).to.equal(0);
sched.dispose();
});
it("iterates over all items after the given time", () => {
const sched = new Timeline();
sched.add({ time: 0 });
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachAfter(0.1, (event) => {
expect(event).to.be.an("object");
expect(event.time).to.be.above(0.1);
count++;
});
expect(count).to.equal(3);
sched.dispose();
});
it("handles time ranges after the available objects", () => {
const sched = new Timeline();
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachAfter(0.5, () => {
count++;
});
expect(count).to.equal(0);
sched.dispose();
});
it("handles time ranges before the first object", () => {
const sched = new Timeline();
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachAfter(-Infinity, () => {
count++;
});
expect(count).to.equal(4);
sched.dispose();
});
it("can iterate after inclusive of the item at the given time", () => {
const sched = new Timeline();
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachFrom(0.2, () => {
count++;
});
expect(count).to.equal(4);
count = 0;
sched.forEachFrom(0.21, () => {
count++;
});
expect(count).to.equal(2);
count = 0;
sched.forEachFrom(0, () => {
count++;
});
expect(count).to.equal(5);
sched.dispose();
});
it("iterates over all items at the given time", () => {
const sched = new Timeline();
sched.add({ time: 0 });
sched.add({ time: 0 });
sched.add({ time: 0.2 });
sched.add({ time: 0.2 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachAtTime(0.1, (event) => {
count++;
});
expect(count).to.equal(0);
// and with an actual time
sched.forEachAtTime(0.2, (event) => {
expect(event.time).to.equal(0.2);
count++;
});
expect(count).to.equal(2);
sched.dispose();
});
it("can remove items during iterations", () => {
const sched = new Timeline();
for (let i = 0; i < 1000; i++) {
sched.add({ time: i });
}
sched.forEach((event) => {
sched.remove(event);
});
expect(sched.length).to.equal(0);
sched.dispose();
});
it("can add items during iteration", () => {
interface AddedInterface {
time: number;
added?: boolean;
}
const sched = new Timeline<AddedInterface>();
for (let i = 0; i < 1000; i++) {
sched.add({ time: i });
}
let added = false;
sched.forEach((event) => {
if (!added) {
added = true;
sched.add({
added: true,
time: 10,
});
}
});
expect(sched.length).to.equal(1001);
sched.dispose();
});
it("can iterate between a time range", () => {
const sched = new Timeline();
sched.add({ time: 0.1 });
sched.add({ time: 0.2 });
sched.add({ time: 0.3 });
sched.add({ time: 0.4 });
let count = 0;
sched.forEachBetween(0.2, 0.4, (event) => {
count++;
expect(event.time).to.be.within(0.2, 0.3);
});
expect(count).to.equal(2);
count = 0;
sched.forEachBetween(0.21, 0.4, (event) => {
count++;
expect(event.time).to.be.within(0.21, 0.3);
});
expect(count).to.equal(1);
count = 0;
sched.forEachBetween(0.21, 0.39, (event) => {
count++;
expect(event.time).to.be.within(0.21, 0.39);
});
expect(count).to.equal(1);
count = 0;
sched.forEachBetween(0, 0.11, (event) => {
count++;
expect(event.time).to.be.within(0, 0.11);
});
expect(count).to.equal(1);
count = 0;
sched.forEachBetween(0, 0.09, (event) => {
count++;
expect(event.time).to.be.within(0, 0.09);
});
expect(count).to.equal(0);
count = 0;
sched.forEachBetween(0.41, 0.5, (event) => {
count++;
expect(event.time).to.be.within(0.41, 0.5);
});
expect(count).to.equal(0);
sched.dispose();
});
});
}); | the_stack |
interface Layui {
$: JQueryStatic;
carousel: Layui.Carousel;
colorpicker: Layui.ColorPicker;
dropdown: Layui.DropDown;
element: Layui.Element;
flow: Layui.Flow;
form: Layui.Form;
global: {};
jquery: JQueryStatic;
lay: Layui.Lay;
laydate: Layui.Laydate;
layedit: Layui.Layedit;
layer: Layui.Layer;
laypage: Layui.Laypage;
laytpl: Layui.Laytpl;
'layui.all': string;
rate: Layui.Rate;
slider: Layui.Slider;
table: Layui.Table;
transfer: Layui.Transfer;
tree: Layui.Tree;
upload: Layui.Upload;
util: Layui.Util;
v: string;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 静态属性。获得一些配置及临时的缓存信息
*/
cache: Layui.CacheData;
/**
* 内置模块名和外置名称映射
*/
modules: Layui.Modules;
// -----------------prototype method-------------------------------------↓↓↓↓
// https://www.layui.com/doc/base/infrastructure.html
/**
* 对象是否为泛数组结构,实例: <br/>
* layui._isArray([1,6]); true <br/>
* layui._isArray($('div')); true <br/>
* layui._isArray(document.querySelectorAll('div')); true
* @param [obj] 如 Array、NodeList、jQuery 对象等等。
*/
_isArray(obj: any): boolean;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 获取详细数据类型(基本数据类型和各类常见引用类型) <br/>
* 常见类型字符:Function|Array|Date|RegExp|Object|Error|Symbol <br/>
* 实例:layui._typeof([]); //array layui._typeof({}); //object layui._typeof(new Date()); //date等等。
* @param [operand] 参数
*/
_typeof(operand: any): string;
/**
* 动态加载 CSS文件(相对路径)
* @param [filename] 文件名,相对路径 比如a.css,/a/a.css
* @param [callback] css文件加载成功后的回调,错误则不会调用
* @param [cssname] 用于id标识,比如xx则生成link标签的id是 layuicss-xx <br/>
* 如果不传,则用文件名拼接,比如layui.js则id是layuicss-layuijs
*/
addcss(filename: string, callback: () => void, cssname?: string): any;
/**
* 动态加载 CSS文件(相对路径)
* @param [filename] 文件名,相对路径 比如a.css,/a/a.css
* @param [cssname] 用于id标识,比如xx则生成link标签的id是 layuicss-xx <br/>
* 如果不传,则用文件名拼接,比如layui.js则id是layuicss-layuijs
*/
addcss(filename: string, cssname?: string): any;
// https://www.layui.com/doc/base/infrastructure.html
// https://www.layui.com/doc/base/modules.html
/**
* 全局配置,设置并返回(layui级别配置,影响layui.xx模块配置)
* @param [options] 参数 可选
*/
config(options?: Layui.GlobalConfigOptions): Layui;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 本地存储 基于localStorage <br/>
* layui对 localStorage 和 sessionStorage 友好封装,可更方便地管理本地数据。
* @param [tableName] key键, 为sessionStorage中的一个key
* @param [row] 存储的json对象数据
*/
data(tableName: string, row?: { key: string; value?: any; remove?: boolean } | null): any;
// https://www.layui.com/doc/base/modules.html#extend
/**
* 扩展一个 layui 模块,挂载到layui上
* @param [mods] 模块名,用于声明当前新定义模块所依赖的模块
* @param [callback] 回调函数: 通过回调中参数export来挂载模块到layui <br/>
* 模块加载完毕的回调函数,它返回一个 exports 参数,用于输出该模块的接口。 <br/>
* 其参数exports 是一个函数,它接受两个参数,第1个参数为模块名,第2个参数为模块接口。
*/
define(mods: string[] | string, callback: Layui.ExportsCallback): any;
/**
* 扩展一个 layui 模块,挂载到layui上
* @param [callback] 回调函数: 通过回调中参数export来挂载模块到layui <br/>
* 模块加载完毕的回调函数,它返回一个 exports 参数,用于输出该模块的接口。 <br/>
* 其参数exports 是一个函数,它接受两个参数,第1个参数为模块名,第2个参数为模块接口。
*/
define(callback: Layui.ExportsCallback): any;
// https://www.layui.com/doc/base/infrastructure.html
// 获取浏览器信息,从navigator.userAgent.toLowerCase()中匹配
/**
* 获取浏览器信息:内置属性
* @param [key] 获取浏览器信息
*/
device(key: 'android' | 'ie' | 'ios' | 'mobile' | 'weixin'): boolean;
/**
* 获取浏览器信息:根据指定的key
* @param [key] 属性
*/
device(key: string): any;
/**
* 获取浏览器信息:系统
* @param [key]
*/
device(key: 'os'): string;
/**
* 获取浏览器信息:全部
*/
device(): {
/**
* 当前浏览器所在的底层操作系统,如:Windows、Linux、Mac 等
*/
os: string;
/**
* 当前浏览器是否为 ie6-11 的版本,如果不是 ie 浏览器,则为 false
*/
ie: boolean;
/**
* 当前浏览器是否为微信 App 环境
*/
weixin: boolean;
/**
* 当前浏览器是否为安卓系统环境
*/
android: boolean;
/**
* 当前浏览器是否为 IOS 系统环境
*/
ios: boolean;
/**
* 当前浏览器是否为移动设备环境
* @since v2.5.7
*/
mobile: boolean;
[index: string]: any;
};
// https://www.layui.com/doc/base/infrastructure.html
/**
* 对象(Array、Object、DOM 对象等)遍历,可用于取代 for 语句
* @param [arry] Array对象
* @param [fn] 回调函数
*/
each(arry: any[], fn?: (k: number, v: any) => void): Layui;
/**
* 对象(Array、Object、DOM 对象等)遍历,可用于取代 for 语句
* @param [obj] Object等对象
* @param [fn] 回调函数
*/
each(obj: object, fn: (k: string, v: any) => void): Layui;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 执行自定义模块事件,搭配 onevent 使用,参数说明:<br/>
* 实例一:按照select后边括号内容filter来匹配,比如filter空或没有括号则可匹配到<br/>
* layui.onevent("form", "select()", console.log);<br/>
* layui.event("form","select()",[1,2,3]);<br/>
* 实例二:{*}可匹配全部filter<br/>
* layui.onevent("form", "select(xx)", console.log);<br/>
* layui.event("form","select({*})",[1,2,3]);<br/>
* 实例三:filter严格匹配<br/>
* layui.onevent("form", "select(xx)", console.log);<br/>
* layui.event("form","select(xx)",[1,2,3]);
* @param [modName] 模块名称,比如form,<br/>
* @param [events] 事件,比如:select(filter)<br/>
* @param [params] 回调参数,作为绑定的回调函数的参数<br/>
* @param [fn] 回调函数,不建议用
*/
event(modName: string, events: string, params?: any, fn?: (...arg: any) => any): any;
// https://www.layui.com/doc/base/modules.html#extend
/**
* 拓展一个模块别名,如:layui.extend({test: '/res/js/test'})
* @param [options]
*/
extend(options: { [index: string]: string }): Layui;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 用于获取模块对应的 define 回调函数
* @param [modName] 模块名
*/
factory(modName: string): (...arg: any) => any;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 获得一个原始 DOM 节点的 style 属性值,如:layui.getStyle(document.body, 'font-size')
* @param [node] 必须dom
* @param [name] 标签的css属性 比如 align-content
*/
getStyle(node: HTMLElement | null, name: string): any;
// https://www.layui.com/doc/base/infrastructure.html#other
/**
* 向控制台打印一些异常信息,目前只返回了 error方法: <br/>
* 实例:layui.hint().error('出错啦');layui.hint().error('出错啦','warn');
*/
hint(): { error: (msg: any, type?: string | 'log' | 'info' | 'error' | 'warn' | 'debug') => void };
// https://www.layui.com/doc/base/infrastructure.html#other
/**
* 图片预加载
* @param [url] 图片地址直接作为Image.src值
* @param [callback] 回调函数,会透出img对象
* @param [error]
*/
img(url: string, callback?: (img: HTMLImageElement) => void, error?: (e: Event | string) => void): any;
// https://www.layui.com/doc/base/infrastructure.html#link
/**
* 动态加载 CSS, 一般只是用于动态加载你的外部 CSS 文件
* @param [href] css文件的地址(绝对or相对)直接作为link的href,如果要加载当前目录/css/aa.css可使用layui.addcss("aa.css")
* @param [callback] css文件加载成功后的回调,错误则不会调用
* @param [cssname] 用于id标识,比如xx则生成link标签的id是 layuicss-xx <br/>
* 如果不传,则用文件名拼接,比如layui.js则id是layuicss-layuijs
*/
link(href: string, callback: () => void, cssname?: string): any;
/**
* 动态加载 CSS
* @param [href] css地址
* @param [cssname] 用于id标识,比如xx则生成link标签的id是 layuicss-xx <br/>
* 如果不传,则用文件名拼接,比如layui.js则id是layuicss-layuijs
*/
link(href: string, cssname?: string): any;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 用于移除模块相关事件的监听
* 如:layui.off('select(filter)', 'form'),那么 form.on('select(filter)', callback)的事件将会被移除。
* @param [events] 事件名
* @param [modName] 模块名,比如 layer,table,form等
*/
off(events: string, modName: string): Layui;
/**
* 禁止使用,请传入callback
* @param [events] 事件名
* @param [modName] 模块名,比如 layer,table,form等
*/
on(events: string, modName: string): Layui;
/**
* 触发指定模块的指定事件 <br/>
* 实例:layui.on("select(filter)","form",console.log);
* @param [events] 事件名
* @param [modName] 模块名,比如 layer,table,form等
* @param [callback] 回调函数
*/
on(events: string, modName: string, callback: (obj: any) => any): (...arg: any) => any;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 禁止使用,请传入callback <br/>
* 增加自定义模块事件。有兴趣的同学可以阅读 layui.js 源码以及 form 模块
* @param [modName] 模块名,比如 layer,table,form等
* @param [events] 事件名
*/
onevent(modName: string, events: string): Layui;
/**
* 增加自定义模块事件。有兴趣的同学可以阅读 layui.js 源码以及 form 模块
* @param [modName] 模块名,比如 layer,table,form等
* @param [events] 事件名
* @param [callback] 回调函数
*/
onevent(modName: string, events: string, callback: (obj: any) => any): (...arg: any) => any;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 获得 location.hash 路由结构,一般在单页面应用中发挥作用。
* @param [hash] 默认 location.hash
*/
router(hash?: string): Layui.UrlHash;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 本地存储 基于sessionStorage <br/>
* layui对 localStorage 和 sessionStorage 友好封装,可更方便地管理本地数据。
* @param [tableName] key键, 为sessionStorage中的一个key
* @param [row] 存储的json对象数据
*/
sessionData(tableName: string, row?: { key: string; value?: any; remove?: boolean } | null): any;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 将数组中的对象按某个成员重新对该数组排序,如: <br/>
* layui.sort([{a: 3},{a: 1},{a: 5}], 'a') 默认升序
* @param [obj] 有比较key的对象数组
* @param [key] 对象的一个属性,用于取值比较
* @param [desc] true则启用降序, 默认false即升序
*/
sort(obj: any[], key: string, desc?: boolean): any;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 阻止事件冒泡
* @param [event] 阻止的事件
*/
stope(event?: Event): void;
// https://www.layui.com/doc/base/infrastructure.html
/**
* 用于将一段 URL 链接中的 pathname、search、hash 属性值进行对象化处理 <br/>
* 参数: href 可选。若不传,则自动读取当前页面的 url(即:location.href) <br/>
* 示例:let url = layui.url();
* @param [href] http(s)地址
*/
url(href?: string): {
hash: Layui.UrlHash;
pathname: string[];
search: object;
};
// use function
// https://www.layui.com/doc/
// https://www.layui.com/doc/base/infrastructure.html
// https://www.layui.com/doc/base/modules.html
/**
* 使用特定模块
* @param [mods] 内置或自定模块名 (若模块不存在则抛js错误,callback不会执行)
* @param [callback] 回调函数
* @param [exports] 数组,存储对 mods解析后加载的模块
*/
use<K extends keyof Layui.LayuiModuleMap>(
mods: K,
callback: (this: Layui, module: Layui.LayuiModuleMap[K]) => any,
exports?: any[],
): { v: string };
/**
* 使用自定模块
* @param [mods] 自定义模块,非内置模块
* @param [callback] 回调函数
* @param [exports] 数组,存储对 mods解析后加载的模块
*/
use(mods: string, callback: (this: Layui, module: any) => any, exports?: any[]): { v: string };
/**
* 使用多模块
* @param [mods] 内置或自定模块名 (若模块不存在则抛js错误,callback不会执行)
* @param [callback] 回调函数 <br/>
* 1、不建议callback中设置参数因为没有TS约束,可用layui.xx调用具体模块; <br/>
* 2、手动在callback回调中指定类型比如 util:layui.Util
* @param [exports] 暴露出挂载的对象
*/
use(mods: string[], callback: (this: Layui, ...module: any) => any, exports?: any[]): { v: string };
/**
* 使用特定模块
* @param [callback] 回调函数, 从 layui 2.6 开始,首个参数是callback函数,则表示引用所有内置模块到layui.xx<br/>
* @param [exports] 无任何用途,可不传
*/
use(callback: (this: Layui, module: { config: object; time: number }) => any, exports?: any[]): { v: string };
/**
* 代码高亮
* https://www.layui.com/doc/modules/code.html
* @param [option] 基础参数
*/
code(option?: Layui.CodeOption): void;
} | the_stack |
import {
Address,
Amount,
BlockHeightTimeout,
ChainId,
Fee,
Hash,
isBlockHeightTimeout,
PubkeyBundle,
SwapId,
SwapIdBytes,
SwapTimeout,
UnsignedTransaction,
} from "@iov/bcp";
import { fromHex, toHex } from "@iov/encoding";
import { isJsonRpcErrorResponse, makeJsonRpcId } from "@iov/jsonrpc";
import BN from "bn.js";
import { Abi } from "../abi";
import { pubkeyToAddress } from "../address";
import { EthereumRpcClient } from "../ethereumrpcclient";
import { EthereumRpcTransactionResult } from "../ethereumrpctransactionresult";
import {
GenericTransactionSerializerParameters,
SerializationCommon,
SignedSerializationOptions,
SwapIdPrefix,
UnsignedSerializationOptions,
ZERO_ETH_QUANTITY,
} from "../serializationcommon";
import { Escrow, EscrowState, SmartContractConfig, SmartContractType } from "../smartcontracts/definitions";
import { decodeHexQuantityString, normalizeHex, toEthereumHex } from "../utils";
interface EscrowBaseTransaction extends UnsignedTransaction {
readonly sender: Address;
readonly chainId: ChainId;
readonly swapId: SwapId;
}
export interface EscrowOpenTransaction extends EscrowBaseTransaction {
readonly kind: "smartcontract/escrow_open";
readonly arbiter: Address;
readonly hash: Hash;
readonly timeout: SwapTimeout;
readonly amount: Amount;
}
export interface EscrowClaimTransaction extends EscrowBaseTransaction {
readonly kind: "smartcontract/escrow_claim";
readonly recipient: Address;
}
export interface EscrowAbortTransaction extends EscrowBaseTransaction {
readonly kind: "smartcontract/escrow_abort";
}
export function isEscrowOpenTransaction(
transaction: UnsignedTransaction,
): transaction is EscrowOpenTransaction {
return (transaction as EscrowOpenTransaction).kind === "smartcontract/escrow_open";
}
export function isEscrowClaimTransaction(
transaction: UnsignedTransaction,
): transaction is EscrowClaimTransaction {
return (transaction as EscrowClaimTransaction).kind === "smartcontract/escrow_claim";
}
export function isEscrowAbortTransaction(
transaction: UnsignedTransaction,
): transaction is EscrowAbortTransaction {
return (transaction as EscrowAbortTransaction).kind === "smartcontract/escrow_abort";
}
export function isEscrowTransaction(transaction: UnsignedTransaction): transaction is EscrowBaseTransaction {
const { kind } = transaction;
return kind.startsWith("smartcontract/escrow_");
}
enum EscrowContractMethod {
Open,
Claim,
Abort,
}
export class EscrowContract {
public static buildTransaction(
input: Uint8Array,
json: EthereumRpcTransactionResult,
chainId: ChainId,
fee: Fee,
signerPubkey: PubkeyBundle,
config: SmartContractConfig,
): EscrowAbortTransaction | EscrowClaimTransaction | EscrowOpenTransaction {
// All methods
const positionMethodIdBegin = 0;
const positionMethodIdEnd = positionMethodIdBegin + 4;
const positionSwapIdBegin = positionMethodIdEnd;
const positionSwapIdEnd = positionSwapIdBegin + 32;
// Open only
const positionArbiterBegin = positionSwapIdEnd;
const positionArbiterEnd = positionArbiterBegin + 32;
const positionHashBegin = positionArbiterEnd;
const positionHashEnd = positionArbiterEnd + 32;
const positionTimeoutBegin = positionHashEnd;
const positionTimeoutEnd = positionTimeoutBegin + 32;
// Claim only
const positionRecipientBegin = positionSwapIdEnd;
const positionRecipientEnd = positionSwapIdEnd + 32;
// Get method type
const method: EscrowContractMethod = EscrowContract.getMethodTypeFromInput(
input.slice(positionMethodIdBegin, positionMethodIdEnd),
);
// Extract swap id
const swapIdWithoutPrefix = {
data: input.slice(positionSwapIdBegin, positionSwapIdEnd) as SwapIdBytes,
};
// The sender is used in multiple places, so let's convert it to address once
const sender: Address = pubkeyToAddress(signerPubkey);
// This is a basic transaction that is common to all methods. This is
// incomplete and the final transaction that will be returned needs more
// information that will be decoded from the binary input
const commonTransaction = {
chainId: chainId,
sender: sender,
swapId: {
...swapIdWithoutPrefix,
prefix: config.tokenType,
},
amount: {
quantity: decodeHexQuantityString(json.value),
fractionalDigits: config.fractionalDigits,
tokenTicker: config.tokenTicker,
},
fee: fee,
};
switch (method) {
case EscrowContractMethod.Open:
return {
...commonTransaction,
kind: "smartcontract/escrow_open",
arbiter: Abi.decodeAddress(input.slice(positionArbiterBegin, positionArbiterEnd)),
hash: input.slice(positionHashBegin, positionHashEnd) as Hash,
timeout: {
height: new BN(input.slice(positionTimeoutBegin, positionTimeoutEnd)).toNumber(),
},
};
case EscrowContractMethod.Claim:
return {
...commonTransaction,
recipient: Abi.decodeAddress(input.slice(positionRecipientBegin, positionRecipientEnd)),
kind: "smartcontract/escrow_claim",
};
case EscrowContractMethod.Abort:
return {
...commonTransaction,
kind: "smartcontract/escrow_abort",
};
}
}
public static checkOpenTransaction(tx: EscrowOpenTransaction): void {
this.checkTransaction(tx);
}
public static checkClaimTransaction(tx: EscrowClaimTransaction): void {
this.checkTransaction(tx);
}
public static checkAbortTransaction(tx: EscrowAbortTransaction): void {
this.checkTransaction(tx);
}
public static abort(swapId: SwapId): Uint8Array {
return new Uint8Array([...Abi.calculateMethodId("abort(bytes32)"), ...swapId.data]);
}
public static claim(swapId: SwapId, recipient: Address): Uint8Array {
return new Uint8Array([
...Abi.calculateMethodId("claim(bytes32,address)"),
...swapId.data,
...Abi.encodeAddress(recipient),
]);
}
public static open(swapId: SwapId, arbiter: Address, hash: Hash, timeout: SwapTimeout): Uint8Array {
const blockHeightTimeout = timeout as BlockHeightTimeout;
return new Uint8Array([
...Abi.calculateMethodId("open(bytes32,address,bytes32,uint256)"),
...swapId.data,
...Abi.encodeAddress(arbiter),
...hash,
...Abi.encodeUint256(blockHeightTimeout.height.toString()),
]);
}
public static serializeUnsignedTransaction(
unsigned: EscrowBaseTransaction,
options: UnsignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (isEscrowOpenTransaction(unsigned)) {
return this.serializeUnsignedOpenTransaction(unsigned, options);
} else if (isEscrowAbortTransaction(unsigned)) {
return this.serializeUnsignedAbortTransaction(unsigned, options);
} else if (isEscrowClaimTransaction(unsigned)) {
return this.serializeUnsignedClaimTransaction(unsigned, options);
} else {
throw new Error("unsupported escrow transaction kind: " + unsigned.kind);
}
}
public static serializeSignedTransaction(
unsigned: EscrowBaseTransaction,
options: SignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (isEscrowOpenTransaction(unsigned)) {
return this.serializeSignedOpenTransaction(unsigned, options);
} else if (isEscrowAbortTransaction(unsigned)) {
return this.serializeSignedAbortTransaction(unsigned, options);
} else if (isEscrowClaimTransaction(unsigned)) {
return this.serializeSignedClaimTransaction(unsigned, options);
} else {
throw new Error("unsupported escrow transaction kind: " + unsigned.kind);
}
}
public static async getEscrowById(
swapId: Uint8Array,
config: SmartContractConfig,
client: EthereumRpcClient,
): Promise<Escrow | null> {
if (swapId.length !== 32) {
throw new Error("Swap id must be 32 bytes");
}
if (config.type !== SmartContractType.EscrowSmartContract) {
throw new Error("Invalid type of smart contract configured for this connection");
}
const data: Uint8Array = Uint8Array.from([...Abi.calculateMethodId("get(bytes32)"), ...swapId]);
const params = [
{
to: config.address,
data: toEthereumHex(data),
},
] as readonly any[];
const swapsResponse = await client.run({
jsonrpc: "2.0",
method: "eth_call",
params: params,
id: makeJsonRpcId(),
});
if (isJsonRpcErrorResponse(swapsResponse)) {
throw new Error(JSON.stringify(swapsResponse.error));
}
if (swapsResponse.result === null) {
return null;
}
const senderBegin = 0;
const senderEnd = senderBegin + 32;
const recipientBegin = senderEnd;
const recipientEnd = recipientBegin + 32;
const arbiterBegin = recipientEnd;
const arbiterEnd = arbiterBegin + 32;
const hashBegin = arbiterEnd;
const hashEnd = hashBegin + 32;
const timeoutBegin = hashEnd;
const timeoutEnd = timeoutBegin + 32;
const amountBegin = timeoutEnd;
const amountEnd = amountBegin + 32;
const stateBegin = amountEnd;
const stateEnd = stateBegin + 32;
const resultArray = fromHex(normalizeHex(swapsResponse.result));
return {
sender: Abi.decodeAddress(resultArray.slice(senderBegin, senderEnd)),
recipient: Abi.decodeAddress(resultArray.slice(recipientBegin, recipientEnd)),
arbiter: Abi.decodeAddress(resultArray.slice(arbiterBegin, arbiterEnd)),
hash: resultArray.slice(hashBegin, hashEnd) as Hash,
amount: {
quantity: new BN(resultArray.slice(amountBegin, amountEnd)).toString(),
fractionalDigits: config.fractionalDigits,
tokenTicker: config.tokenTicker,
},
timeout: {
height: new BN(resultArray.slice(timeoutBegin, timeoutEnd)).toNumber(),
},
state: new BN(resultArray.slice(stateBegin, stateEnd)).toNumber() as EscrowState,
};
}
private static readonly OPEN_METHOD_ID: string = toHex(
Abi.calculateMethodHash("open(bytes32,address,bytes32,uint256)"),
);
private static readonly CLAIM_METHOD_ID: string = toHex(Abi.calculateMethodHash("claim(bytes32,address)"));
private static readonly ABORT_METHOD_ID: string = toHex(Abi.calculateMethodHash("abort(bytes32)"));
private static readonly METHODS: { readonly [key: string]: EscrowContractMethod } = {
[EscrowContract.OPEN_METHOD_ID]: EscrowContractMethod.Open,
[EscrowContract.CLAIM_METHOD_ID]: EscrowContractMethod.Claim,
[EscrowContract.ABORT_METHOD_ID]: EscrowContractMethod.Abort,
};
private static readonly NO_SMART_CONTRACT_ADDRESS_ERROR: Error = new Error(
"Escrow smart contract address not set",
);
private static checkTransaction(tx: EscrowBaseTransaction): void {
const { swapId } = tx;
if (!swapId) {
throw new Error("No swap ID provided");
}
if (swapId.data.length !== 32) {
throw new Error("Swap ID must be 32 bytes");
}
}
private static getMethodTypeFromInput(data: Uint8Array): EscrowContractMethod {
const id = toHex(data);
const method: EscrowContractMethod | undefined = EscrowContract.METHODS[id];
if (method === undefined) {
throw new Error("Unknown method for escrow contract");
}
return method;
}
private static serializeSignedOpenTransaction(
unsigned: EscrowOpenTransaction,
{ v, r, s, gasPriceHex, gasLimitHex, nonce, customSmartContractAddress }: SignedSerializationOptions,
): GenericTransactionSerializerParameters {
const { amount } = unsigned;
if (customSmartContractAddress === undefined) {
throw EscrowContract.NO_SMART_CONTRACT_ADDRESS_ERROR;
}
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: amount.quantity,
data: EscrowContract.open(unsigned.swapId, unsigned.arbiter, unsigned.hash, unsigned.timeout),
v: v,
r: r,
s: s,
};
}
private static serializeSignedClaimTransaction(
unsigned: EscrowClaimTransaction,
{ v, r, s, gasPriceHex, gasLimitHex, nonce, customSmartContractAddress }: SignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (customSmartContractAddress === undefined) {
throw EscrowContract.NO_SMART_CONTRACT_ADDRESS_ERROR;
}
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: EscrowContract.claim(unsigned.swapId, unsigned.recipient),
v: v,
r: r,
s: s,
};
}
private static serializeSignedAbortTransaction(
unsigned: EscrowAbortTransaction,
{ v, r, s, gasPriceHex, gasLimitHex, nonce, customSmartContractAddress }: SignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (customSmartContractAddress === undefined) {
throw EscrowContract.NO_SMART_CONTRACT_ADDRESS_ERROR;
}
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: EscrowContract.abort(unsigned.swapId),
v: v,
r: r,
s: s,
};
}
private static serializeUnsignedOpenTransaction(
unsigned: EscrowOpenTransaction,
{
chainIdHex,
gasPriceHex,
gasLimitHex,
nonce,
erc20Tokens,
customSmartContractAddress,
}: UnsignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (customSmartContractAddress === undefined) {
throw EscrowContract.NO_SMART_CONTRACT_ADDRESS_ERROR;
}
EscrowContract.checkOpenTransaction(unsigned);
if (!isBlockHeightTimeout(unsigned.timeout)) {
throw new Error("Timeout must be specified as a block height");
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (unsigned.swapId.prefix === SwapIdPrefix.Ether) {
// native ETH swap
SerializationCommon.checkEtherAmount([unsigned.amount]);
const escrowOpenCall = EscrowContract.open(
unsigned.swapId,
unsigned.arbiter,
unsigned.hash,
unsigned.timeout,
);
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: unsigned.amount.quantity,
data: escrowOpenCall,
v: chainIdHex,
};
} else {
// ERC20 swap
SerializationCommon.checkErc20Amount([unsigned.amount], erc20Tokens);
const escrowOpenCall = EscrowContract.open(
unsigned.swapId,
unsigned.arbiter,
unsigned.hash,
unsigned.timeout,
);
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: escrowOpenCall,
v: chainIdHex,
};
}
}
private static serializeUnsignedClaimTransaction(
unsigned: EscrowClaimTransaction,
{ chainIdHex, gasPriceHex, gasLimitHex, nonce, customSmartContractAddress }: UnsignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (customSmartContractAddress === undefined) {
throw EscrowContract.NO_SMART_CONTRACT_ADDRESS_ERROR;
}
EscrowContract.checkClaimTransaction(unsigned);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (unsigned.swapId.prefix === SwapIdPrefix.Ether) {
const escrowClaimCall = EscrowContract.claim(unsigned.swapId, unsigned.recipient);
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: escrowClaimCall,
v: chainIdHex,
};
} else {
const escrowClaimCall = EscrowContract.claim(unsigned.swapId, unsigned.recipient);
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: escrowClaimCall,
v: chainIdHex,
};
}
}
private static serializeUnsignedAbortTransaction(
unsigned: EscrowAbortTransaction,
{ chainIdHex, gasPriceHex, gasLimitHex, nonce, customSmartContractAddress }: UnsignedSerializationOptions,
): GenericTransactionSerializerParameters {
if (customSmartContractAddress === undefined) {
throw EscrowContract.NO_SMART_CONTRACT_ADDRESS_ERROR;
}
EscrowContract.checkAbortTransaction(unsigned);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (unsigned.swapId.prefix === SwapIdPrefix.Ether) {
const escrowAbortCall = EscrowContract.abort(unsigned.swapId);
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: escrowAbortCall,
v: chainIdHex,
};
} else {
const escrowAbortCall = EscrowContract.abort(unsigned.swapId);
return {
nonce: nonce,
gasPriceHex: gasPriceHex,
gasLimitHex: gasLimitHex,
recipient: customSmartContractAddress,
value: ZERO_ETH_QUANTITY,
data: escrowAbortCall,
v: chainIdHex,
};
}
}
} | the_stack |
import { autobind } from 'core-decorators';
import FocusTrap from 'focus-trap-react';
import { List, Set } from 'immutable';
import keyboardJS from 'keyboardjs';
import React from 'react';
import { RouteComponentProps } from 'react-router';
import {
CircularProgress,
} from '@material-ui/core';
import {
ITagModel,
ModelId,
TagModel,
} from '../../../../models';
import { ICommentAction } from '../../../../types';
import {
AddIcon,
ApproveIcon,
CommentActionButton,
CommentList,
DeferIcon,
HighlightIcon,
RejectIcon,
Scrim,
ToastMessage,
ToolTip,
} from '../../../components';
import {
approveComments,
deferComments,
highlightComments,
ICommentActionFunction,
rejectComments,
resetComments,
tagCommentSummaryScores,
} from '../../../stores/commentActions';
import {
DARK_COLOR,
GUTTER_DEFAULT_SPACING,
HEADER_HEIGHT,
LIGHT_PRIMARY_TEXT_COLOR,
NICE_MIDDLE_BLUE,
SCRIM_STYLE,
SCRIM_Z_INDEX,
TOOLTIP_Z_INDEX,
WHITE_COLOR,
} from '../../../styles';
import { partial } from '../../../util';
import { css, stylesheet } from '../../../utilx';
import { commentSearchDetailsPageLink, ISearchQueryParams } from '../../routes';
const TOAST_DELAY = 6000;
let showActionIcon: JSX.Element = null;
const ACTION_PLURAL: any = {
highlight: 'highlighted',
approve: 'approved',
defer: 'deferred',
reject: 'rejected',
tag: 'tagged',
};
const sortDefinitions: any = {
relevance: {
sortInfo: '',
},
newest: {
sortInfo: '-sourceCreatedAt',
},
oldest: {
sortInfo: 'sourceCreatedAt',
},
};
const sortOptions = List.of(
TagModel({
key: 'relevance',
label: 'Relevance',
color: '',
}),
TagModel({
key: 'newest',
label: 'Newest',
color: '',
}),
TagModel({
key: 'oldest',
label: 'Oldest',
color: '',
}),
);
const RESULTS_HEADER_HEIGHT = 50;
const STYLES = stylesheet({
children: {
display: 'inline-block',
},
placeholderBgContainer: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
height: window.innerHeight - HEADER_HEIGHT - RESULTS_HEADER_HEIGHT,
width: '100%',
},
resultsHeader: {
alignItems: 'center',
backgroundColor: NICE_MIDDLE_BLUE,
color: LIGHT_PRIMARY_TEXT_COLOR,
display: 'flex',
flexWrap: 'no-wrap',
justifyContent: 'space-between',
height: RESULTS_HEADER_HEIGHT,
},
resultsHeadline: {
marginLeft: 29,
},
resultsActionHeadline: {
color: WHITE_COLOR,
},
moderateButtons: {
display: 'flex',
},
commentActionButton: {
marginRight: `${GUTTER_DEFAULT_SPACING}px`,
},
dropdown: {
position: 'relative',
},
scrim: {
zIndex: SCRIM_Z_INDEX,
background: 'none',
},
actionToastCount: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 24,
lineHeight: 1.5,
textIndent: 4,
},
toolTipWithTags: {
container: {
width: 250,
marginRight: GUTTER_DEFAULT_SPACING,
},
ul: {
listStyle: 'none',
margin: 0,
padding: `${GUTTER_DEFAULT_SPACING}px 0`,
},
button: {
backgroundColor: 'transparent',
border: 'none',
borderRadius: 0,
color: NICE_MIDDLE_BLUE,
cursor: 'pointer',
padding: '8px 20px',
textAlign: 'left',
width: '100%',
':hover': {
backgroundColor: NICE_MIDDLE_BLUE,
color: LIGHT_PRIMARY_TEXT_COLOR,
},
':focus': {
backgroundColor: NICE_MIDDLE_BLUE,
color: LIGHT_PRIMARY_TEXT_COLOR,
},
},
},
});
const actionMap: { [key: string]: ICommentActionFunction } = {
highlight: highlightComments,
approve: approveComments,
defer: deferComments,
reject: rejectComments,
tag: tagCommentSummaryScores,
reset: resetComments,
};
export interface ISearchResultsProps extends RouteComponentProps<{}> {
isLoading: boolean;
isItemChecked(id: string): boolean;
areNoneSelected: boolean;
areAllSelected: boolean;
selectedCount: number;
allCommentIds?: Array<string>;
tags?: List<ITagModel>;
textSizes?: Map<ModelId, number>;
pagingIdentifier?: string;
onToggleSelectAll?(): void;
onToggleSingleItem(item: { id: string }): void;
updateSearchQuery(queryDelta: ISearchQueryParams): void;
searchTerm?: string;
searchByAuthor?: boolean;
}
export interface ISearchResultsState {
selectedCount?: number;
commentSortType?: string;
isTaggingToolTipMetaVisible?: boolean;
taggingToolTipMetaPosition?: {
top: number;
left: number;
};
isConfirmationModalVisible?: boolean;
confirmationAction?: ICommentAction;
toastButtonLabel?: 'Undo' | 'Remove rule';
toastIcon?: JSX.Element;
showCount?: boolean;
actionCount?: number;
actionText?: string;
}
export class SearchResults extends React.Component<ISearchResultsProps, ISearchResultsState> {
commentActionCancelled = false;
state: ISearchResultsState = {
isTaggingToolTipMetaVisible: false,
commentSortType: this.props.searchByAuthor ? 'newest' : 'relevance',
taggingToolTipMetaPosition: {
top: 0,
left: 0,
},
isConfirmationModalVisible: false,
confirmationAction: null,
actionText: '',
toastButtonLabel: null,
toastIcon: null,
showCount: false,
actionCount: 0,
};
componentDidMount() {
keyboardJS.bind('escape', this.onPressEscape);
}
componentWillUnmount() {
keyboardJS.unbind('escape', this.onPressEscape);
}
@autobind
onPressEscape() {
this.setState({
isConfirmationModalVisible: false,
isTaggingToolTipMetaVisible: false,
});
}
/**
* Tell the lazy list to re-query.
*/
updateScope(sort: any) {
let newSort = sortDefinitions[sort] && sortDefinitions[sort].sortInfo;
if (!newSort) {
newSort = null;
}
this.props.updateSearchQuery({sort: newSort});
}
@autobind
onSortChange(event: React.FormEvent<any>) {
const newSort = (event.target as any).value;
this.updateScope(newSort);
this.setState({commentSortType: newSort});
}
@autobind
async onSelectAllChange() {
await this.props.onToggleSelectAll();
}
@autobind
async onSelectionChange(id: string) {
await this.props.onToggleSingleItem({ id });
}
matchAction(action: ICommentAction) {
if (action === 'approve') {
showActionIcon = <ApproveIcon {...css({fill: DARK_COLOR})} />;
} else if (action === 'reject') {
showActionIcon = <RejectIcon {...css({fill: DARK_COLOR})} />;
} else if (action === 'highlight') {
showActionIcon = <HighlightIcon {...css({fill: DARK_COLOR})} />;
} else if (action === 'defer') {
showActionIcon = <DeferIcon {...css({fill: DARK_COLOR})} />;
} else if (action === 'tag') {
showActionIcon = <AddIcon {...css({fill: DARK_COLOR})} />;
}
return showActionIcon;
}
@autobind
onConfirmationClose() {
this.setState({isConfirmationModalVisible: false });
}
@autobind
handleUndoClick() {
this.commentActionCancelled = true;
this.onConfirmationClose();
}
@autobind
async dispatchConfirmedAction(action: ICommentAction, ids?: Array<string>) {
const idsToDispatch = ids || this.getSelectedIDs();
actionMap[action](idsToDispatch);
}
@autobind
getSelectedIDs(): Array<string> {
return this.props.allCommentIds.filter((id) => (
this.props.isItemChecked(id)
));
}
@autobind
calculateTaggingTriggerPosition(ref: HTMLElement) {
if (!ref) {
return;
}
const buttonRect = ref.getBoundingClientRect();
this.setState({
taggingToolTipMetaPosition: {
top: buttonRect.height / 2,
left: (buttonRect.width / 2) - 10,
},
});
}
@autobind
toggleTaggingToolTip() {
this.setState({
isTaggingToolTipMetaVisible: !this.state.isTaggingToolTipMetaVisible,
});
}
@autobind
confirmationClose() {
this.setState({ isConfirmationModalVisible: false });
}
@autobind
onTagButtonClick(tagId: string) {
const ids = this.getSelectedIDs();
this.triggerActionToast('tag', ids.length, () => tagCommentSummaryScores(ids, tagId));
this.toggleTaggingToolTip();
}
@autobind
triggerActionToast(action: ICommentAction, count: number, callback: (action?: ICommentAction) => any) {
this.setState({
isConfirmationModalVisible: true,
confirmationAction: action,
actionCount: count,
actionText: `Comment${count > 1 ? 's' : ''} ` + ACTION_PLURAL[action],
toastButtonLabel: 'Undo',
toastIcon: this.matchAction(action),
showCount: true,
});
setTimeout(async () => {
if (this.commentActionCancelled) {
this.commentActionCancelled = false;
this.confirmationClose();
return false;
} else {
this.setState({
toastButtonLabel: null,
});
await callback(action);
this.confirmationClose();
}
}, TOAST_DELAY);
}
@autobind
async handleAssignTagsSubmit(commentId: ModelId, selectedTagIds: Set<ModelId>) {
selectedTagIds.forEach((tagId) => {
tagCommentSummaryScores([commentId], tagId);
});
this.dispatchConfirmedAction('reject', [commentId]);
}
render() {
const {
textSizes,
isItemChecked,
areNoneSelected,
areAllSelected,
selectedCount,
tags,
allCommentIds,
isLoading,
pagingIdentifier,
searchTerm,
} = this.props;
const {
isTaggingToolTipMetaVisible,
taggingToolTipMetaPosition,
commentSortType,
isConfirmationModalVisible,
actionCount,
actionText,
} = this.state;
function getLinkTarget(commentId: ModelId) {
const query = pagingIdentifier && {pagingIdentifier};
return commentSearchDetailsPageLink(commentId, query);
}
const totalCommentCount = allCommentIds?.length || 0;
return (
<div>
{isLoading && (
<div key="searchIcon" {...css(STYLES.placeholderBgContainer)}>
<CircularProgress color="primary" size={100}/>
</div>
)}
<div key="content" {...css({backgroundColor: 'white'}, {display: 'block'})} >
<div {...css(STYLES.resultsHeader)}>
{searchTerm && !isLoading && (
<p {...css(STYLES.resultsHeadline, !areNoneSelected && STYLES.resultsActionHeadline)}>
{selectedCount > 0 && `${selectedCount} / `}
{totalCommentCount} result{totalCommentCount > 1 && 's'}
{selectedCount > 0 || areAllSelected && ' selected'}
</p>
)}
{isLoading && (
<p {...css(STYLES.resultsHeadline, !areNoneSelected && STYLES.resultsActionHeadline)}>
Loading...
</p>
)}
{ !areNoneSelected && (
<div {...css(STYLES.moderateButtons)}>
<CommentActionButton
disabled={areNoneSelected}
style={STYLES.commentActionButton}
label="Approve"
onClick={partial(
this.triggerActionToast,
'approve',
this.getSelectedIDs().length,
this.dispatchConfirmedAction,
)}
icon={(
<ApproveIcon {...css({fill: LIGHT_PRIMARY_TEXT_COLOR})} />
)}
/>
<CommentActionButton
disabled={areNoneSelected}
style={STYLES.commentActionButton}
label="Reject"
onClick={partial(
this.triggerActionToast,
'reject',
this.getSelectedIDs().length,
this.dispatchConfirmedAction,
)}
icon={(
<RejectIcon {...css({fill: LIGHT_PRIMARY_TEXT_COLOR})} />
)}
/>
<CommentActionButton
disabled={areNoneSelected}
style={STYLES.commentActionButton}
label="Defer"
onClick={partial(
this.triggerActionToast,
'defer',
this.getSelectedIDs().length,
this.dispatchConfirmedAction,
)}
icon={(
<DeferIcon {...css({fill: LIGHT_PRIMARY_TEXT_COLOR})} />
)}
/>
<div {...css(STYLES.dropdown)}>
<CommentActionButton
disabled={areNoneSelected}
buttonRef={this.calculateTaggingTriggerPosition}
label="Tag"
onClick={this.toggleTaggingToolTip}
icon={(
<AddIcon {...css({fill: LIGHT_PRIMARY_TEXT_COLOR})} />
)}
/>
{isTaggingToolTipMetaVisible && (
<ToolTip
arrowPosition="topRight"
backgroundColor={WHITE_COLOR}
hasDropShadow
isVisible={isTaggingToolTipMetaVisible}
onDeactivate={this.toggleTaggingToolTip}
position={taggingToolTipMetaPosition}
size={16}
width={250}
zIndex={TOOLTIP_Z_INDEX}
>
<div {...css(STYLES.toolTipWithTags.container)}>
<ul {...css(STYLES.toolTipWithTags.ul)}>
{tags && tags.map((t, i) => (
<li key={t.id}>
<button
onClick={partial(this.onTagButtonClick, t.id)}
key={`tag-${i}`}
{...css(STYLES.toolTipWithTags.button)}
>
{t.label}
</button>
</li>
))}
</ul>
</div>
</ToolTip>
)}
</div>
</div>
)}
</div>
{!isLoading && searchTerm && totalCommentCount > 0 && (
<CommentList
heightOffset={HEADER_HEIGHT + RESULTS_HEADER_HEIGHT}
textSizes={textSizes}
commentIds={allCommentIds}
areAllSelected={areAllSelected}
currentSort={commentSortType}
getLinkTarget={getLinkTarget}
isItemChecked={isItemChecked}
onSelectAllChange={this.onSelectAllChange}
onSelectionChange={this.onSelectionChange}
onSortChange={this.onSortChange}
sortOptions={sortOptions}
totalItems={totalCommentCount}
searchTerm={searchTerm}
displayArticleTitle
dispatchConfirmedAction={this.dispatchConfirmedAction}
handleAssignTagsSubmit={this.handleAssignTagsSubmit}
/>
)}
</div>
<Scrim
key="confirmationScrim"
scrimStyles={{...STYLES.scrim, ...SCRIM_STYLE.scrim}}
isVisible={isConfirmationModalVisible}
onBackgroundClick={this.confirmationClose}
>
<FocusTrap
focusTrapOptions={{
clickOutsideDeactivates: true,
}}
>
<ToastMessage
icon={this.state.toastIcon}
buttonLabel={this.state.toastButtonLabel}
onClick={this.handleUndoClick}
>
<div key="toastContent">
{ this.state.showCount && (
<span key="toastCount" {...css(STYLES.actionToastCount)}>
{showActionIcon}
{actionCount}
</span>
)}
<p key="actionText">{actionText}</p>
</div>
</ToastMessage>
</FocusTrap>
</Scrim>
</div>
);
}
} | the_stack |
import {
base8BitColors,
bgColors,
colorIncrements216,
COMMAND,
commandToType,
END_GROUP,
ERROR,
fgColors,
getType,
GROUP,
ICON,
maxCommandLength,
NOTICE,
Resets,
SECTION,
specials,
supportedCommands,
WARNING,
} from './action-log-pipeline-commands'
import {
commandEnd,
commandStart,
hashChar,
IAnsiEscapeCodeState,
ILine,
ILogLine,
ILogLineTemplateData,
IParsedContent,
IParsedOutput,
IParseNode,
IRGBColor,
IStyle,
newLineChar,
NodeType,
unsetValue,
} from './actions-log-parser-objects'
import {
BrightClassPostfix,
ESC,
TimestampLength,
TimestampRegex,
UrlRegex,
_ansiEscapeCodeRegex,
} from './actions-logs-ansii'
export function getText(text: string) {
return (text || '').toLocaleLowerCase()
}
export class ActionsLogParser {
private logLines: ILogLine[]
private logContent: string
private rawLogData: string
private lineMetaData: ILine[]
private logLineNumbers: number[]
private timestamps: string[]
/**
* This is used a prefix to the line number if we would want the line numbers
* to be links to dotcom logs.
*
* Example: https://github.com/desktop/desktop/runs/3840220073#step:13
*/
private permalinkPrefix: string
public constructor(rawLogData: string, permalinkPrefix: string) {
this.rawLogData = rawLogData
this.permalinkPrefix = permalinkPrefix
this.logContent = ''
this.lineMetaData = []
this.logLines = []
this.logLineNumbers = []
this.timestamps = []
this.updateLogLines()
}
/**
* Returns the parsed lines in the form of an object with the meta data needed
* to build a an html element for the line.
*
* @param node
* @param groupExpanded
* @returns
*/
public getParsedLogLinesTemplateData(): ReadonlyArray<ILogLineTemplateData> {
return this.logLines.map(ll => this.getParsedLineTemplateData(ll))
}
/**
* Returns a line object with the meta data needed to build a an html element
* for the line.
*
*/
private getParsedLineTemplateData(node: ILogLine): ILogLineTemplateData {
const { lineIndex } = node
const logLineNumber = this.logLineNumbers[lineIndex]
const lineNumber = logLineNumber != null ? logLineNumber : lineIndex + 1
const text = this.getNodeText(node)
// parse() does the ANSI parsing and converts to HTML
const lineContent = this.parse(text)
// The parser assigns a type to each line. Such as "debug" or "command".
// These change the way the line looks. See checks.scss for the css.
const className = `log-line-${getType(node)}`
return {
className,
lineNumber,
lineContent,
timeStamp: this.timestamps[lineIndex],
lineUrl: `${this.permalinkPrefix}:${lineNumber}`,
isGroup: node.type === NodeType.Group,
inGroup: node.group?.lineIndex != null,
isError: node.type === NodeType.Error,
isWarning: node.type === NodeType.Warning,
isNotice: node.type === NodeType.Notice,
groupExpanded: false,
}
}
private updateLogLines() {
this.updateLineMetaData()
this.logLines = []
for (const line of this.lineMetaData) {
this.logLines.push(...line.nodes)
}
}
private updateLineMetaData() {
const lines = this.rawLogData.split(/\r?\n/)
// Example log line with timestamp:
// 2019-07-11T16:56:45.9315998Z #[debug]Evaluating condition for step: 'fourth step'
const timestampRegex = /^(.{27}Z) /
this.timestamps = []
this.logContent = lines
.map(line => {
const match = line.match(timestampRegex)
const timestamp = match && new Date(match[1])
let ts = ''
if (match && timestamp && !isNaN(Number(timestamp))) {
ts = timestamp.toUTCString()
line = line.substring(match[0].length)
}
if (!line.startsWith('##[endgroup]')) {
// endgroup lines are not rendered and do not increase the lineIndex, so we don't want to store a timestamp for them,
// otherwise we will get wrong timestamps in subsequent lines
this.timestamps.push(ts)
}
return line
})
.join('\n')
this.lineMetaData = this.parseLines(this.logContent)
}
private getNodeText(node: ILogLine) {
if (node.text == null) {
node.text = this.logContent.substring(node.start, node.end + 1)
}
return node.text
}
/**
* Converts the content to HTML with appropriate styles, escapes content to prevent XSS
*
* @param content
* @param lineNumber
*/
private parse(content: string): IParsedContent[] {
const result = []
const states = this.getStates(content)
for (const x of states) {
const classNames: string[] = []
const styles: string[] = []
const currentText = x.output
if (x.style) {
const fg = x.style.fg
const bg = x.style.bg
const isFgRGB = x.style.isFgRGB
const isBgRGB = x.style.isBgRGB
if (fg && !isFgRGB) {
classNames.push(`ansifg-${fg}`)
}
if (bg && !isBgRGB) {
classNames.push(`ansibg-${bg}`)
classNames.push(`d-inline-flex`)
}
if (fg && isFgRGB) {
styles.push(`color:rgb(${fg})`)
}
if (bg && isBgRGB) {
styles.push(`background-color:rgb(${bg})`)
classNames.push(`d-inline-flex`)
}
if (x.style.bold) {
classNames.push('text-bold')
}
if (x.style.italic) {
classNames.push('text-italic')
}
if (x.style.underline) {
classNames.push('text-underline')
}
}
const output: IParsedOutput[] = []
// Split the current text using the URL Regex pattern, if there are no URLs, there were will be single entry
const splitUrls = currentText.split(UrlRegex)
for (const entry of splitUrls) {
if (entry === '') {
continue
}
if (entry.match(UrlRegex)) {
const prefixMatch = entry.match(/^[{(<[]*/)
const entryPrefix = prefixMatch == null ? '' : prefixMatch[0]
let entrySuffix = ''
if (entryPrefix) {
const suffixRegex = new RegExp(
`[})>\\]]{${entryPrefix.length}}(?=$)`
)
const suffixMatch = entry.match(suffixRegex)
entrySuffix = suffixMatch == null ? '' : suffixMatch[0]
}
const entryUrl = entry
.replace(entryPrefix, '')
.replace(entrySuffix, '')
output.push({
entry: entryPrefix,
entryUrl,
afterUrl: entrySuffix,
})
} else {
output.push({ entry })
}
}
result.push({
classes: classNames,
styles,
output,
})
}
return result
}
/**
* Parses the content into lines with nodes
*
* @param content content to parse
*/
private parseLines(content: string): ILine[] {
// lines we return
const lines: ILine[] = []
// accumulated nodes for a particular line
let nodes: IParseNode[] = []
// start of a particular line
let lineStartIndex = 0
// start of plain node content
let plainNodeStart = unsetValue
// tells to consider the default logic where we check for plain text etc.,
let considerDefaultLogic = true
// stores the command, to match one of the 'supportedCommands'
let currentCommand = ''
// helps in finding commands in our format "##[command]" or "[command]"
let commandSeeker = ''
// when line ends, this tells if there's any pending node
let pendingLastNode: number = unsetValue
const resetCommandVar = () => {
commandSeeker = ''
currentCommand = ''
}
const resetPlain = () => {
plainNodeStart = unsetValue
}
const resetPending = () => {
pendingLastNode = unsetValue
}
const parseCommandEnd = () => {
// possible continuation of our well-known commands
const commandIndex = supportedCommands.indexOf(currentCommand)
if (commandIndex !== -1) {
considerDefaultLogic = false
// we reached the end and found the command
resetPlain()
// command is for the whole line, so we are not pushing the node here but defering this to when we find the new line
pendingLastNode = commandToType[currentCommand]
if (
currentCommand === SECTION ||
currentCommand === GROUP ||
currentCommand === END_GROUP ||
currentCommand === COMMAND ||
currentCommand === ERROR ||
currentCommand === WARNING ||
currentCommand === NOTICE
) {
// strip off ##[$(currentCommand)] if there are no timestamps at start
const possibleTimestamp =
content.substring(
lineStartIndex,
lineStartIndex + TimestampLength
) || ''
if (!possibleTimestamp.match(TimestampRegex)) {
// ## is optional, so pick the right offfset
const offset =
content.substring(lineStartIndex, lineStartIndex + 2) === '##'
? 4
: 2
lineStartIndex = lineStartIndex + offset + currentCommand.length
}
}
if (currentCommand === GROUP) {
groupStarted = true
}
// group logic- happyCase1: we found endGroup and there's already a group starting
if (currentCommand === END_GROUP && currentGroupNode) {
groupEnded = true
}
}
resetCommandVar()
}
let groupStarted = false
let groupEnded = false
let currentGroupNode: IParseNode | undefined
let nodeIndex = 0
for (let index = 0; index < content.length; index++) {
const char = content.charAt(index)
// start with considering default logic, individual conditions are responsible to set it false
considerDefaultLogic = true
if (char === newLineChar || index === content.length - 1) {
if (char === commandEnd) {
parseCommandEnd()
}
const node = {
type: pendingLastNode,
start: lineStartIndex,
end: index,
lineIndex: lines.length,
} as IParseNode
let pushNode = false
// end of the line/text, push any final nodes
if (pendingLastNode !== NodeType.Plain) {
// there's pending special node to be pushed
pushNode = true
// a new group has just started
if (groupStarted) {
currentGroupNode = node
groupStarted = false
}
// a group has ended
if (groupEnded && currentGroupNode) {
// this is a throw away node
pushNode = false
currentGroupNode.isGroup = true
// since group has ended, clear all of our pointers
groupEnded = false
currentGroupNode = undefined
}
} else if (pendingLastNode === NodeType.Plain) {
// there's pending plain node to be pushed
pushNode = true
}
if (pushNode) {
node.index = nodeIndex++
nodes.push(node)
}
// A group is pending
if (currentGroupNode && node !== currentGroupNode) {
node.group = {
lineIndex: currentGroupNode.lineIndex,
nodeIndex: currentGroupNode.index,
}
}
// end of the line, push all nodes that are accumulated till now
if (nodes.length > 0) {
lines.push({ nodes })
}
// clear node as we are done with the line
nodes = []
// increment lineStart for the next line
lineStartIndex = index + 1
// unset
resetPlain()
resetPending()
resetCommandVar()
considerDefaultLogic = false
} else if (char === hashChar) {
// possible start of our well-known commands
if (commandSeeker === '' || commandSeeker === '#') {
considerDefaultLogic = false
commandSeeker += hashChar
}
} else if (char === commandStart) {
// possible continuation of our well-known commands
if (commandSeeker === '##') {
considerDefaultLogic = false
commandSeeker += commandStart
} else if (commandSeeker.length === 0) {
// covers - "", for live logs, commands will be of [section], with out "##"
considerDefaultLogic = false
commandSeeker += commandStart
}
} else if (char === commandEnd) {
if (currentCommand === ICON) {
const startIndex = index + 1
let endIndex = startIndex
for (let i = startIndex; i < content.length; i++) {
const iconChar = content[i]
if (iconChar === ' ') {
endIndex = i
break
}
}
nodes.push({
type: NodeType.Icon,
lineIndex: lines.length,
start: startIndex,
end: endIndex,
index: nodeIndex++,
})
// jump to post Icon content
index = endIndex + 1
lineStartIndex = index
continue
} else {
parseCommandEnd()
}
}
if (considerDefaultLogic) {
if (commandSeeker === '##[' || commandSeeker === '[') {
// it's possible that we are parsing a command
currentCommand += char.toLowerCase()
}
if (currentCommand.length > maxCommandLength) {
// to avoid accumulating command unncessarily, let's check max length, if it exceeds, it's not a command
resetCommandVar()
}
// considering as plain text
if (plainNodeStart === unsetValue) {
// we didn't set this yet, set now
plainNodeStart = lineStartIndex
// set pending node if there isn't one pending
if (pendingLastNode === unsetValue) {
pendingLastNode = NodeType.Plain
}
}
}
}
return lines
}
/**
* Parses the content into ANSII states
*
* @param content content to parse
*/
private getStates(content: string): IAnsiEscapeCodeState[] {
const result: IAnsiEscapeCodeState[] = []
// Eg: "ESC[0KESC[33;1mWorker informationESC[0m
if (!_ansiEscapeCodeRegex.test(content)) {
// Not of interest, don't touch content
return [
{
output: content,
},
]
}
let command = ''
let currentText = ''
let code = ''
let state = {} as IAnsiEscapeCodeState
let isCommandActive = false
let codes = []
for (let index = 0; index < content.length; index++) {
const character = content[index]
if (isCommandActive) {
if (character === ';') {
if (code) {
codes.push(code)
code = ''
}
} else if (character === 'm') {
if (code) {
isCommandActive = false
// done
codes.push(code)
state.style = state.style || ({} as IStyle)
let setForeground = false
let setBackground = false
let isSingleColorCode = false
let isRGBColorCode = false
const rgbColors: number[] = []
for (const currentCode of codes) {
const style = state.style as IStyle
const codeNumber = parseInt(currentCode)
if (setForeground && isSingleColorCode) {
// set foreground color using 8-bit (256 color) palette - Esc[ 38:5:<n> m
if (codeNumber >= 0 && codeNumber < 16) {
style.fg = this._get8BitColorClasses(codeNumber)
} else if (codeNumber >= 16 && codeNumber < 256) {
style.fg = this._get8BitRGBColors(codeNumber)
style.isFgRGB = true
}
setForeground = false
isSingleColorCode = false
} else if (setForeground && isRGBColorCode) {
// set foreground color using 24-bit (true color) palette - Esc[ 38:2:<r>:<g>:<b> m
if (codeNumber >= 0 && codeNumber < 256) {
rgbColors.push(codeNumber)
if (rgbColors.length === 3) {
style.fg = `${rgbColors[0]},${rgbColors[1]},${rgbColors[2]}`
style.isFgRGB = true
rgbColors.length = 0 // clear array
setForeground = false
isRGBColorCode = false
}
}
} else if (setBackground && isSingleColorCode) {
// set background color using 8-bit (256 color) palette - Esc[ 48:5:<n> m
if (codeNumber >= 0 && codeNumber < 16) {
style.bg = this._get8BitColorClasses(codeNumber)
} else if (codeNumber >= 16 && codeNumber < 256) {
style.bg = this._get8BitRGBColors(codeNumber)
style.isBgRGB = true
}
setBackground = false
isSingleColorCode = false
} else if (setBackground && isRGBColorCode) {
// set background color using 24-bit (true color) palette - Esc[ 48:2:<r>:<g>:<b> m
if (codeNumber >= 0 && codeNumber < 256) {
rgbColors.push(codeNumber)
if (rgbColors.length === 3) {
style.bg = `${rgbColors[0]},${rgbColors[1]},${rgbColors[2]}`
style.isBgRGB = true
rgbColors.length = 0 // clear array
setBackground = false
isRGBColorCode = false
}
}
} else if (setForeground || setBackground) {
if (codeNumber === 5) {
isSingleColorCode = true
} else if (codeNumber === 2) {
isRGBColorCode = true
}
} else if (fgColors[currentCode]) {
style.fg = fgColors[currentCode]
} else if (bgColors[currentCode]) {
style.bg = bgColors[currentCode]
} else if (currentCode === Resets.Reset) {
// reset
state.style = {} as IStyle
} else if (currentCode === Resets.Set_Bg) {
setBackground = true
} else if (currentCode === Resets.Set_Fg) {
setForeground = true
} else if (currentCode === Resets.Default_Fg) {
style.fg = ''
} else if (currentCode === Resets.Default_Bg) {
style.bg = ''
} else if (codeNumber >= 91 && codeNumber <= 97) {
style.fg = fgColors[codeNumber - 60] + BrightClassPostfix
} else if (codeNumber >= 101 && codeNumber <= 107) {
style.bg = bgColors[codeNumber - 60] + BrightClassPostfix
} else if (specials[currentCode]) {
style[specials[currentCode]] = true
} else if (currentCode === Resets.Bold) {
style.bold = false
} else if (currentCode === Resets.Italic) {
style.italic = false
} else if (currentCode === Resets.Underline) {
style.underline = false
}
}
// clear
command = ''
currentText = ''
code = ''
} else {
// To handle ESC[m, we should just ignore them
isCommandActive = false
command = ''
state.style = {} as IStyle
}
codes = []
} else if (isNaN(parseInt(character))) {
// if this is not a number, eg: 0K, this isn't something we support
code = ''
isCommandActive = false
command = ''
} else if (code.length === 4) {
// we probably got code that we don't support, ignore
code = ''
isCommandActive = false
if (character !== ESC) {
// if this is not an ESC, let's not consider command from now on
// eg: ESC[0Ksometexthere, at this point, code would be 0K, character would be 's'
command = ''
currentText += character
}
} else {
code += character
}
continue
} else if (command) {
if (command === ESC && character === '[') {
isCommandActive = true
// push state
if (currentText) {
state.output = currentText
result.push(state)
// deep copy exisiting style for the line to preserve different styles between commands
let previousStyle
if (state.style) {
previousStyle = Object.assign({}, state.style)
}
state = {} as IAnsiEscapeCodeState
if (previousStyle) {
state.style = previousStyle
}
currentText = ''
}
}
continue
}
if (character === ESC) {
command = character
} else {
currentText += character
}
}
// still pending text
if (currentText) {
state.output = currentText + (command ? command : '')
result.push(state)
}
return result
}
/**
* With 8 bit colors, from 16-256, rgb color combinations are used
* 16-231 (216 colors) is a 6 x 6 x 6 color cube
* 232 - 256 are grayscale colors
*
* @param codeNumber 16-256 number
*/
private _get8BitRGBColors(codeNumber: number): string {
let rgbColor: IRGBColor
if (codeNumber < 232) {
rgbColor = this._get216Color(codeNumber - 16)
} else {
rgbColor = this._get8bitGrayscale(codeNumber - 232)
}
return `${rgbColor.r},${rgbColor.g},${rgbColor.b}`
}
/**
* With 8 bit color, from 0-15, css classes are used to represent customer colors
*
* @param codeNumber 0-15 number that indicates the standard or high intensity color code that should be used
*/
private _get8BitColorClasses(codeNumber: number): string {
let colorClass = ''
if (codeNumber < 8) {
colorClass = `${base8BitColors[codeNumber]}`
} else {
colorClass = `${base8BitColors[codeNumber - 8] + BrightClassPostfix}`
}
return colorClass
}
/**
* 6 x 6 x 6 (216 colors) rgb color generator
* https://en.wikipedia.org/wiki/Web_colors#Web-safe_colors
*
* @param increment 0-215 value
*/
private _get216Color(increment: number): IRGBColor {
return {
r: colorIncrements216[Math.floor(increment / 36)],
g: colorIncrements216[Math.floor(increment / 6) % 6],
b: colorIncrements216[increment % 6],
}
}
/**
* Grayscale from black to white in 24 steps. The first value of 0 represents rgb(8,8,8) while the last value represents rgb(238,238,238)
*
* @param increment 0-23 value
*/
private _get8bitGrayscale(increment: number): IRGBColor {
const colorCode = increment * 10 + 8
return {
r: colorCode,
g: colorCode,
b: colorCode,
}
}
} | the_stack |
import { ForumState, forumEmptyState, forumActionCreators, forumReducer } from '../../src/test-cases';
describe('integration/attach', () => {
/*
attach entities of a one-to-one relationship
attach entities of a one-to-many relationship
attach entities of a many-to-many relationship
attach entities of a many-to-many relationship, with indices
attach entities and displace existing attachments
if no such entity type, then no change
if entity not found, then no change
if entity relation does not exist, then no change
if attachable entity not found, then no change
if entity is already attached in a has-many collection, then no change
*/
test('attach entities of a one-to-one relationship', () => {
const state: ForumState = {
entities: {
...forumEmptyState.entities,
account: { a1: {} },
profile: { p1: {} },
},
ids: {
...forumEmptyState.ids,
account: ['a1'],
profile: ['p1'],
},
};
const expectedNextState = {
entities: {
...forumEmptyState.entities,
account: { a1: { profileId: 'p1' } },
profile: { p1: { accountId: 'a1' } },
},
ids: {
...forumEmptyState.ids,
account: ['a1'],
profile: ['p1'],
},
};
let action, nextState;
action = forumActionCreators.attach('account', 'a1', 'profileId', 'p1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('account', 'a1', 'profile', 'p1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('profile', 'p1', 'accountId', 'a1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('profile', 'p1', 'account', 'a1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
});
test('attach entities of a one-to-many relationship', () => {
const state: ForumState = {
entities: {
...forumEmptyState.entities,
profile: { p1: {} },
post: { o1: {} },
},
ids: {
...forumEmptyState.ids,
profile: ['p1'],
post: ['o1'],
},
};
const expectedNextState = {
entities: {
...forumEmptyState.entities,
profile: { p1: { postIds: ['o1'] } },
post: { o1: { profileId: 'p1' } },
},
ids: {
...forumEmptyState.ids,
profile: ['p1'],
post: ['o1'],
},
};
let action, nextState;
action = forumActionCreators.attach('profile', 'p1', 'postIds', 'o1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('profile', 'p1', 'post', 'o1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('post', 'o1', 'profileId', 'p1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('post', 'o1', 'profile', 'p1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
});
test('attach entities of a many-to-many relationship', () => {
// this could be improved by validating that the attachedId is appended (not prepended, etc)
const state: ForumState = {
entities: {
...forumEmptyState.entities,
post: { o1: {} },
category: { c1: {} },
},
ids: {
...forumEmptyState.ids,
post: ['o1'],
category: ['c1'],
},
};
const expectedNextState = {
entities: {
...forumEmptyState.entities,
post: { o1: { categoryIds: ['c1'] } },
category: { c1: { postIds: ['o1'] } },
},
ids: {
...forumEmptyState.ids,
post: ['o1'],
category: ['c1'],
},
};
let action, nextState;
action = forumActionCreators.attach('post', 'o1', 'categoryIds', 'c1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('post', 'o1', 'category', 'c1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('category', 'c1', 'postIds', 'o1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('category', 'c1', 'post', 'o1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
});
test('attach entities of a many-to-many relationship, with indices', () => {
const state: ForumState = {
entities: {
...forumEmptyState.entities,
post: {
o1: { categoryIds: ['c1', 'c2'] },
o2: { categoryIds: ['c1'] },
},
category: {
c1: { postIds: ['o1', 'o2'] },
c2: { postIds: ['o1'] },
c3: { postIds: [] },
},
},
ids: {
...forumEmptyState.ids,
post: ['o1', 'o2'],
category: ['c1', 'c2', 'c3'],
},
};
const expectedNextState = {
entities: {
...forumEmptyState.entities,
post: {
o1: { categoryIds: ['c1', 'c3', 'c2'] },
o2: { categoryIds: ['c1'] },
},
category: {
c1: { postIds: ['o1', 'o2'] },
c2: { postIds: ['o1'] },
c3: { postIds: ['o1'] },
},
},
ids: {
...forumEmptyState.ids,
post: ['o1', 'o2'],
category: ['c1', 'c2', 'c3'],
},
};
let action, nextState;
action = forumActionCreators.attach('post', 'o1', 'categoryIds', 'c3', { index: 1 });
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('post', 'o1', 'category', 'c3', { index: 1 });
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('category', 'c3', 'postIds', 'o1', { reciprocalIndex: 1 });
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('category', 'c3', 'post', 'o1', { reciprocalIndex: 1 });
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
});
test('attach entities and displace existing attachments', () => {
const state: ForumState = {
entities: {
...forumEmptyState.entities,
account: {
a1: { profileId: 'p1' },
a2: {},
},
profile: {
p1: { accountId: 'a1' },
},
},
ids: {
...forumEmptyState.ids,
account: ['a1', 'a2'],
profile: ['p1'],
},
};
const expectedNextState = {
entities: {
...forumEmptyState.entities,
account: {
a1: { profileId: undefined },
a2: { profileId: 'p1' },
},
profile: {
p1: { accountId: 'a2' },
},
},
ids: {
...forumEmptyState.ids,
account: ['a1', 'a2'],
profile: ['p1'],
},
};
let action, nextState;
action = forumActionCreators.attach('account', 'a2', 'profileId', 'p1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('account', 'a2', 'profile', 'p1');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('profile', 'p1', 'accountId', 'a2');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
action = forumActionCreators.attach('profile', 'p1', 'account', 'a2');
nextState = forumReducer(state, action);
expect(nextState).toEqual(expectedNextState);
});
describe('no-op cases', () => {
const state: ForumState = {
entities: {
...forumEmptyState.entities,
account: { a1: {} },
profile: { p1: {} },
},
ids: {
...forumEmptyState.ids,
account: ['a1'],
profile: ['p1'],
},
};
test('if no such entity type, then no change', () => {
const action = forumActionCreators.attach('chicken', 'c1', 'profileId', 'p1');
const nextState = forumReducer(state, action);
expect(nextState).toEqual(state);
});
test('if entity not found, then no change', () => {
const action = forumActionCreators.attach('account', 'a900', 'profileId', 'p1');
const nextState = forumReducer(state, action);
expect(nextState).toEqual(state);
});
test('if entity relation does not exist, then no change', () => {
const action = forumActionCreators.attach('account', 'a1', 'chickenId', 'c1');
const nextState = forumReducer(state, action);
expect(nextState).toEqual(state);
});
test('if attachable entity not found, then no change', () => {
const action = forumActionCreators.attach('account', 'a1', 'profileId', 'p900');
const nextState = forumReducer(state, action);
expect(nextState).toEqual(state);
});
test('if entity is already attached in a has-many collection, then no change', () => {
const state: ForumState = {
entities: {
...forumEmptyState.entities,
post: {
o1: { categoryIds: ['c1', 'c3', 'c2'] },
o2: { categoryIds: ['c1'] },
},
category: {
c1: { postIds: ['o1', 'o2'] },
c2: { postIds: ['o1'] },
c3: { postIds: ['o1'] },
},
},
ids: {
...forumEmptyState.ids,
post: ['o1', 'o2'],
category: ['c1', 'c2', 'c3'],
},
};
let action, nextState;
action = forumActionCreators.attach('post', 'o1', 'categoryIds', 'c3');
nextState = forumReducer(state, action);
expect(nextState).toEqual(state);
});
});
}); | the_stack |
import type { Sprite } from "../../../core/render/Sprite";
import { Graphics, IGraphicsSettings, IGraphicsPrivate } from "../../../core/render/Graphics";
import type { Axis, IAxisDataItem } from "./Axis";
import { Template } from "../../../core/util/Template";
import { ListTemplate } from "../../../core/util/List";
import { AxisTick } from "./AxisTick";
import { Grid } from "./Grid";
import { AxisLabel } from "./AxisLabel";
import type { IPoint } from "../../../core/util/IPoint";
import type { Tooltip } from "../../../core/render/Tooltip";
import type { AxisBullet } from "./AxisBullet";
import type { XYChart } from "../XYChart";
import type { DataItem } from "../../../core/render/Component";
import * as $utils from "../../../core/util/Utils";
import type { IPointerEvent } from "../../../core/render/backend/Renderer";
export interface IAxisRendererSettings extends IGraphicsSettings {
/**
* The minimum distance between grid lines in pixels.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Grid_density} for more info
*/
minGridDistance?: number;
/**
* Set to `true` to invert direction of the axis.
*
* @default false
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Inversed_axes} for more info
*/
inversed?: boolean;
/**
* Indicates relative position where "usable" space of the cell starts.
*
* `0` - beginning, `1` - end, or anything in-between.
*
* @default 0
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Cell_start_end_locations} for more info
*/
cellStartLocation?: number;
/**
* Indicates relative position where "usable" space of the cell ends.
*
* `0` - beginning, `1` - end, or anything in-between.
*
* @default 1
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/axes/#Cell_start_end_locations} for more info
*/
cellEndLocation?: number;
/**
* If set to `"zoom"` will enable axis zoom by panning it in the axis label
* area.
*
* Works on [[AxisRendererX]] and [[AxisRendererY]] only.
*
* For a better result, set `maxDeviation` to `1` or so on the Axis.
*
* Will not work if `inside` is set to `true`.
*
* @since 5.0.7
* @default "none"
*/
pan?: "none" | "zoom"
}
export interface IAxisRendererPrivate extends IGraphicsPrivate {
letter?: "X" | "Y";
}
/**
* Base class for an axis renderer.
*
* Should not be used on its own.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/xy-chart/#Axis_renderer} for more info
*/
export abstract class AxisRenderer extends Graphics {
public static className: string = "AxisRenderer";
public static classNames: Array<string> = Graphics.classNames.concat([AxisRenderer.className]);
// save for quick access
public _axisLength: number = 100;
public _start: number = 0;
public _end: number = 1;
public _inversed: boolean = false;
protected _minSize: number = 0;
/**
* Chart the renderer is used in.
*/
public chart: XYChart | undefined;
protected _lc = 1;
protected _ls = 0;
protected _thumbDownPoint?: IPoint;
protected _downStart?: number;
protected _downEnd?: number;
/**
* @ignore
*/
public makeTick(dataItem: DataItem<IAxisDataItem>, themeTags: Array<string>): AxisTick {
const tick = this.ticks.make();
tick._setDataItem(dataItem);
dataItem.setRaw("tick", tick);
tick.set("themeTags", $utils.mergeTags(tick.get("themeTags"), themeTags));
this.axis.labelsContainer.children.push(tick);
this.ticks.push(tick);
return tick;
}
/**
* A list of ticks in the axis.
*
* `ticks.template` can be used to configure ticks.
*
* @default new ListTemplate<AxisTick>
*/
public readonly ticks: ListTemplate<AxisTick> = new ListTemplate(
Template.new({}),
() => AxisTick._new(this._root, {
themeTags: $utils.mergeTags(this.ticks.template.get("themeTags", []), this.get("themeTags", []))
}, [this.ticks.template])
);
/**
* @ignore
*/
public makeGrid(dataItem: DataItem<IAxisDataItem>, themeTags: Array<string>): Grid {
const grid = this.grid.make();
grid._setDataItem(dataItem);
dataItem.setRaw("grid", grid);
grid.set("themeTags", $utils.mergeTags(grid.get("themeTags"), themeTags));
this.axis.gridContainer.children.push(grid);
this.grid.push(grid);
return grid;
}
/**
* A list of grid elements in the axis.
*
* `grid.template` can be used to configure grid.
*
* @default new ListTemplate<Grid>
*/
public readonly grid: ListTemplate<Grid> = new ListTemplate(
Template.new({}),
() => Grid._new(this._root, {
themeTags: $utils.mergeTags(this.grid.template.get("themeTags", []), this.get("themeTags", []))
}, [this.grid.template])
);
/**
* @ignore
*/
public makeAxisFill(dataItem: DataItem<IAxisDataItem>, themeTags: Array<string>): Grid {
const axisFill = this.axisFills.make();
axisFill._setDataItem(dataItem);
axisFill.set("themeTags", $utils.mergeTags(axisFill.get("themeTags"), themeTags));
this.axis.gridContainer.children.push(axisFill);
dataItem.setRaw("axisFill", axisFill);
this.axisFills.push(axisFill);
return axisFill;
}
/**
* A list of fills in the axis.
*
* `axisFills.template` can be used to configure axis fills.
*
* @default new ListTemplate<Graphics>
*/
public readonly axisFills: ListTemplate<Graphics> = new ListTemplate(
Template.new({}),
() => Graphics._new(this._root, {
themeTags: $utils.mergeTags(this.axisFills.template.get("themeTags", ["axis", "fill"]), this.get("themeTags", []))
}, [this.axisFills.template])
);
/**
* @ignore
*/
public makeLabel(dataItem: DataItem<IAxisDataItem>, themeTags: Array<string>): AxisLabel {
const label = this.labels.make();
if (this.get("opposite" as any)) {
themeTags.push("opposite");
}
if (this.get("inside" as any)) {
themeTags.push("inside");
}
label.set("themeTags", $utils.mergeTags(label.get("themeTags"), themeTags));
this.axis.labelsContainer.children.moveValue(label, 0);
label._setDataItem(dataItem);
dataItem.setRaw("label", label);
this.labels.push(label);
return label;
}
/**
* A list of labels in the axis.
*
* `labels.template` can be used to configure axis labels.
*
* @default new ListTemplate<AxisLabel>
*/
public readonly labels: ListTemplate<AxisLabel> = new ListTemplate(
Template.new({}),
() => AxisLabel._new(this._root, {
themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), this.get("themeTags", []))
}, [this.labels.template])
);
declare public _settings: IAxisRendererSettings;
declare public _privateSettings: IAxisRendererPrivate;
/**
* An [[Axis]] renderer is for.
*/
public axis!: Axis<this>;
public axisLength(): number {
return 0;
}
/**
* @ignore
*/
public gridCount(): number {
return this.axisLength() / this.get("minGridDistance", 50);
}
public _updatePositions() {
}
/**
* @ignore
*/
public abstract updateLabel(_label?: AxisLabel, _position?: number, _endPosition?: number, _count?: number): void;
/**
* @ignore
*/
public abstract updateGrid(_grid?: Grid, _position?: number, _endPosition?: number): void;
/**
* @ignore
*/
public abstract updateTick(_grid?: AxisTick, _position?: number, _endPosition?: number, _count?: number): void;
/**
* @ignore
*/
public abstract updateFill(_fill?: Graphics, _position?: number, _endPosition?: number): void;
/**
* @ignore
*/
public abstract updateBullet(_bullet?: AxisBullet, _position?: number, _endPosition?: number): void;
/**
* @ignore
*/
public abstract positionToPoint(_position: number): IPoint;
public readonly thumb?: Graphics;
protected _afterNew() {
super._afterNew();
this.set("isMeasured", false);
const thumb = this.thumb;
if (thumb) {
this._disposers.push(thumb.events.on("pointerdown", (event) => {
this._handleThumbDown(event.originalEvent);
}));
this._disposers.push(thumb.events.on("globalpointerup", (event) => {
this._handleThumbUp(event.originalEvent);
}));
this._disposers.push(thumb.events.on("globalpointermove", (event) => {
this._handleThumbMove(event.originalEvent);
}));
}
}
public _changed() {
super._changed();
if (this.isDirty("pan")) {
const thumb = this.thumb;
if (thumb) {
const labelsContainer = this.axis.labelsContainer;
const pan = this.get("pan");
if (pan == "zoom") {
labelsContainer.children.push(thumb);
}
else if (pan == "none") {
labelsContainer.children.removeValue(thumb);
}
}
}
}
protected _handleThumbDown(event: IPointerEvent) {
this._thumbDownPoint = this.toLocal(this._root.documentPointToRoot({ x: event.clientX, y: event.clientY }));
const axis = this.axis;
this._downStart = axis.get("start");
this._downEnd = axis.get("end");
}
protected _handleThumbUp(_event: IPointerEvent) {
this._thumbDownPoint = undefined;
}
protected _handleThumbMove(event: IPointerEvent) {
const downPoint = this._thumbDownPoint;
if (downPoint) {
const point = this.toLocal(this._root.documentPointToRoot({ x: event.clientX, y: event.clientY }));
const downStart = this._downStart!;
const downEnd = this._downEnd!;
const extra = this._getPan(point, downPoint) * Math.min(1, (downEnd - downStart)) / 2;
this.axis.setAll({ start: downStart - extra, end: downEnd + extra });
}
}
protected _getPan(_point1: IPoint, _point2: IPoint): number {
return 0;
}
/**
* Converts relative position (0-1) on axis to a pixel coordinate.
*
* @param position Position (0-1)
* @return Coordinate (px)
*/
public positionToCoordinate(position: number): number {
if (this._inversed) {
return (this._end - position) * this._axisLength;
}
else {
return (position - this._start) * this._axisLength;
}
}
/**
* @ignore
*/
public abstract positionTooltip(_tooltip: Tooltip, _position: number): void;
/**
* @ignore
*/
public updateTooltipBounds(_tooltip: Tooltip) { }
public _updateSize() {
this.markDirty()
this._clear = true;
}
public toAxisPosition(position: number): number {
const start = this._start || 0;
const end = this._end || 1;
position = position * (end - start);
if (!this.get("inversed")) {
position = start + position;
}
else {
position = end - position;
}
return position;
}
/**
* @ignore
*/
public fixPosition(position: number) {
if (this.get("inversed")) {
return 1 - position;
}
return position;
}
public _updateLC() {
}
protected toggleVisibility(sprite: Sprite, position: number, minPosition: number, maxPosition: number): void {
let axis = this.axis;
const start = axis.get("start", 0);
const end = axis.get("end", 1);
let updatedStart = start + (end - start) * (minPosition - 0.0001);
let updatedEnd = start + (end - start) * (maxPosition + 0.0001);
if (position < updatedStart || position > updatedEnd) {
sprite.setPrivate("visible", false);
}
else {
sprite.setPrivate("visible", true);
}
}
protected _positionTooltip(tooltip: Tooltip, point: IPoint) {
const chart = this.chart;
if (chart) {
if (chart.inPlot(point)) {
tooltip.set("pointTo", this._display.toGlobal(point));
}
else {
tooltip.hide();
}
}
}
public processAxis() { }
} | the_stack |
import gLong from './gLong';
import {wrapFloat, float2int, descriptor2typestr} from './util';
import {ClassReference, FieldReference, MethodReference, InterfaceMethodReference, IConstantPoolItem, InvokeDynamic, ConstDouble, ConstLong} from './ConstantPool';
import {ClassData, ArrayClassData} from './ClassData';
import {JVMThread, BytecodeStackFrame} from './threading';
import {ThreadStatus, OpCode, ConstantPoolItemType, Constants} from './enums';
import assert from './assert';
import {Method} from './methods';
import * as JVMTypes from '../includes/JVMTypes';
/**
* Interface for individual opcode implementations.
*/
export interface IOpcodeImplementation {
(thread: JVMThread, frame: BytecodeStackFrame, code?: Buffer): void;
}
/**
* Helper function: Checks if object is null. Throws a NullPointerException
* if it is.
* @return True if the object is null.
*/
export function isNull(thread: JVMThread, frame: BytecodeStackFrame, obj: any): boolean {
if (obj == null) {
throwException(thread, frame, 'Ljava/lang/NullPointerException;', '');
return true;
}
return false;
}
/**
* Helper function: Pops off two items, returns the second.
*/
export function pop2(opStack: any[]): any {
// Ignore NULL.
opStack.pop();
return opStack.pop();
}
export function resolveCPItem(thread: JVMThread, frame: BytecodeStackFrame, cpItem: IConstantPoolItem): void {
thread.setStatus(ThreadStatus.ASYNC_WAITING);
cpItem.resolve(thread, frame.getLoader(), frame.method.cls, (status: boolean) => {
if (status) {
thread.setStatus(ThreadStatus.RUNNABLE);
}
}, false);
frame.returnToThreadLoop = true;
}
export function initializeClassFromClass(thread: JVMThread, frame: BytecodeStackFrame, cls: ClassData): void {
thread.setStatus(ThreadStatus.ASYNC_WAITING);
cls.initialize(thread, (cdata: ClassData) => {
if (cdata != null) {
thread.setStatus(ThreadStatus.RUNNABLE);
}
}, false);
frame.returnToThreadLoop = true;
}
/**
* Helper function: Pauses the thread and initializes a class.
*/
export function initializeClass(thread: JVMThread, frame: BytecodeStackFrame, clsRef: ClassReference): void {
thread.setStatus(ThreadStatus.ASYNC_WAITING);
function initialize(cls: ClassData) {
cls.initialize(thread, (cdata: ClassData) => {
if (cdata != null) {
thread.setStatus(ThreadStatus.RUNNABLE);
}
});
}
if (!clsRef.isResolved()) {
clsRef.resolve(thread, frame.getLoader(), frame.method.cls, (status: boolean) => {
if (status) {
initialize(clsRef.cls);
}
}, false);
} else {
initialize(clsRef.cls);
}
frame.returnToThreadLoop = true;
}
/**
* Interrupts the current method's execution and throws an exception.
*
* NOTE: This does *not* interrupt JavaScript control flow, so any opcode
* calling this function must *return* and not do anything else.
*/
export function throwException<T extends JVMTypes.java_lang_Throwable>(thread: JVMThread, frame: BytecodeStackFrame, clsName: string, msg: string): void {
thread.throwNewException<T>(clsName, msg);
frame.returnToThreadLoop = true;
}
export var ArrayTypes : {[t: number]: string; } = {
4: 'Z', 5: 'C', 6: 'F', 7: 'D', 8: 'B', 9: 'S', 10: 'I', 11: 'J'
};
/**
* Contains definitions for all JVM opcodes.
*/
export class Opcodes {
/* 32-bit array load opcodes */
/**
* 32-bit array load opcode
*/
private static _aload_32(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
idx = opStack.pop(),
obj = <JVMTypes.JVMArray<any>> opStack.pop();
if (!isNull(thread, frame, obj)) {
var len = obj.array.length;
if (idx < 0 || idx >= len) {
throwException(thread, frame, 'Ljava/lang/ArrayIndexOutOfBoundsException;', `${idx} not in length ${len} array of type ${obj.getClass().getInternalName()}`);
} else {
opStack.push(obj.array[idx]);
frame.pc++;
}
}
// 'obj' is NULL. isNull threw an exception for us.
}
public static iaload = Opcodes._aload_32;
public static faload = Opcodes._aload_32;
public static aaload = Opcodes._aload_32;
public static baload = Opcodes._aload_32;
public static caload = Opcodes._aload_32;
public static saload = Opcodes._aload_32;
/* 64-bit array load opcodes */
/**
* 64-bit array load opcode.
*/
private static _aload_64(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
idx = opStack.pop(),
obj = <JVMTypes.JVMArray<any>> opStack.pop();
if (!isNull(thread, frame, obj)) {
var len = obj.array.length;
if (idx < 0 || idx >= len) {
throwException(thread, frame, 'Ljava/lang/ArrayIndexOutOfBoundsException;', `${idx} not in length ${len} array of type ${obj.getClass().getInternalName()}`);
} else {
opStack.push(obj.array[idx]);
// 64-bit value.
opStack.push(null);
frame.pc++;
}
}
// 'obj' is NULL. isNull threw an exception for us.
}
public static daload = Opcodes._aload_64;
public static laload = Opcodes._aload_64;
/* 32-bit array store opcodes */
/**
* 32-bit array store.
* @private
*/
private static _astore_32(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
value = opStack.pop(),
idx = opStack.pop(),
obj = <JVMTypes.JVMArray<any>> opStack.pop();
if (!isNull(thread, frame, obj)) {
var len = obj.array.length;
if (idx < 0 || idx >= len) {
throwException(thread, frame, 'Ljava/lang/ArrayIndexOutOfBoundsException;', `${idx} not in length ${len} array of type ${obj.getClass().getInternalName()}`);
} else {
obj.array[idx] = value;
frame.pc++;
}
}
// 'obj' is NULL. isNull threw an exception for us.
}
public static iastore = Opcodes._astore_32;
public static fastore = Opcodes._astore_32;
public static aastore = Opcodes._astore_32;
public static bastore = Opcodes._astore_32;
public static castore = Opcodes._astore_32;
public static sastore = Opcodes._astore_32;
/* 64-bit array store opcodes */
/**
* 64-bit array store.
* @private
*/
private static _astore_64(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
value = opStack.pop2(),
idx = opStack.pop(),
obj = <JVMTypes.JVMArray<any>> opStack.pop();
if (!isNull(thread, frame, obj)) {
var len = obj.array.length;
if (idx < 0 || idx >= len) {
throwException(thread, frame, 'Ljava/lang/ArrayIndexOutOfBoundsException;', `${idx} not in length ${len} array of type ${obj.getClass().getInternalName()}`);
} else {
obj.array[idx] = value;
frame.pc++;
}
}
// 'obj' is NULL. isNull threw an exception for us.
}
public static lastore = Opcodes._astore_64;
public static dastore = Opcodes._astore_64;
/* 32-bit constants */
public static aconst_null(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(null);
frame.pc++;
}
private static _const_0_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(0);
frame.pc++;
}
private static _const_1_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(1);
frame.pc++;
}
private static _const_2_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(2);
frame.pc++;
}
public static iconst_m1(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(-1);
frame.pc++;
}
public static iconst_0 = Opcodes._const_0_32;
public static iconst_1 = Opcodes._const_1_32;
public static iconst_2 = Opcodes._const_2_32;
public static iconst_3(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(3);
frame.pc++;
}
public static iconst_4(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(4);
frame.pc++;
}
public static iconst_5(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(5);
frame.pc++;
}
public static fconst_0 = Opcodes._const_0_32;
public static fconst_1 = Opcodes._const_1_32;
public static fconst_2 = Opcodes._const_2_32;
/* 64-bit constants */
public static lconst_0(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(gLong.ZERO);
frame.pc++;
}
public static lconst_1(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(gLong.ONE);
frame.pc++;
}
public static dconst_0(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(0);
frame.pc++;
}
public static dconst_1(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(1);
frame.pc++;
}
/* 32-bit load opcodes */
private static _load_32(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.opStack.push(frame.locals[code[pc + 1]]);
frame.pc += 2;
}
private static _load_0_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(frame.locals[0]);
frame.pc++;
}
private static _load_1_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(frame.locals[1]);
frame.pc++;
}
private static _load_2_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(frame.locals[2]);
frame.pc++;
}
private static _load_3_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(frame.locals[3]);
frame.pc++;
}
public static iload = Opcodes._load_32;
public static iload_0 = Opcodes._load_0_32;
public static iload_1 = Opcodes._load_1_32;
public static iload_2 = Opcodes._load_2_32;
public static iload_3 = Opcodes._load_3_32;
public static fload = Opcodes._load_32;
public static fload_0 = Opcodes._load_0_32;
public static fload_1 = Opcodes._load_1_32;
public static fload_2 = Opcodes._load_2_32;
public static fload_3 = Opcodes._load_3_32;
public static aload = Opcodes._load_32;
public static aload_0 = Opcodes._load_0_32;
public static aload_1 = Opcodes._load_1_32;
public static aload_2 = Opcodes._load_2_32;
public static aload_3 = Opcodes._load_3_32;
/* 64-bit load opcodes */
private static _load_64(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.opStack.pushWithNull(frame.locals[code[pc + 1]]);
frame.pc += 2;
}
private static _load_0_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(frame.locals[0]);
frame.pc++;
}
private static _load_1_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(frame.locals[1]);
frame.pc++;
}
private static _load_2_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(frame.locals[2]);
frame.pc++;
}
private static _load_3_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.pushWithNull(frame.locals[3]);
frame.pc++;
}
public static lload = Opcodes._load_64;
public static lload_0 = Opcodes._load_0_64;
public static lload_1 = Opcodes._load_1_64;
public static lload_2 = Opcodes._load_2_64;
public static lload_3 = Opcodes._load_3_64;
public static dload = Opcodes._load_64;
public static dload_0 = Opcodes._load_0_64;
public static dload_1 = Opcodes._load_1_64;
public static dload_2 = Opcodes._load_2_64;
public static dload_3 = Opcodes._load_3_64;
/* 32-bit store opcodes */
private static _store_32(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.locals[code[pc + 1]] = frame.opStack.pop();
frame.pc += 2;
}
private static _store_0_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[0] = frame.opStack.pop();
frame.pc++;
}
private static _store_1_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[1] = frame.opStack.pop();
frame.pc++;
}
private static _store_2_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[2] = frame.opStack.pop();
frame.pc++;
}
private static _store_3_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[3] = frame.opStack.pop();
frame.pc++;
}
public static istore = Opcodes._store_32;
public static istore_0 = Opcodes._store_0_32;
public static istore_1 = Opcodes._store_1_32;
public static istore_2 = Opcodes._store_2_32;
public static istore_3 = Opcodes._store_3_32;
public static fstore = Opcodes._store_32;
public static fstore_0 = Opcodes._store_0_32;
public static fstore_1 = Opcodes._store_1_32;
public static fstore_2 = Opcodes._store_2_32;
public static fstore_3 = Opcodes._store_3_32;
public static astore = Opcodes._store_32;
public static astore_0 = Opcodes._store_0_32;
public static astore_1 = Opcodes._store_1_32;
public static astore_2 = Opcodes._store_2_32;
public static astore_3 = Opcodes._store_3_32;
/* 64-bit store opcodes */
private static _store_64(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var offset = code[pc + 1];
// NULL
frame.locals[offset + 1] = frame.opStack.pop();
// The actual value.
frame.locals[offset] = frame.opStack.pop();
frame.pc += 2;
}
private static _store_0_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[1] = frame.opStack.pop();
frame.locals[0] = frame.opStack.pop();
frame.pc++;
}
private static _store_1_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[2] = frame.opStack.pop();
frame.locals[1] = frame.opStack.pop();
frame.pc++;
}
private static _store_2_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[3] = frame.opStack.pop();
frame.locals[2] = frame.opStack.pop();
frame.pc++;
}
private static _store_3_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.locals[4] = frame.opStack.pop();
frame.locals[3] = frame.opStack.pop();
frame.pc++;
}
public static lstore = Opcodes._store_64;
public static lstore_0 = Opcodes._store_0_64;
public static lstore_1 = Opcodes._store_1_64;
public static lstore_2 = Opcodes._store_2_64;
public static lstore_3 = Opcodes._store_3_64;
public static dstore = Opcodes._store_64;
public static dstore_0 = Opcodes._store_0_64;
public static dstore_1 = Opcodes._store_1_64;
public static dstore_2 = Opcodes._store_2_64;
public static dstore_3 = Opcodes._store_3_64;
/* Misc. */
public static sipush(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.opStack.push(code.readInt16BE(pc + 1));
frame.pc += 3;
}
public static bipush(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.opStack.push(code.readInt8(pc + 1));
frame.pc += 2;
}
public static pop(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.dropFromTop(1);
frame.pc++;
}
public static pop2(thread: JVMThread, frame: BytecodeStackFrame) {
// http://i.imgur.com/MieF0KG.jpg
frame.opStack.dropFromTop(2);
frame.pc++;
}
public static dup(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.dup();
frame.pc++;
}
public static dup_x1(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.dup_x1();
frame.pc++;
}
public static dup_x2(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.dup_x2();
frame.pc++;
}
public static dup2(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.dup2();
frame.pc++;
}
public static dup2_x1(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.dup2_x1();
frame.pc++;
}
public static dup2_x2(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v1 = opStack.pop(),
v2 = opStack.pop(),
v3 = opStack.pop(),
v4 = opStack.pop();
opStack.push6(v2, v1, v4, v3, v2, v1);
frame.pc++;
}
public static swap(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.swap();
frame.pc++;
}
/* Math Opcodes */
public static iadd(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push((opStack.pop() + opStack.pop()) | 0);
frame.pc++;
}
public static ladd(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().add(opStack.pop2()));
frame.pc++;
}
public static fadd(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(wrapFloat(opStack.pop() + opStack.pop()));
frame.pc++;
}
public static dadd(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2() + opStack.pop2());
frame.pc++;
}
public static isub(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push((-opStack.pop() + opStack.pop()) | 0);
frame.pc++;
}
public static fsub(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(wrapFloat(-opStack.pop() + opStack.pop()));
frame.pc++;
}
public static dsub(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(-opStack.pop2() + opStack.pop2());
frame.pc++;
}
public static lsub(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().negate().add(opStack.pop2()));
frame.pc++;
}
public static imul(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push((<any> Math).imul(opStack.pop(), opStack.pop()));
frame.pc++;
}
public static lmul(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().multiply(opStack.pop2()));
frame.pc++;
}
public static fmul(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(wrapFloat(opStack.pop() * opStack.pop()));
frame.pc++;
}
public static dmul(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2() * opStack.pop2());
frame.pc++;
}
public static idiv(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack, b: number = opStack.pop(), a: number = opStack.pop();
if (b === 0) {
throwException(thread, frame, 'Ljava/lang/ArithmeticException;', '/ by zero');
} else {
// spec: "if the dividend is the negative integer of largest possible magnitude
// for the int type, and the divisor is -1, then overflow occurs, and the
// result is equal to the dividend."
if (a === Constants.INT_MIN && b === -1) {
opStack.push(a);
} else {
opStack.push((a / b) | 0);
}
frame.pc++;
}
}
public static ldiv(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
b: gLong = opStack.pop2(),
a: gLong = opStack.pop2();
if (b.isZero()) {
throwException(thread, frame, 'Ljava/lang/ArithmeticException;', '/ by zero');
} else {
opStack.pushWithNull(a.div(b));
frame.pc++;
}
}
public static fdiv(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
a: number = opStack.pop();
opStack.push(wrapFloat(opStack.pop() / a));
frame.pc++;
}
public static ddiv(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v: number = opStack.pop2();
opStack.pushWithNull(opStack.pop2() / v);
frame.pc++;
}
public static irem(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
b: number = opStack.pop(),
a: number = opStack.pop();
if (b === 0) {
throwException(thread, frame, 'Ljava/lang/ArithmeticException;', '/ by zero');
} else {
opStack.push(a % b);
frame.pc++;
}
}
public static lrem(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
b: gLong = opStack.pop2(),
a: gLong = opStack.pop2();
if (b.isZero()) {
throwException(thread, frame, 'Ljava/lang/ArithmeticException;', '/ by zero');
} else {
opStack.pushWithNull(a.modulo(b));
frame.pc++;
}
}
public static frem(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
b: number = opStack.pop();
opStack.push(opStack.pop() % b);
frame.pc++;
}
public static drem(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
b: number = opStack.pop2();
opStack.pushWithNull(opStack.pop2() % b);
frame.pc++;
}
public static ineg(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(-opStack.pop() | 0);
frame.pc++;
}
public static lneg(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().negate());
frame.pc++;
}
public static fneg(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(-opStack.pop());
frame.pc++;
}
public static dneg(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(-opStack.pop2());
frame.pc++;
}
/* Bitwise Operations */
public static ishl(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
s: number = opStack.pop();
opStack.push(opStack.pop() << s);
frame.pc++;
}
public static lshl(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
s: number = opStack.pop();
opStack.pushWithNull(opStack.pop2().shiftLeft(gLong.fromInt(s)));
frame.pc++;
}
public static ishr(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
s: number = opStack.pop();
opStack.push(opStack.pop() >> s);
frame.pc++;
}
public static lshr(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
s: number = opStack.pop();
opStack.pushWithNull(opStack.pop2().shiftRight(gLong.fromInt(s)));
frame.pc++;
}
public static iushr(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
s: number = opStack.pop();
opStack.push((opStack.pop() >>> s) | 0);
frame.pc++;
}
public static lushr(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
s: number = opStack.pop();
opStack.pushWithNull(opStack.pop2().shiftRightUnsigned(gLong.fromInt(s)));
frame.pc++;
}
public static iand(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(opStack.pop() & opStack.pop());
frame.pc++;
}
public static land(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().and(opStack.pop2()));
frame.pc++;
}
public static ior(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(opStack.pop() | opStack.pop());
frame.pc++;
}
public static lor(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().or(opStack.pop2()));
frame.pc++;
}
public static ixor(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(opStack.pop() ^ opStack.pop());
frame.pc++;
}
public static lxor(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().xor(opStack.pop2()));
frame.pc++;
}
public static iinc(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var idx = code[pc + 1],
val = code.readInt8(pc + 2);
frame.locals[idx] = (frame.locals[idx] + val) | 0;
frame.pc += 3;
}
public static i2l(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(gLong.fromInt(opStack.pop()));
frame.pc++;
}
public static i2f(thread: JVMThread, frame: BytecodeStackFrame) {
// NOP; we represent ints as floats anyway.
// @todo What about quantities unexpressable as floats?
frame.pc++;
}
public static i2d(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(null);
frame.pc++;
}
public static l2i(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(opStack.pop2().toInt());
frame.pc++;
}
public static l2f(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(opStack.pop2().toNumber());
frame.pc++;
}
public static l2d(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(opStack.pop2().toNumber());
frame.pc++;
}
public static f2i(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(float2int(opStack.pop()));
frame.pc++;
}
public static f2l(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pushWithNull(gLong.fromNumber(opStack.pop()));
frame.pc++;
}
public static f2d(thread: JVMThread, frame: BytecodeStackFrame) {
frame.opStack.push(null);
frame.pc++;
}
public static d2i(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(float2int(opStack.pop2()));
frame.pc++;
}
public static d2l(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
d_val: number = opStack.pop2();
if (d_val === Number.POSITIVE_INFINITY) {
opStack.pushWithNull(gLong.MAX_VALUE);
} else if (d_val === Number.NEGATIVE_INFINITY) {
opStack.pushWithNull(gLong.MIN_VALUE);
} else {
opStack.pushWithNull(gLong.fromNumber(d_val));
}
frame.pc++;
}
public static d2f(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.pop();
opStack.push(wrapFloat(opStack.pop()));
frame.pc++;
}
public static i2b(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push((opStack.pop() << 24) >> 24);
frame.pc++;
}
public static i2c(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push(opStack.pop() & 0xFFFF);
frame.pc++;
}
public static i2s(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack;
opStack.push((opStack.pop() << 16) >> 16);
frame.pc++;
}
public static lcmp(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v2: gLong = opStack.pop2();
opStack.push(opStack.pop2().compare(v2));
frame.pc++;
}
public static fcmpl(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v2 = opStack.pop(),
v1 = opStack.pop();
if (v1 === v2) {
opStack.push(0);
} else if (v1 > v2) {
opStack.push(1);
} else {
// v1 < v2, and if v1 or v2 is NaN.
opStack.push(-1);
}
frame.pc++;
}
public static fcmpg(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v2 = opStack.pop(),
v1 = opStack.pop();
if (v1 === v2) {
opStack.push(0);
} else if (v1 < v2) {
opStack.push(-1);
} else {
// v1 > v2, and if v1 or v2 is NaN.
opStack.push(1);
}
frame.pc++;
}
public static dcmpl(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v2 = opStack.pop2(),
v1 = opStack.pop2();
if (v1 === v2) {
opStack.push(0);
} else if (v1 > v2) {
opStack.push(1);
} else {
// v1 < v2, and if v1 or v2 is NaN.
opStack.push(-1);
}
frame.pc++;
}
public static dcmpg(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack,
v2 = opStack.pop2(),
v1 = opStack.pop2();
if (v1 === v2) {
opStack.push(0);
} else if (v1 < v2) {
opStack.push(-1);
} else {
// v1 > v2, and if v1 or v2 is NaN.
opStack.push(1);
}
frame.pc++;
}
/* Unary branch opcodes */
public static ifeq(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() === 0) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static ifne(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() !== 0) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static iflt(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() < 0) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static ifge(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() >= 0) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static ifgt(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() > 0) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static ifle(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() <= 0) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
/* Binary branch opcodes */
public static if_icmpeq(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 === v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_icmpne(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 !== v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_icmplt(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 < v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_icmpge(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 >= v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_icmpgt(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 > v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_icmple(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 <= v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_acmpeq(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 === v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static if_acmpne(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var v2 = frame.opStack.pop();
var v1 = frame.opStack.pop();
if (v1 !== v2) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
/* Jump opcodes */
public static goto(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
}
public static jsr(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.opStack.push(pc + 3);
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
}
public static ret(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.pc = frame.locals[code[pc + 1]];
}
public static tableswitch(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
let pc = frame.pc;
// Ignore padding bytes. The +1 is to skip the opcode byte.
pc += ((4 - (pc + 1) % 4) % 4) + 1;
var defaultOffset = code.readInt32BE(pc),
low = code.readInt32BE(pc + 4),
high = code.readInt32BE(pc + 8),
offset = frame.opStack.pop();
if (offset >= low && offset <= high) {
frame.pc += code.readInt32BE(pc + 12 + ((offset - low) * 4));
} else {
frame.pc += defaultOffset;
}
}
public static lookupswitch(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
let pc = frame.pc;
// Skip padding bytes. The +1 is to skip the opcode byte.
pc += ((4 - (pc + 1) % 4) % 4) + 1;
var defaultOffset = code.readInt32BE(pc),
nPairs = code.readInt32BE(pc + 4),
i: number,
v: number = frame.opStack.pop();
pc += 8;
for (i = 0; i < nPairs; i++) {
if (code.readInt32BE(pc) === v) {
const offset = code.readInt32BE(pc + 4);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
return;
}
pc += 8;
}
// No match found.
frame.pc += defaultOffset;
}
public static return(thread: JVMThread, frame: BytecodeStackFrame) {
frame.returnToThreadLoop = true;
if (frame.method.accessFlags.isSynchronized()) {
// monitorexit
if (!frame.method.methodLock(thread, frame).exit(thread)) {
// monitorexit threw an exception.
return;
}
}
thread.asyncReturn();
}
/* 32-bit return bytecodes */
private static _return_32(thread: JVMThread, frame: BytecodeStackFrame) {
frame.returnToThreadLoop = true;
if (frame.method.accessFlags.isSynchronized()) {
// monitorexit
if (!frame.method.methodLock(thread, frame).exit(thread)) {
// monitorexit threw an exception.
return;
}
}
thread.asyncReturn(frame.opStack.bottom());
}
public static ireturn = Opcodes._return_32;
public static freturn = Opcodes._return_32;
public static areturn = Opcodes._return_32;
/* 64-bit return opcodes */
private static _return_64(thread: JVMThread, frame: BytecodeStackFrame) {
frame.returnToThreadLoop = true;
if (frame.method.accessFlags.isSynchronized()) {
// monitorexit
if (!frame.method.methodLock(thread, frame).exit(thread)) {
// monitorexit threw an exception.
return;
}
}
thread.asyncReturn(frame.opStack.bottom(), null);
}
public static lreturn = Opcodes._return_64;
public static dreturn = Opcodes._return_64;
public static getstatic(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
assert(fieldInfo.getType() === ConstantPoolItemType.FIELDREF);
if (fieldInfo.isResolved()) {
// Get the *actual* class that owns this field.
// This may not be initialized if it's an interface, so we need to check.
var fieldOwnerCls = fieldInfo.field.cls;
if (fieldOwnerCls.isInitialized(thread)) {
// Opcode is ready to execute! Rewrite to a 'fast' version,
// and run the fast version.
if (fieldInfo.nameAndTypeInfo.descriptor === 'J' || fieldInfo.nameAndTypeInfo.descriptor === 'D') {
code[pc] = OpCode.GETSTATIC_FAST64;
} else {
code[pc] = OpCode.GETSTATIC_FAST32;
}
// Stash the result of field lookup.
fieldInfo.fieldOwnerConstructor = fieldOwnerCls.getConstructor(thread);
} else {
// Initialize class and rerun opcode
initializeClassFromClass(thread, frame, fieldOwnerCls);
}
} else {
// Resolve the field.
resolveCPItem(thread, frame, fieldInfo);
}
}
/**
* A fast version of getstatic that assumes that relevant classes are
* initialized.
*
* Retrieves a 32-bit value.
*/
public static getstatic_fast32(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
frame.opStack.push(fieldInfo.fieldOwnerConstructor[fieldInfo.fullFieldName]);
frame.pc += 3;
}
/**
* A fast version of getstatic that assumes that relevant classes are
* initialized.
*
* Retrieves a 64-bit value.
*/
public static getstatic_fast64(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
frame.opStack.pushWithNull(fieldInfo.fieldOwnerConstructor[fieldInfo.fullFieldName]);
frame.pc += 3;
}
public static putstatic(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
assert(fieldInfo.getType() === ConstantPoolItemType.FIELDREF);
if (fieldInfo.isResolved()) {
// Get the *actual* class that owns this field.
// This may not be initialized if it's an interface, so we need to check.
var fieldOwnerCls = fieldInfo.field.cls;
if (fieldOwnerCls.isInitialized(thread)) {
// Opcode is ready to execute! Rewrite to a 'fast' version,
// and run the fast version.
if (fieldInfo.nameAndTypeInfo.descriptor === 'J' || fieldInfo.nameAndTypeInfo.descriptor === 'D') {
code[pc] = OpCode.PUTSTATIC_FAST64;
} else {
code[pc] = OpCode.PUTSTATIC_FAST32;
}
// Stash the result of field lookup.
fieldInfo.fieldOwnerConstructor = fieldOwnerCls.getConstructor(thread);
} else {
// Initialize class and rerun opcode
initializeClassFromClass(thread, frame, fieldOwnerCls);
}
} else {
// Resolve the field.
resolveCPItem(thread, frame, fieldInfo);
}
}
/**
* A fast version of putstatic that assumes that relevant classes are
* initialized.
*
* Puts a 32-bit value.
*/
public static putstatic_fast32(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
fieldInfo.fieldOwnerConstructor[fieldInfo.fullFieldName] = frame.opStack.pop();
frame.pc += 3;
}
/**
* A fast version of putstatic that assumes that relevant classes are
* initialized.
*
* Puts a 64-bit value.
*/
public static putstatic_fast64(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
fieldInfo.fieldOwnerConstructor[fieldInfo.fullFieldName] = frame.opStack.pop2();
frame.pc += 3;
}
public static getfield(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
loader = frame.getLoader(),
obj = frame.opStack.top();
assert(fieldInfo.getType() === ConstantPoolItemType.FIELDREF);
// Check if the object is null; if we do not do this before get_class, then
// we might try to get a class that we have not initialized!
if (!isNull(thread, frame, obj)) {
// cls is guaranteed to be in the inheritance hierarchy of obj, so it must be
// initialized. However, it may not be loaded in the current class's
// ClassLoader...
if (fieldInfo.isResolved()) {
var field = fieldInfo.field;
if (field.rawDescriptor == 'J' || field.rawDescriptor == 'D') {
code[pc] = OpCode.GETFIELD_FAST64;
} else {
code[pc] = OpCode.GETFIELD_FAST32;
}
// Rerun opcode
} else {
resolveCPItem(thread, frame, fieldInfo);
}
}
}
public static getfield_fast32(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack, obj: JVMTypes.java_lang_Object = opStack.pop();
if (!isNull(thread, frame, obj)) {
opStack.push((<any> obj)[fieldInfo.fullFieldName]);
frame.pc += 3;
}
}
public static getfield_fast64(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack, obj: JVMTypes.java_lang_Object = opStack.pop();
if (!isNull(thread, frame, obj)) {
opStack.pushWithNull((<any> obj)[fieldInfo.fullFieldName]);
frame.pc += 3;
}
}
public static putfield(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
loader = frame.getLoader(),
isLong = fieldInfo.nameAndTypeInfo.descriptor == 'J' || fieldInfo.nameAndTypeInfo.descriptor == 'D',
obj = frame.opStack.fromTop(isLong ? 2 : 1);
assert(fieldInfo.getType() === ConstantPoolItemType.FIELDREF);
// Check if the object is null; if we do not do this before get_class, then
// we might try to get a class that we have not initialized!
if (!isNull(thread, frame, obj)) {
// cls is guaranteed to be in the inheritance hierarchy of obj, so it must be
// initialized. However, it may not be loaded in the current class's
// ClassLoader...
if (fieldInfo.isResolved()) {
var field = fieldInfo.field;
if (isLong) {
code[pc] = OpCode.PUTFIELD_FAST64;
} else {
code[pc] = OpCode.PUTFIELD_FAST32;
}
// Stash the resolved full field name.
fieldInfo.fullFieldName = `${descriptor2typestr(field.cls.getInternalName())}/${fieldInfo.nameAndTypeInfo.name}`;
// Rerun opcode
} else {
resolveCPItem(thread, frame, fieldInfo);
}
}
}
public static putfield_fast32(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var opStack = frame.opStack,
val = opStack.pop(),
obj: JVMTypes.java_lang_Object = opStack.pop(),
fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (!isNull(thread, frame, obj)) {
(<any> obj)[fieldInfo.fullFieldName] = val;
frame.pc += 3;
}
// NPE has been thrown.
}
public static putfield_fast64(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var opStack = frame.opStack,
val = opStack.pop2(),
obj: JVMTypes.java_lang_Object = opStack.pop(),
fieldInfo = <FieldReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (!isNull(thread, frame, obj)) {
(<any> obj)[fieldInfo.fullFieldName] = val;
frame.pc += 3;
}
// NPE has been thrown.
}
public static invokevirtual(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
// Ensure referenced class is loaded in the current classloader.
// Even though we don't use this class for anything, and we know that it
// must be loaded because it is in the object's inheritance hierarchy,
// it needs to be present in the current classloader.
if (methodReference.isResolved()) {
var m = methodReference.method;
if (m.isSignaturePolymorphic()) {
switch (m.name) {
case 'invokeBasic':
code[pc] = OpCode.INVOKEBASIC;
break;
case 'invoke':
case 'invokeExact':
code[pc] = OpCode.INVOKEHANDLE;
break;
default:
throwException(thread, frame, 'Ljava/lang/AbstractMethodError;', `Invalid signature polymorphic method: ${m.cls.getExternalName()}.${m.name}`);
break;
}
} else {
code[pc] = OpCode.INVOKEVIRTUAL_FAST;
}
} else {
resolveCPItem(thread, frame, methodReference);
}
}
public static invokeinterface(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (methodReference.isResolved()) {
if (methodReference.method.cls.isInitialized(thread)) {
// Rewrite to fast and rerun.
code[pc] = OpCode.INVOKEINTERFACE_FAST;
} else {
// Initialize our class and rerun opcode.
// Note that the existance of an object of an interface type does *not*
// mean that the interface is initialized!
initializeClass(thread, frame, methodReference.classInfo);
}
} else {
resolveCPItem(thread, frame, methodReference);
}
}
public static invokedynamic(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var callSiteSpecifier = <InvokeDynamic> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
thread.setStatus(ThreadStatus.ASYNC_WAITING);
callSiteSpecifier.constructCallSiteObject(thread, frame.getLoader(), frame.method.cls, pc, (status: boolean) => {
if (status) {
assert(typeof(callSiteSpecifier.getCallSiteObject(pc)[0].vmtarget) === 'function', "MethodName should be resolved...");
code[pc] = OpCode.INVOKEDYNAMIC_FAST;
// Resume and rerun fast opcode.
thread.setStatus(ThreadStatus.RUNNABLE);
}
});
frame.returnToThreadLoop = true;
}
/**
* XXX: Actually perform superclass method lookup.
*/
public static invokespecial(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference | InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (methodReference.isResolved()) {
// Rewrite and rerun.
code[pc] = OpCode.INVOKENONVIRTUAL_FAST;
} else {
resolveCPItem(thread, frame, methodReference);
}
}
public static invokestatic(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference | InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (methodReference.isResolved()) {
var m = methodReference.method;
if (m.cls.isInitialized(thread)) {
var newOpcode: OpCode = OpCode.INVOKESTATIC_FAST;
if (methodReference.method.isSignaturePolymorphic()) {
switch (methodReference.method.name) {
case 'linkToInterface':
case 'linkToVirtual':
newOpcode = OpCode.LINKTOVIRTUAL;
break;
case 'linkToStatic':
case 'linkToSpecial':
newOpcode = OpCode.LINKTOSPECIAL;
break;
default:
assert(false, "Should be impossible.");
break;
}
}
// Rewrite and rerun.
code[pc] = newOpcode;
} else {
initializeClassFromClass(thread, frame, m.cls);
}
} else {
resolveCPItem(thread, frame, methodReference);
}
}
/// Fast invoke opcodes.
public static invokenonvirtual_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference | InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack, paramSize = methodReference.paramWordSize,
obj: JVMTypes.java_lang_Object = opStack.fromTop(paramSize);
if (!isNull(thread, frame, obj)) {
var args = opStack.sliceFromTop(paramSize);
opStack.dropFromTop(paramSize + 1);
assert(typeof (<any> obj)[methodReference.fullSignature] === 'function', `Resolved method ${methodReference.fullSignature} isn't defined?!`, thread);
(<any> obj)[methodReference.fullSignature](thread, args);
frame.returnToThreadLoop = true;
}
}
public static invokestatic_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference | InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack, paramSize = methodReference.paramWordSize,
args = opStack.sliceAndDropFromTop(paramSize);
assert(methodReference.jsConstructor != null, "jsConstructor is missing?!");
assert(typeof(methodReference.jsConstructor[methodReference.fullSignature]) === 'function', "Resolved method isn't defined?!");
methodReference.jsConstructor[methodReference.fullSignature](thread, args);
frame.returnToThreadLoop = true;
}
public static invokevirtual_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference | InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
count = methodReference.paramWordSize,
opStack = frame.opStack,
obj: JVMTypes.java_lang_Object = opStack.fromTop(count);
if (!isNull(thread, frame, obj)) {
// Use the class of the *object*.
assert(typeof (<any> obj)[methodReference.signature] === 'function', `Resolved method ${methodReference.signature} isn't defined?!`);
(<any> obj)[methodReference.signature](thread, opStack.sliceFromTop(count));
opStack.dropFromTop(count + 1);
frame.returnToThreadLoop = true;
}
// Object is NULL; NPE has been thrown.
}
public static invokeinterface_fast = Opcodes.invokevirtual_fast;
public static invokedynamic_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var callSiteSpecifier = <InvokeDynamic> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
cso = callSiteSpecifier.getCallSiteObject(pc),
appendix = cso[1],
fcn = cso[0].vmtarget,
opStack = frame.opStack, paramSize = callSiteSpecifier.paramWordSize,
args = opStack.sliceAndDropFromTop(paramSize);
if (appendix !== null) {
args.push(appendix);
}
fcn(thread, null, args);
frame.returnToThreadLoop = true;
}
/**
* Opcode for MethodHandle.invoke and MethodHandle.invokeExact.
*/
public static invokehandle(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack,
fcn = methodReference.memberName.vmtarget,
// Add in 1 for the method handle itself.
paramSize = methodReference.paramWordSize + 1,
appendix = methodReference.appendix,
args = opStack.sliceFromTop(paramSize);
if (appendix !== null) {
args.push(appendix);
}
if (!isNull(thread, frame, args[0])) {
opStack.dropFromTop(paramSize);
// fcn will handle invoking 'this' and such.
// TODO: If this can be varargs, pass in parameter types to the function.
fcn(thread, null, args);
frame.returnToThreadLoop = true;
}
}
/**
* Opcode for MethodHandle.invokeBasic.
* Unlike invoke/invokeExact, invokeBasic does not call a generated bytecode
* method. It calls the vmtarget embedded in the MethodHandler directly.
* This can cause crashes with malformed calls, thus it is only accesssible
* to trusted JDK code.
*/
public static invokebasic(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
paramSize = methodReference.getParamWordSize(),
opStack = frame.opStack,
obj: JVMTypes.java_lang_invoke_MethodHandle = opStack.fromTop(paramSize),
// Need to include the MethodHandle in the arguments to vmtarget. vmtarget
// will appropriately invoke it.
args = opStack.sliceFromTop(paramSize + 1),
lmbdaForm: JVMTypes.java_lang_invoke_LambdaForm,
mn: JVMTypes.java_lang_invoke_MemberName,
m: Method;
// obj is a MethodHandle.
if (!isNull(thread, frame, obj)) {
opStack.dropFromTop(paramSize + 1);
lmbdaForm = obj['java/lang/invoke/MethodHandle/form'];
mn = lmbdaForm['java/lang/invoke/LambdaForm/vmentry'];
assert(mn.vmtarget !== null && mn.vmtarget !== undefined, "vmtarget must be defined");
mn.vmtarget(thread, methodReference.nameAndTypeInfo.descriptor, args);
frame.returnToThreadLoop = true;
}
}
/**
* Also used for linkToStatic.
* TODO: De-conflate the two.
* TODO: Varargs functions.
*/
public static linktospecial(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack, paramSize = methodReference.paramWordSize,
// Final argument is the relevant MemberName. Function args are right
// before it.
args = opStack.sliceFromTop(paramSize),
memberName: JVMTypes.java_lang_invoke_MemberName = args.pop(),
// TODO: Use parsed descriptor.
desc = methodReference.nameAndTypeInfo.descriptor;
if (!isNull(thread, frame, memberName)) {
opStack.dropFromTop(paramSize);
assert(memberName.getClass().getInternalName() === "Ljava/lang/invoke/MemberName;");
// parameterTypes for function are the same as the method reference, but without the trailing MemberName.
// TODO: Use parsed descriptor, avoid re-doing work here.
memberName.vmtarget(thread, desc.replace("Ljava/lang/invoke/MemberName;)", ")"), args);
frame.returnToThreadLoop = true;
}
}
// XXX: Varargs functions. We're supposed to box args if target is varargs.
public static linktovirtual(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var methodReference = <MethodReference | InterfaceMethodReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
paramSize = methodReference.paramWordSize,
opStack = frame.opStack,
args = opStack.sliceFromTop(paramSize),
// Final argument is the relevant MemberName. Function args are right
// before it.
memberName: JVMTypes.java_lang_invoke_MemberName = args.pop(),
desc = methodReference.nameAndTypeInfo.descriptor;
if (!isNull(thread, frame, memberName)) {
opStack.dropFromTop(paramSize);
assert(memberName.getClass().getInternalName() === "Ljava/lang/invoke/MemberName;");
// parameterTypes for function are the same as the method reference, but without the trailing MemberName.
memberName.vmtarget(thread, desc.replace("Ljava/lang/invoke/MemberName;)", ")"), args);
frame.returnToThreadLoop = true;
}
}
public static breakpoint(thread: JVMThread, frame: BytecodeStackFrame) {
throwException(thread, frame, "Ljava/lang/Error;", "breakpoint not implemented.");
}
public static new(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (classRef.isResolved()) {
var cls = classRef.cls;
if (cls.isInitialized(thread)) {
code[pc] = OpCode.NEW_FAST;
// Return to thread, rerun opcode.
} else {
initializeClassFromClass(thread, frame, cls);
}
} else {
resolveCPItem(thread, frame, classRef);
}
}
public static new_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
frame.opStack.push(new classRef.clsConstructor(thread));
frame.pc += 3;
}
public static newarray(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
// TODO: Stash all of these array types during JVM startup.
var opStack = frame.opStack,
type = "[" + ArrayTypes[code[pc + 1]],
cls = <ArrayClassData<any>> frame.getLoader().getInitializedClass(thread, type),
length = opStack.pop();
if (length >= 0) {
opStack.push(new (cls.getConstructor(thread))(thread, length));
frame.pc += 2;
} else {
throwException(thread, frame, 'Ljava/lang/NegativeArraySizeException;', `Tried to init ${type} array with length ${length}`);
}
}
public static anewarray(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (classRef.isResolved()) {
// Rewrite and rerun.
code[pc] = OpCode.ANEWARRAY_FAST;
classRef.arrayClass = <ArrayClassData<any>> frame.getLoader().getInitializedClass(thread, `[${classRef.cls.getInternalName()}`);
classRef.arrayClassConstructor = classRef.arrayClass.getConstructor(thread);
} else {
resolveCPItem(thread, frame, classRef);
}
}
public static anewarray_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var opStack = frame.opStack,
classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
length = opStack.pop();
if (length >= 0) {
opStack.push(new classRef.arrayClassConstructor(thread, length));
frame.pc += 3;
} else {
throwException(thread, frame, 'Ljava/lang/NegativeArraySizeException;', `Tried to init ${classRef.arrayClass.getInternalName()} array with length ${length}`);
}
}
public static arraylength(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack, obj: JVMTypes.JVMArray<any> = opStack.pop();
if (!isNull(thread, frame, obj)) {
opStack.push(obj.array.length);
frame.pc++;
}
// obj is NULL. isNull threw an exception for us.
}
public static athrow(thread: JVMThread, frame: BytecodeStackFrame) {
thread.throwException(frame.opStack.pop());
frame.returnToThreadLoop = true;
}
public static checkcast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (classRef.isResolved()) {
// Rewrite to fast version, and re-execute.
code[pc] = OpCode.CHECKCAST_FAST;
} else {
resolveCPItem(thread, frame, classRef);
}
}
public static checkcast_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
cls = classRef.cls,
opStack = frame.opStack,
o: JVMTypes.java_lang_Object = opStack.top();
if ((o != null) && !o.getClass().isCastable(cls)) {
var targetClass = cls.getExternalName();
var candidateClass = o.getClass().getExternalName();
throwException(thread, frame, 'Ljava/lang/ClassCastException;', `${candidateClass} cannot be cast to ${targetClass}`);
} else {
// Success!
frame.pc += 3;
}
}
public static instanceof(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (classRef.isResolved()) {
// Rewrite and rerun.
code[pc] = OpCode.INSTANCEOF_FAST;
} else {
// Fetch class and rerun opcode.
resolveCPItem(thread, frame, classRef);
}
}
public static instanceof_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
cls = classRef.cls,
opStack = frame.opStack,
o = <JVMTypes.java_lang_Object> opStack.pop();
opStack.push(o !== null ? (o.getClass().isCastable(cls) ? 1 : 0) : 0);
frame.pc += 3;
}
public static monitorenter(thread: JVMThread, frame: BytecodeStackFrame) {
var opStack = frame.opStack, monitorObj: JVMTypes.java_lang_Object = opStack.pop(),
monitorEntered = () => {
// [Note: Thread is now in the RUNNABLE state.]
// Increment the PC.
frame.pc++;
};
if (!monitorObj.getMonitor().enter(thread, monitorEntered)) {
// Opcode failed. monitorEntered will be run once we own the monitor.
// The thread is now in the BLOCKED state. Tell the frame to return to
// the thread loop.
frame.returnToThreadLoop = true;
} else {
monitorEntered();
}
}
public static monitorexit(thread: JVMThread, frame: BytecodeStackFrame) {
var monitorObj: JVMTypes.java_lang_Object = frame.opStack.pop();
if (monitorObj.getMonitor().exit(thread)) {
frame.pc++;
} else {
// monitorexit failed, and threw an exception.
frame.returnToThreadLoop = true;
}
}
public static multianewarray(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (classRef.isResolved()) {
// Rewrite and rerun.
code[pc] = OpCode.MULTIANEWARRAY_FAST;
} else {
resolveCPItem(thread, frame, classRef);
}
}
public static multianewarray_fast(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var classRef = <ClassReference> frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1)),
opStack = frame.opStack,
dim = code[pc + 3],
i: number,
// Arguments to the constructor.
args = new Array<number>(dim), dimSize: number;
for (i = 0; i < dim; i++) {
dimSize = opStack.pop();
args[dim - i - 1] = dimSize;
if (dimSize < 0) {
throwException(thread, frame, 'Ljava/lang/NegativeArraySizeException;', `Tried to init ${classRef.cls.getInternalName()} array with a dimension of length ${dimSize}`);
return;
}
}
opStack.push(new (classRef.cls.getConstructor(thread))(thread, args));
frame.pc += 4;
}
public static ifnull(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() == null) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static ifnonnull(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
if (frame.opStack.pop() != null) {
const offset = code.readInt16BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
} else {
frame.pc += 3;
}
}
public static goto_w(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
const offset = code.readInt32BE(pc + 1);
frame.pc += offset;
if (offset < 0) {
frame.method.incrBBEntries();
}
}
public static jsr_w(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
frame.opStack.push(frame.pc + 5);
frame.pc += code.readInt32BE(pc + 1);
}
public static nop(thread: JVMThread, frame: BytecodeStackFrame) {
frame.pc += 1;
}
public static ldc(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var constant = frame.method.cls.constantPool.get(code[pc + 1]);
if (constant.isResolved()) {
assert((() => {
switch (constant.getType()) {
case ConstantPoolItemType.STRING:
case ConstantPoolItemType.CLASS:
case ConstantPoolItemType.METHOD_HANDLE:
case ConstantPoolItemType.METHOD_TYPE:
case ConstantPoolItemType.INTEGER:
case ConstantPoolItemType.FLOAT:
return true;
default:
return false;
}
})(), `Constant pool item ${ConstantPoolItemType[constant.getType()]} is not appropriate for LDC.`);
frame.opStack.push(constant.getConstant(thread));
frame.pc += 2;
} else {
resolveCPItem(thread, frame, constant);
}
}
public static ldc_w(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var constant = frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
if (constant.isResolved()) {
assert((() => {
switch (constant.getType()) {
case ConstantPoolItemType.STRING:
case ConstantPoolItemType.CLASS:
case ConstantPoolItemType.METHOD_HANDLE:
case ConstantPoolItemType.METHOD_TYPE:
case ConstantPoolItemType.INTEGER:
case ConstantPoolItemType.FLOAT:
return true;
default:
return false;
}
})(), `Constant pool item ${ConstantPoolItemType[constant.getType()]} is not appropriate for LDC_W.`);
frame.opStack.push(constant.getConstant(thread));
frame.pc += 3;
} else {
resolveCPItem(thread, frame, constant);
}
}
public static ldc2_w(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var constant = frame.method.cls.constantPool.get(code.readUInt16BE(pc + 1));
assert(constant.getType() === ConstantPoolItemType.LONG
|| constant.getType() === ConstantPoolItemType.DOUBLE,
`Invalid ldc_w constant pool type: ${ConstantPoolItemType[constant.getType()]}`);
frame.opStack.pushWithNull((<ConstLong | ConstDouble> constant).value);
frame.pc += 3;
}
public static wide(thread: JVMThread, frame: BytecodeStackFrame, code: Buffer) {
const pc = frame.pc;
var index = code.readUInt16BE(pc + 2);
// Increment PC before switch to avoid issue where ret chances PC and we
// erroneously increment the PC further.
frame.pc += 4;
switch (code[pc + 1]) {
case OpCode.ILOAD:
case OpCode.FLOAD:
case OpCode.ALOAD:
frame.opStack.push(frame.locals[index]);
break;
case OpCode.LLOAD:
case OpCode.DLOAD:
frame.opStack.pushWithNull(frame.locals[index]);
break;
case OpCode.ISTORE:
case OpCode.FSTORE:
case OpCode.ASTORE:
frame.locals[index] = frame.opStack.pop();
break;
case OpCode.LSTORE:
case OpCode.DSTORE:
// NULL
frame.locals[index + 1] = frame.opStack.pop();
// The actual value.
frame.locals[index] = frame.opStack.pop();
break;
case OpCode.RET:
frame.pc = frame.locals[index];
break;
case OpCode.IINC:
var value = code.readInt16BE(pc + 4);
frame.locals[index] = (frame.locals[index] + value) | 0;
// wide iinc has 2 extra bytes.
frame.pc += 2;
break;
default:
assert(false, `Unknown wide opcode: ${code[pc + 1]}`);
break;
}
}
}
export var LookupTable: IOpcodeImplementation[] = new Array(0xff);
// Put in function closure to prevent scope pollution.
(() => {
for (var i = 0; i < 0xff; i++) {
if (OpCode.hasOwnProperty("" + i)) {
LookupTable[i] = (<any> Opcodes)[OpCode[i].toLowerCase()];
assert(LookupTable[i] != null, `Missing implementation of opcode ${OpCode[i]}`);
}
}
})(); | the_stack |
// eslint-disable-next-line import/no-extraneous-dependencies
import { randomBytes } from 'crypto';
import * as AWS from 'aws-sdk';
import { mock, restore, setSDKInstance } from 'aws-sdk-mock';
import { fake } from 'sinon';
import { sanitizeSecretName, Secret } from '../secret';
// Enable/disable debugging statements.
const DEBUG: boolean = false;
if (!DEBUG) {
console.debug = () => { };
}
describe('Secret class', () => {
beforeEach(() => {
setSDKInstance(AWS);
});
afterEach(() => {
restore('SecretsManager');
});
describe('create', () => {
test('success', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
mock(
'SecretsManager',
'createSecret',
fake.resolves({ ARN: arn }),
);
const name = 'SecretName';
const client = new AWS.SecretsManager();
const secret = await Secret.create({ name, client });
expect(secret).toEqual(Secret.fromArn(arn, client));
});
test('success - all options + string', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
mock(
'SecretsManager',
'createSecret',
fake.resolves({ ARN: arn }),
);
const name = 'SecretName';
const client = new AWS.SecretsManager();
const secret = await Secret.create({
name,
client,
encryptionKey: { arn: 'testArn' },
description: 'test desc',
data: 'test data',
tags: [{ Key: 'key', Value: 'value' }],
});
expect(secret).toEqual(Secret.fromArn(arn, client));
});
test('success - all options + binary', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
mock(
'SecretsManager',
'createSecret',
fake.resolves({ ARN: arn }),
);
const name = 'SecretName';
const client = new AWS.SecretsManager();
const secret = await Secret.create({
name,
client,
encryptionKey: { arn: 'testArn' },
description: 'test desc',
data: Buffer.from(randomBytes(512)),
tags: [{ Key: 'key', Value: 'value' }],
});
expect(secret).toEqual(Secret.fromArn(arn, client));
});
test('missing response', async () => {
mock(
'SecretsManager',
'createSecret',
fake.resolves({}),
);
const name = 'SecretName';
const client = new AWS.SecretsManager();
const secret = await Secret.create({ name, client });
expect(secret).toBeUndefined();
});
test('SecretsManager error', async () => {
mock(
'SecretsManager',
'createSecret',
fake.rejects({}),
);
const name = 'SecretName';
const client = new AWS.SecretsManager();
await expect(Secret.create({ name, client })).rejects.toThrowError();
});
});
describe('delete', () => {
test('success', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeDeleteSecret = fake.resolves({});
mock(
'SecretsManager',
'deleteSecret',
fakeDeleteSecret,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await secret.delete();
expect(fakeDeleteSecret.callCount).toEqual(1);
});
test('secret already deleted', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeDeleteSecret = fake.resolves({});
mock(
'SecretsManager',
'deleteSecret',
fakeDeleteSecret,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await secret.delete();
await expect(() => secret.delete()).rejects.toThrowError('Secret has already been deleted');
expect(fakeDeleteSecret.callCount).toEqual(1);
});
test('SecretManager error', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeDeleteSecret = fake.rejects({});
mock(
'SecretsManager',
'deleteSecret',
fakeDeleteSecret,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await expect(() => secret.delete()).rejects.toThrowError();
});
});
describe('putValue', () => {
test('string success', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakePutSecretValue = fake.resolves({});
mock(
'SecretsManager',
'putSecretValue',
fakePutSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
const value = 'Super secret value'.toString();
await secret.putValue(value);
expect(fakePutSecretValue.callCount).toEqual(1);
expect(fakePutSecretValue.calledWith({
SecretId: arn,
SecretBinary: undefined,
SecretString: value,
})).toBeTruthy();
});
test('Buffer success', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakePutSecretValue = fake.resolves({});
mock(
'SecretsManager',
'putSecretValue',
fakePutSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
const value = Buffer.from(randomBytes(512));
await secret.putValue(value);
expect(fakePutSecretValue.callCount).toEqual(1);
expect(fakePutSecretValue.calledWith({
SecretId: arn,
SecretBinary: value,
SecretString: undefined,
})).toBeTruthy();
});
test('already deleted', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeDeleteSecret = fake.resolves({});
mock(
'SecretsManager',
'deleteSecret',
fakeDeleteSecret,
);
const fakePutSecretValue = fake.resolves({});
mock(
'SecretsManager',
'putSecretValue',
fakePutSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
const value = 'value';
await secret.delete();
await expect(() => secret.putValue(value)).rejects.toThrowError('Secret has been deleted');
expect(fakePutSecretValue.callCount).toEqual(0);
});
test('SecretManager error', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakePutSecretValue = fake.rejects({});
mock(
'SecretsManager',
'putSecretValue',
fakePutSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
const value = 'Super secret value';
await expect(() => secret.putValue(value)).rejects.toThrowError();
expect(fakePutSecretValue.callCount).toEqual(1);
});
});
describe('getValue', () => {
test('SecretString success', async () => {
const value = 'Super secret value'.toString();
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeGetSecretValue = fake.resolves({
SecretString: value,
});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await secret.getValue();
expect(fakeGetSecretValue.callCount).toEqual(1);
});
test('SecrectBinary string success', async () => {
const value = 'Super secret value'.toString();
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeGetSecretValue = fake.resolves({
SecretBinary: value,
});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await expect(secret.getValue()).resolves.toEqual(Buffer.from(value));
expect(fakeGetSecretValue.callCount).toEqual(1);
});
test('SecretBinary Buffer success', async () => {
const value = Buffer.from(randomBytes(512));
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeGetSecretValue = fake.resolves({
SecretBinary: value,
});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await expect(secret.getValue()).resolves.toEqual(value);
expect(fakeGetSecretValue.callCount).toEqual(1);
});
test('SecretBinary ArrayBuffer success', async () => {
const value: ArrayBufferView = new Int32Array();
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeGetSecretValue = fake.resolves({
SecretBinary: value,
});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await expect(secret.getValue()).resolves.toEqual(Buffer.from(value.buffer));
expect(fakeGetSecretValue.callCount).toEqual(1);
});
test('SecretBinary unknown type error', async () => {
const value = new ArrayBuffer(0);
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeGetSecretValue = fake.resolves({
SecretBinary: value,
});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await expect(() => secret.getValue()).rejects.toThrowError('Unknown type for SecretBinary data');
expect(fakeGetSecretValue.callCount).toEqual(1);
});
test('already deleted', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeDeleteSecret = fake.resolves({});
mock(
'SecretsManager',
'deleteSecret',
fakeDeleteSecret,
);
const fakeGetSecretValue = fake.resolves({});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await secret.delete();
await expect(() => secret.getValue()).rejects.toThrowError('Secret has been deleted');
expect(fakeGetSecretValue.callCount).toEqual(0);
});
test('SecretManager error', async () => {
const arn = 'arn:aws:secretsmanager:fake0secret1:123:secret:1a2b/';
const fakeGetSecretValue = fake.rejects({});
mock(
'SecretsManager',
'getSecretValue',
fakeGetSecretValue,
);
const client = new AWS.SecretsManager();
const secret = Secret.fromArn(arn, client);
await expect(() => secret.getValue()).rejects.toThrowError();
expect(fakeGetSecretValue.callCount).toEqual(1);
});
});
});
test('fromArn invalid ARN', async () => {
const invalidArn = 'notAnArn';
const client = new AWS.SecretsManager();
expect(() => Secret.fromArn(invalidArn, client)).toThrowError(`Not a Secret ARN: ${invalidArn}`);
});
test.each([
['test', 'test'],
['Test', 'Test'],
['test_test', 'test_test'],
['test+test', 'test+test'],
['test.test', 'test.test'],
['test@test', 'test@test'],
['test-test', 'test-test'],
['test-test-', 'test-test-'],
['test-----test', 'test-----test'],
['t t', 'tt'],
['t~t', 'tt'],
['t`t', 'tt'],
['t t', 'tt'],
['t ~ t', 'tt'],
])('sanitizeSecretName', (name, nameSanitized) => {
expect(sanitizeSecretName(name)).toEqual(nameSanitized);
}); | the_stack |
namespace eui {
let UIComponentClass = "eui.UIComponent";
/**
* The HorizontalLayout class arranges the layout elements in a horizontal sequence,
* left to right, with optional gaps between the elements and optional padding
* around the elements.
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @includeExample extension/eui/layout/HorizontalLayoutExample.ts
* @language en_US
*/
/**
* HorizontalLayout 类按水平顺序从左到右排列布局元素,在元素和围绕元素的可选填充之间带有可选间隙。
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
* @includeExample extension/eui/layout/HorizontalLayoutExample.ts
* @language zh_CN
*/
export class HorizontalLayout extends LinearLayoutBase {
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected measureReal():void {
let target = this.$target;
let count = target.numElements;
let numElements = count;
let measuredWidth = 0;
let measuredHeight = 0;
let bounds = egret.$TempRectangle;
for (let i = 0; i < count; i++) {
let layoutElement = <UIComponent> (target.getElementAt(i));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
numElements--;
continue;
}
layoutElement.getPreferredBounds(bounds);
measuredWidth += bounds.width;
measuredHeight = Math.max(measuredHeight, bounds.height);
}
measuredWidth += (numElements - 1) * this.$gap;
let hPadding = this.$paddingLeft + this.$paddingRight;
let vPadding = this.$paddingTop + this.$paddingBottom;
target.setMeasuredSize(measuredWidth + hPadding, measuredHeight + vPadding);
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected measureVirtual():void {
let target = this.$target;
let typicalWidth = this.$typicalWidth;
let measuredWidth = this.getElementTotalSize();
let measuredHeight = Math.max(this.maxElementSize, this.$typicalHeight);
let bounds = egret.$TempRectangle;
let endIndex = this.endIndex;
let elementSizeTable = this.elementSizeTable;
for (let index = this.startIndex; index < endIndex; index++) {
let layoutElement = <UIComponent> (target.getElementAt(index));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
continue;
}
layoutElement.getPreferredBounds(bounds);
measuredWidth += bounds.width;
measuredWidth -= isNaN(elementSizeTable[index]) ? typicalWidth : elementSizeTable[index];
measuredHeight = Math.max(measuredHeight, bounds.height);
}
let hPadding = this.$paddingLeft + this.$paddingRight;
let vPadding = this.$paddingTop + this.$paddingBottom;
target.setMeasuredSize(measuredWidth + hPadding, measuredHeight + vPadding);
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected updateDisplayListReal(width:number, height:number):void {
let target = this.$target;
let paddingL = this.$paddingLeft;
let paddingR = this.$paddingRight;
let paddingT = this.$paddingTop;
let paddingB = this.$paddingBottom;
let gap = this.$gap;
let targetWidth = Math.max(0, width - paddingL - paddingR);
let targetHeight = Math.max(0, height - paddingT - paddingB);
let hJustify = this.$horizontalAlign == JustifyAlign.JUSTIFY;
let vJustify = this.$verticalAlign == JustifyAlign.JUSTIFY || this.$verticalAlign == JustifyAlign.CONTENT_JUSTIFY;
let vAlign = 0;
if (!vJustify) {
if (this.$verticalAlign == egret.VerticalAlign.MIDDLE) {
vAlign = 0.5;
}
else if (this.$verticalAlign == egret.VerticalAlign.BOTTOM) {
vAlign = 1;
}
}
let count = target.numElements;
let numElements = count;
let x = paddingL;
let y = paddingT;
let i:number;
let layoutElement:UIComponent;
let totalPreferredWidth = 0;
let totalPercentWidth = 0;
let childInfoArray:any[] = [];
let childInfo:sys.ChildInfo;
let widthToDistribute = targetWidth;
let maxElementHeight = this.maxElementSize;
let bounds = egret.$TempRectangle;
for (i = 0; i < count; i++) {
let layoutElement = <UIComponent> (target.getElementAt(i));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
numElements--;
continue;
}
layoutElement.getPreferredBounds(bounds);
maxElementHeight = Math.max(maxElementHeight, bounds.height);
if (hJustify) {
totalPreferredWidth += bounds.width;
}
else {
let values = layoutElement.$UIComponent;
if (!isNaN(values[sys.UIKeys.percentWidth])) {
totalPercentWidth += values[sys.UIKeys.percentWidth];
childInfo = new sys.ChildInfo();
childInfo.layoutElement = layoutElement;
childInfo.percent = values[sys.UIKeys.percentWidth];
childInfo.min = values[sys.UIKeys.minWidth];
childInfo.max = values[sys.UIKeys.maxWidth];
childInfoArray.push(childInfo);
}
else {
widthToDistribute -= bounds.width;
}
}
}
widthToDistribute -= gap * (numElements - 1);
widthToDistribute = widthToDistribute > 0 ? widthToDistribute : 0;
let excessSpace = targetWidth - totalPreferredWidth - gap * (numElements - 1);
let averageWidth:number;
let largeChildrenCount = numElements;
let widthDic:any = {};
if (hJustify) {
if (excessSpace < 0) {
averageWidth = widthToDistribute / numElements;
for (i = 0; i < count; i++) {
layoutElement = <UIComponent> (target.getElementAt(i));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
continue;
}
layoutElement.getPreferredBounds(bounds);
if (bounds.width <= averageWidth) {
widthToDistribute -= bounds.width;
largeChildrenCount--;
continue;
}
}
widthToDistribute = widthToDistribute > 0 ? widthToDistribute : 0;
}
}
else {
if (totalPercentWidth > 0) {
this.flexChildrenProportionally(targetWidth, widthToDistribute,
totalPercentWidth, childInfoArray);
let roundOff = 0;
let length = childInfoArray.length;
for (i = 0; i < length; i++) {
childInfo = childInfoArray[i];
let childSize = Math.round(childInfo.size + roundOff);
roundOff += childInfo.size - childSize;
widthDic[childInfo.layoutElement.$hashCode] = childSize;
widthToDistribute -= childSize;
}
widthToDistribute = widthToDistribute > 0 ? widthToDistribute : 0;
}
}
if (this.$horizontalAlign == egret.HorizontalAlign.CENTER) {
x = paddingL + widthToDistribute * 0.5;
}
else if (this.$horizontalAlign == egret.HorizontalAlign.RIGHT) {
x = paddingL + widthToDistribute;
}
let maxX = paddingL;
let maxY = paddingT;
let dx = 0;
let dy = 0;
let justifyHeight:number = Math.ceil(targetHeight);
if (this.$verticalAlign == JustifyAlign.CONTENT_JUSTIFY)
justifyHeight = Math.ceil(Math.max(targetHeight, maxElementHeight));
let roundOff = 0;
let layoutElementWidth:number;
let childWidth:number;
for (i = 0; i < count; i++) {
let exceesHeight = 0;
layoutElement = <UIComponent> (target.getElementAt(i));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
continue;
}
layoutElement.getPreferredBounds(bounds);
layoutElementWidth = NaN;
if (hJustify) {
childWidth = NaN;
if (excessSpace > 0) {
childWidth = widthToDistribute * bounds.width / totalPreferredWidth;
}
else if (excessSpace < 0 && bounds.width > averageWidth) {
childWidth = widthToDistribute / largeChildrenCount
}
if (!isNaN(childWidth)) {
layoutElementWidth = Math.round(childWidth + roundOff);
roundOff += childWidth - layoutElementWidth;
}
}
else {
layoutElementWidth = widthDic[layoutElement.$hashCode];
}
if (vJustify) {
y = paddingT;
layoutElement.setLayoutBoundsSize(layoutElementWidth, justifyHeight);
layoutElement.getLayoutBounds(bounds);
}
else {
let layoutElementHeight = NaN;
let values = layoutElement.$UIComponent;
if (!isNaN(layoutElement.percentHeight)) {
let percent = Math.min(100, values[sys.UIKeys.percentHeight]);
layoutElementHeight = Math.round(targetHeight * percent * 0.01);
}
layoutElement.setLayoutBoundsSize(layoutElementWidth, layoutElementHeight);
layoutElement.getLayoutBounds(bounds);
exceesHeight = (targetHeight - bounds.height) * vAlign;
exceesHeight = exceesHeight > 0 ? exceesHeight : 0;
y = paddingT + exceesHeight;
}
layoutElement.setLayoutBoundsPosition(Math.round(x), Math.round(y));
dx = Math.ceil(bounds.width);
dy = Math.ceil(bounds.height);
maxX = Math.max(maxX, x + dx);
maxY = Math.max(maxY, y + dy);
x += dx + gap;
}
this.maxElementSize = maxElementHeight;
target.setContentSize(maxX + paddingR, maxY + paddingB);
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected updateDisplayListVirtual(width:number, height:number):void {
let target = this.$target;
if (this.indexInViewCalculated)
this.indexInViewCalculated = false;
else
this.getIndexInView();
let paddingR = this.$paddingRight;
let paddingT = this.$paddingTop;
let paddingB = this.$paddingBottom;
let gap = this.$gap;
let contentWidth:number;
let numElements = target.numElements;
if (this.startIndex == -1 || this.endIndex == -1) {
contentWidth = this.getStartPosition(numElements) - gap + paddingR;
target.setContentSize(contentWidth, target.contentHeight);
return;
}
let endIndex = this.endIndex;
target.setVirtualElementIndicesInView(this.startIndex, endIndex);
//获取垂直布局参数
let justify = this.$verticalAlign == JustifyAlign.JUSTIFY || this.$verticalAlign == JustifyAlign.CONTENT_JUSTIFY;
let contentJustify = this.$verticalAlign == JustifyAlign.CONTENT_JUSTIFY;
let vAlign = 0;
if (!justify) {
if (this.$verticalAlign == egret.VerticalAlign.MIDDLE) {
vAlign = 0.5;
}
else if (this.$verticalAlign == egret.VerticalAlign.BOTTOM) {
vAlign = 1;
}
}
let bounds = egret.$TempRectangle;
let targetHeight = Math.max(0, height - paddingT - paddingB);
let justifyHeight = Math.ceil(targetHeight);
let layoutElement:UIComponent;
let typicalHeight = this.$typicalHeight;
let typicalWidth = this.$typicalWidth;
let maxElementHeight = this.maxElementSize;
let oldMaxH = Math.max(typicalHeight, this.maxElementSize);
if (contentJustify) {
for (let index = this.startIndex; index <= endIndex; index++) {
layoutElement = <UIComponent> (target.getVirtualElementAt(index));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
continue;
}
layoutElement.getPreferredBounds(bounds);
maxElementHeight = Math.max(maxElementHeight, bounds.height);
}
justifyHeight = Math.ceil(Math.max(targetHeight, maxElementHeight));
}
let x = 0;
let y = 0;
let contentHeight = 0;
let oldElementSize:number;
let needInvalidateSize = false;
let elementSizeTable = this.elementSizeTable;
//对可见区域进行布局
for (let i = this.startIndex; i <= endIndex; i++) {
let exceesHeight = 0;
layoutElement = <UIComponent> (target.getVirtualElementAt(i));
if (!egret.is(layoutElement, UIComponentClass) || !layoutElement.$includeInLayout) {
continue;
}
layoutElement.getPreferredBounds(bounds);
if (!contentJustify) {
maxElementHeight = Math.max(maxElementHeight, bounds.height);
}
if (justify) {
y = paddingT;
layoutElement.setLayoutBoundsSize(NaN, justifyHeight);
layoutElement.getLayoutBounds(bounds);
}
else {
layoutElement.getLayoutBounds(bounds);
exceesHeight = (targetHeight - bounds.height) * vAlign;
exceesHeight = exceesHeight > 0 ? exceesHeight : 0;
y = paddingT + exceesHeight;
}
contentHeight = Math.max(contentHeight, bounds.height);
if (!needInvalidateSize) {
oldElementSize = isNaN(elementSizeTable[i]) ? typicalWidth : elementSizeTable[i];
if (oldElementSize != bounds.width)
needInvalidateSize = true;
}
elementSizeTable[i] = bounds.width;
x = this.getStartPosition(i);
layoutElement.setLayoutBoundsPosition(Math.round(x), Math.round(y));
}
contentHeight += paddingT + paddingB;
contentWidth = this.getStartPosition(numElements) - gap + paddingR;
this.maxElementSize = maxElementHeight;
target.setContentSize(contentWidth, contentHeight);
if (needInvalidateSize || oldMaxH < this.maxElementSize) {
target.invalidateSize();
}
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected getStartPosition(index:number):number {
if (!this.$useVirtualLayout) {
if (this.$target) {
let element = <UIComponent>this.$target.getElementAt(index);
if (element) {
return element.x;
}
}
}
let typicalWidth = this.$typicalWidth;
let startPos = this.$paddingLeft;
let gap = this.$gap;
let elementSizeTable = this.elementSizeTable;
for (let i = 0; i < index; i++) {
let w = elementSizeTable[i];
if(isNaN(w)){
w = typicalWidth;
}
startPos += w + gap;
}
return startPos;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected getElementSize(index:number):number {
if (this.$useVirtualLayout) {
let size = this.elementSizeTable[index];
if(isNaN(size)){
size = this.$typicalWidth;
}
return size;
}
if (this.$target) {
return this.$target.getElementAt(index).width;
}
return 0;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected getElementTotalSize():number {
let typicalWidth = this.$typicalWidth;
let gap = this.$gap;
let totalSize = 0;
let length = this.$target.numElements;
let elementSizeTable = this.elementSizeTable;
for (let i = 0; i < length; i++) {
let w = elementSizeTable[i];
if(isNaN(w)){
w = typicalWidth;
}
totalSize += w + gap;
}
totalSize -= gap;
return totalSize;
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
public elementAdded(index:number):void {
if (!this.useVirtualLayout)
return;
super.elementAdded(index);
this.elementSizeTable.splice(index, 0, this.$typicalWidth);
}
/**
* @inheritDoc
*
* @version Egret 2.4
* @version eui 1.0
* @platform Web,Native
*/
protected getIndexInView():boolean {
let target = this.$target;
if (!target || target.numElements == 0) {
this.startIndex = this.endIndex = -1;
return false;
}
let values = target.$UIComponent;
if (values[sys.UIKeys.width] <= 0 || values[sys.UIKeys.height] <= 0) {
this.startIndex = this.endIndex = -1;
return false;
}
let numElements = target.numElements;
let contentWidth = this.getStartPosition(numElements - 1) +
this.elementSizeTable[numElements - 1] + this.$paddingRight;
let minVisibleX = target.scrollH;
if (minVisibleX > contentWidth - this.$paddingRight) {
this.startIndex = -1;
this.endIndex = -1;
return false;
}
let maxVisibleX = target.scrollH + values[sys.UIKeys.width];
if (maxVisibleX < this.$paddingLeft) {
this.startIndex = -1;
this.endIndex = -1;
return false;
}
let oldStartIndex:number = this.startIndex;
let oldEndIndex:number = this.endIndex;
this.startIndex = this.findIndexAt(minVisibleX, 0, numElements - 1);
if (this.startIndex == -1)
this.startIndex = 0;
this.endIndex = this.findIndexAt(maxVisibleX, 0, numElements - 1);
if (this.endIndex == -1)
this.endIndex = numElements - 1;
return oldStartIndex != this.startIndex || oldEndIndex != this.endIndex;
}
}
} | the_stack |
import { VertexGeometry } from "./VertexGeometry";
import { GeometryTagError } from "../error/GeometryTagError";
import { Transform } from "../../../geo/Transform";
import { isSpherical } from "../../../geo/Geo";
/**
* @class PolygonGeometry
*
* @classdesc Represents a polygon geometry in the 2D basic image coordinate system.
* All polygons and holes provided to the constructor needs to be closed.
*
* @example
* ```js
* var basicPolygon = [[0.5, 0.3], [0.7, 0.3], [0.6, 0.5], [0.5, 0.3]];
* var polygonGeometry = new PolygonGeometry(basicPolygon);
* ```
*/
export class PolygonGeometry extends VertexGeometry {
private _polygon: number[][];
private _holes: number[][][];
/**
* Create a polygon geometry.
*
* @constructor
* @param {Array<Array<number>>} polygon - Array of polygon vertices. Must be closed.
* @param {Array<Array<Array<number>>>} [holes] - Array of arrays of hole vertices.
* Each array of holes vertices must be closed.
*
* @throws {GeometryTagError} Polygon coordinates must be valid basic coordinates.
*/
constructor(polygon: number[][], holes?: number[][][]) {
super();
let polygonLength: number = polygon.length;
if (polygonLength < 3) {
throw new GeometryTagError("A polygon must have three or more positions.");
}
if (polygon[0][0] !== polygon[polygonLength - 1][0] ||
polygon[0][1] !== polygon[polygonLength - 1][1]) {
throw new GeometryTagError("First and last positions must be equivalent.");
}
this._polygon = [];
for (let vertex of polygon) {
if (vertex[0] < 0 || vertex[0] > 1 ||
vertex[1] < 0 || vertex[1] > 1) {
throw new GeometryTagError("Basic coordinates of polygon must be on the interval [0, 1].");
}
this._polygon.push(vertex.slice());
}
this._holes = [];
if (holes == null) {
return;
}
for (let i: number = 0; i < holes.length; i++) {
let hole: number[][] = holes[i];
let holeLength: number = hole.length;
if (holeLength < 3) {
throw new GeometryTagError("A polygon hole must have three or more positions.");
}
if (hole[0][0] !== hole[holeLength - 1][0] ||
hole[0][1] !== hole[holeLength - 1][1]) {
throw new GeometryTagError("First and last positions of hole must be equivalent.");
}
this._holes.push([]);
for (let vertex of hole) {
if (vertex[0] < 0 || vertex[0] > 1 ||
vertex[1] < 0 || vertex[1] > 1) {
throw new GeometryTagError("Basic coordinates of hole must be on the interval [0, 1].");
}
this._holes[i].push(vertex.slice());
}
}
}
/**
* Get polygon property.
* @returns {Array<Array<number>>} Closed 2d polygon.
*/
public get polygon(): number[][] {
return this._polygon;
}
/**
* Get holes property.
* @returns {Array<Array<Array<number>>>} Holes of 2d polygon.
*/
public get holes(): number[][][] {
return this._holes;
}
/**
* Add a vertex to the polygon by appending it after the last vertex.
*
* @param {Array<number>} vertex - Vertex to add.
* @ignore
*/
public addVertex2d(vertex: number[]): void {
let clamped: number[] = [
Math.max(0, Math.min(1, vertex[0])),
Math.max(0, Math.min(1, vertex[1])),
];
this._polygon.splice(this._polygon.length - 1, 0, clamped);
this._notifyChanged$.next(this);
}
/**
* Get the coordinates of a vertex from the polygon representation of the geometry.
*
* @param {number} index - Vertex index.
* @returns {Array<number>} Array representing the 2D basic coordinates of the vertex.
* @ignore
*/
public getVertex2d(index: number): number[] {
return this._polygon[index].slice();
}
/**
* Remove a vertex from the polygon.
*
* @param {number} index - The index of the vertex to remove.
* @ignore
*/
public removeVertex2d(index: number): void {
if (index < 0 ||
index >= this._polygon.length ||
this._polygon.length < 4) {
throw new GeometryTagError("Index for removed vertex must be valid.");
}
if (index > 0 && index < this._polygon.length - 1) {
this._polygon.splice(index, 1);
} else {
this._polygon.splice(0, 1);
this._polygon.pop();
let closing: number[] = this._polygon[0].slice();
this._polygon.push(closing);
}
this._notifyChanged$.next(this);
}
/** @ignore */
public setVertex2d(index: number, value: number[], transform: Transform): void {
let changed: number[] = [
Math.max(0, Math.min(1, value[0])),
Math.max(0, Math.min(1, value[1])),
];
if (index === 0 || index === this._polygon.length - 1) {
this._polygon[0] = changed.slice();
this._polygon[this._polygon.length - 1] = changed.slice();
} else {
this._polygon[index] = changed.slice();
}
this._notifyChanged$.next(this);
}
/** @ignore */
public setCentroid2d(value: number[], transform: Transform): void {
let xs: number[] = this._polygon.map((point: number[]): number => { return point[0]; });
let ys: number[] = this._polygon.map((point: number[]): number => { return point[1]; });
let minX: number = Math.min.apply(Math, xs);
let maxX: number = Math.max.apply(Math, xs);
let minY: number = Math.min.apply(Math, ys);
let maxY: number = Math.max.apply(Math, ys);
let centroid: number[] = this.getCentroid2d();
let minTranslationX: number = -minX;
let maxTranslationX: number = 1 - maxX;
let minTranslationY: number = -minY;
let maxTranslationY: number = 1 - maxY;
let translationX: number = Math.max(minTranslationX, Math.min(maxTranslationX, value[0] - centroid[0]));
let translationY: number = Math.max(minTranslationY, Math.min(maxTranslationY, value[1] - centroid[1]));
for (let point of this._polygon) {
point[0] += translationX;
point[1] += translationY;
}
this._notifyChanged$.next(this);
}
/** @ignore */
public getPoints3d(transform: Transform): number[][] {
return this._getPoints3d(
this._subsample(this._polygon),
transform);
}
/** @ignore */
public getVertex3d(index: number, transform: Transform): number[] {
return transform.unprojectBasic(this._polygon[index], 200);
}
/** @ignore */
public getVertices2d(): number[][] {
return this._polygon.slice();
}
/** @ignore */
public getVertices3d(transform: Transform): number[][] {
return this._getPoints3d(this._polygon, transform);
}
/**
* Get a polygon representation of the 3D coordinates for the vertices of each hole
* of the geometry. Line segments between vertices will possibly be subsampled
* resulting in a larger number of points than the total number of vertices.
*
* @param {Transform} transform - The transform of the image related to the geometry.
* @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
* representing the vertices of each hole of the geometry.
* @ignore
*/
public getHolePoints3d(transform: Transform): number[][][] {
return this._holes
.map(
(hole2d: number[][]): number[][] => {
return this._getPoints3d(
this._subsample(hole2d),
transform);
});
}
/**
* Get a polygon representation of the 3D coordinates for the vertices of each hole
* of the geometry.
*
* @param {Transform} transform - The transform of the image related to the geometry.
* @returns {Array<Array<Array<number>>>} Array of hole polygons in 3D world coordinates
* representing the vertices of each hole of the geometry.
* @ignore
*/
public getHoleVertices3d(transform: Transform): number[][][] {
return this._holes
.map(
(hole2d: number[][]): number[][] => {
return this._getPoints3d(hole2d, transform);
});
}
/** @ignore */
public getCentroid2d(): number[] {
let polygon: number[][] = this._polygon;
let area: number = 0;
let centroidX: number = 0;
let centroidY: number = 0;
for (let i: number = 0; i < polygon.length - 1; i++) {
let xi: number = polygon[i][0];
let yi: number = polygon[i][1];
let xi1: number = polygon[i + 1][0];
let yi1: number = polygon[i + 1][1];
let a: number = xi * yi1 - xi1 * yi;
area += a;
centroidX += (xi + xi1) * a;
centroidY += (yi + yi1) * a;
}
area /= 2;
centroidX /= 6 * area;
centroidY /= 6 * area;
return [centroidX, centroidY];
}
/** @ignore */
public getCentroid3d(transform: Transform): number[] {
let centroid2d: number[] = this.getCentroid2d();
return transform.unprojectBasic(centroid2d, 200);
}
/** @ignore */
public get3dDomainTriangles3d(transform: Transform): number[] {
return this._triangulate(
this._project(this._polygon, transform),
this.getVertices3d(transform),
this._holes
.map(
(hole2d: number[][]): number[][] => {
return this._project(hole2d, transform);
}),
this.getHoleVertices3d(transform));
}
/** @ignore */
public getTriangles3d(transform: Transform): number[] {
if (isSpherical(transform.cameraType)) {
return this._triangulateSpherical(
this._polygon.slice(),
this.holes.slice(),
transform);
}
const points2d: number[][] = this._project(this._subsample(this._polygon), transform);
const points3d: number[][] = this.getPoints3d(transform);
const holes2d: number[][][] = this._holes
.map(
(hole: number[][]): number[][] => {
return this._project(this._subsample(hole), transform);
});
const holes3d: number[][][] = this.getHolePoints3d(transform);
return this._triangulate(
points2d,
points3d,
holes2d,
holes3d);
}
/** @ignore */
public getPoleOfInaccessibility2d(): number[] {
return this._getPoleOfInaccessibility2d(this._polygon.slice());
}
/** @ignore */
public getPoleOfInaccessibility3d(transform: Transform): number[] {
let pole2d: number[] = this._getPoleOfInaccessibility2d(this._polygon.slice());
return transform.unprojectBasic(pole2d, 200);
}
private _getPoints3d(points2d: number[][], transform: Transform): number[][] {
return points2d
.map(
(point: number[]) => {
return transform.unprojectBasic(point, 200);
});
}
} | the_stack |
import * as Tp from 'thingpedia';
import * as events from 'events';
import SpeechRecognizer from './speech_recognizer';
import SpeechSynthesizer from './speech_synthesizer';
import { MessageType } from '../dialogue-agent/protocol';
import type Conversation from '../dialogue-agent/conversation';
import type AudioController from '../dialogue-agent/audio/controller';
import { AudioPlayer, CustomPlayerSpec } from '../dialogue-agent/audio/interface';
import CustomError from '../utils/custom_error';
interface SpeechHandlerOptions {
nlUrl ?: string;
}
class LocalAudioPlayer implements AudioPlayer {
private _platform : Tp.BasePlatform;
private _handler : SpeechHandler
private _cap : Tp.Capabilities.AudioPlayerApi;
readonly conversationId : string;
private _player : Tp.Capabilities.Player|null;
constructor(handler : SpeechHandler, platform : Tp.BasePlatform, conversation : Conversation) {
this.conversationId = conversation.id;
this._handler = handler;
this._platform = platform;
this._cap = platform.getCapability('audio-player')!;
this._player = null;
}
async checkCustomPlayer(spec : CustomPlayerSpec) : Promise<boolean> {
return spec.type === 'url';
}
async prepare(spec ?: CustomPlayerSpec) : Promise<void> {
if (spec && spec.type !== 'url')
throw new Error(`unsupported`);
// wait until the agent finishes speaking to start playing audio
await this._handler.waitFinishSpeaking();
}
async resume() : Promise<void> {
throw new CustomError(`unsupported`, `Resuming is not supported`);
}
async stop() : Promise<void> {
if (this._player)
await this._player.stop();
this._player = null;
}
async pause() : Promise<void> {
// we don't have a way to pause, so we just stop
if (this._player)
await this._player.stop();
this._player = null;
}
async playURLs(urls : string[]) : Promise<void> {
await this.stop();
this._player = await this._cap.play(urls);
}
async setVolume(volume : number) : Promise<void> {
throw new Error('Method not implemented.');
}
async adjustVolume(delta : number) : Promise<void> {
throw new Error('Method not implemented.');
}
async setMute(mute : boolean) : Promise<void> {
throw new Error('Method not implemented.');
}
async setVoiceInput(input : boolean) {
const prefs = this._platform.getSharedPreferences();
prefs.set('enable-voice-input', input);
this._handler.setVoiceInput(input);
}
async setVoiceOutput(input : boolean) {
const prefs = this._platform.getSharedPreferences();
prefs.set('enable-voice-output', input);
this._handler.setVoiceOutput(input);
}
}
export default class SpeechHandler extends events.EventEmitter {
private _platform : Tp.BasePlatform;
private _prefs : Tp.Preferences;
private _conversation : Conversation;
private _pulse : Tp.Capabilities.SoundApi;
private _wakeWordDetector : Tp.Capabilities.WakeWordApi|null;
private _voiceDetector : Tp.Capabilities.VadApi|null;
private _systemLock : Tp.Capabilities.SystemLockApi|null;
private _recognizer : SpeechRecognizer;
private _tts : SpeechSynthesizer;
private _currentRequest : any;
private _started : boolean;
private _enableVoiceInput : boolean;
private _enableVoiceOutput : boolean;
private _stream : any|null = null;
private _audioController : AudioController;
private _queuedAudio : string[];
private _player : LocalAudioPlayer|null;
constructor(conversation : Conversation,
platform : Tp.BasePlatform,
options : SpeechHandlerOptions = {
nlUrl: 'https://almond-nl.stanford.edu'
}) {
super();
this._platform = platform;
this._prefs = platform.getSharedPreferences();
this._conversation = conversation;
this._audioController = conversation.engine.audio;
this._pulse = platform.getCapability('sound')!;
this._wakeWordDetector = platform.getCapability('wakeword-detector');
this._voiceDetector = platform.getCapability('voice-detector');
this._systemLock = platform.getCapability('system-lock');
if (this._wakeWordDetector) {
this._wakeWordDetector.on('wakeword', (wakeword : string, buffer : Buffer) => {
if (this._systemLock && this._systemLock.isActive) {
console.log('Ignored wakeword ' + wakeword + ' because the system is locked');
return;
}
console.log('Wakeword ' + wakeword + ' detected');
this._onDetected(buffer);
});
}
this._recognizer = new SpeechRecognizer({
locale: this._platform.locale,
nlUrl: options.nlUrl,
vad: this._voiceDetector
});
this._recognizer.on('error', (e) => {
this.emit('error', e);
});
this._tts = new SpeechSynthesizer(platform, options.nlUrl);
this._currentRequest = null;
this._queuedAudio = [];
this._started = true;
this._enableVoiceInput = this._prefs.get('enable-voice-input') as boolean ?? true;
this._enableVoiceOutput = this._prefs.get('enable-voice-output') as boolean ?? true;
this._prefs.on('changed', (key : string) => {
if (key === 'enable-voice-input')
this.setVoiceInput(this._prefs.get('enable-voice-input') as boolean ?? true);
else if (key === 'enable-voice-output')
this.setVoiceOutput(this._prefs.get('enable-voice-output') as boolean ?? true);
});
this._player = null;
if (this._platform.hasCapability('audio-player'))
this._player = new LocalAudioPlayer(this, platform, conversation);
}
setVoiceInput(enable : boolean) : void {
if (enable === this._enableVoiceInput)
return;
this._enableVoiceInput = enable;
if (this._started && enable)
this._startVoiceInput();
else
this._stopVoiceInput();
}
setVoiceOutput(enable : boolean) : void {
if (enable === this._enableVoiceOutput)
return;
this._enableVoiceOutput = enable;
if (!enable)
this._tts.clearQueue();
}
// called from conversation
async setHypothesis() {
// ignore, this is called from the conversation when it broadcasts the hypothesis
// to all listeners
}
async addDevice() {
// ignore
}
waitFinishSpeaking() {
return new Promise<void>((resolve, reject) => {
if (!this._tts.speaking) {
resolve();
return;
}
this._tts.once('done', () => resolve());
});
}
async setExpected(expect : string) : Promise<void> {
// flush any request to play audio
if (this._queuedAudio.length) {
const toPlay = this._queuedAudio;
this._queuedAudio = [];
if (!this._player)
return;
const player = this._player;
await this._audioController.requestSystemAudio({
async stop() {
await player.stop();
}
}, this._conversation.id);
await player.playURLs(toPlay);
}
}
async addMessage(message : any) : Promise<void> {
switch (message.type) {
case MessageType.COMMAND:
await this._tts.clearQueue();
break;
case MessageType.TEXT:
if (!this._enableVoiceOutput)
break;
await this._tts.say(message.text);
break;
case MessageType.SOUND_EFFECT: {
const soundEffects = this._platform.getCapability('sound-effects');
if (soundEffects) {
if (message.exclusive) {
// in exclusive mode, we queue the sound effect as if it was
// a regular audio URL
// this means we'll stop other audio and we will synchronize
// with audio messages
const url = soundEffects.getURL(message.name);
if (url)
this._queuedAudio.push(url);
else
console.log(`Ignored unknown sound effect ${message.name}`);
} else {
if (!this._enableVoiceOutput)
break;
this.waitFinishSpeaking().then(() => {
return soundEffects.play(message.name);
}).catch((e) => {
console.error(`Failed to play sound effect: ${e.message}`);
});
}
} else {
console.log(`Ignored sound effect ${message.name}: not supported on this platform`);
}
break;
}
case MessageType.AUDIO:
this._queuedAudio.push(message.url);
break;
// ignore all other message types
}
}
/**
* Programmatically trigger a wakeword.
*
* This can be used to emulate a wakeword with a push button.
*/
wakeword() : void {
this._onDetected(Buffer.from([]));
}
private _onDetected(buffer : Buffer, mustHaveWakeword = true) {
// if we already have a request active, ignore the wakeword, we're
// already streaming the sound to the server
if (this._currentRequest)
return;
this.emit('wakeword');
this._currentRequest = this._recognizer.request(this._stream, buffer);
this._currentRequest.on('hypothesis', (hypothesis : string) => {
this._conversation.setHypothesis(hypothesis);
});
this._currentRequest.on('done', (status : string, utterance : string) => {
this._currentRequest = null;
if (status === 'Success') {
console.log('Recognized as "' + utterance + '"');
if (mustHaveWakeword) {
const wakeWordMatch = /^(computer)[,.!]?/i.exec(utterance);
if (!wakeWordMatch) {
console.log('Ignored because wake-word is missing');
this.emit('no-match');
return;
}
// remove the prefix from the utterance so we don't confuse
// the model
utterance = utterance.substring(wakeWordMatch[0].length).trim();
}
// if there is nothing left, start listening again in case
// the user paused in-between the wakeword and the command
// in that case, we will not check for the wakeword and remove it
//if (!utterance) {
// this._onDetected(Buffer.from([]), false);
// return;
//}
this.emit('match');
this._conversation.setHypothesis('');
this._conversation.handleCommand(utterance);
} else if (status === 'NoMatch' || status === 'InitialSilenceTimeout') {
this.emit('no-match');
} else {
console.log('Recognition error: ' + status);
}
});
this._currentRequest.on('error', (error : Error) => {
this._currentRequest = null;
this._onError(error);
});
}
private _onError(error : Error) {
console.log('Error in speech recognition: ' + error.message);
this._tts.say("Sorry, I had an error understanding your speech: " + error.message);
}
start() : void {
this._conversation.addOutput(this, false);
if (this._player)
this._audioController.addPlayer(this._player);
this._started = true;
if (this._enableVoiceInput)
this._startVoiceInput();
}
private _startVoiceInput() {
this._stream = this._pulse.createRecordStream({
format: 'S16LE',
rate: 16000,
channels: 1,
stream: 'genie-voice-output',
properties: {
'media.role': 'voice-assistant',
'filter.want': 'echo-cancel',
}
});
this._stream!.on('state', (state : string) => {
console.log('Record stream is now ' + state);
if (state === 'ready')
this.emit('ready');
});
if (this._voiceDetector)
this._voiceDetector.setup(16000, 3);
if (this._wakeWordDetector)
this._stream!.pipe(this._wakeWordDetector);
}
destroy() {
if (this._player) {
this._player.stop().catch((e) => {
console.error(`Failed to stop playback: ${e.message}`);
});
this._audioController.removePlayer(this._player);
}
this._conversation.removeOutput(this);
this._started = false;
this._stopVoiceInput();
this._tts.clearQueue();
}
private _stopVoiceInput() {
if (!this._stream)
return;
this._stream.unpipe();
this._stream.end();
this._stream = null;
this._recognizer.close();
}
} | the_stack |
/* tslint:disable */
// import * as import0 from '@angular/core/src/linker/ng_module_factory';
// import * as import1 from '../../app';
// import * as import2 from '@angular/common/src/common_module';
// import * as import3 from '@angular/core/src/application_module';
// import * as import4 from '@angular/platform-browser/src/browser';
// import * as import5 from '@angular/forms/src/directives';
// import * as import6 from '@angular/forms/src/form_providers';
// import * as import7 from '@angular/common/src/localization';
// import * as import8 from '@angular/core/src/application_init';
// import * as import9 from '@angular/core/src/testability/testability';
// import * as import10 from '@angular/core/src/application_ref';
// import * as import11 from '@angular/core/src/linker/compiler';
// import * as import12 from '@angular/platform-browser/src/dom/events/hammer_gestures';
// import * as import13 from '@angular/platform-browser/src/dom/events/event_manager';
// import * as import14 from '@angular/platform-browser/src/dom/shared_styles_host';
// import * as import15 from '@angular/platform-browser/src/dom/dom_renderer';
// import * as import16 from '@angular/platform-browser/src/security/dom_sanitization_service';
// import * as import17 from '@angular/core/src/linker/view_utils';
// import * as import18 from '@angular/forms/src/form_builder';
// import * as import19 from '@angular/forms/src/directives/radio_control_value_accessor';
// import * as import20 from '@angular/core/src/di/injector';
// import * as import21 from '@angular/core/src/application_tokens';
// import * as import22 from '@angular/platform-browser/src/dom/events/dom_events';
// import * as import23 from '@angular/platform-browser/src/dom/events/key_events';
// import * as import24 from '@angular/core/src/zone/ng_zone';
// import * as import25 from '@angular/platform-browser/src/dom/debug/ng_probe';
// import * as import26 from '@angular/core/src/console';
// import * as import27 from '@angular/core/src/i18n/tokens';
// import * as import28 from '@angular/core/src/error_handler';
// import * as import29 from '@angular/platform-browser/src/dom/dom_tokens';
// import * as import30 from '@angular/platform-browser/src/dom/animation_driver';
// import * as import31 from '@angular/core/src/render/api';
// import * as import32 from '@angular/core/src/security';
// import * as import33 from '@angular/core/src/change_detection/differs/iterable_differs';
// import * as import34 from '@angular/core/src/change_detection/differs/keyvalue_differs';
// import * as import35 from '@angular/core/src/i18n/tokens';
// import * as import36 from '@angular/core/src/render/api';
// import * as import37 from '@angular/core/src/linker/view';
// import * as import38 from '@angular/core/src/linker/element';
// import * as import39 from '@angular/core/src/linker/view_utils';
// import * as import40 from '@angular/core/src/linker/view_type';
// import * as import41 from '@angular/core/src/change_detection/change_detection';
// import * as import42 from '@angular/core/src/metadata/view';
// import * as import43 from '@angular/core/src/linker/component_factory';
// import * as import44 from '@angular/forms/src/directives/reactive_directives/form_group_directive';
// import * as import45 from '@angular/forms/src/directives/ng_control_status';
// import * as import46 from '@angular/forms/src/directives/default_value_accessor';
// import * as import47 from '@angular/forms/src/directives/reactive_directives/form_control_name';
// import * as import48 from '@angular/core/src/linker/element_ref';
// import * as import49 from '@angular/forms/src/directives/control_value_accessor';
// import * as import50 from '@angular/forms/src/directives/ng_control';
// import * as import51 from '@angular/forms/src/directives/control_container';
//stubbed out imports
namespace import44 {
export class FormGroupDirective {
constructor(any){}
}
}
namespace import45 {
export class NgControlStatus {
constructor(any){}
}
export class NgControlStatusGroup {
constructor(any){}
}
}
namespace import46 {
export class DefaultValueAccessor {
constructor(any){}
}
}
namespace import47 {
export class FormControlName {
constructor(any){}
}
}
namespace import48 {
export class FormControlName {
constructor(any){}
}
}
//HERE BE DRAGONS
//Using a value here - 65+ seconds to typecheck
namespace import49 {
//real code uses an opaque token, using new String() to simulate.
//export var NG_VALUE_ACCESSOR = new OpaqueToken('ngValueAccessor')
export var NG_VALUE_ACCESSOR = new String('foo')
}
//using a class - < 1 sec typecheck
// namespace import49 {
// export class NG_VALUE_ACCESSOR {
// constructor(any){}
// }
// }
//END DRAGONS
namespace import50 {
export class NgControl {
constructor(any){}
}
}
namespace import51 {
export class ControlContainer {
constructor(any){}
}
}
class _View_AppComponent0 {
_text_0:any;
_el_1:any;
_FormGroupDirective_1_3:import44.FormGroupDirective;
_ControlContainer_1_4:any;
_NgControlStatusGroup_1_5:import45.NgControlStatusGroup;
_text_2:any;
_el_3:any;
_DefaultValueAccessor_3_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_3_4:any[];
_FormControlName_3_5:import47.FormControlName;
_NgControl_3_6:any;
_NgControlStatus_3_7:import45.NgControlStatus;
_el_4:any;
_text_5:any;
_el_6:any;
_DefaultValueAccessor_6_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_6_4:any[];
_FormControlName_6_5:import47.FormControlName;
_NgControl_6_6:any;
_NgControlStatus_6_7:import45.NgControlStatus;
_el_7:any;
_text_8:any;
_el_9:any;
_DefaultValueAccessor_9_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_9_4:any[];
_FormControlName_9_5:import47.FormControlName;
_NgControl_9_6:any;
_NgControlStatus_9_7:import45.NgControlStatus;
_el_10:any;
_text_11:any;
_el_12:any;
_DefaultValueAccessor_12_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_12_4:any[];
_FormControlName_12_5:import47.FormControlName;
_NgControl_12_6:any;
_NgControlStatus_12_7:import45.NgControlStatus;
_el_13:any;
_text_14:any;
_el_15:any;
_DefaultValueAccessor_15_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_15_4:any[];
_FormControlName_15_5:import47.FormControlName;
_NgControl_15_6:any;
_NgControlStatus_15_7:import45.NgControlStatus;
_el_16:any;
_text_17:any;
_el_18:any;
_DefaultValueAccessor_18_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_18_4:any[];
_FormControlName_18_5:import47.FormControlName;
_NgControl_18_6:any;
_NgControlStatus_18_7:import45.NgControlStatus;
_el_19:any;
_text_20:any;
_el_21:any;
_DefaultValueAccessor_21_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_21_4:any[];
_FormControlName_21_5:import47.FormControlName;
_NgControl_21_6:any;
_NgControlStatus_21_7:import45.NgControlStatus;
_el_22:any;
_text_23:any;
_el_24:any;
_DefaultValueAccessor_24_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_24_4:any[];
_FormControlName_24_5:import47.FormControlName;
_NgControl_24_6:any;
_NgControlStatus_24_7:import45.NgControlStatus;
_el_25:any;
_text_26:any;
_el_27:any;
_DefaultValueAccessor_27_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_27_4:any[];
_FormControlName_27_5:import47.FormControlName;
_NgControl_27_6:any;
_NgControlStatus_27_7:import45.NgControlStatus;
_el_28:any;
_text_29:any;
_el_30:any;
_DefaultValueAccessor_30_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_30_4:any[];
_FormControlName_30_5:import47.FormControlName;
_NgControl_30_6:any;
_NgControlStatus_30_7:import45.NgControlStatus;
_el_31:any;
_text_32:any;
_el_33:any;
_DefaultValueAccessor_33_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_33_4:any[];
_FormControlName_33_5:import47.FormControlName;
_NgControl_33_6:any;
_NgControlStatus_33_7:import45.NgControlStatus;
_el_34:any;
_text_35:any;
_el_36:any;
_DefaultValueAccessor_36_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_36_4:any[];
_FormControlName_36_5:import47.FormControlName;
_NgControl_36_6:any;
_NgControlStatus_36_7:import45.NgControlStatus;
_el_37:any;
_text_38:any;
_el_39:any;
_DefaultValueAccessor_39_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_39_4:any[];
_FormControlName_39_5:import47.FormControlName;
_NgControl_39_6:any;
_NgControlStatus_39_7:import45.NgControlStatus;
_el_40:any;
_text_41:any;
_el_42:any;
_DefaultValueAccessor_42_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_42_4:any[];
_FormControlName_42_5:import47.FormControlName;
_NgControl_42_6:any;
_NgControlStatus_42_7:import45.NgControlStatus;
_el_43:any;
_text_44:any;
_el_45:any;
_DefaultValueAccessor_45_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_45_4:any[];
_FormControlName_45_5:import47.FormControlName;
_NgControl_45_6:any;
_NgControlStatus_45_7:import45.NgControlStatus;
_el_46:any;
_text_47:any;
_el_48:any;
_DefaultValueAccessor_48_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_48_4:any[];
_FormControlName_48_5:import47.FormControlName;
_NgControl_48_6:any;
_NgControlStatus_48_7:import45.NgControlStatus;
_el_49:any;
_text_50:any;
_el_51:any;
_DefaultValueAccessor_51_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_51_4:any[];
_FormControlName_51_5:import47.FormControlName;
_NgControl_51_6:any;
_NgControlStatus_51_7:import45.NgControlStatus;
_el_52:any;
_text_53:any;
_el_54:any;
_DefaultValueAccessor_54_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_54_4:any[];
_FormControlName_54_5:import47.FormControlName;
_NgControl_54_6:any;
_NgControlStatus_54_7:import45.NgControlStatus;
_el_55:any;
_text_56:any;
_el_57:any;
_DefaultValueAccessor_57_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_57_4:any[];
_FormControlName_57_5:import47.FormControlName;
_NgControl_57_6:any;
_NgControlStatus_57_7:import45.NgControlStatus;
_el_58:any;
_text_59:any;
_el_60:any;
_DefaultValueAccessor_60_3:import46.DefaultValueAccessor;
_NG_VALUE_ACCESSOR_60_4:any[];
_FormControlName_60_5:import47.FormControlName;
_NgControl_60_6:any;
_NgControlStatus_60_7:import45.NgControlStatus;
_el_61:any;
_text_62:any;
_text_63:any;
/*private*/ _expr_2:any;
/*private*/ _expr_3:any;
/*private*/ _expr_4:any;
/*private*/ _expr_5:any;
/*private*/ _expr_6:any;
/*private*/ _expr_7:any;
/*private*/ _expr_8:any;
/*private*/ _expr_11:any;
/*private*/ _expr_12:any;
/*private*/ _expr_13:any;
/*private*/ _expr_14:any;
/*private*/ _expr_15:any;
/*private*/ _expr_16:any;
/*private*/ _expr_17:any;
/*private*/ _expr_20:any;
/*private*/ _expr_21:any;
/*private*/ _expr_22:any;
/*private*/ _expr_23:any;
/*private*/ _expr_24:any;
/*private*/ _expr_25:any;
/*private*/ _expr_26:any;
/*private*/ _expr_29:any;
/*private*/ _expr_30:any;
/*private*/ _expr_31:any;
/*private*/ _expr_32:any;
/*private*/ _expr_33:any;
/*private*/ _expr_34:any;
/*private*/ _expr_35:any;
/*private*/ _expr_38:any;
/*private*/ _expr_39:any;
/*private*/ _expr_40:any;
/*private*/ _expr_41:any;
/*private*/ _expr_42:any;
/*private*/ _expr_43:any;
/*private*/ _expr_44:any;
/*private*/ _expr_47:any;
/*private*/ _expr_48:any;
/*private*/ _expr_49:any;
/*private*/ _expr_50:any;
/*private*/ _expr_51:any;
/*private*/ _expr_52:any;
/*private*/ _expr_53:any;
/*private*/ _expr_56:any;
/*private*/ _expr_57:any;
/*private*/ _expr_58:any;
/*private*/ _expr_59:any;
/*private*/ _expr_60:any;
/*private*/ _expr_61:any;
/*private*/ _expr_62:any;
/*private*/ _expr_65:any;
/*private*/ _expr_66:any;
/*private*/ _expr_67:any;
/*private*/ _expr_68:any;
/*private*/ _expr_69:any;
/*private*/ _expr_70:any;
/*private*/ _expr_71:any;
/*private*/ _expr_74:any;
/*private*/ _expr_75:any;
/*private*/ _expr_76:any;
/*private*/ _expr_77:any;
/*private*/ _expr_78:any;
/*private*/ _expr_79:any;
/*private*/ _expr_80:any;
/*private*/ _expr_83:any;
/*private*/ _expr_84:any;
/*private*/ _expr_85:any;
/*private*/ _expr_86:any;
/*private*/ _expr_87:any;
/*private*/ _expr_88:any;
/*private*/ _expr_89:any;
/*private*/ _expr_92:any;
/*private*/ _expr_93:any;
/*private*/ _expr_94:any;
/*private*/ _expr_95:any;
/*private*/ _expr_96:any;
/*private*/ _expr_97:any;
/*private*/ _expr_98:any;
/*private*/ _expr_101:any;
/*private*/ _expr_102:any;
/*private*/ _expr_103:any;
/*private*/ _expr_104:any;
/*private*/ _expr_105:any;
/*private*/ _expr_106:any;
/*private*/ _expr_107:any;
/*private*/ _expr_110:any;
/*private*/ _expr_111:any;
/*private*/ _expr_112:any;
/*private*/ _expr_113:any;
/*private*/ _expr_114:any;
/*private*/ _expr_115:any;
/*private*/ _expr_116:any;
/*private*/ _expr_119:any;
/*private*/ _expr_120:any;
/*private*/ _expr_121:any;
/*private*/ _expr_122:any;
/*private*/ _expr_123:any;
/*private*/ _expr_124:any;
/*private*/ _expr_125:any;
/*private*/ _expr_128:any;
/*private*/ _expr_129:any;
/*private*/ _expr_130:any;
/*private*/ _expr_131:any;
/*private*/ _expr_132:any;
/*private*/ _expr_133:any;
/*private*/ _expr_134:any;
/*private*/ _expr_137:any;
/*private*/ _expr_138:any;
/*private*/ _expr_139:any;
/*private*/ _expr_140:any;
/*private*/ _expr_141:any;
/*private*/ _expr_142:any;
/*private*/ _expr_143:any;
/*private*/ _expr_146:any;
/*private*/ _expr_147:any;
/*private*/ _expr_148:any;
/*private*/ _expr_149:any;
/*private*/ _expr_150:any;
/*private*/ _expr_151:any;
/*private*/ _expr_152:any;
/*private*/ _expr_155:any;
/*private*/ _expr_156:any;
/*private*/ _expr_157:any;
/*private*/ _expr_158:any;
/*private*/ _expr_159:any;
/*private*/ _expr_160:any;
/*private*/ _expr_161:any;
/*private*/ _expr_164:any;
/*private*/ _expr_165:any;
/*private*/ _expr_166:any;
/*private*/ _expr_167:any;
/*private*/ _expr_168:any;
/*private*/ _expr_169:any;
/*private*/ _expr_170:any;
/*private*/ _expr_173:any;
/*private*/ _expr_174:any;
/*private*/ _expr_175:any;
/*private*/ _expr_176:any;
/*private*/ _expr_177:any;
/*private*/ _expr_178:any;
/*private*/ _expr_179:any;
/*private*/ _expr_182:any;
/*private*/ _expr_183:any;
/*private*/ _expr_184:any;
/*private*/ _expr_185:any;
/*private*/ _expr_186:any;
/*private*/ _expr_187:any;
/*private*/ _expr_188:any;
constructor(viewUtils:any,parentInjector:any,declarationEl:any) {
}
injectorGetInternal(token:any,requestNodeIndex:number,notFoundResult:any):any {
if (((token === import46.DefaultValueAccessor) && (3 === requestNodeIndex))) { return this._DefaultValueAccessor_3_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (3 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_3_4; }
if (((token === import47.FormControlName) && (3 === requestNodeIndex))) { return this._FormControlName_3_5; }
if (((token === import50.NgControl) && (3 === requestNodeIndex))) { return this._NgControl_3_6; }
if (((token === import45.NgControlStatus) && (3 === requestNodeIndex))) { return this._NgControlStatus_3_7; }
if (((token === import46.DefaultValueAccessor) && (6 === requestNodeIndex))) { return this._DefaultValueAccessor_6_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (6 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_6_4; }
if (((token === import47.FormControlName) && (6 === requestNodeIndex))) { return this._FormControlName_6_5; }
if (((token === import50.NgControl) && (6 === requestNodeIndex))) { return this._NgControl_6_6; }
if (((token === import45.NgControlStatus) && (6 === requestNodeIndex))) { return this._NgControlStatus_6_7; }
if (((token === import46.DefaultValueAccessor) && (9 === requestNodeIndex))) { return this._DefaultValueAccessor_9_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (9 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_9_4; }
if (((token === import47.FormControlName) && (9 === requestNodeIndex))) { return this._FormControlName_9_5; }
if (((token === import50.NgControl) && (9 === requestNodeIndex))) { return this._NgControl_9_6; }
if (((token === import45.NgControlStatus) && (9 === requestNodeIndex))) { return this._NgControlStatus_9_7; }
if (((token === import46.DefaultValueAccessor) && (12 === requestNodeIndex))) { return this._DefaultValueAccessor_12_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (12 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_12_4; }
if (((token === import47.FormControlName) && (12 === requestNodeIndex))) { return this._FormControlName_12_5; }
if (((token === import50.NgControl) && (12 === requestNodeIndex))) { return this._NgControl_12_6; }
if (((token === import45.NgControlStatus) && (12 === requestNodeIndex))) { return this._NgControlStatus_12_7; }
if (((token === import46.DefaultValueAccessor) && (15 === requestNodeIndex))) { return this._DefaultValueAccessor_15_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (15 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_15_4; }
if (((token === import47.FormControlName) && (15 === requestNodeIndex))) { return this._FormControlName_15_5; }
if (((token === import50.NgControl) && (15 === requestNodeIndex))) { return this._NgControl_15_6; }
if (((token === import45.NgControlStatus) && (15 === requestNodeIndex))) { return this._NgControlStatus_15_7; }
if (((token === import46.DefaultValueAccessor) && (18 === requestNodeIndex))) { return this._DefaultValueAccessor_18_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (18 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_18_4; }
if (((token === import47.FormControlName) && (18 === requestNodeIndex))) { return this._FormControlName_18_5; }
if (((token === import50.NgControl) && (18 === requestNodeIndex))) { return this._NgControl_18_6; }
if (((token === import45.NgControlStatus) && (18 === requestNodeIndex))) { return this._NgControlStatus_18_7; }
if (((token === import46.DefaultValueAccessor) && (21 === requestNodeIndex))) { return this._DefaultValueAccessor_21_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (21 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_21_4; }
if (((token === import47.FormControlName) && (21 === requestNodeIndex))) { return this._FormControlName_21_5; }
if (((token === import50.NgControl) && (21 === requestNodeIndex))) { return this._NgControl_21_6; }
if (((token === import45.NgControlStatus) && (21 === requestNodeIndex))) { return this._NgControlStatus_21_7; }
if (((token === import46.DefaultValueAccessor) && (24 === requestNodeIndex))) { return this._DefaultValueAccessor_24_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (24 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_24_4; }
if (((token === import47.FormControlName) && (24 === requestNodeIndex))) { return this._FormControlName_24_5; }
if (((token === import50.NgControl) && (24 === requestNodeIndex))) { return this._NgControl_24_6; }
if (((token === import45.NgControlStatus) && (24 === requestNodeIndex))) { return this._NgControlStatus_24_7; }
if (((token === import46.DefaultValueAccessor) && (27 === requestNodeIndex))) { return this._DefaultValueAccessor_27_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (27 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_27_4; }
if (((token === import47.FormControlName) && (27 === requestNodeIndex))) { return this._FormControlName_27_5; }
if (((token === import50.NgControl) && (27 === requestNodeIndex))) { return this._NgControl_27_6; }
if (((token === import45.NgControlStatus) && (27 === requestNodeIndex))) { return this._NgControlStatus_27_7; }
if (((token === import46.DefaultValueAccessor) && (30 === requestNodeIndex))) { return this._DefaultValueAccessor_30_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (30 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_30_4; }
if (((token === import47.FormControlName) && (30 === requestNodeIndex))) { return this._FormControlName_30_5; }
if (((token === import50.NgControl) && (30 === requestNodeIndex))) { return this._NgControl_30_6; }
if (((token === import45.NgControlStatus) && (30 === requestNodeIndex))) { return this._NgControlStatus_30_7; }
if (((token === import46.DefaultValueAccessor) && (33 === requestNodeIndex))) { return this._DefaultValueAccessor_33_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (33 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_33_4; }
if (((token === import47.FormControlName) && (33 === requestNodeIndex))) { return this._FormControlName_33_5; }
if (((token === import50.NgControl) && (33 === requestNodeIndex))) { return this._NgControl_33_6; }
if (((token === import45.NgControlStatus) && (33 === requestNodeIndex))) { return this._NgControlStatus_33_7; }
if (((token === import46.DefaultValueAccessor) && (36 === requestNodeIndex))) { return this._DefaultValueAccessor_36_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (36 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_36_4; }
if (((token === import47.FormControlName) && (36 === requestNodeIndex))) { return this._FormControlName_36_5; }
if (((token === import50.NgControl) && (36 === requestNodeIndex))) { return this._NgControl_36_6; }
if (((token === import45.NgControlStatus) && (36 === requestNodeIndex))) { return this._NgControlStatus_36_7; }
if (((token === import46.DefaultValueAccessor) && (39 === requestNodeIndex))) { return this._DefaultValueAccessor_39_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (39 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_39_4; }
if (((token === import47.FormControlName) && (39 === requestNodeIndex))) { return this._FormControlName_39_5; }
if (((token === import50.NgControl) && (39 === requestNodeIndex))) { return this._NgControl_39_6; }
if (((token === import45.NgControlStatus) && (39 === requestNodeIndex))) { return this._NgControlStatus_39_7; }
if (((token === import46.DefaultValueAccessor) && (42 === requestNodeIndex))) { return this._DefaultValueAccessor_42_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (42 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_42_4; }
if (((token === import47.FormControlName) && (42 === requestNodeIndex))) { return this._FormControlName_42_5; }
if (((token === import50.NgControl) && (42 === requestNodeIndex))) { return this._NgControl_42_6; }
if (((token === import45.NgControlStatus) && (42 === requestNodeIndex))) { return this._NgControlStatus_42_7; }
if (((token === import46.DefaultValueAccessor) && (45 === requestNodeIndex))) { return this._DefaultValueAccessor_45_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (45 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_45_4; }
if (((token === import47.FormControlName) && (45 === requestNodeIndex))) { return this._FormControlName_45_5; }
if (((token === import50.NgControl) && (45 === requestNodeIndex))) { return this._NgControl_45_6; }
if (((token === import45.NgControlStatus) && (45 === requestNodeIndex))) { return this._NgControlStatus_45_7; }
if (((token === import46.DefaultValueAccessor) && (48 === requestNodeIndex))) { return this._DefaultValueAccessor_48_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (48 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_48_4; }
if (((token === import47.FormControlName) && (48 === requestNodeIndex))) { return this._FormControlName_48_5; }
if (((token === import50.NgControl) && (48 === requestNodeIndex))) { return this._NgControl_48_6; }
if (((token === import45.NgControlStatus) && (48 === requestNodeIndex))) { return this._NgControlStatus_48_7; }
if (((token === import46.DefaultValueAccessor) && (51 === requestNodeIndex))) { return this._DefaultValueAccessor_51_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (51 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_51_4; }
if (((token === import47.FormControlName) && (51 === requestNodeIndex))) { return this._FormControlName_51_5; }
if (((token === import50.NgControl) && (51 === requestNodeIndex))) { return this._NgControl_51_6; }
if (((token === import45.NgControlStatus) && (51 === requestNodeIndex))) { return this._NgControlStatus_51_7; }
if (((token === import46.DefaultValueAccessor) && (54 === requestNodeIndex))) { return this._DefaultValueAccessor_54_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (54 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_54_4; }
if (((token === import47.FormControlName) && (54 === requestNodeIndex))) { return this._FormControlName_54_5; }
if (((token === import50.NgControl) && (54 === requestNodeIndex))) { return this._NgControl_54_6; }
if (((token === import45.NgControlStatus) && (54 === requestNodeIndex))) { return this._NgControlStatus_54_7; }
if (((token === import46.DefaultValueAccessor) && (57 === requestNodeIndex))) { return this._DefaultValueAccessor_57_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (57 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_57_4; }
if (((token === import47.FormControlName) && (57 === requestNodeIndex))) { return this._FormControlName_57_5; }
if (((token === import50.NgControl) && (57 === requestNodeIndex))) { return this._NgControl_57_6; }
if (((token === import45.NgControlStatus) && (57 === requestNodeIndex))) { return this._NgControlStatus_57_7; }
if (((token === import46.DefaultValueAccessor) && (60 === requestNodeIndex))) { return this._DefaultValueAccessor_60_3; }
if (((token === import49.NG_VALUE_ACCESSOR) && (60 === requestNodeIndex))) { return this._NG_VALUE_ACCESSOR_60_4; }
if (((token === import47.FormControlName) && (60 === requestNodeIndex))) { return this._FormControlName_60_5; }
if (((token === import50.NgControl) && (60 === requestNodeIndex))) { return this._NgControl_60_6; }
if (((token === import45.NgControlStatus) && (60 === requestNodeIndex))) { return this._NgControlStatus_60_7; }
if (((token === import44.FormGroupDirective) && ((1 <= requestNodeIndex) && (requestNodeIndex <= 62)))) { return this._FormGroupDirective_1_3; }
if (((token === import51.ControlContainer) && ((1 <= requestNodeIndex) && (requestNodeIndex <= 62)))) { return this._ControlContainer_1_4; }
if (((token === import45.NgControlStatusGroup) && ((1 <= requestNodeIndex) && (requestNodeIndex <= 62)))) { return this._NgControlStatusGroup_1_5; }
return notFoundResult;
}
}
export function viewFactory_AppComponent0(viewUtils:any,parentInjector:any,declarationEl:any):any {
return new _View_AppComponent0(viewUtils,parentInjector,declarationEl);
} | the_stack |
import 'mocha'
import assert = require('assert')
import {
prefix as testPrefix,
strXF,
numToBuf,
bufToNum,
withEachDb,
} from './util'
import {MutationType, tuple, TupleItem, encoders, Watch, keySelector} from '../lib'
process.on('unhandledRejection', err => { throw err })
// Unfortunately assert.rejects doesn't work properly in node 8. For now we'll use a shim.
const assertRejects = async (p: Promise<any>) => {
try {
await p
throw Error('Promise resolved instead of erroring')
} catch (e) {}
}
const codeBuf = (code: number) => {
const b = Buffer.alloc(2)
b.writeUInt16BE(code, 0)
return b
}
const bakeVersionstamp = (vs: Buffer, code: number): TupleItem => ({
type: 'versionstamp', value: Buffer.concat([vs, codeBuf(code)])
})
withEachDb(db => describe('key value functionality', () => {
it('reads its writes inside a txn', async () => {
await db.doTransaction(async tn => {
const val = Buffer.from('hi there')
tn.set('xxx', val)
const result = await tn.get('xxx')
assert.deepStrictEqual(result, val)
})
})
it.skip("returns undefined when keys don't exist in get() and getKey", async () => {
await db.doTn(async tn => {
console.log(await tn.getKey('doesnotexist'))
// assert.strictEqual(await tn.get('doesnotexist'), undefined)
assert.strictEqual(await tn.getKey('doesnotexist'), undefined)
})
// assert.strictEqual(await db.get('doesnotexist'), undefined)
// assert.strictEqual(await db.getKey('doesnotexist'), undefined)
})
it('reads its writes in separate transactions', async () => {
const val = Buffer.from('hi there')
await db.doTransaction(async tn => {
tn.set('xxx', val)
})
await db.doTransaction(async tn => {
const result = await tn.get('xxx')
assert.deepStrictEqual(result, val)
})
})
it('lets you read and write via the database directly', async () => {
const val = Buffer.from('hi there')
await db.set('xxx', val)
const result = await db.get('xxx')
assert.deepStrictEqual(result, val)
})
it('returns the user value from db.doTransaction', async () => {
const val = {}
const result = await db.doTransaction(async tn => val)
assert.strictEqual(val, result)
})
it.skip('lets you cancel a txn', async () => {
// So right now when you cancel a transaction db.doTransaction throws with
// a transaction_cancelled error. I'm not sure if this API is what we want?
await db.doTransaction(async tn => {
tn.rawCancel()
})
})
it('obeys transaction options', async function() {
// We can't test all the options, but we can test at least one.
await db.doTransaction(async tn => {
tn.set('x', 'hi there')
assert.equal(await tn.get('x'), null)
}, {read_your_writes_disable: true})
})
it('retries conflicts', async function() {
// Transactions do exponential backoff when they conflict, so the time
// this test takes to run is super variable based on how unlucky we get
// with concurrency.
this.slow(3000)
this.timeout(10000)
const concurrentWrites = 30
const key = 'num'
await db.set(key, numToBuf(0))
let txnAttempts = 0
await Promise.all(new Array(concurrentWrites).fill(0).map((_, i) => (
db.doTransaction(async tn => {
const val = bufToNum((await tn.get(key)) as Buffer)
tn.set(key, numToBuf(val + 1))
txnAttempts++
})
)))
const result = bufToNum((await db.get(key)) as Buffer)
assert.strictEqual(result, concurrentWrites)
// This doesn't necessarily mean there's an error, but if there weren't
// more attempts than there were increments, the database is running
// serially and this test is doing nothing.
assert(txnAttempts > concurrentWrites)
})
describe('getKey', () => {
it('returns the exact key requested', async () => {
await db.set('x', 'y')
assert.strictEqual((await db.getKey('x'))?.toString(), 'x')
})
it('returns undefined if there is no key that matches', async () => {
assert.strictEqual(await db.getKey('doesnotexist'), undefined)
})
it('returns the key that matches if a key selector is passed', async () => {
await db.set('a', 'y')
await db.set('b', 'y')
assert.strictEqual((await db.getKey(keySelector.firstGreaterThan('a')))?.toString(), 'b')
})
it('returns undefined if the key selector matches outside of the subspace range', async () => {
await db.at('b').set('key', 'val')
const _db = db.at('a')
assert.strictEqual(await _db.getKey(keySelector('', true, 0)), undefined)
})
})
describe('version stamps', () => {
it('handles setVersionstampSuffixedKey correctly', async () => {
const keyPrefix = Buffer.from('hi there')
const keySuffix = Buffer.from('xxyy')
// console.log('suffix', keySuffix)
await db.setVersionstampSuffixedKey(keyPrefix, Buffer.from('yo yo'), keySuffix)
const result = await db.getRangeAllStartsWith(keyPrefix)
// console.log('r', result)
assert.strictEqual(result.length, 1)
const [keyResult, valResult] = result[0]
// console.log('val', keyResult)
// keyResult should be (keyPrefix) (10 bytes of stamp) (2 byte user suffix) (keySuffix).
assert.strictEqual(keyResult.length, keyPrefix.length + 10 + keySuffix.length)
const actualPrefix = keyResult.slice(0, keyPrefix.length)
const actualStamp = keyResult.slice(keyPrefix.length, keyPrefix.length + 10)
const actualSuffix = keyResult.slice(keyPrefix.length + 10)
assert.deepStrictEqual(actualPrefix, keyPrefix)
assert.deepStrictEqual(actualSuffix, keySuffix)
// console.log('stamp', actualStamp)
assert.strictEqual(valResult.toString(), 'yo yo')
})
it('handles setVersionstampedValue', async () => {
const db_ = db.withValueEncoding(strXF)
await db_.setVersionstampPrefixedValue('hi there', 'yooo')
const result = await db_.getVersionstampPrefixedValue('hi there')
assert(result != null)
const {stamp, value} = result!
assert.strictEqual(stamp.length, 10) // Opaque.
assert.strictEqual(value, 'yooo')
})
it('roundtrips a tuple key', async () => {
const db_ = db.withKeyEncoding(encoders.tuple)
await db_.set([1,2,3], 'hi there')
const result = await db_.get([1,2,3])
assert.strictEqual(result!.toString('utf8'), 'hi there')
})
it('commits a tuple with unbound key versionstamps and bakes the vs and code', async () => {
const db_ = db.withKeyEncoding(encoders.tuple).withValueEncoding(encoders.string)
const key1: TupleItem[] = [1,2,3, tuple.unboundVersionstamp()] // should end up with code 0
const key2: TupleItem[] = [1,2,3, tuple.unboundVersionstamp()] // code 1
const key3: TupleItem[] = [1,2,3, tuple.unboundVersionstamp(321)] // code 321
const actualStamp = await (await db_.doTn(async tn => {
tn.setVersionstampedKey(key1, '1')
tn.setVersionstampedKey(key2, '2')
tn.setVersionstampedKey(key3, '3')
return tn.getVersionstamp()
})).promise
// await db_.setVersionstampedKey(key1, 'hi there')
// The versionstamp should have been baked into the object
assert.deepStrictEqual(key1[3], bakeVersionstamp(actualStamp, 0))
assert.deepStrictEqual(key2[3], bakeVersionstamp(actualStamp, 1))
assert.deepStrictEqual(key3[3], bakeVersionstamp(actualStamp, 321))
// const results = await db.getRangeAllStartsWith(tuple.packBound([1,2,3]))
// assert.strictEqual(results.length, 1)
const results = await db_.getRangeAllStartsWith([1,2,3])
assert.deepStrictEqual(results, [
[key1, '1'],
[key2, '2'],
[key3, '3'],
])
})
it('does not bake the vs in setVersionstampedKey(bakeAfterCommit=false)', async () => {
const db_ = db.withKeyEncoding(encoders.tuple)
const key: TupleItem[] = [1,2,3, {type: 'unbound versionstamp'}]
await db_.setVersionstampedKey(key, 'hi', false)
assert.deepStrictEqual(key, [1,2,3, {type: 'unbound versionstamp'}])
})
it('bakes versionstamps in a subspace', async () => {
const subspace = db.withValueEncoding(encoders.tuple);
const value = await db.doTransaction(async tn => {
const value = [tuple.unboundVersionstamp()]
tn.scopedTo(subspace).setVersionstampedValue('some-key', value)
return value
})
assert.strictEqual((value as any)[0].type, 'versionstamp')
})
it('encodes versionstamps in child tuples', async () => {
const db_ = db.withKeyEncoding(encoders.tuple).withValueEncoding(encoders.string)
const key: any[] = [1,[2, {type: 'unbound versionstamp'}]]
const actualStamp = await (await db_.doTn(async tn => {
tn.setVersionstampedKey(key, 'hi there')
return tn.getVersionstamp()
})).promise
// Check its been baked
assert.deepStrictEqual(key, [1,[2, bakeVersionstamp(actualStamp, 0)]])
const results = await db_.getRangeAllStartsWith([])
assert.deepStrictEqual(results, [[key, 'hi there']])
})
it('resets the code in retried transactions')
it('commits a tuple with unbound value versionstamps and bakes the vs and code', async () => {
const db_ = db.withKeyEncoding(encoders.string).withValueEncoding(encoders.tuple)
const val1: TupleItem[] = [1,2,3, {type: 'unbound versionstamp'}, 5] // code 1
const val2: TupleItem[] = [1,2,3, {type: 'unbound versionstamp'}] // code 2
const val3: TupleItem[] = [1,2,3, {type: 'unbound versionstamp', code: 321}] // code 321
const actualStamp = await (await db_.doTn(async tn => {
tn.setVersionstampedValue('1', val1)
tn.setVersionstampedValue('2', val2)
tn.setVersionstampedValue('3', val3)
return tn.getVersionstamp()
})).promise
// await db_.setVersionstampedKey(key1, 'hi there')
// The versionstamp should have been baked into the object
assert.deepStrictEqual(val1[3], bakeVersionstamp(actualStamp, 0))
assert.deepStrictEqual(val2[3], bakeVersionstamp(actualStamp, 1))
assert.deepStrictEqual(val3[3], bakeVersionstamp(actualStamp, 321))
// const results = await db.getRangeAllStartsWith(tuple.packBound([1,2,3]))
// assert.strictEqual(results.length, 1)
const results = await db_.getRangeAllStartsWith('')
assert.deepStrictEqual(results, [
['1', val1],
['2', val2],
['3', val3],
])
})
it('does not crash the program if a getVersionstamp result is aborted due to conflict', async () => {
// We're going to artificially generate a transaction conflict
const tn1 = db.rawCreateTransaction()
const tn2 = db.rawCreateTransaction()
await tn1.get('x')
tn1.set('x', 'hi')
await tn2.get('x')
tn2.set('x', 'yo')
await tn1.rawCommit()
// This will fail, but it shouldn't crash the program.
const vs = tn2.getVersionstamp().promise
// This will throw
try { await tn2.rawCommit() } catch (e) {}
})
})
describe('watch', () => {
it('getAndWatch returns undefined for empty keys', async () => {
const watch = await db.getAndWatch('hi')
assert.strictEqual(watch.value, undefined)
await db.set('hi', 'yo')
assert.strictEqual(true, await watch.promise)
})
it('getAndWatch returns a value when there is one', async () => {
await db.set('foo', 'bar')
const watch = await db.getAndWatch('foo')
assert.deepStrictEqual(watch.value, Buffer.from('bar'))
watch.cancel()
assert.strictEqual(false, await watch.promise)
// await new Promise(resolve => setTimeout(resolve, 200))
})
it('resolves false if the transaction conflicts', async () => {
// Artificially creating a conflict to see what happens.
const tn1 = db.rawCreateTransaction()
tn1.addReadConflictKey('conflict')
tn1.addWriteConflictKey('conflict')
const watch = tn1.watch('x')
const tn2 = db.rawCreateTransaction()
tn2.addWriteConflictKey('conflict')
await tn2.rawCommit()
await tn1.rawCommit().catch(e => {})
watch.cancel()
// Should resolve with false.
assert.strictEqual(false, await watch.promise)
})
it('resolves false if the transaction is cancelled', async () => {
const tn = db.rawCreateTransaction()
const watch = tn.watch('x')
tn.rawCancel()
assert.strictEqual(false, await watch.promise)
})
it('errors if a real error happens', async () => {
// This is a regression. And this is a bit of an ugly test
let watch: Watch
await assertRejects(db.doTn(async tn => {
tn.setReadVersion(Buffer.alloc(8)) // All zeros. This should be too old
watch = tn.watch('x')
await tn.get('x') // this will fail and throw.
}))
await assertRejects(watch!.promise)
})
})
describe('callback API', () => {
// Unless benchmarking shows a significant difference, this will be removed
// in a future version of this library.
it('allows tn.get() with a callback', async () => {
let called = false
await db.doTransaction(async tn => {
tn.set('xxx', 'hi')
// Ok now fetch it. I'm wrapping this in an awaited promise so we don't
// commit the transaction before .get() has resolved.
await new Promise<void>((resolve, reject) => {
tn.get('xxx', (err, data) => {
try {
assert(!called)
called = true
if (err) throw err
assert.deepStrictEqual(data, Buffer.from('hi'))
resolve()
} catch (e) { reject(e) }
})
})
})
assert(called)
})
})
describe('regression', () => {
it('does not trim off the end of a string', async () => {
// https://github.com/josephg/node-foundationdb/issues/40
const _db = db.getRoot()
await _db.set(testPrefix + 'somekey', 'val')
const val = await _db.get(testPrefix + 'somekey')
assert.strictEqual(val?.toString(), 'val')
})
})
})) | the_stack |
'use strict';
import Assert = require('vs/base/common/assert');
import { onUnexpectedError } from 'vs/base/common/errors';
import { IDisposable, combinedDisposable } from 'vs/base/common/lifecycle';
import arrays = require('vs/base/common/arrays');
import { INavigator } from 'vs/base/common/iterator';
import Events = require('vs/base/common/eventEmitter');
import WinJS = require('vs/base/common/winjs.base');
import _ = require('./tree');
interface IMap<T> { [id: string]: T; }
interface IItemMap extends IMap<Item> { }
interface ITraitMap extends IMap<IItemMap> { }
export class LockData extends Events.EventEmitter {
private _item: Item;
constructor(item: Item) {
super();
this._item = item;
}
public get item(): Item {
return this._item;
}
public dispose(): void {
this.emit('unlock');
super.dispose();
}
}
export class Lock {
/* When refreshing tree items, the tree's structured can be altered, by
inserting and removing sub-items. This lock helps to manage several
possibly-structure-changing calls.
API-wise, there are two possibly-structure-changing: refresh(...),
expand(...) and collapse(...). All these calls must call Lock#run(...).
Any call to Lock#run(...) needs to provide the affecting item and a
callback to execute when unlocked. It must also return a promise
which fulfills once the operation ends. Once it is called, there
are three possibilities:
- Nothing is currently running. The affecting item is remembered, and
the callback is executed.
- Or, there are on-going operations. There are two outcomes:
- The affecting item intersects with any other affecting items
of on-going run calls. In such a case, the given callback should
be executed only when the on-going one completes.
- Or, it doesn't. In such a case, both operations can be run in
parallel.
Note: two items A and B intersect if A is a descendant of B, or
vice-versa.
*/
private locks: { [id: string]: LockData; };
constructor() {
this.locks = Object.create({});
}
public isLocked(item: Item): boolean {
return !!this.locks[item.id];
}
public run(item: Item, fn: () => WinJS.Promise): WinJS.Promise {
var lock = this.getLock(item);
if (lock) {
var unbindListener: IDisposable;
return new WinJS.Promise((c, e) => {
unbindListener = lock.addOneTimeListener('unlock', () => {
return this.run(item, fn).then(c, e);
});
}, () => { unbindListener.dispose(); });
}
var result: WinJS.Promise;
return new WinJS.Promise((c, e) => {
if (item.isDisposed()) {
return e(new Error('Item is disposed.'));
}
var lock = this.locks[item.id] = new LockData(item);
result = fn().then((r) => {
delete this.locks[item.id];
lock.dispose();
return r;
}).then(c, e);
return result;
}, () => result.cancel());
}
private getLock(item: Item): LockData {
var key: string;
for (key in this.locks) {
var lock = this.locks[key];
if (item.intersects(lock.item)) {
return lock;
}
}
return null;
}
}
export class ItemRegistry extends Events.EventEmitter {
private _isDisposed = false;
private items: IMap<{ item: Item; disposable: IDisposable; }>;
constructor() {
super();
this.items = {};
}
public register(item: Item): void {
Assert.ok(!this.isRegistered(item.id), 'item already registered: ' + item.id);
this.items[item.id] = { item, disposable: this.addEmitter(item) };
}
public deregister(item: Item): void {
Assert.ok(this.isRegistered(item.id), 'item not registered: ' + item.id);
this.items[item.id].disposable.dispose();
delete this.items[item.id];
}
public isRegistered(id: string): boolean {
return this.items.hasOwnProperty(id);
}
public getItem(id: string): Item {
const result = this.items[id];
return result ? result.item : null;
}
public dispose(): void {
super.dispose();
this.items = null;
this._isDisposed = true;
}
public isDisposed(): boolean {
return this._isDisposed;
}
}
export interface IBaseItemEvent {
item: Item;
}
export interface IItemRefreshEvent extends IBaseItemEvent { }
export interface IItemExpandEvent extends IBaseItemEvent { }
export interface IItemCollapseEvent extends IBaseItemEvent { }
export interface IItemDisposeEvent extends IBaseItemEvent { }
export interface IItemTraitEvent extends IBaseItemEvent {
trait: string;
}
export interface IItemRevealEvent extends IBaseItemEvent {
relativeTop: number;
}
export interface IItemChildrenRefreshEvent extends IBaseItemEvent {
isNested: boolean;
}
export class Item extends Events.EventEmitter {
private registry: ItemRegistry;
private context: _.ITreeContext;
private element: any;
private lock: Lock;
public id: string;
private needsChildrenRefresh: boolean;
private doesHaveChildren: boolean;
public parent: Item;
public previous: Item;
public next: Item;
public firstChild: Item;
public lastChild: Item;
private userContent: HTMLElement;
private height: number;
private depth: number;
private visible: boolean;
private expanded: boolean;
private traits: { [trait: string]: boolean; };
private _isDisposed: boolean;
constructor(id: string, registry: ItemRegistry, context: _.ITreeContext, lock: Lock, element: any) {
super();
this.registry = registry;
this.context = context;
this.lock = lock;
this.element = element;
this.id = id;
this.registry.register(this);
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
this.needsChildrenRefresh = true;
this.parent = null;
this.previous = null;
this.next = null;
this.firstChild = null;
this.lastChild = null;
this.userContent = null;
this.traits = {};
this.depth = 0;
this.expanded = this.context.dataSource.shouldAutoexpand && this.context.dataSource.shouldAutoexpand(this.context.tree, element);
this.emit('item:create', { item: this });
this.visible = this._isVisible();
this.height = this._getHeight();
this._isDisposed = false;
}
public getElement(): any {
return this.element;
}
public hasChildren(): boolean {
return this.doesHaveChildren;
}
public getDepth(): number {
return this.depth;
}
public isVisible(): boolean {
return this.visible;
}
public setVisible(value: boolean): void {
this.visible = value;
}
public isExpanded(): boolean {
return this.expanded;
}
/* protected */ public _setExpanded(value: boolean): void {
this.expanded = value;
}
public reveal(relativeTop: number = null): void {
var eventData: IItemRevealEvent = { item: this, relativeTop: relativeTop };
this.emit('item:reveal', eventData);
}
public expand(): WinJS.Promise {
if (this.isExpanded() || !this.doesHaveChildren || this.lock.isLocked(this)) {
return WinJS.TPromise.as(false);
}
var result = this.lock.run(this, () => {
var eventData: IItemExpandEvent = { item: this };
var result: WinJS.Promise;
this.emit('item:expanding', eventData);
if (this.needsChildrenRefresh) {
result = this.refreshChildren(false, true, true);
} else {
result = WinJS.TPromise.as(null);
}
return result.then(() => {
this._setExpanded(true);
this.emit('item:expanded', eventData);
return true;
});
});
return result.then((r) => {
if (this.isDisposed()) {
return false;
}
// Auto expand single child folders
if (this.context.options.autoExpandSingleChildren && r && this.firstChild !== null && this.firstChild === this.lastChild && this.firstChild.isVisible()) {
return this.firstChild.expand().then(() => { return true; });
}
return r;
});
}
public collapse(recursive: boolean = false): WinJS.Promise {
if (recursive) {
var collapseChildrenPromise = WinJS.TPromise.as(null);
this.forEachChild((child) => {
collapseChildrenPromise = collapseChildrenPromise.then(() => child.collapse(true));
});
return collapseChildrenPromise.then(() => {
return this.collapse(false);
});
} else {
if (!this.isExpanded() || this.lock.isLocked(this)) {
return WinJS.TPromise.as(false);
}
return this.lock.run(this, () => {
var eventData: IItemCollapseEvent = { item: this };
this.emit('item:collapsing', eventData);
this._setExpanded(false);
this.emit('item:collapsed', eventData);
return WinJS.TPromise.as(true);
});
}
}
public addTrait(trait: string): void {
var eventData: IItemTraitEvent = { item: this, trait: trait };
this.traits[trait] = true;
this.emit('item:addTrait', eventData);
}
public removeTrait(trait: string): void {
var eventData: IItemTraitEvent = { item: this, trait: trait };
delete this.traits[trait];
this.emit('item:removeTrait', eventData);
}
public hasTrait(trait: string): boolean {
return this.traits[trait] || false;
}
public getAllTraits(): string[] {
var result: string[] = [];
var trait: string;
for (trait in this.traits) {
if (this.traits.hasOwnProperty(trait) && this.traits[trait]) {
result.push(trait);
}
}
return result;
}
public getHeight(): number {
return this.height;
}
private refreshChildren(recursive: boolean, safe: boolean = false, force: boolean = false): WinJS.Promise {
if (!force && !this.isExpanded()) {
this.needsChildrenRefresh = true;
return WinJS.TPromise.as(this);
}
this.needsChildrenRefresh = false;
var doRefresh = () => {
var eventData: IItemChildrenRefreshEvent = { item: this, isNested: safe };
this.emit('item:childrenRefreshing', eventData);
var childrenPromise: WinJS.Promise;
if (this.doesHaveChildren) {
childrenPromise = this.context.dataSource.getChildren(this.context.tree, this.element);
} else {
childrenPromise = WinJS.TPromise.as([]);
}
const result = childrenPromise.then((elements: any[]) => {
if (this.isDisposed() || this.registry.isDisposed()) {
return WinJS.TPromise.as(null);
}
elements = !elements ? [] : elements.slice(0);
elements = this.sort(elements);
var staleItems: IItemMap = {};
while (this.firstChild !== null) {
staleItems[this.firstChild.id] = this.firstChild;
this.removeChild(this.firstChild);
}
for (var i = 0, len = elements.length; i < len; i++) {
var element = elements[i];
var id = this.context.dataSource.getId(this.context.tree, element);
var item = staleItems[id] || new Item(id, this.registry, this.context, this.lock, element);
item.element = element;
if (recursive) {
item.needsChildrenRefresh = recursive;
}
delete staleItems[id];
this.addChild(item);
}
for (var staleItemId in staleItems) {
if (staleItems.hasOwnProperty(staleItemId)) {
staleItems[staleItemId].dispose();
}
}
if (recursive) {
return WinJS.Promise.join(this.mapEachChild((child) => {
return child.doRefresh(recursive, true);
}));
} else {
return WinJS.TPromise.as(null);
}
});
return result
.then(null, onUnexpectedError)
.then(() => this.emit('item:childrenRefreshed', eventData));
};
return safe ? doRefresh() : this.lock.run(this, doRefresh);
}
private doRefresh(recursive: boolean, safe: boolean = false): WinJS.Promise {
var eventData: IItemRefreshEvent = { item: this };
this.doesHaveChildren = this.context.dataSource.hasChildren(this.context.tree, this.element);
this.height = this._getHeight();
this.setVisible(this._isVisible());
this.emit('item:refresh', eventData);
return this.refreshChildren(recursive, safe);
}
public refresh(recursive: boolean): WinJS.Promise {
return this.doRefresh(recursive);
}
public getNavigator(): INavigator<Item> {
return new TreeNavigator(this);
}
public intersects(other: Item): boolean {
return this.isAncestorOf(other) || other.isAncestorOf(this);
}
public getHierarchy(): Item[] {
var result: Item[] = [];
var node: Item = this;
do {
result.push(node);
node = node.parent;
} while (node);
result.reverse();
return result;
}
private isAncestorOf(item: Item): boolean {
while (item) {
if (item.id === this.id) {
return true;
}
item = item.parent;
}
return false;
}
private addChild(item: Item, afterItem: Item = this.lastChild): void {
var isEmpty = this.firstChild === null;
var atHead = afterItem === null;
var atTail = afterItem === this.lastChild;
if (isEmpty) {
this.firstChild = this.lastChild = item;
item.next = item.previous = null;
} else if (atHead) {
this.firstChild.previous = item;
item.next = this.firstChild;
item.previous = null;
this.firstChild = item;
} else if (atTail) {
this.lastChild.next = item;
item.next = null;
item.previous = this.lastChild;
this.lastChild = item;
} else {
item.previous = afterItem;
item.next = afterItem.next;
afterItem.next.previous = item;
afterItem.next = item;
}
item.parent = this;
item.depth = this.depth + 1;
}
private removeChild(item: Item): void {
var isFirstChild = this.firstChild === item;
var isLastChild = this.lastChild === item;
if (isFirstChild && isLastChild) {
this.firstChild = this.lastChild = null;
} else if (isFirstChild) {
item.next.previous = null;
this.firstChild = item.next;
} else if (isLastChild) {
item.previous.next = null;
this.lastChild = item.previous;
} else {
item.next.previous = item.previous;
item.previous.next = item.next;
}
item.parent = null;
item.depth = null;
}
private forEachChild(fn: (child: Item) => void): void {
var child = this.firstChild, next: Item;
while (child) {
next = child.next;
fn(child);
child = next;
}
}
private mapEachChild<T>(fn: (child: Item) => T): T[] {
var result = [];
this.forEachChild((child) => {
result.push(fn(child));
});
return result;
}
private sort(elements: any[]): any[] {
if (this.context.sorter) {
return elements.sort((element, otherElement) => {
return this.context.sorter.compare(this.context.tree, element, otherElement);
});
}
return elements;
}
/* protected */ public _getHeight(): number {
return this.context.renderer.getHeight(this.context.tree, this.element);
}
/* protected */ public _isVisible(): boolean {
return this.context.filter.isVisible(this.context.tree, this.element);
}
public isDisposed(): boolean {
return this._isDisposed;
}
public dispose(): void {
this.forEachChild((child) => child.dispose());
this.parent = null;
this.previous = null;
this.next = null;
this.firstChild = null;
this.lastChild = null;
var eventData: IItemDisposeEvent = { item: this };
this.emit('item:dispose', eventData);
this.registry.deregister(this);
super.dispose();
this._isDisposed = true;
}
}
class RootItem extends Item {
constructor(id: string, registry: ItemRegistry, context: _.ITreeContext, lock: Lock, element: any) {
super(id, registry, context, lock, element);
}
public isVisible(): boolean {
return false;
}
public setVisible(value: boolean): void {
// no-op
}
public isExpanded(): boolean {
return true;
}
/* protected */ public _setExpanded(value: boolean): void {
// no-op
}
public render(): void {
// no-op
}
/* protected */ public _getHeight(): number {
return 0;
}
/* protected */ public _isVisible(): boolean {
return false;
}
}
export class TreeNavigator implements INavigator<Item> {
private start: Item;
private item: Item;
static lastDescendantOf(item: Item): Item {
if (!item) {
return null;
} else {
if (!(item instanceof RootItem) && (!item.isVisible() || !item.isExpanded() || item.lastChild === null)) {
return item;
} else {
return TreeNavigator.lastDescendantOf(item.lastChild);
}
}
}
constructor(item: Item, subTreeOnly: boolean = true) {
this.item = item;
this.start = subTreeOnly ? item : null;
}
public current(): Item {
return this.item || null;
}
public next(): Item {
if (this.item) {
do {
if ((this.item instanceof RootItem || (this.item.isVisible() && this.item.isExpanded())) && this.item.firstChild) {
this.item = this.item.firstChild;
} else if (this.item === this.start) {
this.item = null;
} else {
// select next brother, next uncle, next great-uncle, etc...
while (this.item && this.item !== this.start && !this.item.next) {
this.item = this.item.parent;
}
if (this.item === this.start) {
this.item = null;
}
this.item = !this.item ? null : this.item.next;
}
} while (this.item && !this.item.isVisible());
}
return this.item || null;
}
public previous(): Item {
if (this.item) {
do {
var previous = TreeNavigator.lastDescendantOf(this.item.previous);
if (previous) {
this.item = previous;
} else if (this.item.parent && this.item.parent !== this.start && this.item.parent.isVisible()) {
this.item = this.item.parent;
} else {
this.item = null;
}
} while (this.item && !this.item.isVisible());
}
return this.item || null;
}
public parent(): Item {
if (this.item) {
var parent = this.item.parent;
if (parent && parent !== this.start && parent.isVisible()) {
this.item = parent;
} else {
this.item = null;
}
}
return this.item || null;
}
public first(): Item {
this.item = this.start;
this.next();
return this.item || null;
}
public last(): Item {
return TreeNavigator.lastDescendantOf(this.start);
}
}
function getRange(one: Item, other: Item): Item[] {
var oneHierarchy = one.getHierarchy();
var otherHierarchy = other.getHierarchy();
var length = arrays.commonPrefixLength(oneHierarchy, otherHierarchy);
var item = oneHierarchy[length - 1];
var nav = item.getNavigator();
var oneIndex: number = null;
var otherIndex: number = null;
var index = 0;
var result: Item[] = [];
while (item && (oneIndex === null || otherIndex === null)) {
result.push(item);
if (item === one) {
oneIndex = index;
}
if (item === other) {
otherIndex = index;
}
index++;
item = nav.next();
}
if (oneIndex === null || otherIndex === null) {
return [];
}
var min = Math.min(oneIndex, otherIndex);
var max = Math.max(oneIndex, otherIndex);
return result.slice(min, max + 1);
}
export interface IBaseEvent {
item: Item;
}
export interface IInputEvent extends IBaseEvent { }
export interface IRefreshEvent extends IBaseEvent {
recursive: boolean;
}
export class TreeModel extends Events.EventEmitter {
private context: _.ITreeContext;
private lock: Lock;
private input: Item;
private registry: ItemRegistry;
private registryDisposable: IDisposable;
private traitsToItems: ITraitMap;
constructor(context: _.ITreeContext) {
super();
this.context = context;
this.input = null;
this.traitsToItems = {};
}
public setInput(element: any): WinJS.Promise {
var eventData: IInputEvent = { item: this.input };
this.emit('clearingInput', eventData);
this.setSelection([]);
this.setFocus();
this.setHighlight();
this.lock = new Lock();
if (this.input) {
this.input.dispose();
}
if (this.registry) {
this.registry.dispose();
this.registryDisposable.dispose();
}
this.registry = new ItemRegistry();
this.registryDisposable = combinedDisposable([
this.addEmitter(this.registry),
this.registry.addListener('item:dispose', (event: IItemDisposeEvent) => {
event.item.getAllTraits()
.forEach(trait => delete this.traitsToItems[trait][event.item.id]);
})
]);
var id = this.context.dataSource.getId(this.context.tree, element);
this.input = new RootItem(id, this.registry, this.context, this.lock, element);
eventData = { item: this.input };
this.emit('setInput', eventData);
return this.refresh(this.input);
}
public getInput(): any {
return this.input ? this.input.getElement() : null;
}
public refresh(element: any = null, recursive: boolean = true): WinJS.Promise {
var item = this.getItem(element);
if (!item) {
return WinJS.TPromise.as(null);
}
var eventData: IRefreshEvent = { item: item, recursive: recursive };
this.emit('refreshing', eventData);
return item.refresh(recursive).then(() => {
this.emit('refreshed', eventData);
});
}
public refreshAll(elements: any[], recursive: boolean = true): WinJS.Promise {
try {
this.beginDeferredEmit();
return this._refreshAll(elements, recursive);
} finally {
this.endDeferredEmit();
}
}
private _refreshAll(elements: any[], recursive: boolean): WinJS.Promise {
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.refresh(elements[i], recursive));
}
return WinJS.Promise.join(promises);
}
public expand(element: any): WinJS.Promise {
var item = this.getItem(element);
if (!item) {
return WinJS.TPromise.as(false);
}
return item.expand();
}
public expandAll(elements?: any[]): WinJS.Promise {
if (!elements) {
elements = [];
var item: Item;
var nav = this.getNavigator();
while (item = nav.next()) {
elements.push(item);
}
}
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.expand(elements[i]));
}
return WinJS.Promise.join(promises);
}
public collapse(element: any, recursive: boolean = false): WinJS.Promise {
var item = this.getItem(element);
if (!item) {
return WinJS.TPromise.as(false);
}
return item.collapse(recursive);
}
public collapseAll(elements: any[] = null, recursive: boolean = false): WinJS.Promise {
if (!elements) {
elements = [this.input];
recursive = true;
}
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.collapse(elements[i], recursive));
}
return WinJS.Promise.join(promises);
}
public toggleExpansion(element: any): WinJS.Promise {
return this.isExpanded(element) ? this.collapse(element) : this.expand(element);
}
public toggleExpansionAll(elements: any[]): WinJS.Promise {
var promises = [];
for (var i = 0, len = elements.length; i < len; i++) {
promises.push(this.toggleExpansion(elements[i]));
}
return WinJS.Promise.join(promises);
}
public isExpanded(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.isExpanded();
}
public getExpandedElements(): any[] {
var result: any[] = [];
var item: Item;
var nav = this.getNavigator();
while (item = nav.next()) {
if (item.isExpanded()) {
result.push(item.getElement());
}
}
return result;
}
public reveal(element: any, relativeTop: number = null): WinJS.Promise {
return this.resolveUnknownParentChain(element).then((chain: any[]) => {
var result = WinJS.TPromise.as(null);
chain.forEach((e) => {
result = result.then(() => this.expand(e));
});
return result;
}).then(() => {
var item = this.getItem(element);
if (item) {
return item.reveal(relativeTop);
}
});
}
private resolveUnknownParentChain(element: any): WinJS.Promise {
return this.context.dataSource.getParent(this.context.tree, element).then((parent) => {
if (!parent) {
return WinJS.TPromise.as([]);
}
return this.resolveUnknownParentChain(parent).then((result) => {
result.push(parent);
return result;
});
});
}
public setHighlight(element?: any, eventPayload?: any): void {
this.setTraits('highlighted', element ? [element] : []);
var eventData: _.IHighlightEvent = { highlight: this.getHighlight(), payload: eventPayload };
this.emit('highlight', eventData);
}
public getHighlight(includeHidden?: boolean): any {
var result = this.getElementsWithTrait('highlighted', includeHidden);
return result.length === 0 ? null : result[0];
}
public isHighlighted(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.hasTrait('highlighted');
}
public select(element: any, eventPayload?: any): void {
this.selectAll([element], eventPayload);
}
public selectRange(fromElement: any, toElement: any, eventPayload?: any): void {
var fromItem = this.getItem(fromElement);
var toItem = this.getItem(toElement);
if (!fromItem || !toItem) {
return;
}
this.selectAll(getRange(fromItem, toItem), eventPayload);
}
public deselectRange(fromElement: any, toElement: any, eventPayload?: any): void {
var fromItem = this.getItem(fromElement);
var toItem = this.getItem(toElement);
if (!fromItem || !toItem) {
return;
}
this.deselectAll(getRange(fromItem, toItem), eventPayload);
}
public selectAll(elements: any[], eventPayload?: any): void {
this.addTraits('selected', elements);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this.emit('selection', eventData);
}
public deselect(element: any, eventPayload?: any): void {
this.deselectAll([element], eventPayload);
}
public deselectAll(elements: any[], eventPayload?: any): void {
this.removeTraits('selected', elements);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this.emit('selection', eventData);
}
public setSelection(elements: any[], eventPayload?: any): void {
this.setTraits('selected', elements);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this.emit('selection', eventData);
}
public toggleSelection(element: any, eventPayload?: any): void {
this.toggleTrait('selected', element);
var eventData: _.ISelectionEvent = { selection: this.getSelection(), payload: eventPayload };
this.emit('selection', eventData);
}
public isSelected(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.hasTrait('selected');
}
public getSelection(includeHidden?: boolean): any[] {
return this.getElementsWithTrait('selected', includeHidden);
}
public selectNext(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void {
var selection = this.getSelection();
var item: Item = selection.length > 0 ? selection[0] : this.input;
var nextItem: Item;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
nextItem = nav.next();
if (!nextItem) {
break;
}
item = nextItem;
}
if (clearSelection) {
this.setSelection([item], eventPayload);
} else {
this.select(item, eventPayload);
}
}
public selectPrevious(count: number = 1, clearSelection: boolean = true, eventPayload?: any): void {
var selection = this.getSelection(),
item: Item = null,
previousItem: Item = null;
if (selection.length === 0) {
var nav = this.getNavigator(this.input);
while (item = nav.next()) {
previousItem = item;
}
item = previousItem;
} else {
item = selection[0];
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
previousItem = nav.previous();
if (!previousItem) {
break;
}
item = previousItem;
}
}
if (clearSelection) {
this.setSelection([item], eventPayload);
} else {
this.select(item, eventPayload);
}
}
public selectParent(eventPayload?: any, clearSelection: boolean = true): void {
var selection = this.getSelection();
var item: Item = selection.length > 0 ? selection[0] : this.input;
var nav = this.getNavigator(item, false);
var parent = nav.parent();
if (parent) {
if (clearSelection) {
this.setSelection([parent], eventPayload);
} else {
this.select(parent, eventPayload);
}
}
}
public setFocus(element?: any, eventPayload?: any): void {
this.setTraits('focused', element ? [element] : []);
var eventData: _.IFocusEvent = { focus: this.getFocus(), payload: eventPayload };
this.emit('focus', eventData);
}
public isFocused(element: any): boolean {
var item = this.getItem(element);
if (!item) {
return false;
}
return item.hasTrait('focused');
}
public getFocus(includeHidden?: boolean): any {
var result = this.getElementsWithTrait('focused', includeHidden);
return result.length === 0 ? null : result[0];
}
public focusNext(count: number = 1, eventPayload?: any): void {
var item: Item = this.getFocus() || this.input;
var nextItem: Item;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
nextItem = nav.next();
if (!nextItem) {
break;
}
item = nextItem;
}
this.setFocus(item, eventPayload);
}
public focusPrevious(count: number = 1, eventPayload?: any): void {
var item: Item = this.getFocus() || this.input;
var previousItem: Item;
var nav = this.getNavigator(item, false);
for (var i = 0; i < count; i++) {
previousItem = nav.previous();
if (!previousItem) {
break;
}
item = previousItem;
}
this.setFocus(item, eventPayload);
}
public focusParent(eventPayload?: any): void {
var item: Item = this.getFocus() || this.input;
var nav = this.getNavigator(item, false);
var parent = nav.parent();
if (parent) {
this.setFocus(parent, eventPayload);
}
}
public focusFirstChild(eventPayload?: any): void {
const item = this.getItem(this.getFocus() || this.input);
const nav = this.getNavigator(item, false);
const next = nav.next();
const parent = nav.parent();
if (parent === item) {
this.setFocus(next, eventPayload);
}
}
public focusFirst(eventPayload?: any): void {
this.focusNth(0, eventPayload);
}
public focusNth(index: number, eventPayload?: any): void {
var nav = this.getNavigator(this.input);
var item = nav.first();
for (var i = 0; i < index; i++) {
item = nav.next();
}
if (item) {
this.setFocus(item, eventPayload);
}
}
public focusLast(eventPayload?: any): void {
var nav = this.getNavigator(this.input);
var item = nav.last();
if (item) {
this.setFocus(item, eventPayload);
}
}
public getNavigator(element: any = null, subTreeOnly: boolean = true): INavigator<Item> {
return new TreeNavigator(this.getItem(element), subTreeOnly);
}
public getItem(element: any = null): Item {
if (element === null) {
return this.input;
} else if (element instanceof Item) {
return element;
} else if (typeof element === 'string') {
return this.registry.getItem(element);
} else {
return this.registry.getItem(this.context.dataSource.getId(this.context.tree, element));
}
}
public addTraits(trait: string, elements: any[]): void {
var items: IItemMap = this.traitsToItems[trait] || <IItemMap>{};
var item: Item;
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
item.addTrait(trait);
items[item.id] = item;
}
}
this.traitsToItems[trait] = items;
}
public removeTraits(trait: string, elements: any[]): void {
var items: IItemMap = this.traitsToItems[trait] || <IItemMap>{};
var item: Item;
var id: string;
if (elements.length === 0) {
for (id in items) {
if (items.hasOwnProperty(id)) {
item = items[id];
item.removeTrait(trait);
}
}
delete this.traitsToItems[trait];
} else {
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
item.removeTrait(trait);
delete items[item.id];
}
}
}
}
public hasTrait(trait: string, element: any): boolean {
var item = this.getItem(element);
return item && item.hasTrait(trait);
}
private toggleTrait(trait: string, element: any): void {
var item = this.getItem(element);
if (!item) {
return;
}
if (item.hasTrait(trait)) {
this.removeTraits(trait, [element]);
} else {
this.addTraits(trait, [element]);
}
}
private setTraits(trait: string, elements: any[]): void {
if (elements.length === 0) {
this.removeTraits(trait, elements);
} else {
var items: { [id: string]: Item; } = {};
var item: Item;
for (var i = 0, len = elements.length; i < len; i++) {
item = this.getItem(elements[i]);
if (item) {
items[item.id] = item;
}
}
var traitItems: IItemMap = this.traitsToItems[trait] || <IItemMap>{};
var itemsToRemoveTrait: Item[] = [];
var id: string;
for (id in traitItems) {
if (traitItems.hasOwnProperty(id)) {
if (items.hasOwnProperty(id)) {
delete items[id];
} else {
itemsToRemoveTrait.push(traitItems[id]);
}
}
}
for (var i = 0, len = itemsToRemoveTrait.length; i < len; i++) {
item = itemsToRemoveTrait[i];
item.removeTrait(trait);
delete traitItems[item.id];
}
for (id in items) {
if (items.hasOwnProperty(id)) {
item = items[id];
item.addTrait(trait);
traitItems[id] = item;
}
}
this.traitsToItems[trait] = traitItems;
}
}
private getElementsWithTrait(trait: string, includeHidden: boolean): any[] {
var elements = [];
var items = this.traitsToItems[trait] || {};
var id: string;
for (id in items) {
if (items.hasOwnProperty(id) && (items[id].isVisible() || includeHidden)) {
elements.push(items[id].getElement());
}
}
return elements;
}
public dispose(): void {
if (this.registry) {
this.registry.dispose();
this.registry = null;
}
super.dispose();
}
} | the_stack |
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { forkJoin, of, Subscription } from 'rxjs';
import { ActivatedRoute } from '@angular/router';
import dayjs from 'dayjs/esm';
import { sum } from 'lodash-es';
import { StudentParticipation } from 'app/entities/participation/student-participation.model';
import { ExportToCsv } from 'export-to-csv';
import { Exercise, ExerciseType, exerciseTypes, IncludedInOverallScore } from 'app/entities/exercise.model';
import { Course } from 'app/entities/course.model';
import { CourseManagementService } from '../manage/course-management.service';
import { SortService } from 'app/shared/service/sort.service';
import { LocaleConversionService } from 'app/shared/service/locale-conversion.service';
import { JhiLanguageHelper } from 'app/core/language/language.helper';
import { ParticipantScoresService, ScoresDTO } from 'app/shared/participant-scores/participant-scores.service';
import { average, round, roundScorePercentSpecifiedByCourseSettings, roundValueSpecifiedByCourseSettings } from 'app/shared/util/utils';
import { captureException } from '@sentry/browser';
import { GradingSystemService } from 'app/grading-system/grading-system.service';
import { GradeType, GradingScale } from 'app/entities/grading-scale.model';
import { catchError } from 'rxjs/operators';
import { HttpResponse } from '@angular/common/http';
import { faDownload, faSort, faSpinner } from '@fortawesome/free-solid-svg-icons';
import { CsvExportRowBuilder } from 'app/shared/export/csv-export-row-builder';
import { CourseScoresStudentStatistics } from 'app/course/course-scores/course-scores-student-statistics';
import { mean, median, standardDeviation } from 'simple-statistics';
import { ExerciseTypeStatisticsMap } from 'app/course/course-scores/exercise-type-statistics-map';
import { CsvExportOptions } from 'app/shared/export/export-modal.component';
import { ButtonSize } from 'app/shared/components/button.component';
import * as XLSX from 'xlsx';
import { VERSION } from 'app/app.constants';
import { ExcelExportRowBuilder } from 'app/shared/export/excel-export-row-builder';
import { ExportRowBuilder, ExportRow } from 'app/shared/export/export-row-builder';
import { ArtemisNavigationUtilService } from 'app/utils/navigation.utils';
import {
BONUS_KEY,
EMAIL_KEY,
GRADE_KEY,
NAME_KEY,
COURSE_OVERALL_POINTS_KEY,
COURSE_OVERALL_SCORE_KEY,
POINTS_KEY,
PRESENTATION_SCORE_KEY,
REGISTRATION_NUMBER_KEY,
SCORE_KEY,
USERNAME_KEY,
} from 'app/shared/export/export-constants';
export enum HighlightType {
AVERAGE = 'average',
MEDIAN = 'median',
NONE = 'none',
}
@Component({
selector: 'jhi-course-scores',
templateUrl: './course-scores.component.html',
styleUrls: ['./course-scores.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CourseScoresComponent implements OnInit, OnDestroy {
private paramSub: Subscription;
private languageChangeSubscription?: Subscription;
course: Course;
allParticipationsOfCourse: StudentParticipation[] = [];
exercisesOfCourseThatAreIncludedInScoreCalculation: Exercise[] = [];
students: CourseScoresStudentStatistics[] = [];
private exerciseTypesWithExercises: ExerciseType[];
private exerciseSuccessfulPerType = new ExerciseTypeStatisticsMap();
private exerciseParticipationsPerType = new ExerciseTypeStatisticsMap();
private exerciseAveragePointsPerType = new ExerciseTypeStatisticsMap();
exerciseMaxPointsPerType = new ExerciseTypeStatisticsMap();
private exercisesPerType = new Map<ExerciseType, Exercise[]>();
exportReady = false;
predicate: string;
reverse: boolean;
// max values
maxNumberOfPointsPerExerciseType = new Map<ExerciseType, number>();
maxNumberOfOverallPoints = 0;
// average values
averageNumberOfParticipatedExercises = 0;
averageNumberOfSuccessfulExercises = 0;
averageNumberOfPointsPerExerciseTypes = new Map<ExerciseType, number>();
averageNumberOfOverallPoints = 0;
// note: these represent the course scores using the participation score table. We might switch to this new
// calculation method completely if it is confirmed that it produces correct results
private studentIdToCourseScoreDTOs: Map<number, ScoresDTO> = new Map<number, ScoresDTO>();
gradingScaleExists = false;
gradingScale?: GradingScale;
isBonus?: boolean;
maxGrade?: string;
averageGrade?: string;
scoresToDisplay: number[];
valueToHighlight: number | undefined;
highlightedType = HighlightType.NONE;
numberOfReleasedExercises: number;
averageScoreIncluded = 0;
medianScoreIncluded = 0;
medianPointsIncluded = 0;
averageScoreTotal = 0;
averagePointsTotal = 0;
medianScoreTotal = 0;
medianPointsTotal = 0;
standardDeviationPointsIncluded = 0;
standardDeviationPointsTotal = 0;
// Expose the imports to the template
readonly exerciseTypes = exerciseTypes;
readonly highlightType = HighlightType;
readonly roundScorePercentSpecifiedByCourseSettings = roundScorePercentSpecifiedByCourseSettings;
readonly roundValueSpecifiedByCourseSettings = roundValueSpecifiedByCourseSettings;
readonly ButtonSize = ButtonSize;
// Icons
faSort = faSort;
faDownload = faDownload;
faSpinner = faSpinner;
constructor(
private route: ActivatedRoute,
private courseService: CourseManagementService,
private sortService: SortService,
private changeDetector: ChangeDetectorRef,
private languageHelper: JhiLanguageHelper,
private localeConversionService: LocaleConversionService,
private participantScoresService: ParticipantScoresService,
private gradingSystemService: GradingSystemService,
private navigationUtilService: ArtemisNavigationUtilService,
) {
this.reverse = false;
this.predicate = 'id';
}
/**
* On init fetch the course, all released exercises and all participations with result for the course from the server.
*/
ngOnInit() {
this.paramSub = this.route.params.subscribe((params) => {
this.courseService.findWithExercises(params['courseId']).subscribe((findWithExercisesResult) => {
this.initializeWithCourse(findWithExercisesResult.body!);
});
});
// Update the view if the language was changed
this.languageChangeSubscription = this.languageHelper.language.subscribe(() => {
this.changeDetector.detectChanges();
});
}
/**
* On destroy unsubscribe.
*/
ngOnDestroy() {
if (this.paramSub) {
this.paramSub.unsubscribe();
}
if (this.languageChangeSubscription) {
this.languageChangeSubscription.unsubscribe();
}
}
sortRows() {
this.sortService.sortByProperty(this.students, this.predicate, this.reverse);
}
/**
* Initialize the component with the given course.
* @param course The course which should be displayed.
* @private
*/
private initializeWithCourse(course: Course) {
this.course = course;
this.initializeExerciseTitles();
this.exercisesOfCourseThatAreIncludedInScoreCalculation = this.determineExercisesIncludedInScore(this.course);
this.numberOfReleasedExercises = this.determineReleasedExercises(this.course).length;
this.calculateCourseStatistics(this.course.id!);
}
/**
* Makes sure the exercise titles are unique.
* @private
*/
private initializeExerciseTitles() {
if (!this.course.exercises) {
return;
}
const titleMap = new Map<string, number>();
for (const exercise of this.course.exercises) {
const title = exercise.title!;
if (titleMap.has(title)) {
const currentValue = titleMap.get(title);
titleMap.set(title, currentValue! + 1);
} else {
titleMap.set(title, 1);
}
}
// this workaround is necessary if the course has exercises with the same title (we add the id to make it unique)
for (const exercise of this.course.exercises) {
if (titleMap.has(exercise.title!) && titleMap.get(exercise.title!)! > 1) {
exercise.title = `${exercise.title} (id=${exercise.id})`;
}
}
}
/**
* Determines the exercises of the course that are included in the score calculation.
* @private
*/
private determineExercisesIncludedInScore(course: Course): Array<Exercise> {
return course
.exercises!.filter((exercise) => {
const isReleasedExercise = !exercise.releaseDate || exercise.releaseDate.isBefore(dayjs());
const isExerciseThatCounts = exercise.includedInOverallScore !== IncludedInOverallScore.NOT_INCLUDED;
return isReleasedExercise && isExerciseThatCounts;
})
.sort(CourseScoresComponent.compareExercises);
}
/**
* Returns all exercise types for which the course has at least one exercise.
* @private
*/
private filterExercisesTypesWithExercises(): Array<ExerciseType> {
return this.exerciseTypes.filter((exerciseType) => {
const exercisesWithType = this.exercisesPerType.get(exerciseType)?.length ?? 0;
return exercisesWithType !== 0;
});
}
/**
* Fetch all participations with results from the server for the specified course and calculate the corresponding course statistics
* @param courseId Id of the course
*/
private calculateCourseStatistics(courseId: number) {
const findParticipationsObservable = this.courseService.findAllParticipationsWithResults(courseId);
// alternative course scores calculation using participant scores table
const courseScoresObservable = this.participantScoresService.findCourseScores(courseId);
// find grading scale if it exists for course
const gradingScaleObservable = this.gradingSystemService.findGradingScaleForCourse(courseId).pipe(catchError(() => of(new HttpResponse<GradingScale>())));
forkJoin([findParticipationsObservable, courseScoresObservable, gradingScaleObservable]).subscribe(([participationsOfCourse, courseScoresResult, gradingScaleResponse]) => {
this.allParticipationsOfCourse = participationsOfCourse;
this.calculateExerciseLevelStatistics();
this.exerciseTypesWithExercises = this.filterExercisesTypesWithExercises();
this.calculateStudentLevelStatistics();
// if grading scale exists set properties
if (gradingScaleResponse.body) {
this.calculateGradingScaleInformation(gradingScaleResponse.body);
}
// comparing with calculation from course scores (using new participation score table)
const courseScoreDTOs = courseScoresResult.body!;
this.compareNewCourseScoresCalculationWithOldCalculation(courseScoreDTOs);
this.calculateAverageAndMedianScores();
this.scoresToDisplay = this.students.map((student) => roundScorePercentSpecifiedByCourseSettings(student.overallPoints / this.maxNumberOfOverallPoints, this.course));
this.highlightBar(HighlightType.AVERAGE);
});
}
/**
* This method compares the course scores computed on the client side with the ones on the server side
* using the participations score table. In the future we might switch to the server side method, so we use
* this method to detect discrepancies.
* @param courseScoreDTOs the course scores sent from the server (new calculation method)
*/
private compareNewCourseScoresCalculationWithOldCalculation(courseScoreDTOs: ScoresDTO[]) {
if (!this.students || !courseScoreDTOs) {
return;
}
for (const courseScoreDTO of courseScoreDTOs) {
this.studentIdToCourseScoreDTOs.set(courseScoreDTO.studentId!, courseScoreDTO);
}
for (const student of this.students) {
this.checkStudentScoreCalculation(student);
}
}
/**
* Checks that the score calculated on the server for the student matches the score calculated in the client.
* @param student The student for which the score should be checked.
* @private
*/
private checkStudentScoreCalculation(student: CourseScoresStudentStatistics) {
const overAllPoints = roundValueSpecifiedByCourseSettings(student.overallPoints, this.course);
const overallScore = roundScorePercentSpecifiedByCourseSettings(student.overallPoints / this.maxNumberOfOverallPoints, this.course);
const regularCalculation = {
scoreAchieved: overallScore,
pointsAchieved: overAllPoints,
userId: student.user.id,
userLogin: student.user.login,
regularPointsAchievable: this.maxNumberOfOverallPoints,
};
// checking if the same as in the course scores map
const courseScoreDTO = this.studentIdToCourseScoreDTOs.get(student.user.id!);
if (!courseScoreDTO) {
const errorMessage = `User scores not included in new calculation: ${JSON.stringify(regularCalculation)}`;
this.logErrorOnSentry(errorMessage);
} else {
courseScoreDTO.scoreAchieved = roundValueSpecifiedByCourseSettings(courseScoreDTO.scoreAchieved, this.course);
courseScoreDTO.pointsAchieved = roundValueSpecifiedByCourseSettings(courseScoreDTO.pointsAchieved, this.course);
if (Math.abs(courseScoreDTO.pointsAchieved - regularCalculation.pointsAchieved) > 0.1) {
const errorMessage = `Different course points in new calculation. Regular Calculation: ${JSON.stringify(regularCalculation)}. New Calculation: ${JSON.stringify(
courseScoreDTO,
)}`;
this.logErrorOnSentry(errorMessage);
}
if (Math.abs(courseScoreDTO.scoreAchieved - regularCalculation.scoreAchieved) > 0.1) {
const errorMessage = `Different course score in new calculation. Regular Calculation: ${JSON.stringify(regularCalculation)}. New Calculation : ${JSON.stringify(
courseScoreDTO,
)}`;
this.logErrorOnSentry(errorMessage);
}
}
}
logErrorOnSentry(errorMessage: string) {
captureException(new Error(errorMessage));
}
/**
* Group the exercises by type and gather statistics for each type (titles, max points, accumulated max points).
*/
private calculateExerciseLevelStatistics() {
for (const exerciseType of this.exerciseTypes) {
const exercisesOfType = this.exercisesOfCourseThatAreIncludedInScoreCalculation.filter((exercise) => exercise.type === exerciseType);
this.exercisesPerType.set(exerciseType, exercisesOfType);
const maxPointsOfAllExercisesOfType = new Map();
exercisesOfType.forEach((exercise) => maxPointsOfAllExercisesOfType.set(exercise.id!, exercise.maxPoints));
this.exerciseMaxPointsPerType.set(exerciseType, maxPointsOfAllExercisesOfType);
const maxPointsOfAllIncludedExercisesOfType = exercisesOfType
// only exercises marked as included_completely increase the maximum reachable number of points
.filter((exercise) => exercise.includedInOverallScore === IncludedInOverallScore.INCLUDED_COMPLETELY)
.map((exercise) => exercise.maxPoints!);
this.maxNumberOfPointsPerExerciseType.set(exerciseType, sum(maxPointsOfAllIncludedExercisesOfType));
}
this.maxNumberOfOverallPoints = 0;
for (const maxNumberOfPointsPerExerciseTypeElement of this.maxNumberOfPointsPerExerciseType) {
this.maxNumberOfOverallPoints += maxNumberOfPointsPerExerciseTypeElement[1];
}
}
/**
* Creates students and calculates the points for each exercise and exercise type.
*/
private calculateStudentLevelStatistics() {
const studentsMap = this.mapStudentIdToStudentStatistics();
// prepare exercises
for (const exercise of this.exercisesOfCourseThatAreIncludedInScoreCalculation) {
exercise.numberOfParticipationsWithRatedResult = 0;
exercise.numberOfSuccessfulParticipations = 0;
}
studentsMap.forEach((student) => {
this.students.push(student);
// We need the information of not included exercises as well in order to compute the total average and median
for (const exercise of this.determineReleasedExercises(this.course)) {
this.updateStudentStatisticsWithExerciseResults(student, exercise);
}
for (const exerciseType of this.exerciseTypes) {
if (this.maxNumberOfPointsPerExerciseType.get(exerciseType)! > 0) {
student.scorePerExerciseType.set(
exerciseType,
(student.sumPointsPerExerciseType.get(exerciseType)! / this.maxNumberOfPointsPerExerciseType.get(exerciseType)!) * 100,
);
}
}
});
for (const exerciseType of this.exerciseTypes) {
// TODO: can we calculate this average only with students who participated in the exercise?
this.averageNumberOfPointsPerExerciseTypes.set(exerciseType, average(this.students.map((student) => student.sumPointsPerExerciseType.get(exerciseType)!)));
}
this.averageNumberOfOverallPoints = average(this.students.map((student) => student.overallPoints));
this.averageNumberOfSuccessfulExercises = average(this.students.map((student) => student.numberOfSuccessfulExercises));
this.averageNumberOfParticipatedExercises = average(this.students.map((student) => student.numberOfParticipatedExercises));
for (const exerciseType of this.exerciseTypes) {
for (const exercise of this.exercisesPerType.get(exerciseType)!) {
exercise.averagePoints = sum(this.students.map((student) => student.pointsPerExercise.get(exercise.id!))) / this.students.length;
this.exerciseAveragePointsPerType.setValue(exerciseType, exercise, exercise.averagePoints);
this.exerciseParticipationsPerType.setValue(exerciseType, exercise, exercise.numberOfParticipationsWithRatedResult!);
this.exerciseSuccessfulPerType.setValue(exerciseType, exercise, exercise.numberOfSuccessfulParticipations!);
}
}
this.exportReady = true;
}
/**
* Goes through all participations and collects the found students.
* @return A map of the student`s id to the student.
* @private
*/
private mapStudentIdToStudentStatistics(): Map<number, CourseScoresStudentStatistics> {
const studentsMap = new Map<number, CourseScoresStudentStatistics>();
for (const participation of this.allParticipationsOfCourse) {
participation.results?.forEach((result) => (result.participation = participation));
// find all students by iterating through the participations
const participationStudents = participation.student ? [participation.student] : participation.team!.students!;
for (const participationStudent of participationStudents) {
let student = studentsMap.get(participationStudent.id!);
if (!student) {
student = new CourseScoresStudentStatistics(participationStudent);
studentsMap.set(participationStudent.id!, student);
}
student.participations.push(participation);
if (participation.presentationScore) {
student.presentationScore += participation.presentationScore;
}
}
}
return studentsMap;
}
/**
* Updates the student statistics with their result in the given exercise.
* @param student The student that should be updated.
* @param exercise The exercise that should be included in the statistics.
* @private
*/
private updateStudentStatisticsWithExerciseResults(student: CourseScoresStudentStatistics, exercise: Exercise) {
const relevantMaxPoints = exercise.maxPoints!;
const participation = student.participations.find((part) => part.exercise!.id === exercise.id);
if (participation && participation.results && participation.results.length > 0) {
// we found a result, there should only be one
const result = participation.results[0];
if (participation.results.length > 1) {
console.warn('found more than one result for student ' + student.user.login + ' and exercise ' + exercise.title);
}
// Note: It is important that we round on the individual exercise level first and then sum up.
// This is necessary so that the student arrives at the same overall result when doing his own recalculation.
// Let's assume that the student achieved 1.05 points in each of 5 exercises.
// In the client, these are now displayed rounded as 1.1 points.
// If the student adds up the displayed points, he gets a total of 5.5 points.
// In order to get the same total result as the student, we have to round before summing.
const pointsAchievedByStudentInExercise = roundValueSpecifiedByCourseSettings((result.score! * relevantMaxPoints) / 100, this.course);
student.pointsPerExercise.set(exercise.id!, pointsAchievedByStudentInExercise);
const includedIDs = this.exercisesOfCourseThatAreIncludedInScoreCalculation.map((includedExercise) => includedExercise.id);
// We only include this exercise if it is included in the exercise score
if (includedIDs.includes(exercise.id)) {
student.overallPoints += pointsAchievedByStudentInExercise;
const oldPointsSum = student.sumPointsPerExerciseType.get(exercise.type!)!;
student.sumPointsPerExerciseType.set(exercise.type!, oldPointsSum + pointsAchievedByStudentInExercise);
student.numberOfParticipatedExercises += 1;
exercise.numberOfParticipationsWithRatedResult! += 1;
if (result.score! >= 100) {
student.numberOfSuccessfulExercises += 1;
exercise.numberOfSuccessfulParticipations! += 1;
}
student.pointsPerExerciseType.setValue(exercise.type!, exercise, pointsAchievedByStudentInExercise);
}
} else {
// there is no result, the student has not participated or submitted too late
student.pointsPerExercise.set(exercise.id!, 0);
student.pointsPerExerciseType.setValue(exercise.type!, exercise, Number.NaN);
}
}
/**
* Sets grading scale related properties
* @param gradingScale the grading scale for the course
*/
calculateGradingScaleInformation(gradingScale: GradingScale) {
this.gradingScaleExists = true;
this.gradingScale = gradingScale;
this.gradingScale.gradeSteps = this.gradingSystemService.sortGradeSteps(this.gradingScale.gradeSteps);
this.isBonus = this.gradingScale.gradeType === GradeType.BONUS;
this.maxGrade = this.gradingSystemService.maxGrade(this.gradingScale.gradeSteps);
if (this.maxNumberOfOverallPoints >= 0) {
const overallPercentage = this.maxNumberOfOverallPoints > 0 ? (this.averageNumberOfOverallPoints / this.maxNumberOfOverallPoints) * 100 : 0;
this.averageGrade = this.gradingSystemService.findMatchingGradeStep(this.gradingScale.gradeSteps, overallPercentage)!.gradeName;
for (const student of this.students) {
const overallPercentageForStudent =
student.overallPoints > 0 && this.maxNumberOfOverallPoints > 0 ? (student.overallPoints / this.maxNumberOfOverallPoints) * 100 : 0;
student.gradeStep = this.gradingSystemService.findMatchingGradeStep(this.gradingScale.gradeSteps, overallPercentageForStudent);
}
}
this.changeDetector.detectChanges();
}
/**
* Localizes a number, e.g. switching the decimal separator
*/
localize(numberToLocalize: number): string {
return this.localeConversionService.toLocaleString(numberToLocalize, this.course.accuracyOfScores);
}
/**
* Method for exporting the csv with the needed data
*/
exportResults(customCsvOptions?: CsvExportOptions) {
if (!this.exportReady || this.students.length === 0) {
return;
}
const rows: ExportRow[] = [];
const keys = this.generateExportColumnNames();
this.students.forEach((student) => rows.push(this.generateStudentStatisticsExportRow(student, customCsvOptions)));
// empty row as separator
rows.push(this.prepareEmptyExportRow('', customCsvOptions).build());
rows.push(this.generateExportRowMaxValues(customCsvOptions));
rows.push(this.generateExportRowAverageValues(customCsvOptions));
rows.push(this.generateExportRowParticipation(customCsvOptions));
rows.push(this.generateExportRowSuccessfulParticipation(customCsvOptions));
if (customCsvOptions) {
// required because the currently used library for exporting to csv does not quote the header fields (keys)
const quotedKeys = keys.map((key) => customCsvOptions.quoteStrings + key + customCsvOptions.quoteStrings);
this.exportAsCsv(quotedKeys, rows, customCsvOptions);
} else {
this.exportAsExcel(keys, rows);
}
}
/**
* Builds an Excel workbook and starts the download.
* @param keys The column names used for the export.
* @param rows The data rows that should be part of the Excel file.
*/
exportAsExcel(keys: string[], rows: ExportRow[]) {
const workbook = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(rows, { header: keys });
const worksheetName = 'Course Scores';
XLSX.utils.book_append_sheet(workbook, ws, worksheetName);
const workbookProps = {
Title: `${this.course.title} Scores`,
Author: `Artemis ${VERSION ?? ''}`,
};
const fileName = `${this.course.title} Scores.xlsx`;
XLSX.writeFile(workbook, fileName, { Props: workbookProps, compression: true });
}
/**
* Builds the CSV from the rows and starts the download.
* @param keys The column names of the CSV.
* @param rows The data rows that should be part of the CSV.
* @param customOptions Custom csv options that should be used for export.
*/
exportAsCsv(keys: string[], rows: ExportRow[], customOptions: CsvExportOptions) {
const generalExportOptions = {
showLabels: true,
showTitle: false,
filename: `${this.course.title} Scores`,
useTextFile: false,
useBom: true,
headers: keys,
};
const combinedOptions = Object.assign(generalExportOptions, customOptions);
const csvExporter = new ExportToCsv(combinedOptions);
csvExporter.generateCsv(rows); // includes download
}
/**
* Constructs a new builder for a new CSV row.
* @param csvExportOptions If present, constructs a CSV row builder with these options, otherwise an Excel row builder is returned.
* @private
*/
private newRowBuilder(csvExportOptions?: CsvExportOptions): ExportRowBuilder {
if (csvExportOptions) {
return new CsvExportRowBuilder(csvExportOptions.decimalSeparator, this.course.accuracyOfScores);
} else {
return new ExcelExportRowBuilder(this.course.accuracyOfScores);
}
}
/**
* Generates the list of columns that should be part of the exported CSV or Excel file.
* @private
*/
private generateExportColumnNames(): Array<string> {
const keys = [NAME_KEY, USERNAME_KEY, EMAIL_KEY, REGISTRATION_NUMBER_KEY];
for (const exerciseType of this.exerciseTypesWithExercises) {
keys.push(...this.exercisesPerType.get(exerciseType)!.map((exercise) => exercise.title!));
keys.push(ExportRowBuilder.getExerciseTypeKey(exerciseType, POINTS_KEY));
keys.push(ExportRowBuilder.getExerciseTypeKey(exerciseType, SCORE_KEY));
}
keys.push(COURSE_OVERALL_POINTS_KEY, COURSE_OVERALL_SCORE_KEY);
if (this.course.presentationScore) {
keys.push(PRESENTATION_SCORE_KEY);
}
if (this.gradingScaleExists) {
keys.push(this.isBonus ? BONUS_KEY : GRADE_KEY);
}
return keys;
}
/**
* Generates a row used in the export file consisting of statistics for the given student.
* @param student The student for which an export row should be created.
* @param csvExportOptions If present, generates a CSV row with these options, otherwise an Excel row is generated.
* @private
*/
private generateStudentStatisticsExportRow(student: CourseScoresStudentStatistics, csvExportOptions?: CsvExportOptions): ExportRow {
const rowData = this.newRowBuilder(csvExportOptions);
rowData.setUserInformation(student.user.name, student.user.login, student.user.email, student.user.visibleRegistrationNumber);
for (const exerciseType of this.exerciseTypesWithExercises) {
const exercisePointsPerType = student.sumPointsPerExerciseType.get(exerciseType)!;
let exerciseScoresPerType = 0;
if (this.maxNumberOfPointsPerExerciseType.get(exerciseType)! > 0) {
exerciseScoresPerType = roundScorePercentSpecifiedByCourseSettings(
student.sumPointsPerExerciseType.get(exerciseType)! / this.maxNumberOfPointsPerExerciseType.get(exerciseType)!,
this.course,
);
}
const exercisesForType = this.exercisesPerType.get(exerciseType)!;
exercisesForType.forEach((exercise) => {
const points = roundValueSpecifiedByCourseSettings(student.pointsPerExerciseType.getValue(exerciseType, exercise), this.course);
rowData.setPoints(exercise.title!, points);
});
rowData.setExerciseTypePoints(exerciseType, exercisePointsPerType);
rowData.setExerciseTypeScore(exerciseType, exerciseScoresPerType);
}
const overallScore = roundScorePercentSpecifiedByCourseSettings(student.overallPoints / this.maxNumberOfOverallPoints, this.course);
rowData.setPoints(COURSE_OVERALL_POINTS_KEY, student.overallPoints);
rowData.setScore(COURSE_OVERALL_SCORE_KEY, overallScore);
if (this.course.presentationScore) {
rowData.setPoints(PRESENTATION_SCORE_KEY, student.presentationScore);
}
this.setExportRowGradeValue(rowData, student.gradeStep?.gradeName);
return rowData.build();
}
/**
* Generates a row for the exported csv with the maximum values of the various statistics.
* @param csvExportOptions If present, generates a CSV row with these options, otherwise an Excel row is generated.
* @private
*/
private generateExportRowMaxValues(csvExportOptions?: CsvExportOptions): ExportRow {
const rowData = this.prepareEmptyExportRow('Max', csvExportOptions);
for (const exerciseType of this.exerciseTypesWithExercises) {
const exercisesForType = this.exercisesPerType.get(exerciseType)!;
exercisesForType.forEach((exercise) => {
rowData.setPoints(exercise.title!, this.exerciseMaxPointsPerType.getValue(exerciseType, exercise) ?? 0);
});
rowData.setExerciseTypePoints(exerciseType, this.maxNumberOfPointsPerExerciseType.get(exerciseType)!);
rowData.setExerciseTypeScore(exerciseType, 100);
}
rowData.setPoints(COURSE_OVERALL_POINTS_KEY, this.maxNumberOfOverallPoints);
rowData.setScore(COURSE_OVERALL_SCORE_KEY, 100);
if (this.course.presentationScore) {
rowData.set(PRESENTATION_SCORE_KEY, '');
}
this.setExportRowGradeValue(rowData, this.maxGrade);
return rowData.build();
}
/**
* Generates a row for the exported csv with the average values of the various statistics.
* @param csvExportOptions If present, generates a CSV row with these options, otherwise an Excel row is generated.
* @private
*/
private generateExportRowAverageValues(csvExportOptions?: CsvExportOptions): ExportRow {
const rowData = this.prepareEmptyExportRow('Average', csvExportOptions);
for (const exerciseType of this.exerciseTypesWithExercises) {
const exercisesForType = this.exercisesPerType.get(exerciseType)!;
exercisesForType.forEach((exercise) => {
const points = roundValueSpecifiedByCourseSettings(this.exerciseAveragePointsPerType.getValue(exerciseType, exercise), this.course);
rowData.setPoints(exercise.title!, points);
});
const averageScore = roundScorePercentSpecifiedByCourseSettings(
this.averageNumberOfPointsPerExerciseTypes.get(exerciseType)! / this.maxNumberOfPointsPerExerciseType.get(exerciseType)!,
this.course,
);
rowData.setExerciseTypePoints(exerciseType, this.averageNumberOfPointsPerExerciseTypes.get(exerciseType)!);
rowData.setExerciseTypeScore(exerciseType, averageScore);
}
const averageOverallScore = roundScorePercentSpecifiedByCourseSettings(this.averageNumberOfOverallPoints / this.maxNumberOfOverallPoints, this.course);
rowData.setPoints(COURSE_OVERALL_POINTS_KEY, this.averageNumberOfOverallPoints);
rowData.setScore(COURSE_OVERALL_SCORE_KEY, averageOverallScore);
if (this.course.presentationScore) {
rowData.set(PRESENTATION_SCORE_KEY, '');
}
this.setExportRowGradeValue(rowData, this.averageGrade);
return rowData.build();
}
/**
* Generates a row for the exported Csv with information about the number of participants.
* @param csvExportOptions If present, generates a CSV row with these options, otherwise an Excel row is generated.
* @private
*/
private generateExportRowParticipation(csvExportOptions?: CsvExportOptions): ExportRow {
const rowData = this.prepareEmptyExportRow('Number of Participations', csvExportOptions);
for (const exerciseType of this.exerciseTypesWithExercises) {
const exercisesForType = this.exercisesPerType.get(exerciseType)!;
exercisesForType.forEach((exercise) => {
rowData.setPoints(exercise.title!, this.exerciseParticipationsPerType.getValue(exerciseType, exercise) ?? 0);
});
rowData.setExerciseTypePoints(exerciseType, '');
rowData.setExerciseTypeScore(exerciseType, '');
}
this.setExportRowGradeValue(rowData, '');
return rowData.build();
}
/**
* Generates a row for the exported Csv with information about the number of successful participants.
* @param csvExportOptions If present, generates a CSV row with these options, otherwise an Excel row is generated.
* @private
*/
private generateExportRowSuccessfulParticipation(csvExportOptions?: CsvExportOptions): ExportRow {
const rowData = this.prepareEmptyExportRow('Number of Successful Participations', csvExportOptions);
for (const exerciseType of this.exerciseTypesWithExercises) {
const exercisesForType = this.exercisesPerType.get(exerciseType)!;
exercisesForType.forEach((exercise) => {
rowData.setPoints(exercise.title!, this.exerciseSuccessfulPerType.getValue(exerciseType, exercise) ?? 0);
});
rowData.setExerciseTypePoints(exerciseType, '');
rowData.setExerciseTypeScore(exerciseType, '');
}
this.setExportRowGradeValue(rowData, '');
return rowData.build();
}
/**
* Prepares an empty row (except for the first column) with an empty column for each exercise type.
* @param firstValue The value that should be placed in the first column of the row.
* @param csvExportOptions If present, generates a CSV row with these options, otherwise an Excel row is generated.
*/
private prepareEmptyExportRow(firstValue: string, csvExportOptions?: CsvExportOptions): ExportRow {
const emptyLine = this.newRowBuilder(csvExportOptions);
emptyLine.set(NAME_KEY, firstValue);
emptyLine.set(USERNAME_KEY, '');
emptyLine.set(EMAIL_KEY, '');
emptyLine.set(REGISTRATION_NUMBER_KEY, '');
emptyLine.set(COURSE_OVERALL_POINTS_KEY, '');
emptyLine.set(COURSE_OVERALL_SCORE_KEY, '');
for (const exerciseType of this.exerciseTypesWithExercises) {
const exercisesForType = this.exercisesPerType.get(exerciseType)!;
exercisesForType.forEach((exercise) => {
emptyLine.set(exercise.title!, '');
});
emptyLine.setExerciseTypePoints(exerciseType, '');
emptyLine.setExerciseTypeScore(exerciseType, '');
}
if (this.course.presentationScore) {
emptyLine.set(PRESENTATION_SCORE_KEY, '');
}
this.setExportRowGradeValue(emptyLine, '');
return emptyLine;
}
/**
* Puts the given value into the grading scale column of the Export row.
* @param exportRow The row in which the value should be stored.
* @param value The value that should be stored in the row.
* @private
*/
private setExportRowGradeValue(exportRow: ExportRow, value: string | number | undefined) {
if (this.gradingScaleExists) {
if (this.isBonus) {
exportRow.set(BONUS_KEY, value);
} else {
exportRow.set(GRADE_KEY, value);
}
}
}
/**
* Compares two exercises to determine which should be first in a sorted list.
*
* Compares them by due date first, then title.
* @param e1 Some exercise.
* @param e2 Another exercise.
* @private
*/
private static compareExercises(e1: Exercise, e2: Exercise): number {
if (e1.dueDate! > e2.dueDate!) {
return 1;
}
if (e1.dueDate! < e2.dueDate!) {
return -1;
}
if (e1.title! > e2.title!) {
return 1;
}
if (e1.title! < e2.title!) {
return -1;
}
return 0;
}
/**
* Filters the course exercises and returns the exercises that are already released or do not have a release date
* @param course the course whose exercises are filtered
* @private
*/
private determineReleasedExercises(course: Course): Exercise[] {
return course.exercises!.filter((exercise) => !exercise.releaseDate || exercise.releaseDate.isBefore(dayjs()));
}
/**
* Computes the average of given scores and returns it rounded based on course settings
* @param scores the scores the average should be computed of
* @private
*/
private calculateAverageScore(scores: number[]): number {
return roundScorePercentSpecifiedByCourseSettings(mean(scores), this.course);
}
/**
* Computes the average of given points and returns it rounded based on course settings
* @param points the points the average should be computed of
* @private
*/
private calculateAveragePoints(points: number[]): number {
return roundValueSpecifiedByCourseSettings(mean(points), this.course);
}
/**
* Computes the median of given scores and returns it rounded based on course settings
* @param scores the scores the median should be computed of
* @private
*/
private calculateMedianScore(scores: number[]): number {
return roundScorePercentSpecifiedByCourseSettings(median(scores), this.course);
}
/**
* Computes the median of given points and returns it rounded based on course settings
* @param points the points the median should be computed of
* @private
*/
private calculateMedianPoints(points: number[]): number {
return roundValueSpecifiedByCourseSettings(median(points), this.course);
}
/**
* Sets the statistical values displayed in the table next to the distribution chart
* @private
*/
private calculateAverageAndMedianScores(): void {
const allCoursePoints = sum(this.course.exercises!.map((exercise) => exercise.maxPoints ?? 0));
const includedPointsPerStudent = this.students.map((student) => student.overallPoints);
// average points and score included
const scores = includedPointsPerStudent.map((point) => point / this.maxNumberOfOverallPoints);
this.averageScoreIncluded = roundScorePercentSpecifiedByCourseSettings(this.averageNumberOfOverallPoints / this.maxNumberOfOverallPoints, this.course);
// average points and score total
const achievedPointsTotal = this.students.map((student) => sum(Array.from(student.pointsPerExercise.values())));
const averageScores = achievedPointsTotal.map((totalPoints) => totalPoints / allCoursePoints);
this.averagePointsTotal = this.calculateAveragePoints(achievedPointsTotal);
this.averageScoreTotal = this.calculateAverageScore(averageScores);
// median points and score included
this.medianPointsIncluded = this.calculateMedianPoints(includedPointsPerStudent);
this.medianScoreIncluded = this.calculateMedianScore(scores);
// median points and score total
this.medianPointsTotal = this.calculateMedianPoints(achievedPointsTotal);
this.medianScoreTotal = this.calculateMedianScore(averageScores);
// Since these two values are only statistical details, there is no need to make the rounding dependent of the course settings
// standard deviation points included
this.standardDeviationPointsIncluded = round(standardDeviation(includedPointsPerStudent), 2);
// standard deviation points total
this.standardDeviationPointsTotal = round(standardDeviation(achievedPointsTotal), 2);
}
/**
* Handles the case if the user selects either the average or the median in the table next to the chart
* @param type the statistical type that is selected by the user
*/
highlightBar(type: HighlightType) {
if (this.highlightedType === type) {
this.valueToHighlight = undefined;
this.highlightedType = HighlightType.NONE;
this.changeDetector.detectChanges();
return;
}
switch (type) {
case HighlightType.AVERAGE:
this.valueToHighlight = this.averageScoreIncluded;
this.highlightedType = HighlightType.AVERAGE;
break;
case HighlightType.MEDIAN:
this.valueToHighlight = this.medianScoreIncluded;
this.highlightedType = HighlightType.MEDIAN;
break;
}
this.changeDetector.detectChanges();
}
/**
* Handles the click on an arbitrary bar in the score distribution
* Delegates the user to the participant scores view of the course
*/
accessParticipantScores(): void {
this.navigationUtilService.routeInNewTab(['course-management', this.course.id, 'participant-scores']);
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { CustomLocations } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { CustomLocationsManagementClientContext } from "../customLocationsManagementClientContext";
import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro";
import { LroImpl } from "../lroImpl";
import {
CustomLocationOperation,
CustomLocationsListOperationsNextOptionalParams,
CustomLocationsListOperationsOptionalParams,
CustomLocation,
CustomLocationsListBySubscriptionNextOptionalParams,
CustomLocationsListBySubscriptionOptionalParams,
CustomLocationsListByResourceGroupNextOptionalParams,
CustomLocationsListByResourceGroupOptionalParams,
EnabledResourceType,
CustomLocationsListEnabledResourceTypesNextOptionalParams,
CustomLocationsListEnabledResourceTypesOptionalParams,
CustomLocationsListOperationsResponse,
CustomLocationsListBySubscriptionResponse,
CustomLocationsListByResourceGroupResponse,
CustomLocationsGetOptionalParams,
CustomLocationsGetResponse,
CustomLocationsCreateOrUpdateOptionalParams,
CustomLocationsCreateOrUpdateResponse,
CustomLocationsDeleteOptionalParams,
CustomLocationsUpdateOptionalParams,
CustomLocationsUpdateResponse,
CustomLocationsListEnabledResourceTypesResponse,
CustomLocationsListOperationsNextResponse,
CustomLocationsListBySubscriptionNextResponse,
CustomLocationsListByResourceGroupNextResponse,
CustomLocationsListEnabledResourceTypesNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing CustomLocations operations. */
export class CustomLocationsImpl implements CustomLocations {
private readonly client: CustomLocationsManagementClientContext;
/**
* Initialize a new instance of the class CustomLocations class.
* @param client Reference to the service client
*/
constructor(client: CustomLocationsManagementClientContext) {
this.client = client;
}
/**
* Lists all available Custom Locations operations.
* @param options The options parameters.
*/
public listOperations(
options?: CustomLocationsListOperationsOptionalParams
): PagedAsyncIterableIterator<CustomLocationOperation> {
const iter = this.listOperationsPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listOperationsPagingPage(options);
}
};
}
private async *listOperationsPagingPage(
options?: CustomLocationsListOperationsOptionalParams
): AsyncIterableIterator<CustomLocationOperation[]> {
let result = await this._listOperations(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listOperationsNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listOperationsPagingAll(
options?: CustomLocationsListOperationsOptionalParams
): AsyncIterableIterator<CustomLocationOperation> {
for await (const page of this.listOperationsPagingPage(options)) {
yield* page;
}
}
/**
* Gets a list of Custom Locations in the specified subscription. The operation returns properties of
* each Custom Location
* @param options The options parameters.
*/
public listBySubscription(
options?: CustomLocationsListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<CustomLocation> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: CustomLocationsListBySubscriptionOptionalParams
): AsyncIterableIterator<CustomLocation[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listBySubscriptionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listBySubscriptionPagingAll(
options?: CustomLocationsListBySubscriptionOptionalParams
): AsyncIterableIterator<CustomLocation> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* Gets a list of Custom Locations in the specified subscription and resource group. The operation
* returns properties of each Custom Location.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: CustomLocationsListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<CustomLocation> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: CustomLocationsListByResourceGroupOptionalParams
): AsyncIterableIterator<CustomLocation[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: CustomLocationsListByResourceGroupOptionalParams
): AsyncIterableIterator<CustomLocation> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Gets the list of the Enabled Resource Types.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param options The options parameters.
*/
public listEnabledResourceTypes(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsListEnabledResourceTypesOptionalParams
): PagedAsyncIterableIterator<EnabledResourceType> {
const iter = this.listEnabledResourceTypesPagingAll(
resourceGroupName,
resourceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listEnabledResourceTypesPagingPage(
resourceGroupName,
resourceName,
options
);
}
};
}
private async *listEnabledResourceTypesPagingPage(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsListEnabledResourceTypesOptionalParams
): AsyncIterableIterator<EnabledResourceType[]> {
let result = await this._listEnabledResourceTypes(
resourceGroupName,
resourceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listEnabledResourceTypesNext(
resourceGroupName,
resourceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listEnabledResourceTypesPagingAll(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsListEnabledResourceTypesOptionalParams
): AsyncIterableIterator<EnabledResourceType> {
for await (const page of this.listEnabledResourceTypesPagingPage(
resourceGroupName,
resourceName,
options
)) {
yield* page;
}
}
/**
* Lists all available Custom Locations operations.
* @param options The options parameters.
*/
private _listOperations(
options?: CustomLocationsListOperationsOptionalParams
): Promise<CustomLocationsListOperationsResponse> {
return this.client.sendOperationRequest(
{ options },
listOperationsOperationSpec
);
}
/**
* Gets a list of Custom Locations in the specified subscription. The operation returns properties of
* each Custom Location
* @param options The options parameters.
*/
private _listBySubscription(
options?: CustomLocationsListBySubscriptionOptionalParams
): Promise<CustomLocationsListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* Gets a list of Custom Locations in the specified subscription and resource group. The operation
* returns properties of each Custom Location.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: CustomLocationsListByResourceGroupOptionalParams
): Promise<CustomLocationsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Gets the details of the customLocation with a specified resource group and name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsGetOptionalParams
): Promise<CustomLocationsGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, options },
getOperationSpec
);
}
/**
* Creates or updates a Custom Location in the specified Subscription and Resource Group
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param parameters Parameters supplied to create or update a Custom Location.
* @param options The options parameters.
*/
async beginCreateOrUpdate(
resourceGroupName: string,
resourceName: string,
parameters: CustomLocation,
options?: CustomLocationsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<CustomLocationsCreateOrUpdateResponse>,
CustomLocationsCreateOrUpdateResponse
>
> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<CustomLocationsCreateOrUpdateResponse> => {
return this.client.sendOperationRequest(args, spec);
};
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,
{ resourceGroupName, resourceName, parameters, options },
createOrUpdateOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "azure-async-operation"
});
}
/**
* Creates or updates a Custom Location in the specified Subscription and Resource Group
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param parameters Parameters supplied to create or update a Custom Location.
* @param options The options parameters.
*/
async beginCreateOrUpdateAndWait(
resourceGroupName: string,
resourceName: string,
parameters: CustomLocation,
options?: CustomLocationsCreateOrUpdateOptionalParams
): Promise<CustomLocationsCreateOrUpdateResponse> {
const poller = await this.beginCreateOrUpdate(
resourceGroupName,
resourceName,
parameters,
options
);
return poller.pollUntilDone();
}
/**
* Deletes the Custom Location with the specified Resource Name, Resource Group, and Subscription Id.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param options The options parameters.
*/
async beginDelete(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>> {
const directSendOperation = async (
args: coreClient.OperationArguments,
spec: coreClient.OperationSpec
): Promise<void> => {
return this.client.sendOperationRequest(args, spec);
};
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,
{ resourceGroupName, resourceName, options },
deleteOperationSpec
);
return new LroEngine(lro, {
resumeFrom: options?.resumeFrom,
intervalInMs: options?.updateIntervalInMs,
lroResourceLocationConfig: "azure-async-operation"
});
}
/**
* Deletes the Custom Location with the specified Resource Name, Resource Group, and Subscription Id.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param options The options parameters.
*/
async beginDeleteAndWait(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsDeleteOptionalParams
): Promise<void> {
const poller = await this.beginDelete(
resourceGroupName,
resourceName,
options
);
return poller.pollUntilDone();
}
/**
* Updates a Custom Location with the specified Resource Name in the specified Resource Group and
* Subscription.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsUpdateOptionalParams
): Promise<CustomLocationsUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, options },
updateOperationSpec
);
}
/**
* Gets the list of the Enabled Resource Types.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param options The options parameters.
*/
private _listEnabledResourceTypes(
resourceGroupName: string,
resourceName: string,
options?: CustomLocationsListEnabledResourceTypesOptionalParams
): Promise<CustomLocationsListEnabledResourceTypesResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, options },
listEnabledResourceTypesOperationSpec
);
}
/**
* ListOperationsNext
* @param nextLink The nextLink from the previous successful call to the ListOperations method.
* @param options The options parameters.
*/
private _listOperationsNext(
nextLink: string,
options?: CustomLocationsListOperationsNextOptionalParams
): Promise<CustomLocationsListOperationsNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listOperationsNextOperationSpec
);
}
/**
* ListBySubscriptionNext
* @param nextLink The nextLink from the previous successful call to the ListBySubscription method.
* @param options The options parameters.
*/
private _listBySubscriptionNext(
nextLink: string,
options?: CustomLocationsListBySubscriptionNextOptionalParams
): Promise<CustomLocationsListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listBySubscriptionNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: CustomLocationsListByResourceGroupNextOptionalParams
): Promise<CustomLocationsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
/**
* ListEnabledResourceTypesNext
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param resourceName Custom Locations name.
* @param nextLink The nextLink from the previous successful call to the ListEnabledResourceTypes
* method.
* @param options The options parameters.
*/
private _listEnabledResourceTypesNext(
resourceGroupName: string,
resourceName: string,
nextLink: string,
options?: CustomLocationsListEnabledResourceTypesNextOptionalParams
): Promise<CustomLocationsListEnabledResourceTypesNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, resourceName, nextLink, options },
listEnabledResourceTypesNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationsOperationSpec: coreClient.OperationSpec = {
path: "/providers/Microsoft.ExtendedLocation/operations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocationOperationsList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.ExtendedLocation/customLocations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocationListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ExtendedLocation/customLocations",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocationListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ExtendedLocation/customLocations/{resourceName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocation
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ExtendedLocation/customLocations/{resourceName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.CustomLocation
},
201: {
bodyMapper: Mappers.CustomLocation
},
202: {
bodyMapper: Mappers.CustomLocation
},
204: {
bodyMapper: Mappers.CustomLocation
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ExtendedLocation/customLocations/{resourceName}",
httpMethod: "DELETE",
responses: {
200: {},
201: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ExtendedLocation/customLocations/{resourceName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.CustomLocation
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: {
parameterPath: {
identity: ["options", "identity"],
tags: ["options", "tags"],
authentication: ["options", "authentication"],
clusterExtensionIds: ["options", "clusterExtensionIds"],
displayName: ["options", "displayName"],
hostResourceId: ["options", "hostResourceId"],
hostType: ["options", "hostType"],
namespace: ["options", "namespace"],
provisioningState: ["options", "provisioningState"]
},
mapper: { ...Mappers.PatchableCustomLocations, required: true }
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listEnabledResourceTypesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ExtendedLocation/customLocations/{resourceName}/enabledResourceTypes",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.EnabledResourceTypesListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName
],
headerParameters: [Parameters.accept],
serializer
};
const listOperationsNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocationOperationsList
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocationListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CustomLocationListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listEnabledResourceTypesNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.EnabledResourceTypesListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.resourceName,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { Injectable } from '@angular/core';
import { arrayModelType } from './expression-language/array.model.type';
import { dateModelType } from './expression-language/date.model.type';
import { eventSchema } from './expression-language/event-schema';
import { jsonModelType } from './expression-language/json.model.type';
import { stringModelType } from './expression-language/string.model.type';
import { ModelingType, ModelingTypeMap, ModelingTypeMethodDescription, ModelingTypePropertyDescription } from './modeling-type-provider.service';
export interface JSONRef {
$ref: string;
}
export interface JSONSchemaInfoBasics {
anyOf?: JSONSchemaPropertyBasics[] | JSONRef[] | JSONSchemaInfoBasics[];
allOf?: JSONSchemaPropertyBasics[] | JSONRef[] | JSONSchemaInfoBasics[];
type?: string | string[] | JSONRef[];
properties?: JSONSchemaPropertyBasics;
items?: JSONRef[] | JSONSchemaPropertyBasics[] | JSONSchemaInfoBasics;
description?: string;
$ref?: string;
}
export interface JSONSchemaPropertyBasics {
[name: string]: JSONSchemaInfoBasics;
}
@Injectable({
providedIn: 'root'
})
export class JSONSchemaToModelingTypesService {
public static readonly EVENT_PREFIX = 'event-';
getPrimitiveModelingTypesFromJSONSchema(jsonSchema: JSONSchemaInfoBasics): ModelingTypeMap {
return this.getModelingTypesFromJSONSchema(jsonSchema, null);
}
getModelingTypesFromJSONSchema(
jsonSchema: JSONSchemaInfoBasics,
schemaName: string,
...existingModelingTypes: ModelingTypeMap[]
): ModelingTypeMap {
let modelingTypes = {};
if (existingModelingTypes?.length > 0) {
existingModelingTypes.forEach(existingTypes => modelingTypes = { ...modelingTypes, ...existingTypes });
}
if (jsonSchema.anyOf) {
this.addModelingType(this.addTypeFromArrayOfTypes(jsonSchema.anyOf, modelingTypes, schemaName, jsonSchema, schemaName), schemaName, modelingTypes, true);
} else if (jsonSchema.allOf) {
this.addModelingType(this.addTypeFromArrayOfTypes(jsonSchema.allOf, modelingTypes, schemaName, jsonSchema, schemaName), schemaName, modelingTypes, true);
} else if (jsonSchema.type) {
switch (jsonSchema.type) {
case 'object':
this.addModelingType({
id: schemaName,
methods: jsonModelType.methods,
properties: this.getProperties(jsonSchema.properties, modelingTypes, schemaName, jsonSchema, schemaName)
}, schemaName, modelingTypes);
break;
case 'array':
this.addModelingType({
id: schemaName,
methods: arrayModelType.methods,
properties: arrayModelType.properties,
collectionOf: this.getArrayCollectionType(jsonSchema.items, modelingTypes, schemaName, jsonSchema, schemaName)
}, schemaName, modelingTypes);
break;
case 'string':
modelingTypes[schemaName] = { ...stringModelType, id: schemaName };
break;
default:
modelingTypes[schemaName] = {
id: schemaName
};
break;
}
}
if (existingModelingTypes?.length > 0) {
existingModelingTypes.forEach(existingTypes => { Object.keys(existingTypes).forEach(key => delete modelingTypes[key]); });
}
return modelingTypes;
}
getModelingTypesFromEventDataJSONSchema(dataJsonSchema: JSONSchemaInfoBasics, schemaName: string) {
const dataModelingTypes = this.getModelingTypesFromJSONSchema(dataJsonSchema, JSONSchemaToModelingTypesService.EVENT_PREFIX + schemaName + '-data');
const eventSchemaModelingTypes = this.getModelingTypesFromJSONSchema(eventSchema, 'event');
const jsonSchema = {
allOf: [
{
type: 'event'
},
{
type: 'object',
properties: {
data: {
type: JSONSchemaToModelingTypesService.EVENT_PREFIX + schemaName + '-data'
}
}
}
]
};
const result = this.getModelingTypesFromJSONSchema(jsonSchema, JSONSchemaToModelingTypesService.EVENT_PREFIX + schemaName, eventSchemaModelingTypes, dataModelingTypes);
return { ...result, ...dataModelingTypes };
}
private addTypeFromArrayOfTypes(
jsonTypesArray: JSONSchemaPropertyBasics[] | JSONRef[] | JSONSchemaInfoBasics[],
modelingTypes: ModelingTypeMap,
typeName: string,
originalJsonSchema: JSONSchemaInfoBasics,
schemaName: string
): ModelingType {
const items: ModelingType[] = this.getModelingTypesFromArray(typeName, jsonTypesArray, modelingTypes, originalJsonSchema, schemaName);
return this.mergeTypes(items, typeName);
}
private mergeTypes(items: ModelingType[], typeName: string) {
let methods = [];
let properties = [];
let collectionOf = null;
items.forEach(item => {
if (item?.methods) {
item.methods.forEach(method => {
if (!methods.find(existingMethod => method.signature === existingMethod.signature && method.parameters === existingMethod.parameters)) {
methods = methods.concat(method);
}
});
}
if (item?.properties) {
item.properties.forEach(itemProperty => {
if (!properties.find(existingProperty => itemProperty.property === existingProperty.property)) {
properties = properties.concat(itemProperty);
}
});
}
if (item?.collectionOf) {
collectionOf = item.collectionOf;
}
});
const modelingType: ModelingType = {
id: typeName,
methods: methods,
properties: properties
};
if (collectionOf) {
modelingType.collectionOf = collectionOf;
}
return modelingType;
}
private getModelingTypesFromArray(
name: string,
jsonTypesArray: JSONSchemaPropertyBasics[] | JSONRef[] | JSONSchemaInfoBasics[],
modelingTypes: ModelingTypeMap,
originalJsonSchema: JSONSchemaInfoBasics,
schemaName: string
): ModelingType[] {
const modelingTypesArray: ModelingType[] = [];
jsonTypesArray.forEach(type => {
const typeName = this.getType(name, type, modelingTypes, null, originalJsonSchema, schemaName);
modelingTypesArray.push(modelingTypes[typeName]);
});
return modelingTypesArray;
}
private getProperties(
properties: JSONSchemaPropertyBasics,
modelingTypes: ModelingTypeMap,
prefix: string,
originalJsonSchema: JSONSchemaInfoBasics,
schemaName: string
): ModelingTypePropertyDescription[] {
const typeProperties: ModelingTypePropertyDescription[] = [];
if (properties) {
Object.keys(properties).forEach(property => {
typeProperties.push({
property,
documentation: properties[property].description,
type: this.getType(property, properties[property], modelingTypes, prefix, originalJsonSchema, schemaName)
});
});
}
return typeProperties;
}
private getType(
name: string,
property: JSONSchemaInfoBasics,
modelingTypes: ModelingTypeMap,
prefix: string,
originalJsonSchema: JSONSchemaInfoBasics,
schemaName: string
): string {
let typeName = this.getTypeName(prefix, name);
if (property.anyOf) {
this.addModelingType(this.addTypeFromArrayOfTypes(property.anyOf, modelingTypes, typeName, originalJsonSchema, schemaName), typeName, modelingTypes, true);
} else if (property.allOf) {
this.addModelingType(this.addTypeFromArrayOfTypes(property.allOf, modelingTypes, typeName, originalJsonSchema, schemaName), typeName, modelingTypes, true);
} else if (property.type) {
if (Array.isArray(property.type)) {
const items = [];
property.type.forEach(item => {
const itemName = this.getType(name, item, modelingTypes, prefix, originalJsonSchema, schemaName);
items.push(modelingTypes[itemName]);
});
const modelingType = this.mergeTypes(items, typeName);
this.addModelingType(modelingType, typeName, modelingTypes);
} else {
switch (property.type) {
case 'object':
this.addModelingType({
id: typeName,
methods: jsonModelType.methods,
properties: this.getProperties(property.properties, modelingTypes, typeName, originalJsonSchema, schemaName)
}, typeName, modelingTypes);
break;
case 'array':
this.addModelingType({
id: typeName,
methods: arrayModelType.methods || [],
properties: arrayModelType.properties || [],
collectionOf: this.getArrayCollectionType(property.items, modelingTypes, typeName, originalJsonSchema, schemaName)
}, typeName, modelingTypes);
break;
case 'string':
if (!schemaName) {
this.addModelingType({
id: 'string',
properties: stringModelType.properties || [],
methods: stringModelType.methods || []
}, 'string', modelingTypes);
}
typeName = 'string';
break;
case 'number':
if (!schemaName) {
this.addModelingType({
id: 'integer'
}, 'integer', modelingTypes);
}
typeName = 'integer';
break;
default:
if (!schemaName) {
this.addModelingType({
id: property.type
}, property.type, modelingTypes);
}
typeName = property.type;
break;
}
}
} else if (property.$ref) {
typeName = this.getTypeFromReference(property.$ref, modelingTypes, originalJsonSchema, schemaName);
}
return typeName;
}
private getTypeFromReference($ref: string, modelingTypes: ModelingTypeMap, originalJsonSchema: JSONSchemaInfoBasics, schemaName: string): string {
const path = $ref.split('/');
let jsonNode = originalJsonSchema;
for (let index = 1; index < path.length - 1; index++) {
jsonNode = jsonNode[path[index]];
}
const nodeName = path[path.length - 1];
return this.getType(nodeName, jsonNode[nodeName], modelingTypes, schemaName ? schemaName : null, originalJsonSchema, schemaName);
}
private getArrayCollectionType(
items: JSONRef[] | JSONSchemaPropertyBasics[] | JSONSchemaInfoBasics,
modelingTypes: ModelingTypeMap,
prefix: string,
originalJsonSchema: JSONSchemaInfoBasics,
schemaName: string
): string {
let typeName: string;
const name = 'array';
if (Array.isArray(items)) {
let methods: ModelingTypeMethodDescription[] = [];
let properties: ModelingTypePropertyDescription[] = [];
items.forEach(item => {
if (item.$ref) {
typeName = this.getType(name, item, modelingTypes, prefix, originalJsonSchema, schemaName);
} else {
Object.keys(item).forEach(key => {
typeName = this.getType(key, item, modelingTypes, prefix, originalJsonSchema, schemaName);
methods = methods.concat(modelingTypes[typeName].methods);
properties = properties.concat(modelingTypes[typeName].properties);
});
typeName = this.getTypeName(name, prefix);
this.addModelingType({
id: typeName,
methods: methods,
properties: properties
}, this.getTypeName(name, prefix), modelingTypes);
}
});
} else {
typeName = this.getType(name, items, modelingTypes, prefix, originalJsonSchema, schemaName);
}
return typeName;
}
private addModelingType(modelingType: ModelingType, typeName: string, modelingTypes: ModelingTypeMap, force = false) {
if (typeName && (!modelingTypes[typeName] || force)) {
if (typeName === 'date' || typeName === 'datetime') {
modelingType = { ...dateModelType, id: typeName };
}
modelingTypes[typeName] = modelingType;
}
}
private getTypeName(prefix: string, name: string) {
let typeName = name;
if (name) {
typeName = prefix ? prefix + '-' + name : name;
}
return typeName;
}
} | the_stack |
* @packageDocumentation
* @module IMessage
*/
import type { AnyJson } from '@polkadot/types/types'
import type { DidSignature, IDidDetails, IDidKeyDetails } from './DidDetails'
import type { CompressedAttestation, IAttestation } from './Attestation'
import type { CompressedCredential, ICredential } from './Credential'
import type { IClaim, IClaimContents, PartialClaim } from './Claim'
import type { ICType } from './CType'
import type { IDelegationNode } from './Delegation'
import type { CompressedQuoteAgreed, IQuoteAgreement } from './Quote'
import type {
CompressedRequestForAttestation,
IRequestForAttestation,
} from './RequestForAttestation'
import type { CompressedTerms, ITerms } from './Terms'
export enum MessageBodyType {
ERROR = 'error',
REJECT = 'reject',
REQUEST_TERMS = 'request-terms',
SUBMIT_TERMS = 'submit-terms',
REJECT_TERMS = 'reject-terms',
REQUEST_ATTESTATION = 'request-attestation',
SUBMIT_ATTESTATION = 'submit-attestation',
REJECT_ATTESTATION = 'reject-attestation',
REQUEST_PAYMENT = 'request-payment',
CONFIRM_PAYMENT = 'confirm-payment',
REQUEST_CREDENTIAL = 'request-credential',
SUBMIT_CREDENTIAL = 'submit-credential',
ACCEPT_CREDENTIAL = 'accept-credential',
REJECT_CREDENTIAL = 'reject-credential',
REQUEST_ACCEPT_DELEGATION = 'request-accept-delegation',
SUBMIT_ACCEPT_DELEGATION = 'submit-accept-delegation',
REJECT_ACCEPT_DELEGATION = 'reject-accept-delegation',
INFORM_CREATE_DELEGATION = 'inform-create-delegation',
}
export type CompressedDelegationData = [
IDelegationNode['account'],
IDelegationNode['id'],
IDelegationNode['id'],
IDelegationNode['permissions'],
boolean
]
interface IMessageBodyBase {
content: any
type: MessageBodyType
}
export interface IError extends IMessageBodyBase {
content: {
/** Optional machine-readable type of the error. */
name?: string
/** Optional human-readable description of the error. */
message?: string
}
type: MessageBodyType.ERROR
}
export interface IReject extends IMessageBodyBase {
content: {
/** Optional machine-readable type of the rejection. */
name?: string
/** Optional human-readable description of the rejection. */
message?: string
}
type: MessageBodyType.REJECT
}
export interface IRequestTerms extends IMessageBodyBase {
content: PartialClaim
type: MessageBodyType.REQUEST_TERMS
}
export interface ISubmitTerms extends IMessageBodyBase {
content: ITerms
type: MessageBodyType.SUBMIT_TERMS
}
export interface IRejectTerms extends IMessageBodyBase {
content: {
claim: PartialClaim
legitimations: ICredential[]
delegationId?: IDelegationNode['id']
}
type: MessageBodyType.REJECT_TERMS
}
export interface ISubmitCredential extends IMessageBodyBase {
content: ICredential[]
type: MessageBodyType.SUBMIT_CREDENTIAL
}
export interface IAcceptCredential extends IMessageBodyBase {
content: Array<ICType['hash']>
type: MessageBodyType.ACCEPT_CREDENTIAL
}
export interface IRejectCredential extends IMessageBodyBase {
content: Array<ICType['hash']>
type: MessageBodyType.REJECT_CREDENTIAL
}
export type CompressedSubmitTerms = [
MessageBodyType.SUBMIT_TERMS,
CompressedTerms
]
export type CompressedSubmitAttestation = [
MessageBodyType.SUBMIT_ATTESTATION,
CompressedAttestation
]
export type CompressedRejectAttestation = [
MessageBodyType.REJECT_ATTESTATION,
IRequestForAttestation['rootHash']
]
export type CompressedSubmitCredentials = [
MessageBodyType.SUBMIT_CREDENTIAL,
CompressedCredential[]
]
export type CompressedAcceptCredential = [
MessageBodyType.ACCEPT_CREDENTIAL,
Array<ICType['hash']>
]
export type CompressedRejectCredential = [
MessageBodyType.REJECT_CREDENTIAL,
Array<ICType['hash']>
]
export type CompressedRejectAcceptDelegation = [
MessageBodyType.REJECT_ACCEPT_DELEGATION,
CompressedDelegationData
]
export interface IRequestAttestationContent {
requestForAttestation: IRequestForAttestation
quote?: IQuoteAgreement
}
export interface IRequestAttestation extends IMessageBodyBase {
content: IRequestAttestationContent
type: MessageBodyType.REQUEST_ATTESTATION
}
export interface ISubmitAttestationContent {
attestation: IAttestation
}
export interface ISubmitAttestation extends IMessageBodyBase {
content: ISubmitAttestationContent
type: MessageBodyType.SUBMIT_ATTESTATION
}
export interface IRejectAttestation extends IMessageBodyBase {
content: IRequestForAttestation['rootHash']
type: MessageBodyType.REJECT_ATTESTATION
}
export interface IRequestPaymentContent {
// Same as the `rootHash` value of the `'request-attestation'` message */
claimHash: string
}
export interface IConfirmPaymentContent {
// Same as the `rootHash` value of the `'request-attestation'` message
claimHash: string
// Hash of the payment transaction */
txHash: string
// hash of the block which includes the payment transaction
blockHash: string
}
export interface IConfirmPayment extends IMessageBodyBase {
content: IConfirmPaymentContent
type: MessageBodyType.CONFIRM_PAYMENT
}
export interface IRequestCredentialContent {
cTypes: Array<{
cTypeHash: ICType['hash']
trustedAttesters?: Array<IDidDetails['did']>
requiredProperties?: string[]
}>
challenge?: string
}
export interface IRequestCredential extends IMessageBodyBase {
content: IRequestCredentialContent
type: MessageBodyType.REQUEST_CREDENTIAL
}
export interface IRequestPayment extends IMessageBodyBase {
content: IRequestPaymentContent
type: MessageBodyType.REQUEST_PAYMENT
}
export interface IDelegationData {
account: IDelegationNode['account']
id: IDelegationNode['id']
parentId: IDelegationNode['id']
permissions: IDelegationNode['permissions']
isPCR: boolean
}
export interface IRejectAcceptDelegation extends IMessageBodyBase {
content: IDelegationData
type: MessageBodyType.REJECT_ACCEPT_DELEGATION
}
export interface IRequestDelegationApproval {
delegationData: IDelegationData
metaData?: AnyJson
signatures: {
inviter: DidSignature
}
}
export interface IRequestAcceptDelegation extends IMessageBodyBase {
content: IRequestDelegationApproval
type: MessageBodyType.REQUEST_ACCEPT_DELEGATION
}
export interface ISubmitDelegationApproval {
delegationData: IDelegationData
signatures: {
inviter: DidSignature
invitee: DidSignature
}
}
export interface ISubmitAcceptDelegation extends IMessageBodyBase {
content: ISubmitDelegationApproval
type: MessageBodyType.SUBMIT_ACCEPT_DELEGATION
}
export interface IInformDelegationCreation {
delegationId: IDelegationNode['id']
isPCR: boolean
}
export interface IInformCreateDelegation extends IMessageBodyBase {
content: IInformDelegationCreation
type: MessageBodyType.INFORM_CREATE_DELEGATION
}
export type CompressedInformDelegationCreation = [
IInformDelegationCreation['delegationId'],
IInformDelegationCreation['isPCR']
]
export type CompressedInformCreateDelegation = [
MessageBodyType.INFORM_CREATE_DELEGATION,
CompressedInformDelegationCreation
]
export type CompressedPartialClaim = [
IClaim['cTypeHash'],
IClaim['owner'] | undefined,
IClaimContents | undefined
]
export type CompressedRequestTerms = [
MessageBodyType.REQUEST_TERMS,
CompressedPartialClaim
]
export type CompressedRejectedTerms = [
CompressedPartialClaim,
CompressedCredential[],
IDelegationNode['id'] | undefined
]
export type CompressedRejectTerms = [
MessageBodyType.REJECT_TERMS,
CompressedRejectedTerms
]
export type CompressedRequestCredentialContent = [
Array<
[
ICType['hash'],
Array<IDidDetails['did']> | undefined,
string[] | undefined
]
>,
string?
]
export type CompressedRequestCredentials = [
MessageBodyType.REQUEST_CREDENTIAL,
CompressedRequestCredentialContent
]
export type CompressedRequestAttestationContent = [
CompressedRequestForAttestation,
CompressedQuoteAgreed | undefined
]
export type CompressedRequestAttestation = [
MessageBodyType.REQUEST_ATTESTATION,
CompressedRequestAttestationContent
]
export type CompressedRequestDelegationApproval = [
CompressedDelegationData,
[DidSignature['signature'], DidSignature['keyId']],
AnyJson
]
export type CompressedRequestAcceptDelegation = [
MessageBodyType.REQUEST_ACCEPT_DELEGATION,
CompressedRequestDelegationApproval
]
export type CompressedSubmitDelegationApproval = [
CompressedDelegationData,
[DidSignature['signature'], DidSignature['keyId']],
[DidSignature['signature'], DidSignature['keyId']]
]
export type CompressedSubmitAcceptDelegation = [
MessageBodyType.SUBMIT_ACCEPT_DELEGATION,
CompressedSubmitDelegationApproval
]
export type MessageBody =
| IError
| IReject
//
| IRequestTerms
| ISubmitTerms
| IRejectTerms
//
| IRequestAttestation
| ISubmitAttestation
| IRejectAttestation
//
| IRequestCredential
| ISubmitCredential
| IAcceptCredential
| IRejectCredential
//
| IRequestAcceptDelegation
| ISubmitAcceptDelegation
| IRejectAcceptDelegation
| IInformCreateDelegation
export type CompressedMessageBody =
| CompressedRequestTerms
| CompressedSubmitTerms
| CompressedRejectTerms
//
| CompressedRequestAttestation
| CompressedSubmitAttestation
| CompressedRejectAttestation
//
| CompressedRequestCredentials
| CompressedSubmitCredentials
| CompressedAcceptCredential
| CompressedRejectCredential
//
| CompressedRequestAcceptDelegation
| CompressedSubmitAcceptDelegation
| CompressedRejectAcceptDelegation
| CompressedInformCreateDelegation
/**
* - `body` - The body of the message, see [[MessageBody]].
* - `createdAt` - The timestamp of the message construction.
* - `receiverAddress` - The public SS58 address of the receiver.
* - `senderAddress` - The public SS58 address of the sender.
* - `senderBoxPublicKex` - The public encryption key of the sender.
* - `messageId` - The message id.
* - `inReplyTo` - The id of the parent-message.
* - `references` - The references or the in-reply-to of the parent-message followed by the message-id of the parent-message.
*/
export interface IMessage {
body: MessageBody
createdAt: number
sender: IDidDetails['did']
receiver: IDidDetails['did']
messageId?: string
receivedAt?: number
inReplyTo?: IMessage['messageId']
references?: Array<IMessage['messageId']>
}
/**
* Everything which is part of the encrypted and protected part of the [[IMessage]].
*/
export type IEncryptedMessageContents = Omit<IMessage, 'receivedAt'>
/**
* Removes the plaintext [[IEncryptedMessageContents]] from an [[IMessage]] and instead includes them in encrypted form.
* This adds the following fields:
* - `ciphertext` - The encrypted message content.
* - `nonce` - The encryption nonce.
* - `receiverKeyId` - The identifier of a DID-associated public key to which to encrypt.
* - `senderKeyId` - The identifier of a DID-associated private key with which to which to encrypt.
*/
export type IEncryptedMessage = Pick<IMessage, 'receivedAt'> & {
receiverKeyId: IDidKeyDetails['id']
senderKeyId: IDidKeyDetails['id']
ciphertext: string
nonce: string
} | the_stack |
import { expect } from "chai";
import { WmtsCapabilities } from "../../../tile/map/WmtsCapabilities";
describe("WmtsCapabilities", () => {
const SMALL_DEGREES_DIFFERENCE = 1.0e-8;
const SMALL_DECIMAL_DIFFERENCE = 1.0e-6;
it("should parse USGS WMTS capabilities", async () => {
const capabilities = await WmtsCapabilities.create("assets/wmts_capabilities/USGSHydroCached_capabilities.xml");
expect(capabilities?.version).to.equal("1.0.0");
// Test GetCapabilities operation metadata
expect(capabilities?.operationsMetadata?.getCapabilities).to.not.undefined;
expect(capabilities?.operationsMetadata?.getCapabilities?.name).to.equals("GetCapabilities");
expect(capabilities?.operationsMetadata?.getCapabilities?.postDcpHttp).to.undefined;
expect(capabilities?.operationsMetadata?.getCapabilities?.getDcpHttp).to.not.undefined;
expect(capabilities?.operationsMetadata?.getCapabilities?.getDcpHttp?.length).to.equals(2);
if (capabilities?.operationsMetadata?.getCapabilities?.getDcpHttp) {
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[0].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[0].encoding).to.equals("RESTful");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[0].url).to.equals("https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/WMTS/1.0.0/WMTSCapabilities.xml");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[1].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[1].encoding).to.equals("KVP");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[1].url).to.equals("https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/WMTS?");
}
// Test GetTile operation metadata
expect(capabilities?.operationsMetadata?.getTile).to.not.undefined;
expect(capabilities?.operationsMetadata?.getTile?.name).to.equals("GetTile");
expect(capabilities?.operationsMetadata?.getTile?.postDcpHttp).to.undefined;
expect(capabilities?.operationsMetadata?.getTile?.getDcpHttp?.length).to.equals(2);
if (capabilities?.operationsMetadata?.getTile?.getDcpHttp) {
expect(capabilities.operationsMetadata.getTile.getDcpHttp[0].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[0].encoding).to.equals("RESTful");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[0].url).to.equals("https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/WMTS/tile/1.0.0/");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[1].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[1].encoding).to.equals("KVP");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[1].url).to.equals("https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer/WMTS?");
}
// Check that no GetFeatureInfo has been configured
expect(capabilities?.operationsMetadata?.getFeatureInfo).to.undefined;
//
// Content
//
expect(capabilities?.contents).to.not.undefined;
expect(capabilities?.contents?.layers.length).to.equal(1);
// Identifier
expect(capabilities?.contents?.layers[0].identifier).to.equal("USGSHydroCached");
// Format
expect(capabilities?.contents?.layers[0].format).to.equal("image/jpgpng");
// BoundingBox
expect(capabilities?.contents?.layers[0].boundingBox).to.not.undefined;
expect(capabilities?.contents?.layers[0].boundingBox?.crs).to.equal("urn:ogc:def:crs:EPSG::3857");
expect(capabilities?.contents?.layers[0].boundingBox?.range).to.not.undefined;
expect(capabilities?.contents?.layers[0].boundingBox?.range?.low.isAlmostEqualXY(-2.003750785759102E7, -3.024245526192411E7));
expect(capabilities?.contents?.layers[0].boundingBox?.range?.low.isAlmostEqualXY(2.003872561259901E7, 3.0240971955423884E7));
// WSG84 BoundingBox
expect(capabilities?.contents?.layers[0].wsg84BoundingBox).to.not.undefined;
expect(capabilities?.contents?.layers[0].wsg84BoundingBox?.west).to.not.undefined;
if (capabilities?.contents?.layers[0].wsg84BoundingBox?.west) {
const area = capabilities.contents.layers[0].wsg84BoundingBox.globalLocationArea;
expect(Math.abs(area.southwest.longitudeDegrees - (-179.99999550841463))).to.be.lessThan(SMALL_DEGREES_DIFFERENCE);
expect(Math.abs(area.southwest.latitudeDegrees - (-88.99999992161116))).to.be.lessThan(SMALL_DEGREES_DIFFERENCE);
expect(Math.abs(area.northeast.longitudeDegrees - (179.99999550841463))).to.be.lessThan(SMALL_DEGREES_DIFFERENCE);
expect(Math.abs(area.northeast.latitudeDegrees - (88.99999992161116))).to.be.lessThan(SMALL_DEGREES_DIFFERENCE);
}
// Style
expect(capabilities?.contents?.layers[0].styles).to.not.undefined;
expect(capabilities?.contents?.layers[0].styles.length).to.equal(1);
expect(capabilities?.contents?.layers[0].styles[0].identifier).to.equal("default");
expect(capabilities?.contents?.layers[0].styles[0].title).to.equal("Default Style");
expect(capabilities?.contents?.layers[0].styles[0].isDefault).to.equal(true);
// TileMatrixSetLinks
expect(capabilities?.contents?.layers[0].tileMatrixSetLinks.length).to.equal(2);
expect(capabilities?.contents?.layers[0].tileMatrixSetLinks[0].tileMatrixSet).to.equal("default028mm");
expect(capabilities?.contents?.layers[0].tileMatrixSetLinks[1].tileMatrixSet).to.equal("GoogleMapsCompatible");
// Validate TileMatrix set
expect(capabilities?.contents?.tileMatrixSets.length).to.equals(2);
expect(capabilities?.contents?.tileMatrixSets[0].identifier).to.equal("default028mm");
expect(capabilities?.contents?.tileMatrixSets[0].title).to.equal("TileMatrix using 0.28mm");
expect(capabilities?.contents?.tileMatrixSets[0].abstract).to.contains("dpi assumes 0.28mm");
expect(capabilities?.contents?.tileMatrixSets[0].supportedCrs).to.contains("urn:ogc:def:crs:EPSG::3857");
// Validate first tile matrix definition.
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix.length).to.equals(24);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].identifier).to.equals("0");
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].scaleDenominator).to.not.undefined;
if (capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].scaleDenominator)
expect(Math.abs(capabilities.contents.tileMatrixSets[0].tileMatrix[0].scaleDenominator - (5.590822640285016E8))).to.lessThan(SMALL_DECIMAL_DIFFERENCE);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].topLeftCorner).to.not.undefined;
if (capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].topLeftCorner)
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].topLeftCorner.isAlmostEqualXY(-2.0037508342787E7, 2.0037508342787E7)).to.true;
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].tileWidth).to.equals(256);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].tileHeight).to.equals(256);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].matrixWidth).to.equals(2);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].matrixHeight).to.equals(2);
expect(capabilities?.contents?.tileMatrixSets[1].wellKnownScaleSet).to.contains("urn:ogc:def:wkss:OGC:1.0:GoogleMapsCompatible");
});
it("should parse sample OGC WMTS capabilities", async () => {
const capabilities = await WmtsCapabilities.create("assets/wmts_capabilities/OGCSample_capabilities.xml");
// Test ServiceIdentification metadata
expect(capabilities?.serviceIdentification).to.not.undefined;
expect(capabilities?.serviceIdentification?.abstract).to.includes("Example service that constrains");
expect(capabilities?.serviceIdentification?.title).to.equals("World example Web Map Tile Service");
expect(capabilities?.serviceIdentification?.serviceType).to.equals("OGC WMTS");
expect(capabilities?.serviceIdentification?.serviceTypeVersion).to.equals("1.0.0");
expect(capabilities?.serviceIdentification?.keywords?.length).to.equals(4);
if (capabilities?.serviceIdentification?.keywords)
expect(capabilities?.serviceIdentification?.keywords[0]).to.equals("World");
expect(capabilities?.serviceIdentification?.fees).to.equals("none");
expect(capabilities?.serviceIdentification?.accessConstraints).to.equals("none");
// Test GetCapabilities operation metadata
expect(capabilities?.operationsMetadata?.getCapabilities).to.not.undefined;
expect(capabilities?.operationsMetadata?.getCapabilities?.name).to.equals("GetCapabilities");
expect(capabilities?.operationsMetadata?.getCapabilities?.getDcpHttp).to.not.undefined;
expect(capabilities?.operationsMetadata?.getCapabilities?.getDcpHttp?.length).to.equals(1);
if (capabilities?.operationsMetadata?.getCapabilities?.getDcpHttp) {
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[0].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[0].encoding).to.equals("KVP");
expect(capabilities.operationsMetadata.getCapabilities.getDcpHttp[0].url).to.equals("http://www.maps.bob/maps.cgi?");
}
expect(capabilities?.operationsMetadata?.getCapabilities?.postDcpHttp).to.not.undefined;
expect(capabilities?.operationsMetadata?.getCapabilities?.postDcpHttp?.length).to.equals(1);
if (capabilities?.operationsMetadata?.getCapabilities?.postDcpHttp) {
expect(capabilities.operationsMetadata.getCapabilities.postDcpHttp[0].constraintName).to.equals("PostEncoding");
expect(capabilities.operationsMetadata.getCapabilities.postDcpHttp[0].encoding).to.equals("SOAP");
expect(capabilities.operationsMetadata.getCapabilities.postDcpHttp[0].url).to.equals("http://www.maps.bob/maps.cgi?");
}
// Test GetTile operation metadata
expect(capabilities?.operationsMetadata?.getTile).to.not.undefined;
expect(capabilities?.operationsMetadata?.getTile?.name).to.equals("GetTile");
expect(capabilities?.operationsMetadata?.getTile?.getDcpHttp).to.not.undefined;
expect(capabilities?.operationsMetadata?.getTile?.getDcpHttp?.length).to.equals(1);
if (capabilities?.operationsMetadata?.getTile?.getDcpHttp) {
expect(capabilities.operationsMetadata.getTile.getDcpHttp[0].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[0].encoding).to.equals("KVP");
expect(capabilities.operationsMetadata.getTile.getDcpHttp[0].url).to.equals("http://www.maps.bob/maps.cgi?");
}
expect(capabilities?.operationsMetadata?.getTile?.postDcpHttp).to.undefined;
// Test GetFeatureInfo operation metadata
expect(capabilities?.operationsMetadata?.getFeatureInfo).to.not.undefined;
expect(capabilities?.operationsMetadata?.getFeatureInfo?.name).to.equals("GetFeatureInfo");
expect(capabilities?.operationsMetadata?.getFeatureInfo?.getDcpHttp).to.not.undefined;
expect(capabilities?.operationsMetadata?.getFeatureInfo?.getDcpHttp?.length).to.equals(1);
if (capabilities?.operationsMetadata?.getFeatureInfo?.getDcpHttp) {
expect(capabilities.operationsMetadata.getFeatureInfo.getDcpHttp[0].constraintName).to.equals("GetEncoding");
expect(capabilities.operationsMetadata.getFeatureInfo.getDcpHttp[0].encoding).to.equals("KVP");
expect(capabilities.operationsMetadata.getFeatureInfo.getDcpHttp[0].url).to.equals("http://www.maps.bob/maps.cgi?");
}
expect(capabilities?.operationsMetadata?.getFeatureInfo?.postDcpHttp).to.undefined;
// Content
expect(capabilities?.version).to.equal("1.0.0");
expect(capabilities?.contents).to.not.undefined;
// layer
expect(capabilities?.contents?.layers.length).to.equal(2); // this sample capabilities has 2 layers
expect(capabilities?.contents?.layers[0].identifier).to.equal("etopo2");
// tileMatrixSetLinks
expect(capabilities?.contents?.layers[0].tileMatrixSetLinks.length).to.equal(1);
expect(capabilities?.contents?.layers[0].tileMatrixSetLinks[0].tileMatrixSet).to.equal("WholeWorld_CRS_84");
expect(capabilities?.contents?.layers[1].identifier).to.equal("AdminBoundaries");
expect(capabilities?.contents?.layers[1].tileMatrixSetLinks.length).to.equal(1);
expect(capabilities?.contents?.layers[1].tileMatrixSetLinks[0].tileMatrixSet).to.equal("WholeWorld_CRS_84");
// Validate first tile matrix definition.
expect(capabilities?.contents?.tileMatrixSets.length).to.equals(1);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix.length).to.equals(7);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].identifier).to.equals("2g");
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].tileWidth).to.equals(320);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].tileHeight).to.equals(200);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].matrixWidth).to.equals(1);
expect(capabilities?.contents?.tileMatrixSets[0].tileMatrix[0].matrixHeight).to.equals(1);
});
it("should parse Great artesian basin sample", async () => {
const capabilities = await WmtsCapabilities.create("assets/wmts_capabilities/great-artesian-basin.xml");
// I check only things that are different from other datasets
// Check the layer styles
expect(capabilities?.contents?.layers).to.not.undefined;
expect(capabilities?.contents?.layers.length).to.equal(1); // this sample capabilities has 2 layers
expect(capabilities?.contents?.layers[0].styles.length).to.equal(2);
expect(capabilities?.contents?.layers[0].styles[0].identifier).to.equal("gab:gab_formation_elevation_equalised_histogram");
expect(capabilities?.contents?.layers[0].styles[0].isDefault).to.equal(false);
expect(capabilities?.contents?.layers[0].styles[1].identifier).to.equal("gab:gab_formation_elevation_min-max");
expect(capabilities?.contents?.layers[0].styles[1].isDefault).to.equal(true);
// tileMatrixSetLinks
expect(capabilities?.contents?.tileMatrixSets.length).to.equal(6);
const googleTms = capabilities?.contents?.getGoogleMapsCompatibleTileMatrixSet();
expect(googleTms?.length).to.equal(2);
});
}); | the_stack |
import {
expect as expectCDK,
haveResource,
haveResourceLike,
} from '@aws-cdk/assert';
import {
AmazonLinuxGeneration,
Instance,
InstanceType,
IVpc,
MachineImage,
SecurityGroup,
Vpc,
WindowsVersion,
} from '@aws-cdk/aws-ec2';
import {
ContainerImage,
} from '@aws-cdk/aws-ecs';
import {
ILogGroup,
} from '@aws-cdk/aws-logs';
import {
Stack,
} from '@aws-cdk/core';
import {
LogGroupFactoryProps,
} from '../../core/lib';
import {
RenderQueue,
Repository,
Version,
VersionQuery,
WorkerInstanceConfiguration,
} from '../lib';
import {
linuxConfigureWorkerScriptBoilerplate,
linuxCloudWatchScriptBoilerplate,
windowsConfigureWorkerScriptBoilerplate,
windowsCloudWatchScriptBoilerplate,
} from './asset-constants';
describe('Test WorkerInstanceConfiguration for Linux', () => {
let stack: Stack;
let vpc: IVpc;
let instance: Instance;
beforeEach(() => {
stack = new Stack();
vpc = new Vpc(stack, 'Vpc');
instance = new Instance(stack, 'Instance', {
vpc,
instanceType: new InstanceType('t3.small'),
machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }),
});
});
test('basic setup', () => {
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
});
const userData = stack.resolve(instance.userData.render());
// // THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'#!/bin/bash\nmkdir -p $(dirname \'/tmp/',
...linuxConfigureWorkerScriptBoilerplate(
`\' \'\' \'\' \'\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${WorkerInstanceConfiguration['DEFAULT_LISTENER_PORT']} /tmp/`),
],
],
});
});
test('custom listener port', () => {
const otherListenerPort = 55555;
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
workerSettings: {
listenerPort: otherListenerPort,
},
});
const userData = stack.resolve(instance.userData.render());
// // THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'#!/bin/bash\nmkdir -p $(dirname \'/tmp/',
...linuxConfigureWorkerScriptBoilerplate(`\' \'\' \'\' \'\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${otherListenerPort} /tmp/`),
],
],
});
});
test('groups, pools, region setup', () => {
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
workerSettings: {
groups: ['g1', 'g2'],
pools: ['p1', 'p2'],
region: 'r1',
},
});
const userData = stack.resolve(instance.userData.render());
// // THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'#!/bin/bash\nmkdir -p $(dirname \'/tmp/',
...linuxConfigureWorkerScriptBoilerplate(
`\' \'g1,g2\' \'p1,p2\' \'r1\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${WorkerInstanceConfiguration['DEFAULT_LISTENER_PORT']} /tmp/`),
],
],
});
});
test('log setup', () => {
// GIVEN
const logGroupProps: LogGroupFactoryProps = {
logGroupPrefix: '/test-prefix/',
};
// WHEN
const config = new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
cloudWatchLogSettings: logGroupProps,
});
const logGroup = config.node.findChild('ConfigLogGroupWrapper');
const logGroupName = stack.resolve((logGroup as ILogGroup).logGroupName);
const userData = stack.resolve(instance.userData.render());
// THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'#!/bin/bash\nmkdir -p $(dirname \'/tmp/',
...linuxCloudWatchScriptBoilerplate(
`\' \'\' \'\' \'\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${WorkerInstanceConfiguration['DEFAULT_LISTENER_PORT']} /tmp/`),
],
],
});
expectCDK(stack).to(haveResource('AWS::SSM::Parameter', {
Value: {
'Fn::Join': [
'',
[
'{\"logs\":{\"logs_collected\":{\"files\":{\"collect_list\":[{\"log_group_name\":\"',
logGroupName,
'\",\"log_stream_name\":\"cloud-init-output-{instance_id}\",\"file_path\":\"/var/log/cloud-init-output.log\",\"timezone\":\"Local\"},{\"log_group_name\":\"',
logGroupName,
'\",\"log_stream_name\":\"WorkerLogs-{instance_id}\",\"file_path\":\"/var/log/Thinkbox/Deadline10/deadlineslave*.log\",\"timezone\":\"Local\"},{\"log_group_name\":\"',
logGroupName,
'\",\"log_stream_name\":\"LauncherLogs-{instance_id}\",\"file_path\":\"/var/log/Thinkbox/Deadline10/deadlinelauncher*.log\",\"timezone\":\"Local\"}]}},\"log_stream_name\":\"DefaultLogStream-{instance_id}\",\"force_flush_interval\":15}}',
],
],
},
}));
});
});
describe('Test WorkerInstanceConfiguration for Windows', () => {
let stack: Stack;
let vpc: IVpc;
let instance: Instance;
beforeEach(() => {
stack = new Stack();
vpc = new Vpc(stack, 'Vpc');
instance = new Instance(stack, 'Instance', {
vpc,
instanceType: new InstanceType('t3.small'),
machineImage: MachineImage.latestWindows(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE),
});
});
test('basic setup', () => {
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
});
const userData = stack.resolve(instance.userData.render());
// THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'<powershell>mkdir (Split-Path -Path \'C:/temp/',
...windowsConfigureWorkerScriptBoilerplate(
`\' \'\' \'\' \'\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${WorkerInstanceConfiguration['DEFAULT_LISTENER_PORT']} C:/temp/`),
'\"\' -ErrorAction Stop }</powershell>',
],
],
});
});
test('groups, pools, region setup', () => {
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
workerSettings: {
groups: ['g1', 'g2'],
pools: ['p1', 'p2'],
region: 'r1',
},
});
const userData = stack.resolve(instance.userData.render());
// THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'<powershell>mkdir (Split-Path -Path \'C:/temp/',
...windowsConfigureWorkerScriptBoilerplate(
`\' \'g1,g2\' \'p1,p2\' \'r1\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${WorkerInstanceConfiguration['DEFAULT_LISTENER_PORT']} C:/temp/`),
'\"\' -ErrorAction Stop }</powershell>',
],
],
});
});
test('custom listner port', () => {
const otherListenerPort = 55555;
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
workerSettings: {
listenerPort: otherListenerPort,
},
});
const userData = stack.resolve(instance.userData.render());
// THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'<powershell>mkdir (Split-Path -Path \'C:/temp/',
...windowsConfigureWorkerScriptBoilerplate(
`\' \'\' \'\' \'\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${otherListenerPort} C:/temp/`),
'\"\' -ErrorAction Stop }</powershell>',
],
],
});
});
test('log setup', () => {
// GIVEN
const logGroupProps: LogGroupFactoryProps = {
logGroupPrefix: '/test-prefix/',
};
// WHEN
const config = new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
cloudWatchLogSettings: logGroupProps,
});
const logGroup = config.node.findChild('ConfigLogGroupWrapper');
const logGroupName = stack.resolve((logGroup as ILogGroup).logGroupName);
const userData = stack.resolve(instance.userData.render());
// THEN
expect(userData).toStrictEqual({
'Fn::Join': [
'',
[
'<powershell>mkdir (Split-Path -Path \'C:/temp/',
...windowsCloudWatchScriptBoilerplate(
`\' \'\' \'\' \'\' \'${Version.MINIMUM_SUPPORTED_DEADLINE_VERSION.toString()}\' ${WorkerInstanceConfiguration['DEFAULT_LISTENER_PORT']} C:/temp/`),
'\"\' -ErrorAction Stop }</powershell>',
],
],
});
expectCDK(stack).to(haveResource('AWS::SSM::Parameter', {
Value: {
'Fn::Join': [
'',
[
'{\"logs\":{\"logs_collected\":{\"files\":{\"collect_list\":[{\"log_group_name\":\"',
logGroupName,
'\",\"log_stream_name\":\"UserdataExecution-{instance_id}\",\"file_path\":\"C:\\\\ProgramData\\\\Amazon\\\\EC2-Windows\\\\Launch\\\\Log\\\\UserdataExecution.log\",\"timezone\":\"Local\"},{\"log_group_name\":\"',
logGroupName,
'\",\"log_stream_name\":\"WorkerLogs-{instance_id}\",\"file_path\":\"C:\\\\ProgramData\\\\Thinkbox\\\\Deadline10\\\\logs\\\\deadlineslave*.log\",\"timezone\":\"Local\"},{\"log_group_name\":\"',
logGroupName,
'\",\"log_stream_name\":\"LauncherLogs-{instance_id}\",\"file_path\":\"C:\\\\ProgramData\\\\Thinkbox\\\\Deadline10\\\\logs\\\\deadlinelauncher*.log\",\"timezone\":\"Local\"}]}},\"log_stream_name\":\"DefaultLogStream-{instance_id}\",\"force_flush_interval\":15}}',
],
],
},
}));
});
});
describe('Test WorkerInstanceConfiguration connect to RenderQueue', () => {
let stack: Stack;
let vpc: IVpc;
let renderQueue: RenderQueue;
let renderQueueSGId: any;
beforeEach(() => {
stack = new Stack();
vpc = new Vpc(stack, 'Vpc');
const rcsImage = ContainerImage.fromAsset(__dirname);
const version = new VersionQuery(stack, 'Version');
renderQueue = new RenderQueue(stack, 'RQ', {
version,
vpc,
images: { remoteConnectionServer: rcsImage },
repository: new Repository(stack, 'Repository', {
vpc,
version,
secretsManagementSettings: { enabled: false },
}),
trafficEncryption: { externalTLS: { enabled: false } },
});
const rqSecGrp = renderQueue.connections.securityGroups[0] as SecurityGroup;
renderQueueSGId = stack.resolve(rqSecGrp.securityGroupId);
});
test('For Linux', () => {
// GIVEN
const instance = new Instance(stack, 'Instance', {
vpc,
instanceType: new InstanceType('t3.small'),
machineImage: MachineImage.latestAmazonLinux({ generation: AmazonLinuxGeneration.AMAZON_LINUX_2 }),
});
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
renderQueue,
});
const instanceSG = instance.connections.securityGroups[0] as SecurityGroup;
const instanceSGId = stack.resolve(instanceSG.securityGroupId);
// THEN
// Open-box testing. We know that we invoked the connection method on the
// render queue if the security group for the instance has an ingress rule to the RQ.
expectCDK(stack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', {
IpProtocol: 'tcp',
ToPort: 8080,
SourceSecurityGroupId: instanceSGId,
GroupId: renderQueueSGId,
}));
});
test('For Windows', () => {
// GIVEN
const instance = new Instance(stack, 'Instance', {
vpc,
instanceType: new InstanceType('t3.small'),
machineImage: MachineImage.latestWindows(WindowsVersion.WINDOWS_SERVER_2019_ENGLISH_FULL_BASE),
});
// WHEN
new WorkerInstanceConfiguration(stack, 'Config', {
worker: instance,
renderQueue,
});
const instanceSG = instance.connections.securityGroups[0] as SecurityGroup;
const instanceSGId = stack.resolve(instanceSG.securityGroupId);
// THEN
// Open-box testing. We know that we invoked the connection method on the
// render queue if the security group for the instance has an ingress rule to the RQ.
expectCDK(stack).to(haveResourceLike('AWS::EC2::SecurityGroupIngress', {
IpProtocol: 'tcp',
ToPort: 8080,
SourceSecurityGroupId: instanceSGId,
GroupId: renderQueueSGId,
}));
});
}); | the_stack |
import axios from 'axios';
import { Injectable, Inject } from '@nestjs/common';
import { map, reduce } from 'p-iteration';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { orderBy } from 'lodash';
import { ParameterKey } from 'src/app.dto';
import { recursiveCamelCase } from 'src/utils/recursive-camel-case';
import { ParamsService } from 'src/modules/params/params.service';
import { TVSeasonDAO } from 'src/entities/dao/tvseason.dao';
import { TVShowDAO } from 'src/entities/dao/tvshow.dao';
import { MovieDAO } from 'src/entities/dao/movie.dao';
import {
TMDBMovie,
TMDBTVShow,
TMDBFormattedTVSeason,
TMDBTVEpisode,
TMDBGenres,
TMDBLanguage,
GetDiscoverQueries,
TMDBPagination,
Entertainment,
TMDBRequestParams,
} from './tmdb.dto';
import { CacheMethod } from '../redis/cache.interceptor';
import { CacheKeys } from '../redis/cache.dto';
import { RedisService } from '../redis/redis.service';
@Injectable()
export class TMDBService {
// eslint-disable-next-line max-params
public constructor(
@Inject(WINSTON_MODULE_PROVIDER) private logger: Logger,
private readonly paramsService: ParamsService,
private readonly tvSeasonDAO: TVSeasonDAO,
private readonly tvShowDAO: TVShowDAO,
private readonly movieDAO: MovieDAO,
private readonly redisService: RedisService // required for @CacheMethod
) {
this.logger = logger.child({ context: 'TMDBService' });
}
private async request<TData>(path: string, params: TMDBRequestParams = {}) {
const apiKey = await this.paramsService.get(ParameterKey.TMDB_API_KEY);
const language = await this.paramsService.get(ParameterKey.LANGUAGE);
const client = axios.create({
params: { api_key: apiKey, language },
baseURL: 'https://api.themoviedb.org/3/',
});
client.interceptors.response.use(
(response) => response,
(error) => {
this.logger.error('request error', {
error: error?.response?.data || error,
path,
params,
});
return Promise.reject(
new Error(
JSON.stringify(
error.response && error.response.data
? error.response.data
: error.response
)
)
);
}
);
return client
.get<TData>(path, { params })
.then(({ data }) => data);
}
@CacheMethod({
key: CacheKeys.TMDB_GET_MOVIE,
ttl: 6.048e8, // seven days
})
public getMovie(movieTMDBId: number) {
return this.request<TMDBMovie>(`/movie/${movieTMDBId}`);
}
@CacheMethod({
key: CacheKeys.TMDB_GET_TV_SHOW,
ttl: 6.048e8, // seven days
})
public getTVShow(tvShowTMDBId: number, params?: { language: string }) {
return this.request<TMDBTVShow>(`/tv/${tvShowTMDBId}`, params);
}
@CacheMethod({
key: CacheKeys.TMDB_GET_ENGLISH_TV_SHOW_NAME,
ttl: 6.048e8, // seven days
})
public async getEnglishTVShowName(tvShowTMDBId: number) {
const { name } = await this.request<TMDBTVShow>(`/tv/${tvShowTMDBId}`, {
language: 'en',
});
return name;
}
@CacheMethod({
key: CacheKeys.TMDB_GET_TV_EPISODE,
ttl: 6.048e8, // seven days
})
public getTVEpisode(
tvShowTMDBId: number,
seasonNumber: number,
episodeNumber: number
) {
return this.request<TMDBTVEpisode>(
`/tv/${tvShowTMDBId}/season/${seasonNumber}/episode/${episodeNumber}`
);
}
public async getTVShowSeasons(tvShowTMDBId: number) {
const tvShow = await this.getTVShow(tvShowTMDBId);
return map(tvShow.seasons, async (season) =>
recursiveCamelCase<TMDBFormattedTVSeason>({
...season,
inLibrary: await this.tvSeasonDAO.inLibrary(
tvShowTMDBId,
season.season_number
),
})
);
}
public async searchMovie(query: string, params = {}) {
this.logger.info('start search movie', { query, params });
const data = await this.request<{ results: TMDBMovie[] }>('/search/movie', {
query,
...params,
});
const results = data.results.map(this.mapMovie);
this.logger.info(`found ${results.length} movies`, { query, params });
return results;
}
public async searchTVShow(query: string, params = {}) {
this.logger.info('start search tvshow', { query, params });
const data = await this.request<{ results: TMDBTVShow[] }>('/search/tv', {
query,
...params,
});
const results = data.results.map(this.mapTVShow);
this.logger.info(`found ${results.length} tvshows`);
return results;
}
public async search(query: string) {
return {
movies: await this.searchMovie(query),
tvShows: await this.searchTVShow(query),
};
}
public async getPopular() {
this.logger.info('start get popular');
const region = await this.paramsService.get(ParameterKey.REGION);
const [movies, tvShows] = await Promise.all([
this.request<{ results: TMDBMovie[] }>('/movie/popular', {
region,
}).then(({ results }) => results.map(this.mapMovie)),
this.request<{ results: TMDBTVShow[] }>('/tv/popular', {
region,
}).then(({ results }) => results.map(this.mapTVShow)),
]);
this.logger.info('finish get popular');
return { movies, tvShows };
}
public async getRecommended(type: 'tvshow' | 'movie') {
this.logger.info(`start get recommended ${type}s`);
const url =
type === 'tvshow'
? (id: number) => `/tv/${id}/recommendations`
: (id: number) => `/movie/${id}/recommendations`;
const entities =
type === 'tvshow'
? await this.tvShowDAO.find()
: await this.movieDAO.find();
const allSimilars = await reduce<any, any[]>(
entities,
async (results, entity) => {
const data = await this.cachedRecommendationsRequest<{
results: Array<TMDBTVShow | TMDBMovie>;
}>(url(entity.tmdbId));
const similarsWithoutAlreadyInLibrary = data.results.filter(
(a) => !entities.some((b: any) => a.id === b.tmdbId)
);
const mergedResults = [...results, ...similarsWithoutAlreadyInLibrary];
const mergedResultsWithCount = mergedResults.reduce(
(merged: Array<Record<string, any>>, curr) => {
// if already found as recommendation increment count
if (merged.some((m) => m.id === curr.id)) {
return merged.map((m) => {
const count = m.id === curr.id ? m.count + 1 : m.count;
return { ...m, count };
});
}
// new recommendation
return [...merged, { ...curr, count: 1 }];
},
[]
);
return mergedResultsWithCount;
},
[]
);
this.logger.info(`found ${allSimilars.length} recommendations`);
this.logger.info(`finish get recommended ${type}s`);
return orderBy(allSimilars, ['count', 'popularity'], ['desc', 'desc'])
.filter((_row, index) => index <= 50)
.map(type === 'movie' ? this.mapMovie : this.mapTVShow);
}
@CacheMethod({
key: CacheKeys.TMDB_GET_RECOMMENDATIONS,
ttl: 6.048e8, // seven days
})
private cachedRecommendationsRequest<TData>(url: string) {
return this.request<TData>(url);
}
public async discover(args: GetDiscoverQueries) {
this.logger.info('start discovery filter', args);
const {
primaryReleaseYear,
entertainment,
originLanguage,
score,
genres,
page,
} = args;
const normalizedArgs = {
'vote_count.gte': 50,
with_genres: genres?.join(','),
with_original_language: originLanguage,
'vote_average.gte': score && score / 10,
...(Entertainment.Movie && {
primary_release_year: Number(primaryReleaseYear),
}),
...(Entertainment.TvShow && {
first_air_date_year: Number(primaryReleaseYear),
}),
page,
};
this.logger.info('finish discovery filter');
if (entertainment === Entertainment.Movie) {
return await this.discoverMovie(normalizedArgs);
}
return await this.discoverTvShow(normalizedArgs);
}
private async discoverMovie(args: TMDBRequestParams) {
const TMDBResults = await this.request<TMDBPagination<TMDBMovie[]>>(
`/discover/movie`,
args
);
// eslint-disable-next-line @typescript-eslint/naming-convention
const { page, total_pages, total_results, results } = TMDBResults;
return {
page,
totalResults: total_results,
totalPages: total_pages,
results: results.map(this.mapMovie),
};
}
private async discoverTvShow(args: TMDBRequestParams) {
const TMDBResults = await this.request<TMDBPagination<TMDBTVShow[]>>(
`/discover/tv`,
args
);
// eslint-disable-next-line @typescript-eslint/naming-convention
const { page, total_pages, total_results, results } = TMDBResults;
return {
page,
totalResults: total_results,
totalPages: total_pages,
results: results.map(this.mapTVShow),
};
}
public async getLanguages() {
this.logger.info('start get TMDB languages');
const results = await this.request<TMDBLanguage[]>(
'/configuration/languages'
);
this.logger.info('finish get TMDB languages');
return results.map(({ iso_639_1: code, english_name: language }) => ({
code,
language,
}));
}
public async getGenres() {
this.logger.info('start get TMDB genres');
const [movieGenres, tvShowGenres] = await Promise.all([
this.request<{ genres: TMDBGenres[] }>('/genre/movie/list'),
this.request<{ genres: TMDBGenres[] }>('/genre/tv/list'),
]);
this.logger.info('finish get TMDB genres');
return {
movieGenres: movieGenres.genres,
tvShowGenres: tvShowGenres.genres,
};
}
public mapMovie(result: TMDBMovie) {
return {
id: result.id,
tmdbId: result.id,
title: result.title,
overview: result.overview,
runtime: result.runtime,
originalTitle: result.original_title,
originCountry: result.original_language,
releaseDate: result.release_date,
posterPath: result.poster_path,
voteAverage: result.vote_average,
};
}
public mapTVShow(result: TMDBTVShow) {
return {
id: result.id,
tmdbId: result.id,
title: result.name,
overview: result.overview,
originalTitle: result.original_name,
originCountry: result.origin_country,
releaseDate: result.first_air_date,
posterPath: result.poster_path,
voteAverage: result.vote_average,
};
}
} | the_stack |
import {Window, TextObj} from "../../Window";
import {kill_all_sprites} from "../../utils";
import {item_types} from "../../Item";
import {effect_operators, effect_types} from "../../Effect";
import {GoldenSun} from "../../GoldenSun";
import {MainChar} from "../../MainChar";
import {effect_type_stat, main_stats} from "../../Player";
import * as _ from "lodash";
const BASE_X = 128;
const BASE_Y = 88;
const BASE_WIDTH = 108;
const BASE_HEIGHT = 68;
const CANT_EQUIP_X = 14;
const CANT_EQUIP_Y = 32;
const TXT_GROUP_X = 8;
const TXT_GROUP_Y = 8;
const LINE_SHIFT = 16;
const CURR_STAT_END_X = 53;
const NEW_STAT_END_X = CURR_STAT_END_X + 40;
const ARROW_X = 65;
const ARROW_Y = 7;
const UP_ARROW_Y_SHIFT = -1;
const SEPARATOR_X = 4;
const SEPARATOR_Y = 19;
const SEPARATOR_LENGTH = 104;
const SEPARATOR_COUNT = 3;
/*Compares the character's equipped item with another item
Used in shop menus. Will show stat differences
Input: game [Phaser:Game] - Reference to the running game object
data [GoldenSun] - Reference to the main JS Class instance*/
export class EquipCompare {
public game: Phaser.Game;
public data: GoldenSun;
public selected_item: string;
public selected_char: MainChar;
public is_open: boolean;
public window: Window;
public text_group: Phaser.Group;
public arrow_group: Phaser.Group;
public cant_equip_text: TextObj;
public atk_label_text: TextObj;
public def_label_text: TextObj;
public agi_label_text: TextObj;
public item_name_text: TextObj;
public curr_atk_text: TextObj;
public curr_def_text: TextObj;
public curr_agi_text: TextObj;
public new_atk_text: TextObj;
public new_def_text: TextObj;
public new_agi_text: TextObj;
constructor(game: Phaser.Game, data: GoldenSun) {
this.game = game;
this.data = data;
this.selected_item = null;
this.selected_char = null;
this.is_open = false;
this.window = new Window(this.game, BASE_X, BASE_Y, BASE_WIDTH, BASE_HEIGHT);
this.text_group = this.window.define_internal_group("texts", {x: TXT_GROUP_X, y: TXT_GROUP_Y});
this.arrow_group = this.window.define_internal_group("arrows", {x: ARROW_X, y: ARROW_Y});
this.cant_equip_text = this.window.set_text_in_position("Can't equip", CANT_EQUIP_X, CANT_EQUIP_Y, {
italic: true,
color: this.window.font_color,
});
this.cant_equip_text.text.visible = false;
this.cant_equip_text.shadow.visible = false;
this.atk_label_text = this.init_text_sprite("ATK", 0, 0, false);
this.def_label_text = this.init_text_sprite("DEF", 0, LINE_SHIFT, false);
this.agi_label_text = this.init_text_sprite("AGL", 0, 2 * LINE_SHIFT, false);
this.item_name_text = this.init_text_sprite("", 0, 3 * LINE_SHIFT, false);
this.curr_atk_text = this.init_text_sprite("", CURR_STAT_END_X, 0, true);
this.curr_def_text = this.init_text_sprite("", CURR_STAT_END_X, LINE_SHIFT, true);
this.curr_agi_text = this.init_text_sprite("", CURR_STAT_END_X, 2 * LINE_SHIFT, true);
this.new_atk_text = this.init_text_sprite("", NEW_STAT_END_X, 0, true);
this.new_def_text = this.init_text_sprite("", NEW_STAT_END_X, LINE_SHIFT, true);
this.new_agi_text = this.init_text_sprite("", NEW_STAT_END_X, 2 * LINE_SHIFT, true);
this.text_group.visible = false;
this.arrow_group.visible = false;
}
/*Initializes a text-shadow pair
Input: text [string] - The text to display
x, y [number] - The text position
right_align - If true, the text will be right-aligned*/
init_text_sprite(text: string, x: number, y: number, right_align: boolean) {
let txt = this.window.set_text_in_position(text, x, y, {right_align: right_align});
this.window.add_to_internal_group("texts", txt.shadow);
this.window.add_to_internal_group("texts", txt.text);
return txt;
}
/*Creates or recycles an arrow sprite
Input: diff [number] - Stat difference, affects the arrow type
line [number] - Line index for displaying purposes*/
make_arrow(diff: number, line: number) {
if (diff === 0) return;
let arrow_x = 0;
let arrow_y = LINE_SHIFT * line + (diff > 0 ? UP_ARROW_Y_SHIFT : 0);
let key = diff > 0 ? "up_arrow" : "down_arrow";
let dead_arrows = this.arrow_group.children.filter((a: Phaser.Sprite) => {
return a.alive === false && a.frameName === key;
});
if (dead_arrows.length > 0) (dead_arrows[0] as Phaser.Sprite).reset(arrow_x, arrow_y);
else this.window.create_at_group(arrow_x, arrow_y, "menu", {frame: key, internal_group_key: "arrows"});
}
/*Finds the statistical difference in a stat for two items
Input: equipped [string] - Key name for the equipped item
new_item [string] - Key name for the item being compared
stat [string] - Stat to compare
current_val [number] - Current value of the stat*/
compare_items(equipped: string, new_item: string, stat: string, current_val: number) {
let eq_effects = {};
if (equipped) {
eq_effects = _.mapKeys(this.data.info.items_list[equipped].effects, effect => effect.type);
}
let nitem_effects = _.mapKeys(this.data.info.items_list[new_item].effects, effect => effect.type);
let eq_stat = 0;
let nitem_stat = 0;
if (eq_effects[stat]) {
switch (eq_effects[stat].operator) {
case effect_operators.PLUS:
eq_stat = eq_effects[stat].quantity;
break;
case effect_operators.MINUS:
eq_stat = -1 * eq_effects[stat].quantity;
break;
case effect_operators.TIMES:
eq_stat = eq_effects[stat].quantity * current_val;
break;
case effect_operators.DIVIDE:
eq_stat = (eq_effects[stat].quantity / current_val) | 0;
break;
}
}
if (nitem_effects[stat]) {
switch (nitem_effects[stat].operator) {
case effect_operators.PLUS:
nitem_stat = nitem_effects[stat].quantity;
break;
case effect_operators.MINUS:
nitem_stat = -1 * nitem_effects[stat].quantity;
break;
case effect_operators.TIMES:
nitem_stat = nitem_effects[stat].quantity * current_val;
break;
case effect_operators.DIVIDE:
nitem_stat = -(current_val / nitem_effects[stat].quantity) | 0;
break;
}
}
return nitem_stat - eq_stat;
}
/*Updates the text and creates arrows if necessary
Input: stat [string] - "attack", "defense", "agility"
curr_val [number] - The current stat
stat_diff [number] - Stat difference*/
display_stat(stat: string, curr_val: number, stat_diff: number) {
let new_stat_text = null;
let curr_stat_text = null;
let line = 0;
switch (stat) {
case effect_types.ATTACK:
new_stat_text = this.new_atk_text;
curr_stat_text = this.curr_atk_text;
line = 0;
break;
case effect_types.DEFENSE:
new_stat_text = this.new_def_text;
curr_stat_text = this.curr_def_text;
line = 1;
break;
case effect_types.AGILITY:
new_stat_text = this.new_agi_text;
curr_stat_text = this.curr_agi_text;
line = 2;
break;
}
new_stat_text.text.visible = stat_diff === 0 ? false : true;
new_stat_text.shadow.visible = stat_diff === 0 ? false : true;
this.window.update_text(String(curr_val), curr_stat_text);
if (stat_diff === 0) return;
this.window.update_text(String(curr_val + stat_diff), new_stat_text);
this.make_arrow(stat_diff, line);
}
/*Compare the same item for a different character*/
change_character(key_name: string) {
this.selected_char = this.data.info.party_data.members.filter(c => {
return c.key_name === key_name;
})[0];
kill_all_sprites(this.arrow_group);
this.show_stat_compare();
}
/*Displays the stat comparison*/
show_stat_compare() {
if (!this.data.info.items_list[this.selected_item].equipable_chars.includes(this.selected_char.key_name)) {
this.show_cant_equip();
return;
}
this.cant_equip_text.text.visible = false;
this.cant_equip_text.shadow.visible = false;
let selected_item_type = this.data.info.items_list[this.selected_item].type;
let char_current_item = null;
let eq_slots = this.selected_char.equip_slots;
let eq_types = ["WEAPONS", "ARMOR", "CHEST_PROTECTOR", "HEAD_PROTECTOR", "RING", "LEG_PROTECTOR", "UNDERWEAR"];
let slot_types = ["weapon", "body", "chest", "head", "ring", "boots", "underwear"];
for (let i = 0; i < eq_types.length; i++) {
if (selected_item_type === item_types[eq_types[i]] && eq_slots[slot_types[i]])
char_current_item = this.data.info.items_list[eq_slots[slot_types[i]].key_name].key_name;
}
let diffs = {
[main_stats.ATTACK]: 0,
[main_stats.DEFENSE]: 0,
[main_stats.AGILITY]: 0,
};
let labels = [effect_types.ATTACK, effect_types.DEFENSE, effect_types.AGILITY];
for (let i = 0; i < labels.length; i++) {
diffs[effect_type_stat[labels[i]]] = this.compare_items(
char_current_item,
this.selected_item,
labels[i],
this.selected_char[effect_type_stat[labels[i]]]
);
this.display_stat(
labels[i],
this.selected_char[effect_type_stat[labels[i]]],
diffs[effect_type_stat[labels[i]]]
);
}
let name = this.data.info.items_list[char_current_item]
? this.data.info.items_list[char_current_item].name
: "";
this.window.update_text(name, this.item_name_text);
for (let i = 0; i < SEPARATOR_COUNT; i++) {
this.window.draw_separator(
SEPARATOR_X,
SEPARATOR_Y + LINE_SHIFT * i,
SEPARATOR_X + SEPARATOR_LENGTH,
SEPARATOR_Y + LINE_SHIFT * i,
false
);
}
this.text_group.visible = true;
this.arrow_group.visible = true;
}
/*Displays the "Can't equip" message*/
show_cant_equip() {
this.text_group.visible = false;
this.arrow_group.visible = false;
this.window.clear_separators();
this.cant_equip_text.text.visible = true;
this.cant_equip_text.shadow.visible = true;
}
/*Opens this window with the selected member
Input: char_key [string] - The character's key name
item [string] - Key name of the item to compare
open_callback [function] - Callback function (Optional)*/
open(char_key: string, item: string, open_callback?: () => void) {
this.selected_char = this.data.info.party_data.members.filter((c: MainChar) => {
return c.key_name === char_key;
})[0];
this.selected_item = item;
this.show_stat_compare();
this.is_open = true;
this.window.show(open_callback, false);
}
/*Clears information and closes the window
Input: destroy [boolean] - If true, sprites are destroyed*/
close(callback?: () => void, destroy: boolean = false) {
kill_all_sprites(this.arrow_group, destroy);
if (destroy) kill_all_sprites(this.text_group, destroy);
this.selected_item = null;
this.selected_char = null;
this.is_open = false;
this.window.close(callback, false);
}
} | the_stack |
import {Model} from "../../model"
import {indexOf} from "core/util/arrayable"
import {contains, uniq} from "core/util/array"
import {HitTestResult} from "core/hittest"
import {Geometry} from "core/geometry"
import {SelectionMode} from "core/enums"
import * as p from "core/properties"
import {Selection} from "../selections/selection"
import {GraphRenderer, GraphRendererView} from "../renderers/graph_renderer"
import {ColumnarDataSource} from "../sources/columnar_data_source"
import type {GlyphRendererView} from "../renderers/glyph_renderer"
export namespace GraphHitTestPolicy {
export type Attrs = p.AttrsOf<Props>
export type Props = Model.Props
}
export interface GraphHitTestPolicy extends Model.Attrs {}
export abstract class GraphHitTestPolicy extends Model {
override properties: GraphHitTestPolicy.Props
constructor(attrs?: Partial<GraphHitTestPolicy.Attrs>) {
super(attrs)
}
abstract hit_test(geometry: Geometry, graph_view: GraphRendererView): HitTestResult
abstract do_selection(hit_test_result: HitTestResult, graph: GraphRenderer, final: boolean, mode: SelectionMode): boolean
abstract do_inspection(hit_test_result: HitTestResult, geometry: Geometry, graph_view: GraphRendererView, final: boolean, mode: SelectionMode): boolean
protected _hit_test(geometry: Geometry, graph_view: GraphRendererView, renderer_view: GlyphRendererView): HitTestResult {
if (!graph_view.model.visible)
return null
const hit_test_result = renderer_view.glyph.hit_test(geometry)
if (hit_test_result == null)
return null
else
return renderer_view.model.view.convert_selection_from_subset(hit_test_result)
}
}
export namespace EdgesOnly {
export type Attrs = p.AttrsOf<Props>
export type Props = GraphHitTestPolicy.Props
}
export interface EdgesOnly extends EdgesOnly.Attrs {}
export class EdgesOnly extends GraphHitTestPolicy {
override properties: EdgesOnly.Props
constructor(attrs?: Partial<EdgesOnly.Attrs>) {
super(attrs)
}
hit_test(geometry: Geometry, graph_view: GraphRendererView): HitTestResult {
return this._hit_test(geometry, graph_view, graph_view.edge_view)
}
do_selection(hit_test_result: HitTestResult, graph: GraphRenderer, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const edge_selection = graph.edge_renderer.data_source.selected
edge_selection.update(hit_test_result, final, mode)
graph.edge_renderer.data_source._select.emit()
return !edge_selection.is_empty()
}
do_inspection(hit_test_result: HitTestResult, geometry: Geometry, graph_view: GraphRendererView, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const {edge_renderer} = graph_view.model
const edge_inspection = edge_renderer.get_selection_manager().get_or_create_inspector(graph_view.edge_view.model)
edge_inspection.update(hit_test_result, final, mode)
// silently set inspected attr to avoid triggering data_source.change event and rerender
graph_view.edge_view.model.data_source.setv({inspected: edge_inspection}, {silent: true})
graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, {geometry}])
return !edge_inspection.is_empty()
}
}
export namespace NodesOnly {
export type Attrs = p.AttrsOf<Props>
export type Props = GraphHitTestPolicy.Props
}
export interface NodesOnly extends NodesOnly.Attrs {}
export class NodesOnly extends GraphHitTestPolicy {
override properties: NodesOnly.Props
constructor(attrs?: Partial<NodesOnly.Attrs>) {
super(attrs)
}
hit_test(geometry: Geometry, graph_view: GraphRendererView): HitTestResult {
return this._hit_test(geometry, graph_view, graph_view.node_view)
}
do_selection(hit_test_result: HitTestResult, graph: GraphRenderer, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const node_selection = graph.node_renderer.data_source.selected
node_selection.update(hit_test_result, final, mode)
graph.node_renderer.data_source._select.emit()
return !node_selection.is_empty()
}
do_inspection(hit_test_result: HitTestResult, geometry: Geometry, graph_view: GraphRendererView, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const {node_renderer} = graph_view.model
const node_inspection = node_renderer.get_selection_manager().get_or_create_inspector(graph_view.node_view.model)
node_inspection.update(hit_test_result, final, mode)
// silently set inspected attr to avoid triggering data_source.change event and rerender
graph_view.node_view.model.data_source.setv({inspected: node_inspection}, {silent: true})
graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, {geometry}])
return !node_inspection.is_empty()
}
}
export namespace NodesAndLinkedEdges {
export type Attrs = p.AttrsOf<Props>
export type Props = GraphHitTestPolicy.Props
}
export interface NodesAndLinkedEdges extends NodesAndLinkedEdges.Attrs {}
export class NodesAndLinkedEdges extends GraphHitTestPolicy {
override properties: NodesAndLinkedEdges.Props
constructor(attrs?: Partial<NodesAndLinkedEdges.Attrs>) {
super(attrs)
}
hit_test(geometry: Geometry, graph_view: GraphRendererView): HitTestResult {
return this._hit_test(geometry, graph_view, graph_view.node_view)
}
get_linked_edges(node_source: ColumnarDataSource, edge_source: ColumnarDataSource, mode: string): Selection {
let node_indices = []
if (mode == "selection") {
node_indices = node_source.selected.indices.map((i) => node_source.data.index[i])
} else if (mode == "inspection") {
node_indices = node_source.inspected.indices.map((i) => node_source.data.index[i])
}
const edge_indices = []
for (let i = 0; i < edge_source.data.start.length; i++) {
if (contains(node_indices, edge_source.data.start[i]) || contains(node_indices, edge_source.data.end[i]))
edge_indices.push(i)
}
const linked_edges = new Selection()
for (const i of edge_indices) {
linked_edges.multiline_indices[i] = [0] //currently only supports 2-element multilines, so this is all of it
}
linked_edges.indices = edge_indices
return linked_edges
}
do_selection(hit_test_result: HitTestResult, graph: GraphRenderer, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const node_selection = graph.node_renderer.data_source.selected
node_selection.update(hit_test_result, final, mode)
const edge_selection = graph.edge_renderer.data_source.selected
const linked_edges_selection = this.get_linked_edges(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection")
edge_selection.update(linked_edges_selection, final, mode)
graph.node_renderer.data_source._select.emit()
return !node_selection.is_empty()
}
do_inspection(hit_test_result: HitTestResult, geometry: Geometry, graph_view: GraphRendererView, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model)
node_inspection.update(hit_test_result, final, mode)
graph_view.node_view.model.data_source.setv({inspected: node_inspection}, {silent: true})
const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model)
const linked_edges = this.get_linked_edges(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection")
edge_inspection.update(linked_edges, final, mode)
//silently set inspected attr to avoid triggering data_source.change event and rerender
graph_view.edge_view.model.data_source.setv({inspected: edge_inspection}, {silent: true})
graph_view.node_view.model.data_source.inspect.emit([graph_view.node_view.model, {geometry}])
return !node_inspection.is_empty()
}
}
export namespace EdgesAndLinkedNodes {
export type Attrs = p.AttrsOf<Props>
export type Props = GraphHitTestPolicy.Props
}
export interface EdgesAndLinkedNodes extends EdgesAndLinkedNodes.Attrs {}
export class EdgesAndLinkedNodes extends GraphHitTestPolicy {
override properties: EdgesAndLinkedNodes.Props
constructor(attrs?: Partial<EdgesAndLinkedNodes.Attrs>) {
super(attrs)
}
hit_test(geometry: Geometry, graph_view: GraphRendererView): HitTestResult {
return this._hit_test(geometry, graph_view, graph_view.edge_view)
}
get_linked_nodes(node_source: ColumnarDataSource, edge_source: ColumnarDataSource, mode: string): Selection {
let edge_indices: number[] = []
if (mode == "selection")
edge_indices = edge_source.selected.indices
else if (mode == "inspection")
edge_indices = edge_source.inspected.indices
const nodes = []
for (const i of edge_indices) {
nodes.push(edge_source.data.start[i])
nodes.push(edge_source.data.end[i])
}
const node_indices = uniq(nodes).map((i) => indexOf(node_source.data.index, i))
return new Selection({indices: node_indices})
}
do_selection(hit_test_result: HitTestResult, graph: GraphRenderer, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const edge_selection = graph.edge_renderer.data_source.selected
edge_selection.update(hit_test_result, final, mode)
const node_selection = graph.node_renderer.data_source.selected
const linked_nodes = this.get_linked_nodes(graph.node_renderer.data_source, graph.edge_renderer.data_source, "selection")
node_selection.update(linked_nodes, final, mode)
graph.edge_renderer.data_source._select.emit()
return !edge_selection.is_empty()
}
do_inspection(hit_test_result: HitTestResult, geometry: Geometry, graph_view: GraphRendererView, final: boolean, mode: SelectionMode): boolean {
if (hit_test_result == null)
return false
const edge_inspection = graph_view.edge_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.edge_view.model)
edge_inspection.update(hit_test_result, final, mode)
graph_view.edge_view.model.data_source.setv({inspected: edge_inspection}, {silent: true})
const node_inspection = graph_view.node_view.model.data_source.selection_manager.get_or_create_inspector(graph_view.node_view.model)
const linked_nodes = this.get_linked_nodes(graph_view.node_view.model.data_source, graph_view.edge_view.model.data_source, "inspection")
node_inspection.update(linked_nodes, final, mode)
// silently set inspected attr to avoid triggering data_source.change event and rerender
graph_view.node_view.model.data_source.setv({inspected: node_inspection}, {silent: true})
graph_view.edge_view.model.data_source.inspect.emit([graph_view.edge_view.model, {geometry}])
return !edge_inspection.is_empty()
}
} | the_stack |
import { Id, NullableId, Params, ServiceMethods } from '@feathersjs/feathers'
import { Application } from '../../../declarations'
import { BadRequest } from '@feathersjs/errors'
import _ from 'lodash'
import Sequelize, { Op } from 'sequelize'
import getLocalServerIp from '../../util/get-local-server-ip'
import logger from '../../logger'
import config from '../../appconfig'
const releaseRegex = /^([a-zA-Z0-9]+)-/
interface Data {}
interface ServiceOptions {}
interface GameserverAddress {
ipAddress: string | null
port: string | null
}
const gsNameRegex = /gameserver-([a-zA-Z0-9]{5}-[a-zA-Z0-9]{5})/
const pressureThresholdPercent = 0.8
/**
* An method which start server for instance
* @author Vyacheslav Solovjov
*/
export async function getFreeGameserver(
app: Application,
iteration: number,
locationId: string,
channelId: string
): Promise<any> {
await app.service('instance').Model.destroy({
where: {
assigned: true,
assignedAt: {
[Op.lt]: new Date(new Date().getTime() - 30000)
}
}
})
if (!config.kubernetes.enabled) {
//Clear any instance assignments older than 30 seconds - those assignments have not been
//used, so they should be cleared and the GS they were attached to can be used for something else.
console.log('Local server spinning up new instance')
const localIp = await getLocalServerIp(channelId != null)
const stringIp = `${localIp.ipAddress}:${localIp.port}`
return checkForDuplicatedAssignments(app, stringIp, iteration, locationId, channelId)
}
console.log('Getting free gameserver')
const serverResult = await (app as any).k8AgonesClient.get('gameservers')
const readyServers = _.filter(serverResult.items, (server: any) => {
const releaseMatch = releaseRegex.exec(server.metadata.name)
return server.status.state === 'Ready' && releaseMatch != null && releaseMatch[1] === config.server.releaseName
})
const ipAddresses = readyServers.map((server) => `${server.status.address}:${server.status.ports[0].port}`)
const assignedInstances = await app.service('instance').find({
query: {
ipAddress: {
$in: ipAddresses
},
ended: false
}
})
const nonAssignedInstances = ipAddresses.filter(
(ipAddress) => !assignedInstances.data.find((instance) => instance.ipAddress === ipAddress)
)
const instanceIpAddress = nonAssignedInstances[Math.floor(Math.random() * nonAssignedInstances.length)]
if (instanceIpAddress == null) {
return {
id: null,
ipAddress: null,
port: null
}
}
return checkForDuplicatedAssignments(app, instanceIpAddress, iteration, locationId, channelId)
}
export async function checkForDuplicatedAssignments(
app: Application,
ipAddress: string,
iteration: number,
locationId: string,
channelId: string
) {
//Create an assigned instance at this IP
const assignResult = await app.service('instance').create({
ipAddress: ipAddress,
locationId: locationId,
channelId: channelId,
assigned: true,
assignedAt: new Date()
})
//Check to see if there are any other non-ended instances assigned to this IP
const duplicateAssignment = await app.service('instance').find({
query: {
ipAddress: ipAddress,
assigned: true,
ended: false
}
})
//If there's more than one instance assigned to this IP, then one of them was made in error, possibly because
//there were two instance-provision calls at almost the same time.
if (duplicateAssignment.total > 1) {
let isFirstAssignment = true
//Iterate through all of the assignments to this IP address. If this one is later than any other one,
//then this one needs to find a different GS
for (let instance of duplicateAssignment.data) {
if (instance.id !== assignResult.id && instance.assignedAt < assignResult.assignedAt) {
isFirstAssignment = false
break
}
}
if (!isFirstAssignment) {
//If this is not the first assignment to this IP, remove the assigned instance row
await app.service('instance').remove(assignResult.id)
//If this is the 10th or more attempt to get a free gameserver, then there probably aren't any free ones,
//
if (iteration < 10) {
return getFreeGameserver(app, iteration + 1, locationId, channelId)
} else {
console.log('Made 10 attempts to get free gameserver without success, returning null')
return {
id: null,
ipAddress: null,
port: null
}
}
}
}
const split = ipAddress.split(':')
return {
id: assignResult.id,
ipAddress: split[0],
port: split[1]
}
}
/**
* @class for InstanceProvision service
*
* @author Vyacheslav Solovjov
*/
export class InstanceProvision implements ServiceMethods<Data> {
app: Application
options: ServiceOptions
docs: any
constructor(options: ServiceOptions = {}, app: Application) {
this.options = options
this.app = app
}
async setup() {}
/**
* A method which get instance of GameServer
* @param availableLocationInstances for Gameserver
* @param locationId
* @param channelId
* @returns id, ipAddress and port
* @author Vyacheslav Solovjov
*/
async getGSInService(availableLocationInstances, locationId: string, channelId: string): Promise<any> {
await this.app.service('instance').Model.destroy({
where: {
assigned: true,
assignedAt: {
[Op.lt]: new Date(new Date().getTime() - 30000)
}
}
})
const instanceModel = (this.app.service('instance') as any).Model
const instanceUserSort = _.orderBy(availableLocationInstances, ['currentUsers'], ['desc'])
const nonPressuredInstances = instanceUserSort.filter((instance: typeof instanceModel) => {
return instance.currentUsers < pressureThresholdPercent * instance.location.maxUsersPerInstance
})
const instances = nonPressuredInstances.length > 0 ? nonPressuredInstances : instanceUserSort
if (!config.kubernetes.enabled) {
logger.info('Resetting local instance to ' + instances[0].id)
const localIp = await getLocalServerIp(channelId != null)
return {
id: instances[0].id,
...localIp
}
}
const gsCleanup = await this.gsCleanup(instances[0])
if (gsCleanup) {
logger.info('GS did not exist and was cleaned up')
if (availableLocationInstances.length > 1)
return this.getGSInService(availableLocationInstances.slice(1), locationId, channelId)
else return getFreeGameserver(this.app, 0, locationId, channelId)
}
logger.info('GS existed, using it')
const ipAddressSplit = instances[0].ipAddress.split(':')
return {
id: instances[0].id,
ipAddress: ipAddressSplit[0],
port: ipAddressSplit[1]
}
}
/**
* A method that attempts to clean up a gameserver that no longer exists
* Currently-running gameservers are fetched via Agones client and their IP addresses
* compared against that of the instance in question. If there's no match, then the instance
* record is out-of date, it should be set to 'ended', and its subdomain provision should be freed.
* Returns false if the GS still exists and no cleanup was done, true if the GS does not exist and
* a cleanup was performed.
*
* @param instance of ipaddress and port
* @returns {@Boolean}
* @author Vyacheslav Solovjov
*/
async gsCleanup(instance): Promise<boolean> {
const gameservers = await (this.app as any).k8AgonesClient.get('gameservers')
const gsIds = gameservers.items.map((gs) =>
gsNameRegex.exec(gs.metadata.name) != null ? gsNameRegex.exec(gs.metadata.name)![1] : null!
)
const [ip, port] = instance.ipAddress.split(':')
const match = gameservers?.items?.find((gs) => {
const inputPort = gs.status.ports?.find((port) => port.name === 'default')
return gs.status.address === ip && inputPort?.port?.toString() === port
})
if (match == null) {
await this.app.service('instance').patch(instance.id, {
ended: true
})
await this.app.service('gameserver-subdomain-provision').patch(
null,
{
allocated: false
},
{
query: {
instanceId: null,
gs_id: {
$nin: gsIds
}
}
}
)
return true
}
await this.app.service('instance').Model.destroy({
where: {
assigned: true,
assignedAt: {
[Op.lt]: new Date(new Date().getTime() - 30000)
}
}
})
return false
}
/**
* A method which find running Gameserver
*
* @param params of query of locationId and instanceId
* @returns {@function} getFreeGameserver and getGSInService
* @author Vyacheslav Solovjov
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async find(params: Params): Promise<any> {
try {
let userId
const locationId = params.query!.locationId
const instanceId = params.query!.instanceId
const channelId = params.query!.channelId
const token = params.query!.token
if (channelId != null) {
// Check if JWT resolves to a user
if (token != null) {
const authResult = await (this.app.service('authentication') as any).strategies.jwt.authenticate(
{ accessToken: token },
{}
)
const identityProvider = authResult['identity-provider']
if (identityProvider != null) {
userId = identityProvider.userId
} else {
throw new BadRequest('Invalid user credentials')
}
}
const channelInstance = await (this.app.service('instance') as any).Model.findOne({
where: {
channelId: channelId,
ended: false
}
})
if (channelInstance == null) return getFreeGameserver(this.app, 0, null!, channelId)
else {
if (config.kubernetes.enabled) {
const gsCleanup = await this.gsCleanup(channelInstance)
if (gsCleanup) return getFreeGameserver(this.app, 0, null!, channelId)
}
const ipAddressSplit = channelInstance.ipAddress.split(':')
return {
id: channelInstance.id,
ipAddress: ipAddressSplit[0],
port: ipAddressSplit[1]
}
}
} else {
// Check if JWT resolves to a user
if (token != null) {
const authResult = await (this.app.service('authentication') as any).strategies.jwt.authenticate(
{ accessToken: token },
{}
)
const identityProvider = authResult['identity-provider']
if (identityProvider != null) {
userId = identityProvider.userId
} else {
throw new BadRequest('Invalid user credentials')
}
}
if (locationId == null) {
throw new BadRequest('Missing location ID')
}
const location = await this.app.service('location').get(locationId)
if (location == null) {
throw new BadRequest('Invalid location ID')
}
if (instanceId != null) {
const instance = await this.app.service('instance').get(instanceId)
if (instance == null || instance.ended === true) return getFreeGameserver(this.app, 0, locationId, null!)
let gsCleanup
if (config.kubernetes.enabled) gsCleanup = await this.gsCleanup(instance)
if (
(!config.kubernetes.enabled || (config.kubernetes.enabled && !gsCleanup)) &&
instance.currentUsers < location.maxUsersPerInstance
) {
const ipAddressSplit = instance.ipAddress.split(':')
return {
id: instance.id,
ipAddress: ipAddressSplit[0],
port: ipAddressSplit[1]
}
}
}
// const user = await this.app.service('user').get(userId)
// If the user is in a party, they should be sent to their party's server as long as they are
// trying to go to the scene their party is in.
// If the user is going to a different scene, they will be removed from the party and sent to a random instance
// if (user.partyId) {
// const partyOwnerResult = await this.app.service('party-user').find({
// query: {
// partyId: user.partyId,
// isOwner: true
// }
// });
// const partyOwner = (partyOwnerResult as any).data[0];
// // Only redirect non-party owners. Party owner will be provisioned below this and will pull the
// // other party members with them.
// if (partyOwner?.userId !== userId && partyOwner?.user.instanceId) {
// const partyInstance = await this.app.service('instance').get(partyOwner.user.instanceId);
// // Only provision the party's instance if the non-owner is trying to go to the party's scene.
// // If they're not, they'll be removed from the party
// if (partyInstance.locationId === locationId) {
// if (!config.kubernetes.enabled) {
// return getLocalServerIp();
// }
// const addressSplit = partyInstance.ipAddress.split(':');
// return {
// ipAddress: addressSplit[0],
// port: addressSplit[1]
// };
// } else {
// // Remove the party user for this user, as they're going to a different scene from their party.
// const partyUser = await this.app.service('party-user').find({
// query: {
// userId: user.id,
// partyId: user.partyId
// }
// });
// const {query, ...paramsCopy} = params;
// paramsCopy.query = {};
// await this.app.service('party-user').remove((partyUser as any).data[0].id, paramsCopy);
// }
// } else if (partyOwner?.userId === userId && partyOwner?.user.instanceId) {
// const partyInstance = await this.app.service('instance').get(partyOwner.user.instanceId);
// if (partyInstance.locationId === locationId) {
// if (!config.kubernetes.enabled) {
// return getLocalServerIp();
// }
// const addressSplit = partyInstance.ipAddress.split(':');
// return {
// ipAddress: addressSplit[0],
// port: addressSplit[1]
// };
// }
// }
// }
const friendsAtLocationResult = await (this.app.service('user') as any).Model.findAndCountAll({
include: [
{
model: (this.app.service('user-relationship') as any).Model,
where: {
relatedUserId: userId,
userRelationshipType: 'friend'
}
},
{
model: (this.app.service('instance') as any).Model,
where: {
locationId: locationId,
ended: false
}
}
]
})
if (friendsAtLocationResult.count > 0) {
const instances = {}
friendsAtLocationResult.rows.forEach((friend) => {
if (instances[friend.instanceId] == null) {
instances[friend.instanceId] = 1
} else {
instances[friend.instanceId]++
}
})
let maxFriends, maxInstanceId
Object.keys(instances).forEach((key) => {
if (maxFriends == null) {
maxFriends = instances[key]
maxInstanceId = key
} else {
if (instances[key] > maxFriends) {
maxFriends = instances[key]
maxInstanceId = key
}
}
})
const maxInstance = await this.app.service('instance').get(maxInstanceId)
if (!config.kubernetes.enabled) {
logger.info('Resetting local instance to ' + maxInstanceId)
const localIp = await getLocalServerIp(false)
return {
id: maxInstanceId,
...localIp
}
}
const ipAddressSplit = maxInstance.ipAddress.split(':')
return {
id: maxInstance.id,
ipAddress: ipAddressSplit[0],
port: ipAddressSplit[1]
}
}
const availableLocationInstances = await (this.app.service('instance') as any).Model.findAll({
where: {
locationId: location.id,
ended: false
},
include: [
{
model: (this.app.service('location') as any).Model,
where: {
maxUsersPerInstance: {
[Op.gt]: Sequelize.col('instance.currentUsers')
}
}
},
{
model: (this.app.service('instance-authorized-user') as any).Model,
required: false
}
]
})
const allowedLocationInstances = availableLocationInstances.filter(
(instance) =>
instance.instance_authorized_users.length === 0 ||
instance.instance_authorized_users.find(
(instanceAuthorizedUser) => instanceAuthorizedUser.userId === userId
)
)
if (allowedLocationInstances.length === 0) return getFreeGameserver(this.app, 0, locationId, null!)
else return this.getGSInService(allowedLocationInstances, locationId, channelId)
}
} catch (err) {
logger.error(err)
throw err
}
}
/**
* A method which get specific instance
*
* @param id of instance
* @param params
* @returns id and text
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async get(id: Id, params: Params): Promise<Data> {
return {
id,
text: `A new message with ID: ${id}!`
}
}
/**
* A method which is used to create instance
*
* @param data which is used to create instance
* @param params
* @returns data of instance
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async create(data: Data, params: Params): Promise<Data> {
if (Array.isArray(data)) {
return Promise.all(data.map((current) => this.create(current, params)))
}
return data
}
/**
* A method used to update instance
*
* @param id
* @param data which is used to update instance
* @param params
* @returns data of updated instance
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async update(id: NullableId, data: Data, params: Params): Promise<Data> {
return data
}
/**
*
* @param id
* @param data
* @param params
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async patch(id: NullableId, data: Data, params: Params): Promise<Data> {
return data
}
/**
* A method used to remove specific instance
*
* @param id of instance
* @param params
* @returns id
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async remove(id: NullableId, params: Params): Promise<Data> {
return { id }
}
} | the_stack |
* ------------------------------------------------------------------------------
* Requirements
* ------------------------------------------------------------------------------
*/
import * as url from 'url';
/*
* This require is to tell webpack to include the code necessary to
* pollyfill the setImmediate and clearImmediate.
*/
require('setimmediate');
import * as chalk from 'chalk';
import { EventEmitter2 as EventEmitter, Listener } from 'eventemitter2';
import remove = require('lodash/remove');
import * as logger from '@hint/utils/dist/src/logging';
import { HintConfig } from '@hint/utils/dist/src/config/types';
import { HttpHeaders, Problem, Severity } from '@hint/utils-types';
import { HTMLDocument, HTMLElement } from '@hint/utils-dom';
import { debug as d } from '@hint/utils-debug';
import { getSeverity } from './config/config-hints';
import {
Events,
HintResources,
IConnector,
IConnectorConstructor,
IFetchOptions,
IFormatter,
IHint,
IHintConstructor,
NetworkData,
Parser,
StringKeyOf
} from './types';
import { HintContext } from './hint-context';
import { HintScope } from './enums/hint-scope';
import { Configuration } from './config';
const debug: debug.IDebugger = d(__filename);
/*
* ------------------------------------------------------------------------------
* Public interface
* ------------------------------------------------------------------------------
*/
export class Engine<E extends Events = Events> extends EventEmitter {
// TODO: review which ones need to be private or not
private parsers: Parser[]
private hints: Map<string, IHint>
private connector: IConnector
private messages: Problem[]
private browserslist: string[] = [];
private ignoredUrls: Map<string, RegExp[]>;
private _formatters: IFormatter[]
private _timeout: number = 60000;
private _lang: string;
/** The DOM of the loaded page. */
public get pageDOM(): HTMLDocument | undefined {
return this.connector.dom;
}
/** The HTML of the loaded page. */
public get pageContent(): string | undefined {
return this.connector.html;
}
/** The headers used in the requests. */
public get pageHeaders(): HttpHeaders | undefined {
return this.connector.headers;
}
/** The list of targetted browsers. */
public get targetedBrowsers(): string[] {
return this.browserslist;
}
/** The list of configured formatters. */
public get formatters(): IFormatter[] {
return this._formatters;
}
/** The max time an event should run. */
public get timeout(): number {
return this._timeout;
}
private isIgnored(urls: RegExp[], resource: string): boolean {
if (!urls) {
return false;
}
return urls.some((urlIgnored: RegExp) => {
return urlIgnored.test(resource);
});
}
public constructor(config: Configuration, resources: HintResources) {
super({
delimiter: '::',
maxListeners: 0,
wildcard: true
});
debug('Initializing hint engine');
this._timeout = config.hintsTimeout;
this.messages = [];
this.browserslist = config.browserslist;
this.ignoredUrls = config.ignoredUrls;
this._lang = config.language!;
const Connector: IConnectorConstructor | null = resources.connector;
const connectorId = config.connector && config.connector.name;
if (!Connector) {
throw new Error(`Connector "${connectorId}" not found`);
}
this.connector = new Connector(this, config.connector && config.connector.options);
this._formatters = resources.formatters.map((Formatter) => {
return new Formatter();
});
this.parsers = resources.parsers.map((ParserConstructor) => {
debug(`Loading parser`);
return new ParserConstructor(this);
});
debug(`Parsers loaded: ${this.parsers.length}`);
this.hints = new Map();
/**
* Returns the configuration for a given hint ID. In the case of a hint
* pointing to a path, it will return the content of the first entry
* in the config that contains the ID. E.g.:
* * `../hint-x-content-type-options` is the key in the config
* * `x-content-type-options` is the ID of the hint
* * One of the keys in the config `includes` the hint ID so it's a match
*
* @param id The id of the hint
*/
const getHintConfig = (id: string): HintConfig | HintConfig[] => {
if (config.hints[id]) {
return config.hints[id];
}
const hintEntries = Object.keys(config.hints);
const idParts = id.split('/');
/**
* At this point we are trying to find the configuration of a hint specified
* via a path.
* The id of a hint (define in `Hint.meta.id`) will be `packageName/hint-id`
* but most likely the code is not going to be on a path that ends like that
* and will be more similar to `packageName/dist/src/hint-id.js`
*
* To solve this, we iterate over all the keys of the `hints` object until
* we find the first entry that includes all the parts of the id
* (`packageName` and `hint-id` in the example).
*
* E.g.:
* * `../hint-packageName/dist/src/hint-id.js` --> Passes
* * `../hint-packageAnotherName/dist/src/hint-id.js` --> Fails because
* `packageName` is not in that path
*/
const hintKey = hintEntries.find((entry) => {
return idParts.every((idPart) => {
return entry.includes(idPart);
});
});
return config.hints[hintKey || ''];
};
resources.hints.forEach((Hint) => {
debug('Loading hints');
const id = Hint.meta.id;
// Use default ignored URLs if no overrides are specified for this hint.
if (Hint.meta.ignoredUrls && !this.ignoredUrls.has(id)) {
this.ignoredUrls.set(id, Hint.meta.ignoredUrls);
}
const ignoreHint = (HintCtor: IHintConstructor): boolean => {
const ignoredConnectors: string[] = HintCtor.meta.ignoredConnectors || [];
return (connectorId === 'local' && HintCtor.meta.scope === HintScope.site) ||
(connectorId !== 'local' && HintCtor.meta.scope === HintScope.local) ||
ignoredConnectors.includes(connectorId || '');
};
const getIgnoredUrls = () => {
const urlsIgnoredForAll = this.ignoredUrls.get('all') || [];
const urlsIgnoredForHint = this.ignoredUrls.get(id) || [];
return urlsIgnoredForAll.concat(urlsIgnoredForHint);
};
const hintOptions: HintConfig | HintConfig[] = getHintConfig(id);
const severity: Severity | null = getSeverity(hintOptions);
if (ignoreHint(Hint)) {
debug(`Hint "${id}" is disabled for the connector "${connectorId}"`);
// TODO: I don't think we should have a dependency on logger here. Maybe send a warning event?
logger.log(chalk.yellow(`Warning: The hint "${id}" will be ignored for the connector "${connectorId}"`));
} else if (severity) {
const context: HintContext = new HintContext(id, this, severity, hintOptions, Hint.meta, getIgnoredUrls());
const hint: IHint = new Hint(context);
this.hints.set(id, hint);
} else {
debug(`Hint "${id}" is disabled`);
}
});
}
public onHintEvent<K extends StringKeyOf<E>>(id: string, eventName: K, listener: (data: E[K], event: string) => void) {
const that = this;
const createEventHandler = (handler: (data: E[K], event: string) => void, hintId: string) => {
/*
* Using fake `this` parameter for typing: https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
* `this.event` defined by eventemitter2: https://github.com/EventEmitter2/EventEmitter2#differences-non-breaking-compatible-with-existing-eventemitter
*/
return function (this: { event: string }, event: E[K]): Promise<any> | null {
const urlsIgnoredForAll = that.ignoredUrls.get('all') || [];
const urlsIgnoredForHint = that.ignoredUrls.get(hintId) || [];
const urlsIgnored = urlsIgnoredForHint.concat(urlsIgnoredForAll);
const eventName = this.event; // eslint-disable-line no-invalid-this
if (that.isIgnored(urlsIgnored, (event as any).resource)) {
return null;
}
// If a hint is spending a lot of time to finish we should ignore it.
return new Promise((resolve, reject) => {
let immediateId: any;
const timeoutId = setTimeout(() => {
if (immediateId) {
clearImmediate(immediateId);
immediateId = null;
}
debug(`Hint ${hintId} timeout`);
resolve(null);
}, that._timeout);
immediateId = setImmediate(async () => {
try {
const result: any = await handler(event, eventName);
if (timeoutId) {
clearTimeout(timeoutId);
}
resolve(result);
} catch (e) {
reject(e);
}
});
});
};
};
this.on(eventName as any, createEventHandler(listener, id));
}
public fetchContent(target: string | url.URL, headers?: object): Promise<NetworkData> {
return this.connector.fetchContent(target, headers);
}
public evaluate(source: string) {
return this.connector.evaluate(source);
}
/** Releases any used resource and/or browser. */
public async close() {
await this.connector.close();
}
/** Reports a message from one of the hints. */
public report(problem: Problem) {
this.messages.push(problem);
}
public clean(fileUrl: url.URL) {
const file = url.format(fileUrl);
remove(this.messages, (message) => {
return message.resource === file;
});
}
public clear() {
this.messages = [];
}
public async notify(this: Engine<Events>, resource: string) {
await this.emitAsync('print', {
problems: this.messages,
resource
});
}
/** Runs all the configured hints on a target */
public async executeOn(target: url.URL, options?: IFetchOptions): Promise<Problem[]> {
const start: number = Date.now();
debug(`Starting the analysis on ${target.href}`);
await this.connector.collect(target, options);
debug(`Total runtime ${Date.now() - start}`);
return this.messages;
}
public querySelectorAll(selector: string): HTMLElement[] {
return this.connector.querySelectorAll(selector);
}
public emit<K extends StringKeyOf<E>>(event: K, data: E[K]): boolean {
return super.emit(event, data);
}
public emitAsync<K extends StringKeyOf<E>>(event: K, data: E[K]): Promise<any[]> {
const ignoredUrls = this.ignoredUrls.get('all') || [];
if (this.isIgnored(ignoredUrls, (data as any).resource)) {
return Promise.resolve([]);
}
return super.emitAsync(event, data);
}
public on<K extends StringKeyOf<E>>(event: K, listener: (data: E[K]) => void): this | Listener {
return super.on(event, listener);
}
public get language() {
return this._lang;
}
} | the_stack |
declare namespace dojox {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl.html
*
* Deprecated. Should require dojox/dtl modules directly rather than trying to access them through
* this module.
*
*/
interface dtl {
}
namespace dtl {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_Templated.html
*
* The base-class for DTL-templated widgets.
*
* @param params Hash of initialization parameters for widget, including scalar values (like title, duration etc.)and functions, typically callbacks like onClick.The hash can contain any of the widget's properties, excluding read-only properties.
* @param srcNodeRef OptionalIf a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree.
*/
class _Templated extends dijit._TemplatedMixin {
constructor(params?: Object, srcNodeRef?: HTMLElement);
/**
* Object to which attach points and events will be scoped. Defaults
* to 'this'.
*
*/
"attachScope": Object;
/**
*
*/
"searchContainerNode": boolean;
/**
* Path to template (HTML file) for this widget relative to dojo.baseUrl.
* Deprecated: use templateString with require([... "dojo/text!..."], ...) instead
*
*/
"templatePath": string;
/**
* A string that represents the widget template.
* Use in conjunction with dojo.cache() to load from a file.
*
*/
"templateString": string;
/**
*
*/
buildRendering(): void;
/**
*
*/
destroyRendering(): void;
/**
* Layer for dijit._Templated.getCachedTemplate
*
* @param templatePath
* @param templateString
* @param alwaysUseString
*/
getCachedTemplate(templatePath: any, templateString: any, alwaysUseString: any): any;
/**
* Renders the widget.
*
*/
render(): void;
/**
*
*/
startup(): void;
/**
* Static method to get a template based on the templatePath or
* templateString key
*/
getCachedTemplate(): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.html
*
*
*/
interface _base {
/**
*
*/
BOOLS: Object;
/**
*
*/
data: Object;
/**
*
*/
date: Object;
/**
*
*/
dates: Object;
/**
*
*/
dijit: Object;
/**
*
*/
dom: Object;
/**
*
*/
html: Object;
/**
*
*/
htmlstrings: Object;
/**
*
*/
integers: Object;
/**
*
*/
lists: Object;
/**
*
*/
loader: Object;
/**
*
*/
logic: Object;
/**
*
*/
loop: Object;
/**
*
*/
misc: Object;
/**
*
*/
objects: Object;
/**
* A register for filters and tags.
*
*/
register: Object;
/**
*
*/
strings: Object;
/**
*
*/
text: Object;
/**
*
*/
TOKEN_ATTR: number;
/**
*
*/
TOKEN_BLOCK: number;
/**
*
*/
TOKEN_CHANGE: number;
/**
*
*/
TOKEN_COMMENT: number;
/**
*
*/
TOKEN_CUSTOM: number;
/**
*
*/
TOKEN_NODE: number;
/**
*
*/
TOKEN_TEXT: number;
/**
*
*/
TOKEN_VAR: number;
/**
*
* @param key
* @param value
*/
AttributeNode(key: any, value: any): void;
/**
* Changes the parent during render/unrender
*
* @param node
* @param up Optional
* @param root
*/
ChangeNode(node: any, up: boolean, root: boolean): void;
/**
* Represents a runtime context used by DTL templates.
*
* @param dict
*/
Context(dict: Object): void;
/**
* Allows the manipulation of DOM
* Use this to append a child, change the parent, or
* change the attribute of the current node.
*
* @param parent The parent node.
*/
DomBuffer(parent: HTMLElement): void;
/**
*
* @param args
* @param node
*/
DomInline(args: any, node: any): void;
/**
* The template class for DOM templating.
*
* @param obj
*/
DomTemplate(obj: String): void;
/**
* The template class for DOM templating.
*
* @param obj
*/
DomTemplate(obj: HTMLElement): void;
/**
* The template class for DOM templating.
*
* @param obj
*/
DomTemplate(obj: dojo._base.url): void;
/**
*
* @param args
* @param node
*/
Inline(args: any, node: any): void;
/**
*
* @param value
*/
mark_safe(value: any): void;
/**
*
* @param str
*/
quickFilter(str: any): void;
/**
* The base class for text-based templates.
*
* @param template The string or location of the string touse as a template
* @param isString Indicates whether the template is a string or a url.
*/
Template(template: String, isString: boolean): void;
/**
* The base class for text-based templates.
*
* @param template The string or location of the string touse as a template
* @param isString Indicates whether the template is a string or a url.
*/
Template(template: dojo._base.url, isString: boolean): void;
}
module _base {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base._base.html
*
*
*/
interface _base {
/**
* Escapes a string's HTML
*
* @param value
*/
escape(value: any): void;
/**
*
* @param value
*/
safe(value: any): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.BOOLS.html
*
*
*/
interface BOOLS {
/**
*
*/
checked: number;
/**
*
*/
disabled: number;
/**
*
*/
readonly: number;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.date.html
*
*
*/
interface date {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.data.html
*
*
*/
interface data {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.dates.html
*
*
*/
interface dates {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.dijit.html
*
*
*/
interface dijit {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.dom.html
*
*
*/
interface dom {
/**
*
* @param text
*/
getTemplate(text: any): Object;
/**
*
* @param nodes
*/
tokenize(nodes: HTMLElement): any[];
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.html.html
*
*
*/
interface html {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.htmlstrings.html
*
*
*/
interface htmlstrings {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.integers.html
*
*
*/
interface integers {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.loader.html
*
*
*/
interface loader {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.lists.html
*
*
*/
interface lists {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.loop.html
*
*
*/
interface loop {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.logic.html
*
*
*/
interface logic {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.misc.html
*
*
*/
interface misc {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.objects.html
*
*
*/
interface objects {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.register.html
*
* A register for filters and tags.
*
*/
interface register {
/**
* Register the specified filter libraries.
* The locations parameter defines the contents of each library as a hash whose keys are the library names and values
* an array of the filters exported by the library. For example, the filters exported by the date library would be:
*
* { "dates": ["date", "time", "timesince", "timeuntil"] }
*
* @param base The base path of the libraries.
* @param locations An object defining the filters for each library as a hash whose keys are the library names and values an array of the filters exported by the library.
*/
filters(base: String, locations: Object): void;
/**
* Register the specified tag libraries.
* The locations parameter defines the contents of each library as a hash whose keys are the library names and values
* an array of the tags exported by the library. For example, the tags exported by the logic library would be:
*
* { logic: ["if", "for", "ifequal", "ifnotequal"] }
*
* @param base The base path of the libraries.
* @param locations An object defining the tags for each library as a hash whose keys are the library names and values an array of the tags or filters exported by the library.
*/
tags(base: String, locations: Object): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.strings.html
*
*
*/
interface strings {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_base.text.html
*
*
*/
interface text {
/**
*
* @param name
* @param errorless
*/
getFilter(name: any, errorless: any): any;
/**
*
* @param name
* @param errorless
*/
getTag(name: any, errorless: any): any;
/**
*
* @param file
*/
getTemplate(file: any): any;
/**
*
* @param file
*/
getTemplateString(file: any): String;
/**
*
* @param str
*/
tokenize(str: any): any;
}
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/dom.html
*
*
*/
interface dom {
/**
*
* @param text
*/
getTemplate(text: any): Object;
/**
*
* @param nodes
*/
tokenize(nodes: HTMLElement): any[];
}
namespace dom {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/dom._uppers.html
*
*
*/
interface _uppers {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/dom._attributes.html
*
*
*/
interface _attributes {
}
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/_DomTemplated.html
*
* The base class for DOM-based templating.
*
*/
interface _DomTemplated{(): void}
module _DomTemplated {
/**
* Constructs the DOM representation.
*
*/
interface buildRendering{(): void}
/**
* Renders this template.
*
* @param context OptionalThe runtime context.
* @param tpl OptionalThe template to render. Optional.
*/
interface render{(context: dojox.dtl.Context, tpl: dojox.dtl._DomTemplated): void}
/**
* Quickly switch between templated by location
*
* @param template The new template.
* @param context OptionalThe runtime context.
*/
interface setTemplate{(template: String, context: dojox.dtl.Context): void}
/**
* Quickly switch between templated by location
*
* @param template The new template.
* @param context OptionalThe runtime context.
*/
interface setTemplate{(template: dojo._base.url, context: dojox.dtl.Context): void}
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/Context.html
*
* Represents a runtime context used by DTL templates.
*
* @param dict
*/
interface Context{(dict: Object): void}
namespace Context {
/**
* Returns a clone of this context object, with the items from the passed objecct mixed in.
*
* @param obj The object to extend.
*/
interface extend{(obj: dojox.dtl.Context ): any}
/**
* Returns a clone of this context object, with the items from the passed objecct mixed in.
*
* @param obj The object to extend.
*/
interface extend{(obj: Object): any}
/**
* Returns a clone of this context, only containing the items defined in the filter.
*
* @param filter
*/
interface filter{(filter: dojox.dtl.Context ): any}
/**
* Returns a clone of this context, only containing the items defined in the filter.
*
* @param filter
*/
interface filter{(filter: Object): any}
/**
* Returns a clone of this context, only containing the items defined in the filter.
*
* @param filter
*/
interface filter{(filter: String[]): any}
/**
*
* @param key
* @param otherwise
*/
interface get{(key: any, otherwise: any): any}
/**
* Returns the set of keys exported by this context.
*
*/
interface getKeys{(): any[]}
/**
* Gets the object on which to perform operations.
*
*/
interface getThis{(): any}
/**
* Indicates whether the specified key is defined on this context.
*
* @param key The key to look up.
*/
interface hasKey{(key: String): boolean}
/**
*
*/
interface pop{(): void}
/**
*
*/
interface push{(): any}
/**
* Sets the object on which to perform operations.
*
* @param scope the this ref.
*/
interface setThis{(scope: Object): void}
/**
*
* @param dict
*/
interface update{(dict: any): any}
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/DomInline.html
*
*
* @param args
* @param node
*/
class DomInline {
constructor(args: Object, node: HTMLElement);
/**
* Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute
* for each XXX attribute to be mapped to the DOM.
*
* attributeMap sets up a "binding" between attributes (aka properties)
* of the widget and the widget's DOM.
* Changes to widget attributes listed in attributeMap will be
* reflected into the DOM.
*
* For example, calling set('title', 'hello')
* on a TitlePane will automatically cause the TitlePane's DOM to update
* with the new title.
*
* attributeMap is a hash where the key is an attribute of the widget,
* and the value reflects a binding to a:
*
* DOM node attribute
* focus: {node: "focusNode", type: "attribute"}
* Maps this.focus to this.focusNode.focus
*
* DOM node innerHTML
* title: { node: "titleNode", type: "innerHTML" }
* Maps this.title to this.titleNode.innerHTML
*
* DOM node innerText
* title: { node: "titleNode", type: "innerText" }
* Maps this.title to this.titleNode.innerText
*
* DOM node CSS class
* myClass: { node: "domNode", type: "class" }
* Maps this.myClass to this.domNode.className
*
* If the value is an array, then each element in the array matches one of the
* formats of the above list.
*
* There are also some shorthands for backwards compatibility:
*
* string --> { node: string, type: "attribute" }, for example:
* "focusNode" ---> { node: "focusNode", type: "attribute" }
* "" --> { node: "domNode", type: "attribute" }
*
*/
attributeMap: Object
/**
* Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate
* widget state.
*
*/
baseClass: string
/**
*
*/
"class": string
/**
* Designates where children of the source DOM node will be placed.
* "Children" in this case refers to both DOM nodes and widgets.
* For example, for myWidget:
*
* <div data-dojo-type=myWidget>
* <b> here's a plain DOM node
* <span data-dojo-type=subWidget>and a widget</span>
* <i> and another plain DOM node </i>
* </div>
* containerNode would point to:
*
* <b> here's a plain DOM node
* <span data-dojo-type=subWidget>and a widget</span>
* <i> and another plain DOM node </i>
* In templated widgets, "containerNode" is set via a
* data-dojo-attach-point assignment.
*
* containerNode must be defined for any widget that accepts innerHTML
* (like ContentPane or BorderContainer or even Button), and conversely
* is null for widgets that don't, like TextBox.
*
*/
containerNode: HTMLElement
/**
*
*/
context: Object
/**
*
*/
declaredClass: string
/**
* Bi-directional support, as defined by the HTML DIR
* attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's
* default direction.
*
*/
dir: string
/**
* This is our visible representation of the widget! Other DOM
* Nodes may by assigned to other properties, usually through the
* template system's data-dojo-attach-point syntax, but the domNode
* property is the canonical "top level" node in widget UI.
*
*/
domNode: HTMLElement
/**
* This widget or a widget it contains has focus, or is "active" because
* it was recently clicked.
*
*/
focused: boolean
/**
* A unique, opaque ID string that can be assigned by users or by the
* system. If the developer passes an ID which is known not to be
* unique, the specified ID is ignored and the system-generated ID is
* used instead.
*
*/
id: string
/**
* Rarely used. Overrides the default Dojo locale used to render this widget,
* as defined by the HTML LANG attribute.
* Value must be among the list of locales specified during by the Dojo bootstrap,
* formatted according to RFC 3066 (like en-us).
*
*/
lang: string
/**
* The document this widget belongs to. If not specified to constructor, will default to
* srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global
*
*/
ownerDocument: Object
/**
* pointer to original DOM node
*
*/
srcNodeRef: HTMLElement
/**
* HTML style attributes as cssText string or name/value hash
*
*/
style: string
/**
* HTML title attribute.
*
* For form widgets this specifies a tooltip to display when hovering over
* the widget (just like the native HTML title attribute).
*
* For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer,
* etc., it's used to specify the tab label, accordion pane title, etc. In this case it's
* interpreted as HTML.
*
*/
title: string
/**
* When this widget's title attribute is used to for a tab label, accordion pane title, etc.,
* this specifies the tooltip to appear when the mouse is hovered over that text.
*
*/
tooltip: string
/**
*
*/
buildRendering(): void
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: String, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: String, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: Function, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: Function, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: String, method: Function): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: String, method: Function): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: Function, method: Function): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: Function, method: Function): any
/**
* Wrapper to setTimeout to avoid deferred functions executing
* after the originating widget has been destroyed.
* Returns an object handle with a remove method (that returns null) (replaces clearTimeout).
*
* @param fcn Function reference.
* @param delay OptionalDelay, defaults to 0.
*/
defer(fcn: Function, delay: number): Object
/**
* Destroy this widget, but not its descendants. Descendants means widgets inside of
* this.containerNode. Will also destroy any resources (including widgets) registered via this.own().
*
* This method will also destroy internal widgets such as those created from a template,
* assuming those widgets exist inside of this.domNode but outside of this.containerNode.
*
* For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not
* depend on the current ability to destroy a widget without destroying its descendants. Generally
* they should use destroyRecursive() for widgets with children.
*
* @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets
*/
destroy(preserveDom: boolean): void
/**
* Recursively destroy the children of this widget and their
* descendants.
*
* @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets.
*/
destroyDescendants(preserveDom: boolean): void
/**
* Destroy this widget and its descendants
* This is the generic "destructor" function that all widget users
* should call to cleanly discard with a widget. Once a widget is
* destroyed, it is removed from the manager object.
*
* @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets.
*/
destroyRecursive(preserveDom: boolean): void
/**
* Destroys the DOM nodes associated with this widget.
*
* @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet.
*/
destroyRendering(preserveDom: boolean): void
/**
* Deprecated, will be removed in 2.0, use handle.remove() instead.
*
* Disconnects handle created by connect.
*
* @param handle
*/
disconnect(handle: any): void
/**
* Used by widgets to signal that a synthetic event occurred, ex:
*
* myWidget.emit("attrmodified-selectedChildWidget", ).
* Emits an event on this.domNode named type.toLowerCase(), based on eventObj.
* Also calls onType() method, if present, and returns value from that method.
* By default passes eventObj to callback, but will pass callbackArgs instead, if specified.
* Modifies eventObj by adding missing parameters (bubbles, cancelable, widget).
*
* @param type
* @param eventObj Optional
* @param callbackArgs Optional
*/
emit(type: String, eventObj: Object, callbackArgs: any[]): any
/**
* Get a property from a widget.
* Get a named property from a widget. The property may
* potentially be retrieved via a getter method. If no getter is defined, this
* just retrieves the object's property.
*
* For example, if the widget has properties foo and bar
* and a method named _getFooAttr(), calling:
* myWidget.get("foo") would be equivalent to calling
* widget._getFooAttr() and myWidget.get("bar")
* would be equivalent to the expression
* widget.bar2
*
* @param name The property to get.
*/
get(name: any): any
/**
* Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent
* is this widget. Note that it does not return all descendants, but rather just direct children.
* Analogous to Node.childNodes,
* except containing widgets rather than DOMNodes.
*
* The result intentionally excludes internally created widgets (a.k.a. supporting widgets)
* outside of this.containerNode.
*
* Note that the array returned is a simple array. Application code should not assume
* existence of methods like forEach().
*
*/
getChildren(): any[]
/**
* Returns the parent widget of this widget.
*
*/
getParent(): any
/**
* Return true if this widget can currently be focused
* and false if not
*
*/
isFocusable(): any
/**
* Return this widget's explicit or implicit orientation (true for LTR, false for RTL)
*
*/
isLeftToRight(): any
/**
* Call specified function when event occurs, ex: myWidget.on("click", function() ... ).
* Call specified function when event type occurs, ex: myWidget.on("click", function() ... ).
* Note that the function is not run in any particular scope, so if (for example) you want it to run in the
* widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)).
*
* @param type Name of event (ex: "click") or extension event like touch.press.
* @param func
*/
on(type: String, func: Function): any
/**
* Call specified function when event occurs, ex: myWidget.on("click", function() ... ).
* Call specified function when event type occurs, ex: myWidget.on("click", function() ... ).
* Note that the function is not run in any particular scope, so if (for example) you want it to run in the
* widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)).
*
* @param type Name of event (ex: "click") or extension event like touch.press.
* @param func
*/
on(type: Function, func: Function): any
/**
* Track specified handles and remove/destroy them when this instance is destroyed, unless they were
* already removed/destroyed manually.
*
*/
own(): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: String, position: String): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: HTMLElement, position: String): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: dijit._WidgetBase, position: String): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: String, position: number): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: HTMLElement, position: number): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: dijit._WidgetBase, position: number): any
/**
* Processing after the DOM fragment is created
* Called after the DOM fragment has been created, but not necessarily
* added to the document. Do not include any operations which rely on
* node dimensions or placement.
*
*/
postCreate(): void
/**
*
*/
postMixInProperties(): void
/**
*
* @param context Optional
*/
render(context: dojox.dtl.Context): void
/**
* Set a property on a widget
* Sets named properties on a widget which may potentially be handled by a
* setter in the widget.
*
* For example, if the widget has properties foo and bar
* and a method named _setFooAttr(), calling
* myWidget.set("foo", "Howdy!") would be equivalent to calling
* widget._setFooAttr("Howdy!") and myWidget.set("bar", 3)
* would be equivalent to the statement widget.bar = 3;
*
* set() may also be called with a hash of name/value pairs, ex:
*
* myWidget.set({
* foo: "Howdy",
* bar: 3
* });
* This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
*
* @param name The property to set.
* @param value The value to set in the property.
*/
set(name: any, value: any): any
/**
* Processing after the DOM fragment is added to the document
* Called after a widget and its children have been created and added to the page,
* and all related widgets have finished their create() cycle, up through postCreate().
*
* Note that startup() may be called while the widget is still hidden, for example if the widget is
* inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer.
* For widgets that need to do layout, it's best to put that layout code inside resize(), and then
* extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible.
*
*/
startup(): void
/**
* Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead.
*
* Subscribes to the specified topic and calls the specified method
* of this object and registers for unsubscribe() on widget destroy.
*
* Provide widget-specific analog to dojo.subscribe, except with the
* implicit use of this widget as the target object.
*
* @param t The topic
* @param method The callback
*/
subscribe(t: String, method: Function): any
/**
* Returns a string that represents the widget.
* When a widget is cast to a string, this method will be used to generate the
* output. Currently, it does not implement any sort of reversible
* serialization.
*
*/
toString(): string
/**
* Deprecated. Override destroy() instead to implement custom widget tear-down
* behavior.
*
*/
uninitialize(): boolean
/**
* Deprecated, will be removed in 2.0, use handle.remove() instead.
*
* Unsubscribes handle created by this.subscribe.
* Also removes handle from this widget's list of subscriptions
*
* @param handle
*/
unsubscribe(handle: Object): void
/**
* Watches a property for changes
*
* @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched
* @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value.
*/
watch(name: String, callback: Function): any
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/Inline.html
*
*
* @param args
* @param node
*/
class Inline {
constructor(args:Object, node:HTMLElement);
/**
* Deprecated. Instead of attributeMap, widget should have a _setXXXAttr attribute
* for each XXX attribute to be mapped to the DOM.
*
* attributeMap sets up a "binding" between attributes (aka properties)
* of the widget and the widget's DOM.
* Changes to widget attributes listed in attributeMap will be
* reflected into the DOM.
*
* For example, calling set('title', 'hello')
* on a TitlePane will automatically cause the TitlePane's DOM to update
* with the new title.
*
* attributeMap is a hash where the key is an attribute of the widget,
* and the value reflects a binding to a:
*
* DOM node attribute
* focus: {node: "focusNode", type: "attribute"}
* Maps this.focus to this.focusNode.focus
*
* DOM node innerHTML
* title: { node: "titleNode", type: "innerHTML" }
* Maps this.title to this.titleNode.innerHTML
*
* DOM node innerText
* title: { node: "titleNode", type: "innerText" }
* Maps this.title to this.titleNode.innerText
*
* DOM node CSS class
* myClass: { node: "domNode", type: "class" }
* Maps this.myClass to this.domNode.className
*
* If the value is an array, then each element in the array matches one of the
* formats of the above list.
*
* There are also some shorthands for backwards compatibility:
*
* string --> { node: string, type: "attribute" }, for example:
* "focusNode" ---> { node: "focusNode", type: "attribute" }
* "" --> { node: "domNode", type: "attribute" }
*
*/
attributeMap: Object
/**
* Root CSS class of the widget (ex: dijitTextBox), used to construct CSS classes to indicate
* widget state.
*
*/
baseClass: string
/**
*
*/
class: string
/**
* Designates where children of the source DOM node will be placed.
* "Children" in this case refers to both DOM nodes and widgets.
* For example, for myWidget:
*
* <div data-dojo-type=myWidget>
* <b> here's a plain DOM node
* <span data-dojo-type=subWidget>and a widget</span>
* <i> and another plain DOM node </i>
* </div>
* containerNode would point to:
*
* <b> here's a plain DOM node
* <span data-dojo-type=subWidget>and a widget</span>
* <i> and another plain DOM node </i>
* In templated widgets, "containerNode" is set via a
* data-dojo-attach-point assignment.
*
* containerNode must be defined for any widget that accepts innerHTML
* (like ContentPane or BorderContainer or even Button), and conversely
* is null for widgets that don't, like TextBox.
*
*/
containerNode: HTMLElement
/**
*
*/
context: Object
/**
*
*/
declaredClass: string
/**
* Bi-directional support, as defined by the HTML DIR
* attribute. Either left-to-right "ltr" or right-to-left "rtl". If undefined, widgets renders in page's
* default direction.
*
*/
dir: string
/**
* This is our visible representation of the widget! Other DOM
* Nodes may by assigned to other properties, usually through the
* template system's data-dojo-attach-point syntax, but the domNode
* property is the canonical "top level" node in widget UI.
*
*/
domNode: HTMLElement
/**
* This widget or a widget it contains has focus, or is "active" because
* it was recently clicked.
*
*/
focused: boolean
/**
* A unique, opaque ID string that can be assigned by users or by the
* system. If the developer passes an ID which is known not to be
* unique, the specified ID is ignored and the system-generated ID is
* used instead.
*
*/
id: string
/**
* Rarely used. Overrides the default Dojo locale used to render this widget,
* as defined by the HTML LANG attribute.
* Value must be among the list of locales specified during by the Dojo bootstrap,
* formatted according to RFC 3066 (like en-us).
*
*/
lang: string
/**
* The document this widget belongs to. If not specified to constructor, will default to
* srcNodeRef.ownerDocument, or if no sourceRef specified, then to the document global
*
*/
ownerDocument: Object
/**
* pointer to original DOM node
*
*/
srcNodeRef: HTMLElement
/**
* HTML style attributes as cssText string or name/value hash
*
*/
style: string
/**
* HTML title attribute.
*
* For form widgets this specifies a tooltip to display when hovering over
* the widget (just like the native HTML title attribute).
*
* For TitlePane or for when this widget is a child of a TabContainer, AccordionContainer,
* etc., it's used to specify the tab label, accordion pane title, etc. In this case it's
* interpreted as HTML.
*
*/
title: string
/**
* When this widget's title attribute is used to for a tab label, accordion pane title, etc.,
* this specifies the tooltip to appear when the mouse is hovered over that text.
*
*/
tooltip: string
/**
*
*/
buildRendering(): void
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: String, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: String, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: Function, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: Function, method: String): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: String, method: Function): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: String, method: Function): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: Object, event: Function, method: Function): any
/**
* Deprecated, will be removed in 2.0, use this.own(on(...)) or this.own(aspect.after(...)) instead.
*
* Connects specified obj/event to specified method of this object
* and registers for disconnect() on widget destroy.
*
* Provide widget-specific analog to dojo.connect, except with the
* implicit use of this widget as the target object.
* Events connected with this.connect are disconnected upon
* destruction.
*
* @param obj
* @param event
* @param method
*/
connect(obj: any, event: Function, method: Function): any
/**
* Wrapper to setTimeout to avoid deferred functions executing
* after the originating widget has been destroyed.
* Returns an object handle with a remove method (that returns null) (replaces clearTimeout).
*
* @param fcn Function reference.
* @param delay OptionalDelay, defaults to 0.
*/
defer(fcn: Function, delay: number): Object
/**
* Destroy this widget, but not its descendants. Descendants means widgets inside of
* this.containerNode. Will also destroy any resources (including widgets) registered via this.own().
*
* This method will also destroy internal widgets such as those created from a template,
* assuming those widgets exist inside of this.domNode but outside of this.containerNode.
*
* For 2.0 it's planned that this method will also destroy descendant widgets, so apps should not
* depend on the current ability to destroy a widget without destroying its descendants. Generally
* they should use destroyRecursive() for widgets with children.
*
* @param preserveDom If true, this method will leave the original DOM structure alone.Note: This will not yet work with _TemplatedMixin widgets
*/
destroy(preserveDom: boolean): void
/**
* Recursively destroy the children of this widget and their
* descendants.
*
* @param preserveDom OptionalIf true, the preserveDom attribute is passed to all descendantwidget's .destroy() method. Not for use with _Templatedwidgets.
*/
destroyDescendants(preserveDom: boolean): void
/**
* Destroy this widget and its descendants
* This is the generic "destructor" function that all widget users
* should call to cleanly discard with a widget. Once a widget is
* destroyed, it is removed from the manager object.
*
* @param preserveDom OptionalIf true, this method will leave the original DOM structurealone of descendant Widgets. Note: This will NOT work withdijit._TemplatedMixin widgets.
*/
destroyRecursive(preserveDom: boolean): void
/**
* Destroys the DOM nodes associated with this widget.
*
* @param preserveDom OptionalIf true, this method will leave the original DOM structure aloneduring tear-down. Note: this will not work with _Templatedwidgets yet.
*/
destroyRendering(preserveDom: boolean): void
/**
* Deprecated, will be removed in 2.0, use handle.remove() instead.
*
* Disconnects handle created by connect.
*
* @param handle
*/
disconnect(handle: any): void
/**
* Used by widgets to signal that a synthetic event occurred, ex:
*
* myWidget.emit("attrmodified-selectedChildWidget", {}).
* Emits an event on this.domNode named type.toLowerCase(), based on eventObj.
* Also calls onType() method, if present, and returns value from that method.
* By default passes eventObj to callback, but will pass callbackArgs instead, if specified.
* Modifies eventObj by adding missing parameters (bubbles, cancelable, widget).
*
* @param type
* @param eventObj Optional
* @param callbackArgs Optional
*/
emit(type: String, eventObj: Object, callbackArgs: any[]): any
/**
* Get a property from a widget.
* Get a named property from a widget. The property may
* potentially be retrieved via a getter method. If no getter is defined, this
* just retrieves the object's property.
*
* For example, if the widget has properties foo and bar
* and a method named _getFooAttr(), calling:
* myWidget.get("foo") would be equivalent to calling
* widget._getFooAttr() and myWidget.get("bar")
* would be equivalent to the expression
* widget.bar2
*
* @param name The property to get.
*/
get(name: any): any
/**
* Returns all direct children of this widget, i.e. all widgets underneath this.containerNode whose parent
* is this widget. Note that it does not return all descendants, but rather just direct children.
* Analogous to Node.childNodes,
* except containing widgets rather than DOMNodes.
*
* The result intentionally excludes internally created widgets (a.k.a. supporting widgets)
* outside of this.containerNode.
*
* Note that the array returned is a simple array. Application code should not assume
* existence of methods like forEach().
*
*/
getChildren(): any[]
/**
* Returns the parent widget of this widget.
*
*/
getParent(): any
/**
* Return true if this widget can currently be focused
* and false if not
*
*/
isFocusable(): any
/**
* Return this widget's explicit or implicit orientation (true for LTR, false for RTL)
*
*/
isLeftToRight(): any
/**
* Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }).
* Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }).
* Note that the function is not run in any particular scope, so if (for example) you want it to run in the
* widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)).
*
* @param type Name of event (ex: "click") or extension event like touch.press.
* @param func
*/
on(type: String, func: Function): any
/**
* Call specified function when event occurs, ex: myWidget.on("click", function(){ ... }).
* Call specified function when event type occurs, ex: myWidget.on("click", function(){ ... }).
* Note that the function is not run in any particular scope, so if (for example) you want it to run in the
* widget's scope you must do myWidget.on("click", lang.hitch(myWidget, func)).
*
* @param type Name of event (ex: "click") or extension event like touch.press.
* @param func
*/
on(type: Function, func: Function): any
/**
* Track specified handles and remove/destroy them when this instance is destroyed, unless they were
* already removed/destroyed manually.
*
*/
own(): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: String, position: String): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: HTMLElement, position: String): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: dijit._WidgetBase, position: String): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: String, position: number): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: HTMLElement, position: number): any
/**
* Place this widget somewhere in the DOM based
* on standard domConstruct.place() conventions.
* A convenience function provided in all _Widgets, providing a simple
* shorthand mechanism to put an existing (or newly created) Widget
* somewhere in the dom, and allow chaining.
*
* @param reference Widget, DOMNode, or id of widget or DOMNode
* @param position OptionalIf reference is a widget (or id of widget), and that widget has an ".addChild" method,it will be called passing this widget instance into that method, supplying the optionalposition index passed. In this case position (if specified) should be an integer.If reference is a DOMNode (or id matching a DOMNode but not a widget),the position argument can be a numeric index or a string"first", "last", "before", or "after", same as dojo/dom-construct::place().
*/
placeAt(reference: dijit._WidgetBase, position: number): any
/**
* Processing after the DOM fragment is created
* Called after the DOM fragment has been created, but not necessarily
* added to the document. Do not include any operations which rely on
* node dimensions or placement.
*
*/
postCreate(): void
/**
*
*/
postMixInProperties(): void
/**
*
* @param context Optional
*/
render(context: Object): void
/**
*
* @param context Optional
*/
render(context: dojox.dtl.Context): void
/**
* Set a property on a widget
* Sets named properties on a widget which may potentially be handled by a
* setter in the widget.
*
* For example, if the widget has properties foo and bar
* and a method named _setFooAttr(), calling
* myWidget.set("foo", "Howdy!") would be equivalent to calling
* widget._setFooAttr("Howdy!") and myWidget.set("bar", 3)
* would be equivalent to the statement widget.bar = 3;
*
* set() may also be called with a hash of name/value pairs, ex:
*
* myWidget.set({
* foo: "Howdy",
* bar: 3
* });
* This is equivalent to calling set(foo, "Howdy") and set(bar, 3)
*
* @param name The property to set.
* @param value The value to set in the property.
*/
set(name: any, value: any): any
/**
* Processing after the DOM fragment is added to the document
* Called after a widget and its children have been created and added to the page,
* and all related widgets have finished their create() cycle, up through postCreate().
*
* Note that startup() may be called while the widget is still hidden, for example if the widget is
* inside a hidden dijit/Dialog or an unselected tab of a dijit/layout/TabContainer.
* For widgets that need to do layout, it's best to put that layout code inside resize(), and then
* extend dijit/layout/_LayoutWidget so that resize() is called when the widget is visible.
*
*/
startup(): void
/**
* Deprecated, will be removed in 2.0, use this.own(topic.subscribe()) instead.
*
* Subscribes to the specified topic and calls the specified method
* of this object and registers for unsubscribe() on widget destroy.
*
* Provide widget-specific analog to dojo.subscribe, except with the
* implicit use of this widget as the target object.
*
* @param t The topic
* @param method The callback
*/
subscribe(t: String, method: Function): any
/**
* Returns a string that represents the widget.
* When a widget is cast to a string, this method will be used to generate the
* output. Currently, it does not implement any sort of reversible
* serialization.
*
*/
toString(): string
/**
* Deprecated. Override destroy() instead to implement custom widget tear-down
* behavior.
*
*/
uninitialize(): boolean
/**
* Deprecated, will be removed in 2.0, use handle.remove() instead.
*
* Unsubscribes handle created by this.subscribe.
* Also removes handle from this widget's list of subscriptions
*
* @param handle
*/
unsubscribe(handle: Object): void
/**
* Watches a property for changes
*
* @param name OptionalIndicates the property to watch. This is optional (the callback may be theonly parameter), and if omitted, all the properties will be watched
* @param callback The function to execute when the property changes. This will be called afterthe property has been changed. The callback will be called with the |this|set to the instance, the first argument as the name of the property, thesecond argument as the old value and the third argument as the new value.
*/
watch(name: String, callback: Function): any
}
namespace contrib {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/contrib/objects.html
*
*
*/
interface objects {
/**
*
* @param value
* @param arg
*/
key(value: any, arg: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/contrib/dijit.html
*
*
*/
interface dijit {
/**
*
*/
widgetsInTemplate: boolean;
/**
*
* @param keys
* @param object
*/
AttachNode(keys: any, object: any): void;
/**
*
* @param parser
* @param token
*/
data_dojo_attach_event(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
data_dojo_attach_point(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
data_dojo_type(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
dojoAttachEvent(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
dojoAttachPoint(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
dojoType(parser: any, token: any): any;
/**
*
* @param node
* @param parsed
*/
DojoTypeNode(node: any, parsed: any): void;
/**
*
* @param command
* @param obj
*/
EventNode(command: any, obj: any): void;
/**
* Associates an event type to a function (on the current widget) by name
*
* @param parser
* @param token
*/
on(parser: any, token: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/contrib/data.html
*
*
*/
interface data {
/**
* Turns a list of data store items into DTL compatible items
*
* @param parser
* @param token
*/
bind_data(parser: any, token: any): any;
/**
* Queries a data store and makes the returned items DTL compatible
*
* @param parser
* @param token
*/
bind_query(parser: any, token: any): any;
/**
*
* @param items
* @param query
* @param store
* @param alias
*/
BindDataNode(items: any, query: any, store: any, alias: any): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/contrib/dom.html
*
*
*/
interface dom {
/**
* Buffer large DOM manipulations during re-render.
* When using DomTemplate, wrap any content
* that you expect to change often during
* re-rendering. It will then remove its parent
* from the main document while it re-renders that
* section of code. It will only remove it from
* the main document if a mainpulation of somes sort
* happens. ie It won't swap out if it diesn't have to.
*
* @param parser
* @param token
*/
buffer(parser: any, token: any): any;
/**
*
* @param nodelist
* @param options
*/
BufferNode(nodelist: any, options: any): void;
/**
*
* @param parser
* @param token
*/
html(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
style_(parser: any, token: any): any;
/**
*
* @param styles
*/
StyleNode(styles: any): void;
}
}
namespace ext_dojo {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/ext-dojo/NodeList.html
*
* Array-like object which adds syntactic
* sugar for chaining, common iteration operations, animation, and
* node manipulation. NodeLists are most often returned as the
* result of dojo/query() calls.
* NodeList instances provide many utilities that reflect
* core Dojo APIs for Array iteration and manipulation, DOM
* manipulation, and event handling. Instead of needing to dig up
* functions in the dojo package, NodeLists generally make the
* full power of Dojo available for DOM manipulation tasks in a
* simple, chainable way.
*
* @param array
*/
interface NodeList{(array: any): void}
namespace NodeList {
/**
*
*/
var events: any[]
/**
* adds the specified class to every node in the list
*
* @param className A String class name to add, or several space-separated class names,or an array of class names.
*/
interface addClass{(className: String): void}
/**
* adds the specified class to every node in the list
*
* @param className A String class name to add, or several space-separated class names,or an array of class names.
*/
interface addClass{(className: any[]): void}
/**
* Animate the effects of adding a class to all nodes in this list.
* see dojox.fx.addClass
*
* @param cssClass
* @param args
*/
interface addClassFx{(cssClass: any, args: any): {type:Function;value:any}}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: String, position: String): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: HTMLElement, position: String): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: Object, position: String): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: dojo.NodeList, position: String): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: String, position: number): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: HTMLElement, position: number): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: Object, position: number): Function}
/**
* add a node, NodeList or some HTML as a string to every item in the
* list. Returns the original list.
* a copy of the HTML content is added to each item in the
* list, with an optional position argument. If no position
* argument is provided, the content is appended to the end of
* each item.
*
* @param content the content to be set on the parent element.This can be an html string, a node reference or a NodeList, dojo/NodeList, Array or other enumerable list of nodes
* @param position Optionalcan be one of:"last"||"end" (default)"first||"start""before""after""replace" (replaces nodes in this NodeList with new content)"only" (removes other children of the nodes so new content is the only child)or an offset in the childNodes property
*/
interface addContent{(content: dojo.NodeList, position: number): Function}
/**
* places any/all elements in queryOrListOrNode at a
* position relative to the first element in this list.
* Returns a dojo/NodeList of the adopted elements.
*
* @param queryOrListOrNode a DOM node or a query string or a query result.Represents the nodes to be adopted relative to thefirst element of this NodeList.
* @param position Optionalcan be one of:"last" (default)"first""before""after""only""replace"or an offset in the childNodes property
*/
interface adopt{(queryOrListOrNode: String, position: String): any}
/**
* places any/all elements in queryOrListOrNode at a
* position relative to the first element in this list.
* Returns a dojo/NodeList of the adopted elements.
*
* @param queryOrListOrNode a DOM node or a query string or a query result.Represents the nodes to be adopted relative to thefirst element of this NodeList.
* @param position Optionalcan be one of:"last" (default)"first""before""after""only""replace"or an offset in the childNodes property
*/
interface adopt{(queryOrListOrNode: any[], position: String): any}
/**
* places any/all elements in queryOrListOrNode at a
* position relative to the first element in this list.
* Returns a dojo/NodeList of the adopted elements.
*
* @param queryOrListOrNode a DOM node or a query string or a query result.Represents the nodes to be adopted relative to thefirst element of this NodeList.
* @param position Optionalcan be one of:"last" (default)"first""before""after""only""replace"or an offset in the childNodes property
*/
interface adopt{(queryOrListOrNode: HTMLElement, position: String): any}
/**
* Places the content after every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface after{(content: String): any}
/**
* Places the content after every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface after{(content: HTMLElement): any}
/**
* Places the content after every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface after{(content: NodeList): any}
/**
* Adds the nodes from the previous dojo/NodeList to the current dojo/NodeList.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
*/
interface andSelf{(): any}
/**
* Animate one or more CSS properties for all nodes in this list.
* The returned animation object will already be playing when it
* is returned. See the docs for dojo.anim for full details.
*
* @param properties the properties to animate. does NOT support the auto parameter like otherNodeList-fx methods.
* @param duration OptionalOptional. The time to run the animations for
* @param easing OptionalOptional. The easing function to use.
* @param onEnd OptionalA function to be called when the animation ends
* @param delay Optionalhow long to delay playing the returned animation
*/
interface anim{(properties: Object, duration: number, easing: Function, onEnd: Function, delay: number): any}
/**
* Animate all elements of this NodeList across the properties specified.
* syntax identical to dojo.animateProperty
*
* @param args OptionalAdditional dojo/_base/fx.Animation arguments to mix into this set with the addition ofan auto parameter.
*/
interface animateProperty{(args: Object): any}
/**
* appends the content to every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface append{(content: String): any}
/**
* appends the content to every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface append{(content: HTMLElement): any}
/**
* appends the content to every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface append{(content: NodeList): any}
/**
* appends nodes in this NodeList to the nodes matched by
* the query passed to appendTo.
* The nodes in this NodeList will be cloned if the query
* matches more than one element. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param query
*/
interface appendTo{(query: String): any}
/**
* Returns a new NodeList comprised of items in this NodeList
* at the given index or indices.
*
* @param index One or more 0-based indices of items in the currentNodeList. A negative index will start at the end of thelist and go backwards.
*/
interface at{(index: number[]): any}
/**
* gets or sets the DOM attribute for every element in the
* NodeList. See also dojo/dom-attr
*
* @param property the attribute to get/set
* @param value Optionaloptional. The value to set the property to
*/
interface attr{(property: String, value: String): any}
/**
* Places the content before every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface before{(content: String): any}
/**
* Places the content before every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface before{(content: HTMLElement): any}
/**
* Places the content before every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface before{(content: NodeList): any}
/**
* Returns all immediate child elements for nodes in this dojo/NodeList.
* Optionally takes a query to filter the child elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface children{(query: String): any}
/**
* Clones all the nodes in this NodeList and returns them as a new NodeList.
* Only the DOM nodes are cloned, not any attached event handlers.
*
*/
interface clone{(): any}
/**
* Returns closest parent that matches query, including current node in this
* dojo/NodeList if it matches the query.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query a CSS selector.
* @param root OptionalIf specified, query is relative to "root" rather than document body.
*/
interface closest{(query: String, root: String): any}
/**
* Returns closest parent that matches query, including current node in this
* dojo/NodeList if it matches the query.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query a CSS selector.
* @param root OptionalIf specified, query is relative to "root" rather than document body.
*/
interface closest{(query: String, root: HTMLElement): any}
/**
* Returns a new NodeList comprised of items in this NodeList
* as well as items passed in as parameters
* This method behaves exactly like the Array.concat method
* with the caveat that it returns a NodeList and not a
* raw Array. For more details, see the Array.concat
* docs
*
* @param item OptionalAny number of optional parameters may be passed in to bespliced into the NodeList
*/
interface concat{(item: Object): any}
/**
* Attach event handlers to every item of the NodeList. Uses dojo.connect()
* so event properties are normalized.
*
* Application must manually require() "dojo/_base/connect" before using this method.
*
* @param methodName the name of the method to attach to. For DOM events, this should bethe lower-case name of the event
* @param objOrFunc if 2 arguments are passed (methodName, objOrFunc), objOrFunc shouldreference a function or be the name of the function in the globalnamespace to attach. If 3 arguments are provided(methodName, objOrFunc, funcName), objOrFunc must be the scope tolocate the bound function in
* @param funcName Optionaloptional. A string naming the function in objOrFunc to bind to theevent. May also be a function reference.
*/
interface connect{(methodName: String, objOrFunc: Object, funcName: String): void}
/**
* Attach event handlers to every item of the NodeList. Uses dojo.connect()
* so event properties are normalized.
*
* Application must manually require() "dojo/_base/connect" before using this method.
*
* @param methodName the name of the method to attach to. For DOM events, this should bethe lower-case name of the event
* @param objOrFunc if 2 arguments are passed (methodName, objOrFunc), objOrFunc shouldreference a function or be the name of the function in the globalnamespace to attach. If 3 arguments are provided(methodName, objOrFunc, funcName), objOrFunc must be the scope tolocate the bound function in
* @param funcName Optionaloptional. A string naming the function in objOrFunc to bind to theevent. May also be a function reference.
*/
interface connect{(methodName: String, objOrFunc: Function, funcName: String): void}
/**
* Attach event handlers to every item of the NodeList. Uses dojo.connect()
* so event properties are normalized.
*
* Application must manually require() "dojo/_base/connect" before using this method.
*
* @param methodName the name of the method to attach to. For DOM events, this should bethe lower-case name of the event
* @param objOrFunc if 2 arguments are passed (methodName, objOrFunc), objOrFunc shouldreference a function or be the name of the function in the globalnamespace to attach. If 3 arguments are provided(methodName, objOrFunc, funcName), objOrFunc must be the scope tolocate the bound function in
* @param funcName Optionaloptional. A string naming the function in objOrFunc to bind to theevent. May also be a function reference.
*/
interface connect{(methodName: String, objOrFunc: String, funcName: String): void}
/**
* Deprecated: Use position() for border-box x/y/w/h
* or marginBox() for margin-box w/h/l/t.
* Returns the box objects of all elements in a node list as
* an Array (not a NodeList). Acts like domGeom.coords, though assumes
* the node passed is each node in this list.
*
*/
interface coords{(): void}
/**
* stash or get some arbitrary data on/from these nodes.
* Stash or get some arbitrary data on/from these nodes. This private _data function is
* exposed publicly on dojo/NodeList, eg: as the result of a dojo/query call.
* DIFFERS from jQuery.data in that when used as a getter, the entire list is ALWAYS
* returned. EVEN WHEN THE LIST IS length == 1.
*
* A single-node version of this function is provided as dojo._nodeData, which follows
* the same signature, though expects a String ID or DomNode reference in the first
* position, before key/value arguments.
*
* @param key OptionalIf an object, act as a setter and iterate over said object setting data items as defined.If a string, and value present, set the data for defined key to valueIf a string, and value absent, act as a getter, returning the data associated with said key
* @param value OptionalThe value to set for said key, provided key is a string (and not an object)
*/
interface data{(key: Object, value: any): any}
/**
* stash or get some arbitrary data on/from these nodes.
* Stash or get some arbitrary data on/from these nodes. This private _data function is
* exposed publicly on dojo/NodeList, eg: as the result of a dojo/query call.
* DIFFERS from jQuery.data in that when used as a getter, the entire list is ALWAYS
* returned. EVEN WHEN THE LIST IS length == 1.
*
* A single-node version of this function is provided as dojo._nodeData, which follows
* the same signature, though expects a String ID or DomNode reference in the first
* position, before key/value arguments.
*
* @param key OptionalIf an object, act as a setter and iterate over said object setting data items as defined.If a string, and value present, set the data for defined key to valueIf a string, and value absent, act as a getter, returning the data associated with said key
* @param value OptionalThe value to set for said key, provided key is a string (and not an object)
*/
interface data{(key: String, value: any): any}
/**
* Monitor nodes in this NodeList for [bubbled] events on nodes that match selector.
* Calls fn(evt) for those events, where (inside of fn()), this == the node
* that matches the selector.
* Sets up event handlers that can catch events on any subnodes matching a given selector,
* including nodes created after delegate() has been called.
*
* This allows an app to setup a single event handler on a high level node, rather than many
* event handlers on subnodes. For example, one onclick handler for a Tree widget, rather than separate
* handlers for each node in the tree.
* Since setting up many event handlers is expensive, this can increase performance.
*
* Note that delegate() will not work for events that don't bubble, like focus.
* onmouseenter/onmouseleave also don't currently work.
*
* @param selector CSS selector valid to dojo.query, like ".foo" or "div > span". Theselector is relative to the nodes in this NodeList, not the document root.For example myNodeList.delegate("> a", "onclick", ...) will catch events onanchor nodes which are (immediate) children of the nodes in myNodeList.
* @param eventName Standard event name used as an argument to dojo.connect, like "onclick".
* @param fn Callback function passed the event object, and where this == the node that matches the selector.That means that for example, after setting up a handler viadojo.query("body").delegate("fieldset", "onclick", ...)clicking on a fieldset or any nodes inside of a fieldset will be reportedas a click on the fieldset itself.
*/
interface delegate{(selector: String, eventName: String, fn: Function): any}
/**
* Renders the specified template in each of the NodeList entries.
*
* @param template The template string or location
* @param context The context object or location
*/
interface dtl{(template: String, context: Object): Function}
/**
* clears all content from each node in the list. Effectively
* equivalent to removing all child nodes from every item in
* the list.
*
*/
interface empty{(): any}
/**
* Ends use of the current NodeList by returning the previous NodeList
* that generated the current NodeList.
* Returns the NodeList that generated the current NodeList. If there
* is no parent NodeList, an empty NodeList is returned.
*
*/
interface end{(): any}
/**
* Returns the even nodes in this dojo/NodeList as a dojo/NodeList.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
*/
interface even{(): any}
/**
* see dojo/_base/array.every() and the Array.every
* docs.
* Takes the same structure of arguments and returns as
* dojo/_base/array.every() with the caveat that the passed array is
* implicitly this NodeList
*
* @param callback the callback
* @param thisObject Optionalthe context
*/
interface every{(callback: Function, thisObject: Object): any}
/**
* fade in all elements of this NodeList via dojo.fadeIn
*
* @param args OptionalAdditional dojo/_base/fx.Animation arguments to mix into this set with the addition ofan auto parameter.
*/
interface fadeIn{(args: Object): any}
/**
* fade out all elements of this NodeList via dojo.fadeOut
*
* @param args OptionalAdditional dojo/_base/fx.Animation arguments to mix into this set with the addition ofan auto parameter.
*/
interface fadeOut{(args: Object): any}
/**
* "masks" the built-in javascript filter() method (supported
* in Dojo via dojo.filter) to support passing a simple
* string filter in addition to supporting filtering function
* objects.
*
* @param filter If a string, a CSS rule like ".thinger" or "div > span".
*/
interface filter{(filter: String): any}
/**
* "masks" the built-in javascript filter() method (supported
* in Dojo via dojo.filter) to support passing a simple
* string filter in addition to supporting filtering function
* objects.
*
* @param filter If a string, a CSS rule like ".thinger" or "div > span".
*/
interface filter{(filter: Function): any}
/**
* Returns the first node in this dojo/NodeList as a dojo/NodeList.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
*/
interface first{(): any}
/**
* see dojo/_base/array.forEach(). The primary difference is that the acted-on
* array is implicitly this NodeList. If you want the option to break out
* of the forEach loop, use every() or some() instead.
*
* @param callback
* @param thisObj
*/
interface forEach{(callback: any, thisObj: any): Function}
/**
* allows setting the innerHTML of each node in the NodeList,
* if there is a value passed in, otherwise, reads the innerHTML value of the first node.
* This method is simpler than the dojo/NodeList.html() method provided by
* dojo/NodeList-html. This method just does proper innerHTML insertion of HTML fragments,
* and it allows for the innerHTML to be read for the first node in the node list.
* Since dojo/NodeList-html already took the "html" name, this method is called
* "innerHTML". However, if dojo/NodeList-html has not been loaded yet, this
* module will define an "html" method that can be used instead. Be careful if you
* are working in an environment where it is possible that dojo/NodeList-html could
* have been loaded, since its definition of "html" will take precedence.
* The nodes represented by the value argument will be cloned if more than one
* node is in this NodeList. The nodes in this NodeList are returned in the "set"
* usage of this method, not the HTML that was inserted.
*
* @param value Optional
*/
interface html{(value: String): any}
/**
* allows setting the innerHTML of each node in the NodeList,
* if there is a value passed in, otherwise, reads the innerHTML value of the first node.
* This method is simpler than the dojo/NodeList.html() method provided by
* dojo/NodeList-html. This method just does proper innerHTML insertion of HTML fragments,
* and it allows for the innerHTML to be read for the first node in the node list.
* Since dojo/NodeList-html already took the "html" name, this method is called
* "innerHTML". However, if dojo/NodeList-html has not been loaded yet, this
* module will define an "html" method that can be used instead. Be careful if you
* are working in an environment where it is possible that dojo/NodeList-html could
* have been loaded, since its definition of "html" will take precedence.
* The nodes represented by the value argument will be cloned if more than one
* node is in this NodeList. The nodes in this NodeList are returned in the "set"
* usage of this method, not the HTML that was inserted.
*
* @param value Optional
*/
interface html{(value: HTMLElement): any}
/**
* allows setting the innerHTML of each node in the NodeList,
* if there is a value passed in, otherwise, reads the innerHTML value of the first node.
* This method is simpler than the dojo/NodeList.html() method provided by
* dojo/NodeList-html. This method just does proper innerHTML insertion of HTML fragments,
* and it allows for the innerHTML to be read for the first node in the node list.
* Since dojo/NodeList-html already took the "html" name, this method is called
* "innerHTML". However, if dojo/NodeList-html has not been loaded yet, this
* module will define an "html" method that can be used instead. Be careful if you
* are working in an environment where it is possible that dojo/NodeList-html could
* have been loaded, since its definition of "html" will take precedence.
* The nodes represented by the value argument will be cloned if more than one
* node is in this NodeList. The nodes in this NodeList are returned in the "set"
* usage of this method, not the HTML that was inserted.
*
* @param value Optional
*/
interface html{(value: NodeList): any}
/**
* see dojo/_base/array.indexOf(). The primary difference is that the acted-on
* array is implicitly this NodeList
* For more details on the behavior of indexOf, see Mozilla's
* indexOf
* docs
*
* @param value The value to search for.
* @param fromIndex OptionalThe location to start searching from. Optional. Defaults to 0.
*/
interface indexOf{(value: Object, fromIndex: number): any}
/**
* allows setting the innerHTML of each node in the NodeList,
* if there is a value passed in, otherwise, reads the innerHTML value of the first node.
* This method is simpler than the dojo/NodeList.html() method provided by
* dojo/NodeList-html. This method just does proper innerHTML insertion of HTML fragments,
* and it allows for the innerHTML to be read for the first node in the node list.
* Since dojo/NodeList-html already took the "html" name, this method is called
* "innerHTML". However, if dojo/NodeList-html has not been loaded yet, this
* module will define an "html" method that can be used instead. Be careful if you
* are working in an environment where it is possible that dojo/NodeList-html could
* have been loaded, since its definition of "html" will take precedence.
* The nodes represented by the value argument will be cloned if more than one
* node is in this NodeList. The nodes in this NodeList are returned in the "set"
* usage of this method, not the HTML that was inserted.
*
* @param value Optional
*/
interface innerHTML{(value: String): any}
/**
* allows setting the innerHTML of each node in the NodeList,
* if there is a value passed in, otherwise, reads the innerHTML value of the first node.
* This method is simpler than the dojo/NodeList.html() method provided by
* dojo/NodeList-html. This method just does proper innerHTML insertion of HTML fragments,
* and it allows for the innerHTML to be read for the first node in the node list.
* Since dojo/NodeList-html already took the "html" name, this method is called
* "innerHTML". However, if dojo/NodeList-html has not been loaded yet, this
* module will define an "html" method that can be used instead. Be careful if you
* are working in an environment where it is possible that dojo/NodeList-html could
* have been loaded, since its definition of "html" will take precedence.
* The nodes represented by the value argument will be cloned if more than one
* node is in this NodeList. The nodes in this NodeList are returned in the "set"
* usage of this method, not the HTML that was inserted.
*
* @param value Optional
*/
interface innerHTML{(value: HTMLElement): any}
/**
* allows setting the innerHTML of each node in the NodeList,
* if there is a value passed in, otherwise, reads the innerHTML value of the first node.
* This method is simpler than the dojo/NodeList.html() method provided by
* dojo/NodeList-html. This method just does proper innerHTML insertion of HTML fragments,
* and it allows for the innerHTML to be read for the first node in the node list.
* Since dojo/NodeList-html already took the "html" name, this method is called
* "innerHTML". However, if dojo/NodeList-html has not been loaded yet, this
* module will define an "html" method that can be used instead. Be careful if you
* are working in an environment where it is possible that dojo/NodeList-html could
* have been loaded, since its definition of "html" will take precedence.
* The nodes represented by the value argument will be cloned if more than one
* node is in this NodeList. The nodes in this NodeList are returned in the "set"
* usage of this method, not the HTML that was inserted.
*
* @param value Optional
*/
interface innerHTML{(value: NodeList): any}
/**
* The nodes in this NodeList will be placed after the nodes
* matched by the query passed to insertAfter.
* The nodes in this NodeList will be cloned if the query
* matches more than one element. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param query
*/
interface insertAfter{(query: String): any}
/**
* The nodes in this NodeList will be placed after the nodes
* matched by the query passed to insertAfter.
* The nodes in this NodeList will be cloned if the query
* matches more than one element. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param query
*/
interface insertBefore{(query: String): any}
/**
* Create a new instance of a specified class, using the
* specified properties and each node in the NodeList as a
* srcNodeRef.
*
* @param declaredClass
* @param properties Optional
*/
interface instantiate{(declaredClass: String, properties: Object): any}
/**
* Create a new instance of a specified class, using the
* specified properties and each node in the NodeList as a
* srcNodeRef.
*
* @param declaredClass
* @param properties Optional
*/
interface instantiate{(declaredClass: Object, properties: Object): any}
/**
* Returns the last node in this dojo/NodeList as a dojo/NodeList.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
*/
interface last{(): any}
/**
* see dojo/_base/array.lastIndexOf(). The primary difference is that the
* acted-on array is implicitly this NodeList
* For more details on the behavior of lastIndexOf, see
* Mozilla's lastIndexOf
* docs
*
* @param value The value to search for.
* @param fromIndex OptionalThe location to start searching from. Optional. Defaults to 0.
*/
interface lastIndexOf{(value: Object, fromIndex: number): any}
/**
* see dojo/_base/array.map(). The primary difference is that the acted-on
* array is implicitly this NodeList and the return is a
* NodeList (a subclass of Array)
*
* @param func
* @param obj Optional
*/
interface map{(func: Function, obj: Function): any}
/**
* Returns margin-box size of nodes
*
*/
interface marginBox{(): void}
/**
* Returns the next element for nodes in this dojo/NodeList.
* Optionally takes a query to filter the next elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface next{(query: String): any}
/**
* Returns all sibling elements that come after the nodes in this dojo/NodeList.
* Optionally takes a query to filter the sibling elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface nextAll{(query: String): any}
/**
* Returns the odd nodes in this dojo/NodeList as a dojo/NodeList.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
*/
interface odd{(): any}
/**
* Listen for events on the nodes in the NodeList. Basic usage is:
*
* @param eventName
* @param listener
*/
interface on{(eventName: any, listener: any): any}
/**
* removes elements in this list that match the filter
* from their parents and returns them as a new NodeList.
*
* @param filter OptionalCSS selector like ".foo" or "div > span"
*/
interface orphan{(filter: String): any}
/**
* Returns immediate parent elements for nodes in this dojo/NodeList.
* Optionally takes a query to filter the parent elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface parent{(query: String): any}
/**
* Returns all parent elements for nodes in this dojo/NodeList.
* Optionally takes a query to filter the child elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface parents{(query: String): any}
/**
* places elements of this node list relative to the first element matched
* by queryOrNode. Returns the original NodeList. See: dojo/dom-construct.place
*
* @param queryOrNode may be a string representing any valid CSS3 selector or a DOM node.In the selector case, only the first matching element will be usedfor relative positioning.
* @param position can be one of:"last" (default)"first""before""after""only""replace"or an offset in the childNodes property
*/
interface place{(queryOrNode: String, position: String): any}
/**
* places elements of this node list relative to the first element matched
* by queryOrNode. Returns the original NodeList. See: dojo/dom-construct.place
*
* @param queryOrNode may be a string representing any valid CSS3 selector or a DOM node.In the selector case, only the first matching element will be usedfor relative positioning.
* @param position can be one of:"last" (default)"first""before""after""only""replace"or an offset in the childNodes property
*/
interface place{(queryOrNode: HTMLElement, position: String): any}
/**
* Returns border-box objects (x/y/w/h) of all elements in a node list
* as an Array (not a NodeList). Acts like dojo/dom-geometry-position, though
* assumes the node passed is each node in this list.
*
*/
interface position{(): any}
/**
* prepends the content to every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface prepend{(content: String): any}
/**
* prepends the content to every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface prepend{(content: HTMLElement): any}
/**
* prepends the content to every node in the NodeList.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface prepend{(content: NodeList): any}
/**
* prepends nodes in this NodeList to the nodes matched by
* the query passed to prependTo.
* The nodes in this NodeList will be cloned if the query
* matches more than one element. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param query
*/
interface prependTo{(query: String): any}
/**
* Returns the previous element for nodes in this dojo/NodeList.
* Optionally takes a query to filter the previous elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface prev{(query: String): any}
/**
* Returns all sibling elements that come before the nodes in this dojo/NodeList.
* Optionally takes a query to filter the sibling elements.
* The returned nodes will be in reverse DOM order -- the first node in the list will
* be the node closest to the original node/NodeList.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface prevAll{(query: String): any}
/**
* Returns a new list whose members match the passed query,
* assuming elements of the current NodeList as the root for
* each search.
*
* @param queryStr
*/
interface query{(queryStr: String): any}
/**
* removes elements in this list that match the filter
* from their parents and returns them as a new NodeList.
*
* @param filter OptionalCSS selector like ".foo" or "div > span"
*/
interface remove{(filter: String): any}
/**
* Removes an attribute from each node in the list.
*
* @param name the name of the attribute to remove
*/
interface removeAttr{(name: String): void}
/**
* removes the specified class from every node in the list
*
* @param className OptionalAn optional String class name to remove, or several space-separatedclass names, or an array of class names. If omitted, all class nameswill be deleted.
*/
interface removeClass{(className: String): any}
/**
* removes the specified class from every node in the list
*
* @param className OptionalAn optional String class name to remove, or several space-separatedclass names, or an array of class names. If omitted, all class nameswill be deleted.
*/
interface removeClass{(className: any[]): any}
/**
* Animate the effect of removing a class to all nodes in this list.
* see dojox.fx.removeClass
*
* @param cssClass
* @param args
*/
interface removeClassFx{(cssClass: any, args: any): {type:Function;value:any}}
/**
* Remove the data associated with these nodes.
*
* @param key OptionalIf omitted, clean all data for this node.If passed, remove the data item found at key
*/
interface removeData{(key: String): void}
/**
* replaces nodes matched by the query passed to replaceAll with the nodes
* in this NodeList.
* The nodes in this NodeList will be cloned if the query
* matches more than one element. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param query
*/
interface replaceAll{(query: String): any}
/**
* Replaces one or more classes on a node if not present.
* Operates more quickly than calling removeClass() and addClass()
*
* @param addClassStr A String class name to add, or several space-separated class names,or an array of class names.
* @param removeClassStr OptionalA String class name to remove, or several space-separated class names,or an array of class names.
*/
interface replaceClass{(addClassStr: String, removeClassStr: String): void}
/**
* Replaces one or more classes on a node if not present.
* Operates more quickly than calling removeClass() and addClass()
*
* @param addClassStr A String class name to add, or several space-separated class names,or an array of class names.
* @param removeClassStr OptionalA String class name to remove, or several space-separated class names,or an array of class names.
*/
interface replaceClass{(addClassStr: any[], removeClassStr: String): void}
/**
* Replaces one or more classes on a node if not present.
* Operates more quickly than calling removeClass() and addClass()
*
* @param addClassStr A String class name to add, or several space-separated class names,or an array of class names.
* @param removeClassStr OptionalA String class name to remove, or several space-separated class names,or an array of class names.
*/
interface replaceClass{(addClassStr: String, removeClassStr: any[]): void}
/**
* Replaces one or more classes on a node if not present.
* Operates more quickly than calling removeClass() and addClass()
*
* @param addClassStr A String class name to add, or several space-separated class names,or an array of class names.
* @param removeClassStr OptionalA String class name to remove, or several space-separated class names,or an array of class names.
*/
interface replaceClass{(addClassStr: any[], removeClassStr: any[]): void}
/**
* Replaces each node in ths NodeList with the content passed to replaceWith.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface replaceWith{(content: String): any}
/**
* Replaces each node in ths NodeList with the content passed to replaceWith.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface replaceWith{(content: HTMLElement): any}
/**
* Replaces each node in ths NodeList with the content passed to replaceWith.
* The content will be cloned if the length of NodeList
* is greater than 1. Only the DOM nodes are cloned, not
* any attached event handlers.
*
* @param content
*/
interface replaceWith{(content: NodeList): any}
/**
* Returns all sibling elements for nodes in this dojo/NodeList.
* Optionally takes a query to filter the sibling elements.
* .end() can be used on the returned dojo/NodeList to get back to the
* original dojo/NodeList.
*
* @param query Optionala CSS selector.
*/
interface siblings{(query: String): any}
/**
* Returns a new NodeList, maintaining this one in place
* This method behaves exactly like the Array.slice method
* with the caveat that it returns a dojo/NodeList and not a
* raw Array. For more details, see Mozilla's slice
* documentation
*
* @param begin Can be a positive or negative integer, with positiveintegers noting the offset to begin at, and negativeintegers denoting an offset from the end (i.e., to the leftof the end)
* @param end OptionalOptional parameter to describe what position relative tothe NodeList's zero index to end the slice at. Like begin,can be positive or negative.
*/
interface slice{(begin: number, end: number): any}
/**
* slide all elements of the node list to the specified place via dojo/fx.slideTo()
*
* @param args OptionalAdditional dojo/_base/fx.Animation arguments to mix into this set with the addition ofan auto parameter.
*/
interface slideTo{(args: Object): any}
/**
* Takes the same structure of arguments and returns as
* dojo/_base/array.some() with the caveat that the passed array is
* implicitly this NodeList. See dojo/_base/array.some() and Mozilla's
* Array.some
* documentation.
*
* @param callback the callback
* @param thisObject Optionalthe context
*/
interface some{(callback: Function, thisObject: Object): any}
/**
* Returns a new NodeList, manipulating this NodeList based on
* the arguments passed, potentially splicing in new elements
* at an offset, optionally deleting elements
* This method behaves exactly like the Array.splice method
* with the caveat that it returns a dojo/NodeList and not a
* raw Array. For more details, see Mozilla's splice
* documentation
* For backwards compatibility, calling .end() on the spliced NodeList
* does not return the original NodeList -- splice alters the NodeList in place.
*
* @param index begin can be a positive or negative integer, with positiveintegers noting the offset to begin at, and negativeintegers denoting an offset from the end (i.e., to the leftof the end)
* @param howmany OptionalOptional parameter to describe what position relative tothe NodeList's zero index to end the slice at. Like begin,can be positive or negative.
* @param item OptionalAny number of optional parameters may be passed in to bespliced into the NodeList
*/
interface splice{(index: number, howmany: number, item: Object[]): any}
/**
* gets or sets the CSS property for every element in the NodeList
*
* @param property the CSS property to get/set, in JavaScript notation("lineHieght" instead of "line-height")
* @param value Optionaloptional. The value to set the property to
*/
interface style{(property: String, value: String): any}
/**
* allows setting the text value of each node in the NodeList,
* if there is a value passed in, otherwise, returns the text value for all the
* nodes in the NodeList in one string.
*
* @param value
*/
interface text{(value: String): any}
/**
* Adds a class to node if not present, or removes if present.
* Pass a boolean condition if you want to explicitly add or remove.
*
* @param className the CSS class to add
* @param condition OptionalIf passed, true means to add the class, false means to remove.
*/
interface toggleClass{(className: String, condition: boolean): void}
/**
* Animate the effect of adding or removing a class to all nodes in this list.
* see dojox.fx.toggleClass
*
* @param cssClass
* @param force
* @param args
*/
interface toggleClassFx{(cssClass: any, force: any, args: any): {type:Function;value:any}}
/**
*
*/
interface toString{(): any}
/**
* If a value is passed, allows seting the value property of form elements in this
* NodeList, or properly selecting/checking the right value for radio/checkbox/select
* elements. If no value is passed, the value of the first node in this NodeList
* is returned.
*
* @param value
*/
interface val{(value: String): any}
/**
* If a value is passed, allows seting the value property of form elements in this
* NodeList, or properly selecting/checking the right value for radio/checkbox/select
* elements. If no value is passed, the value of the first node in this NodeList
* is returned.
*
* @param value
*/
interface val{(value: any[]): any}
/**
* wipe in all elements of this NodeList via dojo/fx.wipeIn()
*
* @param args OptionalAdditional dojo/_base/fx.Animation arguments to mix into this set with the addition ofan auto parameter.
*/
interface wipeIn{(args: Object): any}
/**
* wipe out all elements of this NodeList via dojo/fx.wipeOut()
*
* @param args OptionalAdditional dojo/_base/fx.Animation arguments to mix into this set with the addition ofan auto parameter.
*/
interface wipeOut{(args: Object): any}
/**
* Wrap each node in the NodeList with html passed to wrap.
* html will be cloned if the NodeList has more than one
* element. Only DOM nodes are cloned, not any attached
* event handlers.
*
* @param html
*/
interface wrap{(html: String): any}
/**
* Wrap each node in the NodeList with html passed to wrap.
* html will be cloned if the NodeList has more than one
* element. Only DOM nodes are cloned, not any attached
* event handlers.
*
* @param html
*/
interface wrap{(html: HTMLElement): any}
/**
* Insert html where the first node in this NodeList lives, then place all
* nodes in this NodeList as the child of the html.
*
* @param html
*/
interface wrapAll{(html: String): any}
/**
* Insert html where the first node in this NodeList lives, then place all
* nodes in this NodeList as the child of the html.
*
* @param html
*/
interface wrapAll{(html: HTMLElement): any}
/**
* For each node in the NodeList, wrap all its children with the passed in html.
* html will be cloned if the NodeList has more than one
* element. Only DOM nodes are cloned, not any attached
* event handlers.
*
* @param html
*/
interface wrapInner{(html: String): any}
/**
* For each node in the NodeList, wrap all its children with the passed in html.
* html will be cloned if the NodeList has more than one
* element. Only DOM nodes are cloned, not any attached
* event handlers.
*
* @param html
*/
interface wrapInner{(html: HTMLElement): any}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/ext-dojo/NodeList._nodeDataCache.html
*
*
*/
interface _nodeDataCache {
}
}
}
namespace filter {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/dates.html
*
*
*/
interface dates {
/**
* Formats a date according to the given format
*
* @param value
* @param arg
*/
date(value: any, arg: any): String;
/**
* Formats a time according to the given format
*
* @param value
* @param arg
*/
time(value: any, arg: any): String;
/**
* Formats a date as the time since that date (i.e. "4 days, 6 hours")
*
* @param value
* @param arg
*/
timesince(value: any, arg: any): String;
/**
* Formats a date as the time until that date (i.e. "4 days, 6 hours")
*
* @param value
* @param arg
*/
timeuntil(value: any, arg: any): String;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/htmlstrings.html
*
*
*/
interface htmlstrings {
/**
* Converts newlines into <p> and <br />s
*
* @param value
*/
linebreaks(value: any): any;
/**
* Converts newlines into <br />s
*
* @param value
*/
linebreaksbr(value: any): any;
/**
* Removes a space separated list of [X]HTML tags from the output"
*
* @param value
* @param arg
*/
removetags(value: any, arg: any): any;
/**
* Strips all [X]HTML tags
*
* @param value
*/
striptags(value: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/integers.html
*
*
*/
interface integers {
/**
*
* @param value
* @param arg
*/
add(value: any, arg: any): number;
/**
* Given a whole number, returns the 1-based requested digit of it
*
* @param value
* @param arg
*/
get_digit(value: any, arg: any): number;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/logic.html
*
*
*/
interface logic {
/**
* If value is unavailable, use given default
*
* @param value
* @param arg
*/
default_(value: any, arg: any): String;
/**
* If value is null, use given default
*
* @param value
* @param arg
*/
default_if_none(value: any, arg: any): String;
/**
* Returns true if the value is divisible by the argument"
*
* @param value
* @param arg
*/
divisibleby(value: any, arg: any): boolean;
/**
* arg being a comma-delimited string, value of true/false/none
* chooses the appropriate item from the string
*
* @param value
* @param arg
*/
yesno(value: any, arg: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/misc.html
*
*
*/
interface misc {
/**
* Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102bytes, etc).
*
* @param value
*/
filesizeformat(value: any): String;
/**
* Takes a phone number and converts it in to its numerical equivalent
*
* @param value
*/
phone2numeric(value: any): String;
/**
* Returns a plural suffix if the value is not 1, for '1 vote' vs. '2 votes'
* By default, 's' is used as a suffix; if an argument is provided, that string
* is used instead. If the provided argument contains a comma, the text before
* the comma is used for the singular case.
*
* @param value
* @param arg
*/
pluralize(value: any, arg: any): String;
/**
* A wrapper around toJson unless something better comes along
*
* @param value
*/
pprint(value: any): any;
}
namespace misc {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/misc._phone2numeric.html
*
*
*/
interface _phone2numeric {
/**
*
*/
a: number;
/**
*
*/
b: number;
/**
*
*/
c: number;
/**
*
*/
d: number;
/**
*
*/
e: number;
/**
*
*/
f: number;
/**
*
*/
g: number;
/**
*
*/
h: number;
/**
*
*/
i: number;
/**
*
*/
j: number;
/**
*
*/
k: number;
/**
*
*/
l: number;
/**
*
*/
m: number;
/**
*
*/
n: number;
/**
*
*/
o: number;
/**
*
*/
p: number;
/**
*
*/
r: number;
/**
*
*/
s: number;
/**
*
*/
t: number;
/**
*
*/
u: number;
/**
*
*/
v: number;
/**
*
*/
w: number;
/**
*
*/
x: number;
/**
*
*/
y: number;
}
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/lists.html
*
*
*/
interface lists {
/**
* Takes a list of dicts, returns that list sorted by the property given in the argument.
*
* @param value
* @param arg
*/
dictsort(value: any, arg: any): any;
/**
* Takes a list of dicts, returns that list sorted in reverse order by the property given in the argument.
*
* @param value
* @param arg
*/
dictsortreversed(value: any, arg: any): any;
/**
* Returns the first item in a list
*
* @param value
*/
first(value: any): String;
/**
* Joins a list with a string, like Python's str.join(list)
* Django throws a compile error, but JS can't do arg checks
* so we're left with run time errors, which aren't wise for something
* as trivial here as an empty arg.
*
* @param value
* @param arg
*/
join(value: any, arg: any): any;
/**
* Returns the length of the value - useful for lists
*
* @param value
*/
length(value: any): any;
/**
* Returns a boolean of whether the value's length is the argument
*
* @param value
* @param arg
*/
length_is(value: any, arg: any): boolean;
/**
* Returns a random item from the list
*
* @param value
*/
random(value: any): any;
/**
* Returns a slice of the list.
* Uses the same syntax as Python's list slicing; see
* http://www.diveintopython.net/native_data_types/lists.html#odbchelper.list.slice
* for an introduction.
* Also uses the optional third value to denote every X item.
*
* @param value
* @param arg
*/
slice(value: any, arg: any): any;
/**
* Recursively takes a self-nested list and returns an HTML unordered list --
* WITHOUT opening and closing <ul> tags.
* The list is assumed to be in the proper format. For example, if var contains
* ['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]],
* then {{ var|unordered_list }} would return::
*
* <li>States
* <ul>
* <li>Kansas
* <ul>
* <li>Lawrence</li>
* <li>Topeka</li>
* </ul>
* </li>
* <li>Illinois</li>
* </ul>
* </li>
*
* @param value
*/
unordered_list(value: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/strings.html
*
*
*/
interface strings {
/**
* Adds slashes - useful for passing strings to JavaScript, for example.
*
* @param value
*/
addslashes(value: any): any;
/**
* Capitalizes the first character of the value
*
* @param value
*/
capfirst(value: any): number;
/**
* Centers the value in a field of a given width
*
* @param value
* @param arg
*/
center(value: any, arg: any): String;
/**
* Removes all values of arg from the given string
*
* @param value
* @param arg
*/
cut(value: any, arg: any): any;
/**
* Replaces ampersands with & entities
*
* @param value
*/
fix_ampersands(value: any): any;
/**
* Format a number according to arg
* If called without an argument, displays a floating point
* number as 34.2 -- but only if there's a point to be displayed.
* With a positive numeric argument, it displays that many decimal places
* always.
* With a negative numeric argument, it will display that many decimal
* places -- but only if there's places to be displayed.
*
* @param value
* @param arg
*/
floatformat(value: any, arg: any): any;
/**
*
* @param value
*/
iriencode(value: any): any;
/**
* Displays text with line numbers
*
* @param value
*/
linenumbers(value: any): any;
/**
*
* @param value
* @param arg
*/
ljust(value: any, arg: any): String;
/**
* Converts a string into all lowercase
*
* @param value
*/
lower(value: any): any;
/**
* Returns the value turned into a list. For an integer, it's a list of
* digits. For a string, it's a list of characters.
*
* @param value
*/
make_list(value: any): any[];
/**
*
* @param value
* @param arg
*/
rjust(value: any, arg: any): String;
/**
* Converts to lowercase, removes
* non-alpha chars and converts spaces to hyphens
*
* @param value
*/
slugify(value: any): any;
/**
* Formats the variable according to the argument, a string formatting specifier.
* This specifier uses Python string formatting syntax, with the exception that
* the leading "%" is dropped.
*
* @param value
* @param arg
*/
stringformat(value: any, arg: any): any;
/**
* Converts a string into titlecase
*
* @param value
*/
title(value: any): String;
/**
* Truncates a string after a certain number of words
*
* @param value
* @param arg Number of words to truncate after
*/
truncatewords(value: any, arg: number): any;
/**
*
* @param value
* @param arg
*/
truncatewords_html(value: any, arg: any): String;
/**
*
* @param value
*/
upper(value: any): any;
/**
*
* @param value
*/
urlencode(value: any): any;
/**
*
* @param value
*/
urlize(value: any): any;
/**
*
* @param value
* @param arg
*/
urlizetrunc(value: any, arg: any): any;
/**
*
* @param value
*/
wordcount(value: any): number;
/**
*
* @param value alias name: 'cent', 'pound' ..
* @param arg
*/
wordwrap(value: String, arg: any): any;
}
namespace strings {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/strings._strings.html
*
*
*/
interface _strings {
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/filter/strings._truncate_singlets.html
*
*
*/
interface _truncate_singlets {
/**
*
*/
area: boolean;
/**
*
*/
base: boolean;
/**
*
*/
br: boolean;
/**
*
*/
col: boolean;
/**
*
*/
hr: boolean;
/**
*
*/
img: boolean;
/**
*
*/
input: boolean;
/**
*
*/
link: boolean;
/**
*
*/
param: boolean;
}
}
}
namespace render {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/render/dom.html
*
*
*/
interface dom {
/**
*
* @param attachPoint Optional
* @param tpl Optional
*/
Render(attachPoint: HTMLElement, tpl: dojox.dtl._DomTemplated): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/render/html.html
*
*
*/
interface html {
/**
*
* @param attachPoint Optional
* @param tpl Optional
*/
Render(attachPoint: HTMLElement, tpl: dojox.dtl._DomTemplated): void;
}
}
namespace tag {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/tag/date.html
*
*
*/
interface date {
/**
*
* @param parser
* @param token
*/
now(parser: any, token: any): void;
/**
*
* @param format
* @param node
*/
NowNode(format: any, node: any): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/tag/logic.html
*
*
*/
interface logic {
/**
*
* @param parser
* @param token
*/
for_(parser: any, token: any): any;
/**
*
* @param assign
* @param loop
* @param reversed
* @param nodelist
*/
ForNode(assign: any, loop: any, reversed: any, nodelist: any): void;
/**
*
* @param parser
* @param token
*/
if_(parser: any, token: any): any;
/**
*
* @param parser
* @param token
*/
ifequal(parser: any, token: any): any;
/**
*
* @param var1
* @param var2
* @param trues
* @param falses
* @param negate
*/
IfEqualNode(var1: any, var2: any, trues: any, falses: any, negate: any): void;
/**
*
* @param bools
* @param trues
* @param falses
* @param type
*/
IfNode(bools: any, trues: any, falses: any, type: any): void;
/**
*
* @param parser
* @param token
*/
ifnotequal(parser: any, token: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/tag/loader.html
*
*
*/
interface loader {
/**
*
* @param parser
* @param token
*/
block(parser: any, token: any): any;
/**
*
* @param name
* @param nodelist
*/
BlockNode(name: any, nodelist: any): void;
/**
*
* @param parser
* @param token
*/
extends_(parser: any, token: any): any;
/**
*
* @param getTemplate
* @param nodelist
* @param shared
* @param parent
* @param key
*/
ExtendsNode(getTemplate: any, nodelist: any, shared: any, parent: any, key: any): void;
/**
*
* @param parser
* @param token
*/
include(parser: any, token: any): any;
/**
*
* @param path
* @param constant
* @param getTemplate
* @param text
* @param parsed
*/
IncludeNode(path: any, constant: any, getTemplate: any, text: any, parsed: any): void;
/**
*
* @param parser
* @param token
*/
ssi(parser: any, token: any): any;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/tag/loop.html
*
*
*/
interface loop {
/**
* Cycle among the given strings each time this tag is encountered
*
* @param parser
* @param token
*/
cycle(parser: any, token: any): any;
/**
*
* @param cyclevars
* @param name
* @param text
* @param shared
*/
CycleNode(cyclevars: any, name: any, text: any, shared: any): void;
/**
*
* @param parser
* @param token
*/
ifchanged(parser: any, token: any): any;
/**
*
* @param nodes
* @param vars
* @param shared
*/
IfChangedNode(nodes: any, vars: any, shared: any): void;
/**
*
* @param parser
* @param token
*/
regroup(parser: any, token: any): any;
/**
*
* @param expression
* @param key
* @param alias
*/
RegroupNode(expression: any, key: any, alias: any): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/tag/misc.html
*
*
*/
interface misc {
/**
* Ignore everything between {% comment %} and {% endcomment %}
*
* @param parser
* @param token
*/
comment(parser: any, token: any): any;
/**
* Output the current context, maybe add more stuff later.
*
* @param parser
* @param token
*/
debug(parser: any, token: any): any;
/**
*
* @param text
*/
DebugNode(text: any): void;
/**
* Filter the contents of the blog through variable filters.
*
* @param parser
* @param token
*/
filter(parser: any, token: any): any;
/**
*
* @param varnode
* @param nodelist
*/
FilterNode(varnode: any, nodelist: any): void;
/**
*
* @param parser
* @param token
*/
firstof(parser: any, token: any): any;
/**
*
* @param vars
* @param text
*/
FirstOfNode(vars: any, text: any): void;
/**
*
* @param parser
* @param token
*/
spaceless(parser: any, token: any): any;
/**
*
* @param nodelist
* @param text
*/
SpacelessNode(nodelist: any, text: any): void;
/**
*
* @param parser
* @param token
*/
templatetag(parser: any, token: any): any;
/**
*
* @param tag
* @param text
*/
TemplateTagNode(tag: any, text: any): void;
/**
*
* @param parser
* @param token
*/
widthratio(parser: any, token: any): any;
/**
*
* @param current
* @param max
* @param width
* @param text
*/
WidthRatioNode(current: any, max: any, width: any, text: any): void;
/**
*
* @param parser
* @param token
*/
with_(parser: any, token: any): any;
/**
*
* @param target
* @param alias
* @param nodelist
*/
WithNode(target: any, alias: any, nodelist: any): void;
}
}
namespace utils {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/dtl/utils/date.html
*
*
*/
interface date {
/**
* Format the internal date object
*
* @param format
*/
DateFormat(format: String): void;
}
}
}
}
declare module "dojox/dtl" {
var exp: dojox.dtl
export=exp;
}
declare module "dojox/dtl/_Templated" {
var exp: dojox.dtl._Templated
export=exp;
}
declare module "dojox/dtl/Context" {
var exp: dojox.dtl.Context
export=exp;
}
declare module "dojox/dtl/_DomTemplated" {
var exp: dojox.dtl._DomTemplated
export=exp;
}
declare module "dojox/dtl/DomInline" {
var exp: dojox.dtl.DomInline
export=exp;
}
declare module "dojox/dtl/Inline" {
var exp: dojox.dtl.Inline
export=exp;
}
declare module "dojox/dtl/_base" {
var exp: dojox.dtl._base
export=exp;
}
declare module "dojox/dtl/_base._base" {
var exp: dojox.dtl._base._base
export=exp;
}
declare module "dojox/dtl/_base.BOOLS" {
var exp: dojox.dtl._base.BOOLS
export=exp;
}
declare module "dojox/dtl/_base.data" {
var exp: dojox.dtl._base.data
export=exp;
}
declare module "dojox/dtl/_base.date" {
var exp: dojox.dtl._base.date
export=exp;
}
declare module "dojox/dtl/_base.dates" {
var exp: dojox.dtl._base.dates
export=exp;
}
declare module "dojox/dtl/_base.dijit" {
var exp: dojox.dtl._base.dijit
export=exp;
}
declare module "dojox/dtl/_base.html" {
var exp: dojox.dtl._base.html
export=exp;
}
declare module "dojox/dtl/_base.htmlstrings" {
var exp: dojox.dtl._base.htmlstrings
export=exp;
}
declare module "dojox/dtl/_base.dom" {
var exp: dojox.dtl._base.dom
export=exp;
}
declare module "dojox/dtl/_base.integers" {
var exp: dojox.dtl._base.integers
export=exp;
}
declare module "dojox/dtl/_base.logic" {
var exp: dojox.dtl._base.logic
export=exp;
}
declare module "dojox/dtl/_base.loader" {
var exp: dojox.dtl._base.loader
export=exp;
}
declare module "dojox/dtl/_base.loop" {
var exp: dojox.dtl._base.loop
export=exp;
}
declare module "dojox/dtl/_base.misc" {
var exp: dojox.dtl._base.misc
export=exp;
}
declare module "dojox/dtl/_base.objects" {
var exp: dojox.dtl._base.objects
export=exp;
}
declare module "dojox/dtl/_base.strings" {
var exp: dojox.dtl._base.strings
export=exp;
}
declare module "dojox/dtl/_base.register" {
var exp: dojox.dtl._base.register
export=exp;
}
declare module "dojox/dtl/_base.text" {
var exp: dojox.dtl._base.text
export=exp;
}
declare module "dojox/dtl/dom" {
var exp: dojox.dtl.dom
export=exp;
}
declare module "dojox/dtl/dom._uppers" {
var exp: dojox.dtl.dom._uppers
export=exp;
}
declare module "dojox/dtl/dom._attributes" {
var exp: dojox.dtl.dom._attributes
export=exp;
}
declare module "dojox/dtl/contrib/data" {
var exp: dojox.dtl.contrib.data
export=exp;
}
declare module "dojox/dtl/contrib/objects" {
var exp: dojox.dtl.contrib.objects
export=exp;
}
declare module "dojox/dtl/contrib/dom" {
var exp: dojox.dtl.contrib.dom
export=exp;
}
declare module "dojox/dtl/contrib/dijit" {
var exp: dojox.dtl.contrib.dijit
export=exp;
}
declare module "dojox/dtl/ext-dojo/NodeList" {
var exp: dojox.dtl.ext_dojo.NodeList
export=exp;
}
declare module "dojox/dtl/ext-dojo/NodeList._nodeDataCache" {
var exp: dojox.dtl.ext_dojo.NodeList._nodeDataCache
export=exp;
}
declare module "dojox/dtl/filter/dates" {
var exp: dojox.dtl.filter.dates
export=exp;
}
declare module "dojox/dtl/filter/htmlstrings" {
var exp: dojox.dtl.filter.htmlstrings
export=exp;
}
declare module "dojox/dtl/filter/integers" {
var exp: dojox.dtl.filter.integers
export=exp;
}
declare module "dojox/dtl/filter/logic" {
var exp: dojox.dtl.filter.logic
export=exp;
}
declare module "dojox/dtl/filter/misc" {
var exp: dojox.dtl.filter.misc
export=exp;
}
declare module "dojox/dtl/filter/misc._phone2numeric" {
var exp: dojox.dtl.filter.misc._phone2numeric
export=exp;
}
declare module "dojox/dtl/filter/lists" {
var exp: dojox.dtl.filter.lists
export=exp;
}
declare module "dojox/dtl/filter/strings" {
var exp: dojox.dtl.filter.strings
export=exp;
}
declare module "dojox/dtl/filter/strings._strings" {
var exp: dojox.dtl.filter.strings._strings
export=exp;
}
declare module "dojox/dtl/filter/strings._truncate_singlets" {
var exp: dojox.dtl.filter.strings._truncate_singlets
export=exp;
}
declare module "dojox/dtl/render/html" {
var exp: dojox.dtl.render.html
export=exp;
}
declare module "dojox/dtl/render/dom" {
var exp: dojox.dtl.render.dom
export=exp;
}
declare module "dojox/dtl/tag/date" {
var exp: dojox.dtl.tag.date
export=exp;
}
declare module "dojox/dtl/tag/loader" {
var exp: dojox.dtl.tag.loader
export=exp;
}
declare module "dojox/dtl/tag/logic" {
var exp: dojox.dtl.tag.logic
export=exp;
}
declare module "dojox/dtl/tag/loop" {
var exp: dojox.dtl.tag.loop
export=exp;
}
declare module "dojox/dtl/tag/misc" {
var exp: dojox.dtl.tag.misc
export=exp;
}
declare module "dojox/dtl/utils/date" {
var exp: dojox.dtl.utils.date
export=exp;
} | the_stack |
import React, { useEffect } from 'react';
import {
Alert,
AppRegistry,
Button,
SafeAreaView,
ScrollView,
StyleSheet,
Text,
View,
} from 'react-native';
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/messaging';
import Notifee, {
AndroidChannel,
AndroidImportance,
Notification,
EventType,
Event,
AuthorizationStatus,
TimestampTrigger,
RepeatFrequency,
} from '@notifee/react-native';
import { notifications } from './notifications';
import { FirebaseMessagingTypes } from '@react-native-firebase/messaging';
type RemoteMessage = FirebaseMessagingTypes.RemoteMessage;
const colors: { [key: string]: string } = {
custom_sound: '#f449ee',
high: '#f44336',
default: '#2196f3',
low: '#ffb300',
min: '#9e9e9e',
};
const channels: AndroidChannel[] = [
{
name: 'High Importance',
id: 'high',
importance: AndroidImportance.HIGH,
// sound: 'hollow',
},
{
name: '🐴 Sound',
id: 'custom_sound',
importance: AndroidImportance.HIGH,
sound: 'horse.mp3',
},
{
name: 'Default Importance',
id: 'default',
importance: AndroidImportance.DEFAULT,
},
{
name: 'Low Importance',
id: 'low',
importance: AndroidImportance.LOW,
},
{
name: 'Min Importance',
id: 'min',
importance: AndroidImportance.MIN,
},
];
async function onMessage(message: RemoteMessage): Promise<void> {
console.log('New FCM Message', message.messageId);
await Notifee.displayNotification({
title: 'onMessage',
body: `with message ${message.messageId}`,
android: { channelId: 'default', tag: 'hello1' },
});
}
async function onBackgroundMessage(message: RemoteMessage): Promise<void> {
console.log('onBackgroundMessage New FCM Message', message);
// await Notifee.displayNotification({
// title: 'onMessage',
// body: `with message ${message.messageId}`,
// android: { channelId: 'default', tag: 'hello1' },
// });
}
firebase.messaging().setBackgroundMessageHandler(onBackgroundMessage);
function Root(): any {
const [id, setId] = React.useState<string | null>(null);
async function init(): Promise<void> {
const fcmToken = await firebase.messaging().getToken();
console.log({ fcmToken });
firebase.messaging().onMessage(onMessage);
const initialNotification = await Notifee.getInitialNotification();
console.log('init: ', { initialNotification });
await Promise.all(channels.map($ => Notifee.createChannel($)));
await Notifee.setNotificationCategories([
{
id: 'actions',
actions: [
{
id: 'like',
title: 'Like Post',
},
{
id: 'dislike',
title: 'Dislike Post',
},
],
},
{
id: 'stop',
actions: [
{
id: 'stop',
title: 'Dismiss',
},
],
},
{
id: 'dismiss',
actions: [
{
id: 'dismiss',
title: 'Dismiss',
},
],
},
]);
}
useEffect(() => {
init().catch(console.error);
}, []);
async function displayNotification(
notification: Notification | Notification[],
channelId: string,
): Promise<void> {
let currentPermissions = await Notifee.getNotificationSettings();
if (currentPermissions.authorizationStatus !== AuthorizationStatus.AUTHORIZED) {
await Notifee.requestPermission({ sound: true, criticalAlert: true }).then(props =>
console.log('fullfilled,', props),
);
}
currentPermissions = await Notifee.getNotificationSettings();
console.log('currentPermissions', currentPermissions);
await Notifee.setNotificationCategories([
{
id: 'stop',
actions: [
{
id: 'stop',
title: 'Dismiss',
},
],
},
]);
if (Array.isArray(notification)) {
Promise.all(notification.map($ => Notifee.displayNotification($))).catch(console.error);
} else {
if (!notification.android) notification.android = {};
notification.android.channelId = channelId;
const date = new Date(Date.now());
date.setSeconds(date.getSeconds() + 15);
const trigger: TimestampTrigger = {
type: 0,
timestamp: date.getTime(),
alarmManager: true,
repeatFrequency: RepeatFrequency.HOURLY,
};
Notifee.createTriggerNotification(notification, trigger)
.then(notificationId => setId(notificationId))
.catch(console.error);
}
}
return (
<SafeAreaView style={[styles.container]}>
<ScrollView style={[styles.container]}>
<View>
<Button
title={`get notification settings`}
onPress={async (): Promise<void> => {
const notificationSettings = await Notifee.getNotificationSettings();
console.log('notifications Settings : ', JSON.stringify(notificationSettings));
Alert.alert(
'Notification Settings',
JSON.stringify(notificationSettings),
[
{
text: 'Cancel',
onPress: () => {
//no-Op
},
style: 'cancel',
},
],
{
cancelable: true,
},
);
}}
/>
<Button
title={`get delivered notifications`}
onPress={async (): Promise<void> => {
const displayedNotifications = await Notifee.getDisplayedNotifications();
console.log('notifications: ', displayedNotifications?.[0]?.notification?.android);
}}
/>
<Button
title={`get trigger notifications`}
onPress={async (): Promise<void> => {
const triggerNotifications = await Notifee.getTriggerNotifications();
console.log('trigger notifications: ', triggerNotifications);
}}
/>
<Button
title={`get power manager info`}
onPress={async (): Promise<void> => {
console.log(await Notifee.getPowerManagerInfo());
}}
/>
<Button
title={`open power manager `}
onPress={async (): Promise<void> => {
console.log(await Notifee.openPowerManagerSettings());
}}
/>
<Button
title={`open alarm special access settings`}
onPress={async (): Promise<void> => {
console.log(await Notifee.openAlarmPermissionSettings());
}}
/>
{id != null && (
<>
<Button
title={`Cancel ${id}`}
onPress={(): void => {
Notifee.cancelNotification(id, 'example-tag');
}}
/>
<Button
title={`Cancel trigger ${id}`}
onPress={(): void => {
if (id != null) Notifee.cancelTriggerNotification(id);
}}
/>
<Button
title={`Cancel displayed ${id}`}
onPress={async () => {
if (id != null) await Notifee.cancelDisplayedNotification(id);
}}
/>
<Button
title={`Cancel all `}
onPress={async () => {
await Notifee.cancelDisplayedNotifications([id]);
}}
/>
</>
)}
<Button
title={`get channels`}
onPress={async (): Promise<void> => {
const buttonChannels = await Notifee.getChannels();
buttonChannels.forEach(res => {
if (res.id === 'custom-vibrations') {
console.log('res', res);
}
});
}}
/>
<Button
title={`get channels`}
onPress={async (): Promise<void> => {
const triggerNotifications = await Notifee.getTriggerNotifications();
console.log('triggerNotifications', triggerNotifications);
}}
/>
</View>
{notifications.map(({ key, notification }): any => (
<View key={key} style={styles.rowItem}>
<Text style={styles.header}>{key}</Text>
<View style={styles.row}>
{channels.map(channel => (
<View key={channel.id + key} style={styles.rowItem}>
<Button
title={`>.`}
onPress={(): any => displayNotification(notification, channel.id)}
color={colors[channel.id]}
/>
</View>
))}
</View>
</View>
))}
</ScrollView>
</SafeAreaView>
);
}
function logEvent(state: string, event: any): void {
const { type, detail } = event;
let eventTypeString;
switch (type) {
case EventType.UNKNOWN:
eventTypeString = 'UNKNOWN';
console.log('Notification Id', detail.notification?.id);
break;
case EventType.DISMISSED:
eventTypeString = 'DISMISSED';
console.log('Notification Id', detail.notification?.id);
break;
case EventType.PRESS:
eventTypeString = 'PRESS';
console.log('Action ID', detail.pressAction?.id || 'N/A');
console.warn(`Received a ${eventTypeString} ${state} event in JS mode.`, event);
break;
case EventType.ACTION_PRESS:
eventTypeString = 'ACTION_PRESS';
console.log('Action ID', detail.pressAction?.id || 'N/A');
break;
case EventType.DELIVERED:
eventTypeString = 'DELIVERED';
break;
case EventType.APP_BLOCKED:
eventTypeString = 'APP_BLOCKED';
console.log('Blocked', detail.blocked);
break;
case EventType.CHANNEL_BLOCKED:
eventTypeString = 'CHANNEL_BLOCKED';
console.log('Channel', detail.channel);
break;
case EventType.CHANNEL_GROUP_BLOCKED:
eventTypeString = 'CHANNEL_GROUP_BLOCKED';
console.log('Channel Group', detail.channelGroup);
break;
case EventType.TRIGGER_NOTIFICATION_CREATED:
eventTypeString = 'TRIGGER_NOTIFICATION_CREATED';
console.log('Trigger Notification');
break;
default:
eventTypeString = 'UNHANDLED_NATIVE_EVENT';
}
console.warn(`Received a ${eventTypeString} ${state} event in JS mode.`, event);
console.warn(JSON.stringify(event));
}
Notifee.onForegroundEvent(event => {
logEvent('Foreground', event);
});
Notifee.onBackgroundEvent(async ({ type, detail }) => {
console.log('onBackgroundEvent');
logEvent('Background', { type, detail });
const { notification, pressAction } = detail;
// Check if the user pressed a cancel action
if (
type === EventType.ACTION_PRESS &&
['first_action', 'second_action'].includes(pressAction?.id || 'N/A')
) {
// Remove the notification
await Notifee.cancelNotification(notification?.id || 'N/A');
console.warn('Notification Cancelled', pressAction?.id);
}
});
Notifee.registerForegroundService(notification => {
console.warn('Foreground service started.', notification);
return new Promise(resolve => {
/**
* Cancel the notification and resolve the service promise so the Headless task quits.
*/
async function stopService(id?: string): Promise<void> {
console.warn('Stopping service, using notification id: ' + id);
clearInterval(interval);
if (id) {
await Notifee.cancelNotification(id);
}
return resolve();
}
/**
* Cancel our long running task if the user presses the 'stop' action.
*/
async function handleStopActionEvent({ type, detail }: Event): Promise<void> {
console.log('handleStopActionEvent1 type:', type, 'pressactionid', detail?.pressAction?.id);
if (type !== EventType.ACTION_PRESS) return;
console.log('handleStopActionEvent2 type:', type, 'pressactionid', detail?.pressAction?.id);
if (detail?.pressAction?.id === 'stop') {
console.warn('Stop action was pressed');
await stopService(detail.notification?.id);
}
}
Notifee.onForegroundEvent(handleStopActionEvent);
Notifee.onBackgroundEvent(handleStopActionEvent);
// A fake progress updater.
let current = 1;
const interval = setInterval(async () => {
notification.android = {
progress: { current: current },
};
Notifee.displayNotification(notification);
current++;
}, 125);
setTimeout(async () => {
clearInterval(interval);
console.warn('Background work has completed.');
await stopService(notification.id);
}, 15000);
});
});
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
fontSize: 16,
padding: 8,
marginBottom: 8,
fontWeight: 'bold',
},
row: {
flexDirection: 'row',
marginBottom: 8,
paddingBottom: 20,
borderBottomColor: '#c1c1c1',
borderBottomWidth: 1,
},
rowItem: {
flex: 1,
justifyContent: 'center',
marginHorizontal: 8,
},
});
// AppRegistry.registerComponent('testing', () => Root);
function TestComponent(): any {
useEffect(() => {
(async () => {
const initialNotification = await Notifee.getInitialNotification();
console.log('TestComponent initialNotification', initialNotification);
})();
}, []);
return (
// eslint-disable-next-line react-native/no-inline-styles
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Test Component</Text>
</View>
);
}
AppRegistry.registerComponent('test_component', () => TestComponent);
function FullScreenComponent(): any {
return (
// eslint-disable-next-line react-native/no-inline-styles
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>FullScreen Component</Text>
</View>
);
}
AppRegistry.registerComponent('full_screen', () => FullScreenComponent);
export default Root; | the_stack |
import JoynrRuntime from "./JoynrRuntime";
import { ShutdownSettings, UdsLibJoynrProvisioning } from "./interface/Provisioning";
import UdsClient from "../messaging/uds/UdsClient";
import JoynrMessage from "../messaging/JoynrMessage";
import InProcessMessagingSkeleton from "../messaging/inprocess/InProcessMessagingSkeleton";
import InProcessMessagingStub from "../messaging/inprocess/InProcessMessagingStub";
import * as DiagnosticTags from "../system/DiagnosticTags";
import RoutingProxy from "../../generated/joynr/system/RoutingProxy";
import DiscoveryQos from "../proxy/DiscoveryQos";
import DiscoveryScope from "../../generated/joynr/types/DiscoveryScope";
import DiscoveryProxy from "../../generated/joynr/system/DiscoveryProxy";
import MessageReplyToAddressCalculator from "../messaging/MessageReplyToAddressCalculator";
import DiscoveryEntryWithMetaInfo, {
DiscoveryEntryWithMetaInfoMembers
} from "../../generated/joynr/types/DiscoveryEntryWithMetaInfo";
import defaultLibjoynrSettings from "./settings/defaultLibjoynrSettings";
import nanoid from "nanoid";
//import InProcessAddress from "../messaging/inprocess/InProcessAddress";
//import InProcessMessagingStubFactory from "../messaging/inprocess/InProcessMessagingStubFactory";
import MessagingStubFactory from "../messaging/MessagingStubFactory";
import MessagingQos from "../messaging/MessagingQos";
import UdsAddress from "../../generated/joynr/system/RoutingTypes/UdsAddress";
import UdsClientAddress from "../../generated/joynr/system/RoutingTypes/UdsClientAddress";
import LocalDiscoveryAggregator = require("../capabilities/discovery/LocalDiscoveryAggregator");
import UdsMulticastAddressCalculator from "../messaging/uds/UdsMulticastAddressCalculator";
import JoynrStates = require("./JoynrStates");
import loggingManager from "../system/LoggingManager";
import JoynrRuntimeException from "../exceptions/JoynrRuntimeException";
const log = loggingManager.getLogger("joynr.start.UdsLibJoynrRuntime");
/**
* The UdsLibJoynrRuntime is the version of the libjoynr-js runtime that communicates with
* a cluster controller via a unix domain socket (UDS). The cluster controller is the UDS Server, and the
* libjoynr connects to it with a single socket for all communication.
*
* @name UdsLibJoynrRuntime
* @constructor
*/
class UdsLibJoynrRuntime extends JoynrRuntime<UdsLibJoynrProvisioning> {
private udsClient!: UdsClient;
private messageReplyToAddressCalculator: MessageReplyToAddressCalculator;
public constructor(onFatalRuntimeError: (error: JoynrRuntimeException) => void) {
super(onFatalRuntimeError);
this.messageReplyToAddressCalculator = new MessageReplyToAddressCalculator({});
}
/**
* Starts up the libjoynr instance
*
* @param {UdsLibJoynrProvisioning} provisioning
* @returns an A+ promise object, reporting when libjoynr startup is
* completed or has failed
* @throws {Error} if libjoynr is not in SHUTDOWN state
*/
public async start(provisioning: UdsLibJoynrProvisioning): Promise<void> {
super.start(provisioning);
const udsProvisioning = provisioning.uds || {};
udsProvisioning.socketPath = udsProvisioning.socketPath || "/var/run/joynr/cluster-controller.sock";
udsProvisioning.clientId = udsProvisioning.clientId || nanoid();
udsProvisioning.connectSleepTimeMs = udsProvisioning.connectSleepTimeMs || 500;
// routing table is still required for addMulticastReceiver and removeMulticastReceiver
const initialRoutingTable: Record<string, any> = {};
let untypedCapabilities: DiscoveryEntryWithMetaInfoMembers[] = this.provisioning.capabilities || [];
const defaultCapabilities = defaultLibjoynrSettings.capabilities || [];
untypedCapabilities = untypedCapabilities.concat(defaultCapabilities);
const ccAddress = new UdsAddress({
path: udsProvisioning.socketPath
});
// provisioned capabilities for Arbitrator
const typedCapabilities = [];
for (let i = 0; i < untypedCapabilities.length; i++) {
const capability = new DiscoveryEntryWithMetaInfo(untypedCapabilities[i]);
initialRoutingTable[capability.participantId] = ccAddress;
typedCapabilities.push(capability);
}
const localAddress = new UdsClientAddress({
id: udsProvisioning.clientId
});
// TODO
// MessagingStubFactory is only required for the constructor of MessageRouter.
// It is used there for routing which is not required in UdsLibJoynrRuntime.
// This will be refactored and optimized later.
const messagingStubFactories: Record<string, any> = {};
//messagingStubFactories[InProcessAddress._typeName] = new InProcessMessagingStubFactory();
const messagingStubFactory = new MessagingStubFactory({
messagingStubFactories
});
// TODO
// MulticastAddressCalculator is only required for the constructor of MessageRouter.
// It is used there for routing which is not required in UdsLibJoynrRuntime.
// This will be refactored and optimized later.
const messageRouterSettings = {
initialRoutingTable,
messagingStubFactory,
incomingAddress: localAddress,
parentMessageRouterAddress: ccAddress,
multicastAddressCalculator: new UdsMulticastAddressCalculator({
globalAddress: ccAddress
})
};
const localDiscoveryAggregator = new LocalDiscoveryAggregator();
await super.initializePersistency(provisioning);
super.createMessageRouter(provisioning, messageRouterSettings);
// InProcessMessagingSkeleton and InProcessMessagingStub used for direct handling of outgoing messages
// from the dispatcher to the UDS client
const clusterControllerMessagingSkeleton = new InProcessMessagingSkeleton();
const clusterControllerMessagingStub = new InProcessMessagingStub(clusterControllerMessagingSkeleton);
super.initializeComponents(
provisioning,
localDiscoveryAggregator,
clusterControllerMessagingStub,
typedCapabilities
);
// Forward incoming messages directly to Dispatcher.receive() (no routing)
const onUdsClientMessageCallback = (joynrMessage: JoynrMessage): void => {
log.debug(`<<< INCOMING <<< message with ID ${joynrMessage.msgId}`);
this.dispatcher.receive(joynrMessage);
};
this.udsClient = new UdsClient({
socketPath: udsProvisioning.socketPath,
clientId: udsProvisioning.clientId,
connectSleepTimeMs: udsProvisioning.connectSleepTimeMs,
onMessageCallback: onUdsClientMessageCallback,
onFatalRuntimeError: this.onFatalRuntimeError
});
// Forward all outgoing messages directly to udsClient.send() (no routing)
const onMessageSend = (joynrMessage: JoynrMessage): Promise<void> => {
if (!joynrMessage.isLocalMessage) {
try {
this.messageReplyToAddressCalculator.setReplyTo(joynrMessage);
} catch (error) {
log.warn(
`replyTo address could not be set: ${error}. Dropping message.`,
DiagnosticTags.forJoynrMessage(joynrMessage)
);
return Promise.resolve();
}
}
return this.udsClient.send(joynrMessage);
};
clusterControllerMessagingSkeleton.registerListener(onMessageSend);
const internalMessagingQos = new MessagingQos({ ttl: MessagingQos.DEFAULT_TTL + 10000 });
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.proxyBuilder!.build(RoutingProxy, {
domain: "io.joynr",
messagingQos: internalMessagingQos,
discoveryQos: new DiscoveryQos({
discoveryScope: DiscoveryScope.LOCAL_ONLY
}),
staticArbitration: true
})
.then(newRoutingProxy => {
return this.messageRouter.setRoutingProxy(newRoutingProxy);
})
.catch((error: any) => {
throw new Error(`Failed to create routing proxy: ${error}`);
})
.then(() => {
return this.messageRouter.getReplyToAddressFromRoutingProxy();
})
.catch((error: any) => {
throw new Error(`Failed to initialize replyToAddress: ${error}`);
})
.then(address => {
this.messageReplyToAddressCalculator.setReplyToAddress(address);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.proxyBuilder!.build(DiscoveryProxy, {
domain: "io.joynr",
messagingQos: internalMessagingQos,
discoveryQos: new DiscoveryQos({
discoveryScope: DiscoveryScope.LOCAL_ONLY
}),
staticArbitration: true
});
})
.then((newDiscoveryProxy: DiscoveryProxy) => {
localDiscoveryAggregator.setDiscoveryProxy(newDiscoveryProxy);
this.joynrState = JoynrStates.STARTED;
log.debug("UdsLibJoynrRuntime initialized");
})
.catch(async error => {
log.error(`error starting up joynr: ${error}`);
await this.shutdown();
throw error;
});
}
/**
* Sends subscriptionStop messages for all active subscriptions.
*
* @param timeout {number} optional timeout defaulting to 0 = no timeout
* @returns - resolved after all SubscriptionStop messages are sent.
* - rejected in case of any issues or timeout occurs.
*/
public terminateAllSubscriptions(timeout = 0): Promise<any> {
this.udsClient.enableShutdownMode();
return super.terminateAllSubscriptions(timeout);
}
/**
* Shuts down libjoynr
* @param settings.clearSubscriptionsTimeoutMs {number} time in ms till clearSubscriptionsPromise will be rejected
* if it's not resolved yet
* @param settings.clearSubscriptionsEnabled {boolean} clear all subscriptions before shutting down.
* Set this to false in process.exit handler as this is not synchronous.
*
* @returns - resolved after successful shutdown
* - rejected in case of any issues
*/
public async shutdown(settings?: ShutdownSettings): Promise<any> {
if (this.udsClient) {
this.udsClient.enableShutdownMode();
}
await super.shutdown(settings);
if (this.udsClient) {
this.udsClient.shutdown();
}
}
}
export = UdsLibJoynrRuntime; | the_stack |
import * as _ from "underscore";
import {TableSchema} from "../table-schema";
import {TableFieldPartition} from "../TableFieldPartition";
import {TableFieldPolicy} from "../TableFieldPolicy";
import {DefaultTableSchema} from "../default-table-schema.model";
import {TableColumnDefinition} from "../TableColumnDefinition";
import {ObjectUtils} from "../../../../lib/common/utils/object-utils";
import {SourceTableSchema} from "./feed-source-table-schema.model";
import {TableOptions} from "./feed.model";
import {FeedTableSchema} from "./feed-table-schema.model";
import {KyloObject} from "../../../../lib/common/common.model";
import {SchemaField} from "../schema-field";
import {CloneUtil} from "../../../common/utils/clone-util";
export class FeedTableDefinition implements KyloObject{
public static OBJECT_TYPE:string = 'FeedTableDefinition'
public objectType:string = FeedTableDefinition.OBJECT_TYPE;
tableSchema: FeedTableSchema
sourceTableSchema: SourceTableSchema
feedTableSchema: FeedTableSchema;
feedDefinitionTableSchema:FeedTableSchema;
method: string;
existingTableName: string;
structured: boolean;
targetMergeStrategy: string;
feedFormat: string;
targetFormat: string;
feedTblProperties: string;
fieldPolicies: TableFieldPolicy[]
feedDefinitionFieldPolicies:TableFieldPolicy[];
partitions: TableFieldPartition[]
options: TableOptions
sourceTableIncrementalDateField: string
schemaChanged:boolean;
public constructor(init?:Partial<FeedTableDefinition>) {
//set the defaults
this.initialize();
//apply the new object
Object.assign(this, init);
//ensure object types
this.ensureObjectTypes();
}
initialize(){
this.tableSchema= new FeedTableSchema(),
this.sourceTableSchema= new SourceTableSchema(),
this.feedTableSchema = new FeedTableSchema(),
this.feedDefinitionTableSchema = new FeedTableSchema(),
this.method= 'SAMPLE_FILE',
this.existingTableName= null,
this.structured= false,
this.targetMergeStrategy= 'DEDUPE_AND_MERGE',
this.feedFormat= 'ROW FORMAT SERDE \'org.apache.hadoop.hive.serde2.OpenCSVSerde\''
+ ' WITH SERDEPROPERTIES ( \'separatorChar\' = \',\' ,\'escapeChar\' = \'\\\\\' ,\'quoteChar\' = \'"\')'
+ ' STORED AS TEXTFILE',
this.targetFormat= 'STORED AS ORC',
this.feedTblProperties= '',
this.fieldPolicies= [],
this.feedDefinitionFieldPolicies = [],
this.partitions= [],
this.options= {compress: false, compressionFormat: 'NONE', auditLogging: true, encrypt: false, trackHistory: false},
this.sourceTableIncrementalDateField= null
}
update(oldFields:TableColumnDefinition[], oldPartitions:TableFieldPartition[]){
let tableFieldMap: { [key: string]: TableColumnDefinition; } = {};
this.feedDefinitionTableSchema.fields.forEach((field: TableColumnDefinition, index: number) => {
field._id = (<TableColumnDefinition> oldFields[index])._id;
tableFieldMap[field.name] = field;
});
this.partitions.forEach((partition: TableFieldPartition, index: number) => {
let oldPartition = (<TableFieldPartition> oldPartitions[index]);
partition._id = (<TableFieldPartition> oldPartitions[index])._id;
//update the columnDef ref
if (oldPartition.sourceField && tableFieldMap[oldPartition.sourceField] != undefined) {
//find the matching column field
partition.columnDef = tableFieldMap[oldPartition.sourceField];
}
});
this.ensureTableFieldPolicyTypes();
// this.tableSchema = ObjectUtils.getAs(this.tableSchema,FeedTableSchema);
// this.sourceTableSchema = ObjectUtils.getAs(this.sourceTableSchema,SourceTableSchema);
// this.feedTableSchema = ObjectUtils.getAs(this.feedTableSchema,FeedTableSchema);
}
public ensureObjectTypes() {
this.tableSchema = ObjectUtils.getAs(this.tableSchema,FeedTableSchema);
this.feedDefinitionTableSchema = (this.feedDefinitionTableSchema && this.feedDefinitionTableSchema.fields.length >0) ? ObjectUtils.getAs(this.feedDefinitionTableSchema,FeedTableSchema) : CloneUtil.deepCopy(this.tableSchema);
//ensure the table fields are correct objects
let tableFieldMap: { [key: string]: TableColumnDefinition; } = {};
this.feedDefinitionTableSchema.fields.forEach((field: TableColumnDefinition) => {
tableFieldMap[field.name] = field;
});
//ensure the table partitions are correct objects
let partitions = this.partitions.map((partition: any) => {
let partitionObject = ObjectUtils.getAs<TableFieldPartition>(partition,TableFieldPartition,TableFieldPartition.OBJECT_TYPE);
//ensure it has the correct columnDef ref
if (partitionObject.sourceField && tableFieldMap[partitionObject.sourceField] != undefined) {
//find the matching column field
partitionObject.columnDef = tableFieldMap[partitionObject.sourceField];
}
return partitionObject;
});
this.partitions = partitions;
this.sourceTableSchema = ObjectUtils.getAs(this.sourceTableSchema,SourceTableSchema);
this.feedTableSchema = ObjectUtils.getAs(this.feedTableSchema,FeedTableSchema);
this.ensureTableFieldPolicyTypes();
}
private fieldPolicyAsObject(policy:any,isTarget:boolean) {
let policyObj = ObjectUtils.getAs(policy,TableFieldPolicy, TableFieldPolicy.OBJECT_TYPE);
let columnDef = isTarget ? this.getTargetColumnFieldByName(policyObj.fieldName) : this.getColumnDefinitionByName(policyObj.fieldName);
policyObj.field = columnDef;
columnDef.fieldPolicy = policyObj;
return policyObj;
}
ensureTableFieldPolicyTypes(){
this.feedDefinitionFieldPolicies = this.feedDefinitionFieldPolicies && this.feedDefinitionFieldPolicies.length >0 ?this.feedDefinitionFieldPolicies : this.fieldPolicies;
this.feedDefinitionFieldPolicies = this.feedDefinitionFieldPolicies.map((policy: any) => this.fieldPolicyAsObject(policy,false));
this.fieldPolicies = this.fieldPolicies.map((policy: any) => this.fieldPolicyAsObject(policy,true));
}
syncFieldPolicy(columnDef: TableColumnDefinition, index: number){
var name = columnDef.name;
if (name != undefined) {
this.feedDefinitionFieldPolicies[index].name = name;
this.feedDefinitionFieldPolicies[index].fieldName = name;
this.feedDefinitionFieldPolicies[index].field = columnDef;
columnDef.fieldPolicy = this.feedDefinitionFieldPolicies[index];
}
else {
if (this.feedDefinitionFieldPolicies[index].field) {
this.feedDefinitionFieldPolicies[index].field == null;
columnDef.fieldPolicy = undefined;
}
}
}
syncTableFieldPolicyNames():void{
this.feedDefinitionTableSchema.fields.forEach((columnDef: TableColumnDefinition, index: number) => {
this.syncFieldPolicy(columnDef, index);
});
//remove any extra columns in the policies
while (this.feedDefinitionFieldPolicies.length > this.feedDefinitionTableSchema.fields.length) {
this.feedDefinitionFieldPolicies.splice(this.feedDefinitionTableSchema.fields.length, 1);
}
}
/**
* For a given list of incoming Table schema fields ({@see this#newTableFieldDefinition}) it will create a new FieldPolicy object ({@see this#newTableFieldPolicy} for it
*/
setTableFields(fields: TableColumnDefinition[] | SchemaField[], policies: TableFieldPolicy[] = null) {
//ensure the fields are of type TableColumnDefinition
let newFields = _.map(fields,(field) => {
if(!field['objectType'] || field['objectType'] != 'TableColumnDefinition' ){
return new TableColumnDefinition(field);
}
else {
return field;
}
})
this.feedDefinitionTableSchema.fields = newFields;
this.feedDefinitionFieldPolicies = (policies != null && policies.length > 0) ? policies : newFields.map(field => TableFieldPolicy.forName(field.name));
}
/**
* Adding a new Column to the schema
* This is called both when the user clicks the "Add Field" button or when the sample file is uploaded
* If adding from the UI the {@code columnDef} will be null, otherwise it will be the parsed ColumnDef from the sample file
* @param columnDef
*/
addColumn(columnDef?: TableColumnDefinition, syncFieldPolicies?: boolean) :TableColumnDefinition{
//add to the fields
let newColumn = this.feedDefinitionTableSchema.addColumn(columnDef);
// when adding a new column this is also called to synchronize the field policies array with the columns
let policy = TableFieldPolicy.forName(newColumn.name);
this.feedDefinitionFieldPolicies.push(policy);
newColumn.fieldPolicy = policy;
policy.field = columnDef;
this.sourceTableSchema.fields.push(newColumn.copy());
if (syncFieldPolicies == undefined || syncFieldPolicies == true) {
this.syncTableFieldPolicyNames();
}
return newColumn;
}
undoColumn(index: number):TableColumnDefinition {
var columnDef = <TableColumnDefinition> this.feedDefinitionTableSchema.fields[index];
columnDef.history.pop();
let prevValue = columnDef.history[columnDef.history.length - 1];
columnDef.undo(prevValue);
return columnDef;
};
getColumnDefinitionByName(name:string) :TableColumnDefinition{
return <TableColumnDefinition> this.feedDefinitionTableSchema.fields.find(columnDef => columnDef.name == name);
}
getTargetColumnFieldByName(name:string) :TableColumnDefinition {
return <TableColumnDefinition> this.tableSchema.fields.find(columnDef => columnDef.name == name);
}
/**
* get the partition objects for a given column
* @param {string} columnName
* @return {TableFieldPartition[]}
*/
getPartitionsOnColumn(columnName:string){
let partitions = this.partitions
.filter((partition: any) => {
return partition.columnDef.name === columnName;
});
return partitions;
}
/**
* Remove a column from the schema
* @param index
*/
removeColumn(index: number) :TableColumnDefinition{
var columnDef = <TableColumnDefinition> this.feedDefinitionTableSchema.fields[index];
columnDef.deleteColumn();
return columnDef;
}
} | the_stack |
import * as React from 'react';
import { Environment, EnvironmentType } from '@microsoft/sp-core-library';
import { IWebPartContext } from '@microsoft/sp-webpart-base';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { IPropertyFieldSPFolderPickerPropsInternal } from './PropertyFieldSPFolderPicker';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { IconButton, DefaultButton, PrimaryButton, CommandButton, IButtonProps } from 'office-ui-fabric-react/lib/Button';
import { Dialog, DialogType } from 'office-ui-fabric-react/lib/Dialog';
import { Spinner, SpinnerType } from 'office-ui-fabric-react/lib/Spinner';
import { List } from 'office-ui-fabric-react/lib/List';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import * as strings from 'sp-client-custom-fields/strings';
/**
* @interface
* PropertyFieldSPFolderPickerHost properties interface
*
*/
export interface IPropertyFieldSPFolderPickerHostProps extends IPropertyFieldSPFolderPickerPropsInternal {
}
/**
* @interface
* Interface to define the state of the rendering control
*
*/
export interface IPropertyFieldSPFolderPickerHostState {
isOpen: boolean;
loading: boolean;
currentSPFolder?: string;
childrenFolders?: ISPFolders;
selectedFolder?: string;
confirmFolder?: string;
errorMessage?: string;
}
/**
* @class
* Renders the controls for PropertyFieldSPFolderPicker component
*/
export default class PropertyFieldSPFolderPickerHost extends React.Component<IPropertyFieldSPFolderPickerHostProps, IPropertyFieldSPFolderPickerHostState> {
private currentPage: number = 0;
private pageItemCount: number = 6;
private latestValidateValue: string;
private async: Async;
private delayedValidate: (value: string) => void;
/**
* @function
* Constructor
*/
constructor(props: IPropertyFieldSPFolderPickerHostProps) {
super(props);
//Bind the current object to the external called methods
this.onBrowseClick = this.onBrowseClick.bind(this);
this.onDismiss = this.onDismiss.bind(this);
this.onRenderCell = this.onRenderCell.bind(this);
this.onClickNext = this.onClickNext.bind(this);
this.onClickPrevious = this.onClickPrevious.bind(this);
this.onClickLink = this.onClickLink.bind(this);
this.onClickParent = this.onClickParent.bind(this);
this.onFolderChecked = this.onFolderChecked.bind(this);
this.onClickSelect = this.onClickSelect.bind(this);
this.onClearSelectionClick = this.onClearSelectionClick.bind(this);
//Inits the intial folders
var initialFolder: string;
var currentSPFolder: string = '';
if (props.baseFolder != null)
currentSPFolder = props.baseFolder;
if (props.initialFolder != null && props.initialFolder != '') {
initialFolder = props.initialFolder;
currentSPFolder = this.getParentFolder(initialFolder);
}
//Inits the state
this.state = {
isOpen: false,
loading: true,
currentSPFolder: currentSPFolder,
confirmFolder: initialFolder,
selectedFolder: initialFolder,
childrenFolders: { value: [] },
errorMessage: ''
};
this.async = new Async(this);
this.validate = this.validate.bind(this);
this.notifyAfterValidate = this.notifyAfterValidate.bind(this);
this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime);
}
/**
* @function
* Function called when the user wants to browse folders
*/
private onBrowseClick(): void {
this.currentPage = 0;
this.LoadChildrenFolders();
}
/**
* @function
* Function called when the user erase the current selection
*/
private onClearSelectionClick(): void {
this.state.confirmFolder = '';
this.state.currentSPFolder = '';
if (this.props.baseFolder != null)
this.state.currentSPFolder = this.props.baseFolder;
this.currentPage = 0;
this.setState({ isOpen: false, loading: true, selectedFolder: this.state.selectedFolder, currentSPFolder: this.state.currentSPFolder, childrenFolders: this.state.childrenFolders });
this.delayedValidate(this.state.confirmFolder);
}
/**
* @function
* Loads the sub folders from the current
*/
private LoadChildrenFolders(): void {
//Loading
this.state.childrenFolders = { value: [] };
this.setState({ isOpen: true, loading: true, selectedFolder: this.state.selectedFolder, currentSPFolder: this.state.currentSPFolder, childrenFolders: this.state.childrenFolders });
//Inits the service
var folderService: SPFolderPickerService = new SPFolderPickerService(this.props.context);
folderService.getFolders(this.state.currentSPFolder, this.currentPage, this.pageItemCount).then((response: ISPFolders) => {
//Binds the results
this.state.childrenFolders = response;
this.setState({ isOpen: true, loading: false, selectedFolder: this.state.selectedFolder, currentSPFolder: this.state.currentSPFolder, childrenFolders: this.state.childrenFolders });
});
}
/**
* @function
* User clicks on the previous button
*/
private onClickPrevious(): void {
this.currentPage = this.currentPage - 1;
this.state.selectedFolder = '';
if (this.currentPage < 0)
this.currentPage = 0;
this.LoadChildrenFolders();
}
/**
* @function
* User clicks on the next button
*/
private onClickNext(): void {
this.state.selectedFolder = '';
this.currentPage = this.currentPage + 1;
this.LoadChildrenFolders();
}
/**
* @function
* User clicks on a sub folder
*/
private onClickLink(element?: any): void {
this.currentPage = 0;
this.state.selectedFolder = '';
this.state.currentSPFolder = element.currentTarget.value;
this.LoadChildrenFolders();
}
/**
* @function
* User clicks on the go-to parent button
*/
private onClickParent(): void {
var parentFolder: string = this.getParentFolder(this.state.currentSPFolder);
if (parentFolder == this.props.context.pageContext.web.serverRelativeUrl)
parentFolder = '';
this.currentPage = 0;
this.state.selectedFolder = '';
this.state.currentSPFolder = parentFolder;
this.LoadChildrenFolders();
}
/**
* @function
* Gets the parent folder server relative url from a folder url
*/
private getParentFolder(folderUrl: string): string {
var splitted = folderUrl.split('/');
var parentFolder: string = '';
for (var i = 0; i < splitted.length -1; i++) {
var node: string = splitted[i];
if (node != null && node != '') {
parentFolder += '/';
parentFolder += splitted[i];
}
}
return parentFolder;
}
/**
* @function
* Occurs when the selected folder changed
*/
private onFolderChecked(element?: any): void {
this.state.selectedFolder = element.currentTarget.value;
this.setState({ isOpen: true, loading: false, selectedFolder: this.state.selectedFolder, currentSPFolder: this.state.currentSPFolder, childrenFolders: this.state.childrenFolders });
}
/**
* @function
* User clicks on Select button
*/
private onClickSelect(): void {
this.state.confirmFolder = this.state.selectedFolder;
this.state = { isOpen: false, loading: false, selectedFolder: this.state.selectedFolder,
confirmFolder: this.state.selectedFolder,
currentSPFolder: this.state.currentSPFolder,
childrenFolders: this.state.childrenFolders };
this.setState(this.state);
this.delayedValidate(this.state.confirmFolder);
}
/**
* @function
* Validates the new custom field value
*/
private validate(value: string): void {
if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) {
this.notifyAfterValidate(this.props.initialFolder, value);
return;
}
if (this.latestValidateValue === value)
return;
this.latestValidateValue = value;
var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || '');
if (result !== undefined) {
if (typeof result === 'string') {
if (result === undefined || result === '')
this.notifyAfterValidate(this.props.initialFolder, value);
this.state.errorMessage = result;
this.setState(this.state);
}
else {
result.then((errorMessage: string) => {
if (errorMessage === undefined || errorMessage === '')
this.notifyAfterValidate(this.props.initialFolder, value);
this.state.errorMessage = errorMessage;
this.setState(this.state);
});
}
}
else {
this.notifyAfterValidate(this.props.initialFolder, value);
}
}
/**
* @function
* Notifies the parent Web Part of a property value change
*/
private notifyAfterValidate(oldValue: string, newValue: string) {
if (this.props.onPropertyChange && newValue != null) {
this.props.properties[this.props.targetProperty] = newValue;
this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue);
if (!this.props.disableReactivePropertyChanges && this.props.render != null)
this.props.render();
}
}
/**
* @function
* Called when the component will unmount
*/
public componentWillUnmount() {
this.async.dispose();
}
/**
* @function
* User close the dialog wihout saving
*/
private onDismiss(ev?: React.MouseEvent<any>): any {
this.setState({ isOpen: false, loading: false, selectedFolder: this.state.selectedFolder, currentSPFolder: this.state.currentSPFolder, childrenFolders: this.state.childrenFolders });
}
/**
* @function
* Renders the controls
*/
public render(): JSX.Element {
var currentFolderisRoot: boolean = false;
if (this.state.currentSPFolder == null || this.state.currentSPFolder == '' || this.state.currentSPFolder == this.props.baseFolder)
currentFolderisRoot = true;
//Renders content
return (
<div>
<Label>{this.props.label}</Label>
<table style={{width: '100%', borderSpacing: 0}}>
<tbody>
<tr>
<td width="*">
<TextField
disabled={this.props.disabled}
style={{width:'100%'}}
readOnly={true}
value={this.state.confirmFolder} />
</td>
<td width="64">
<table style={{width: '100%', borderSpacing: 0}}>
<tbody>
<tr>
<td><IconButton disabled={this.props.disabled} iconProps={ { iconName: 'FolderSearch' } } onClick={this.onBrowseClick} /></td>
<td><IconButton disabled={this.props.disabled} iconProps={ { iconName: 'Delete' } } onClick={this.onClearSelectionClick} /></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
{ this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ?
<div style={{paddingBottom: '8px'}}><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div>
<span>
<p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p>
</span>
</div>
: ''}
<Dialog type={DialogType.close} title={strings.SPFolderPickerDialogTitle} isOpen={this.state.isOpen} isDarkOverlay={true} isBlocking={false} onDismiss={this.onDismiss}>
<div style={{ height: '330px'}}>
{ this.state.loading ? <div><Spinner type={ SpinnerType.normal } /></div> : null }
{ this.state.loading === false && currentFolderisRoot === false ? <IconButton onClick={this.onClickParent} iconProps={ { iconName: 'Reply' } }>...</IconButton> : null }
<List items={this.state.childrenFolders.value} onRenderCell={this.onRenderCell} />
{ this.state.loading === false ?
<IconButton iconProps={ { iconName: 'CaretLeft8' } } onClick={this.onClickPrevious}
disabled={ this.currentPage > 0 ? false : true }
/>
: null }
{ this.state.loading === false ?
<IconButton iconProps={ { iconName: 'CaretRight8' } } onClick={this.onClickNext}
disabled={ this.state.childrenFolders.value.length < this.pageItemCount ? true : false }
/>
: null }
</div>
<div style={{marginTop: '20px'}}>
<PrimaryButton disabled={this.state.selectedFolder != null && this.state.selectedFolder != '' ? false : true }
onClick={this.onClickSelect}>{strings.SPFolderPickerSelectButton}</PrimaryButton>
<DefaultButton onClick={this.onDismiss}>{strings.SPFolderPickerCancelButton}</DefaultButton>
</div>
</Dialog>
</div>
);
}
/**
* @function
* Renders a list cell
*/
private onRenderCell(item?: any, index?: number): React.ReactNode {
var idUnique: string = 'radio-' + item.ServerRelativeUrl;
return (
<div style={{fontSize: '14px', padding: '4px'}}>
<div className="ms-ChoiceField">
<input id={idUnique} style={{width: '18px', height: '18px'}}
defaultChecked={item.ServerRelativeUrl === this.state.confirmFolder ? true: false}
aria-checked={item.ServerRelativeUrl === this.state.confirmFolder ? true: false}
onChange={this.onFolderChecked} type="radio" name="radio1" value={item.ServerRelativeUrl}/>
<label htmlFor={idUnique} >
<span className="ms-Label">
<i className="ms-Icon ms-Icon--FolderFill" style={{color: '#0062AF', fontSize: '22px'}}></i>
<span style={{paddingLeft: '5px'}}>
<CommandButton style={{paddingBottom: '0', height: '27px'}} value={item.ServerRelativeUrl} onClick={this.onClickLink}>
<span className="ms-Button-label">
{item.Name}
</span>
</CommandButton>
</span>
</span>
</label>
</div>
</div>
);
}
}
/**
* @interface
* Defines a collection of SharePoint folders
*/
export interface ISPFolders {
value: ISPFolder[];
}
/**
* @interface
* Defines a SharePoint folder
*/
export interface ISPFolder {
Name: string;
ServerRelativeUrl: string;
}
/**
* @class
* Service implementation to get folders from current SharePoint site
*/
class SPFolderPickerService {
private context: IWebPartContext;
/**
* @function
* Service constructor
*/
constructor(pageContext: IWebPartContext){
this.context = pageContext;
}
/**
* @function
* Gets the collection of sub folders of the given folder
*/
public getFolders(parentFolderServerRelativeUrl?: string, currentPage?: number, pageItemCount?: number): Promise<ISPFolders> {
if (Environment.type === EnvironmentType.Local) {
//If the running environment is local, load the data from the mock
return this.getFoldersMock(parentFolderServerRelativeUrl);
}
else {
//If the running environment is SharePoint, request the folders REST service
var queryUrl: string = this.context.pageContext.web.absoluteUrl;
var skipNumber = currentPage * pageItemCount;
if (parentFolderServerRelativeUrl == null || parentFolderServerRelativeUrl == '' || parentFolderServerRelativeUrl == '/') {
//The folder is the web root site
queryUrl += "/_api/web/folders?$select=Name,ServerRelativeUrl&$orderBy=Name&$top=";
queryUrl += pageItemCount;
queryUrl += "&$skip=";
queryUrl += skipNumber;
}
else {
//Loads sub folders
queryUrl += "/_api/web/GetFolderByServerRelativeUrl('";
queryUrl += parentFolderServerRelativeUrl;
queryUrl += "')/folders?$select=Name,ServerRelativeUrl&$orderBy=Name&$top=";
queryUrl += pageItemCount;
queryUrl += "&$skip=";
queryUrl += skipNumber;
}
return this.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
return response.json();
});
}
}
/**
* @function
* Returns 3 fake SharePoint folders for the Mock mode
*/
private getFoldersMock(parentFolderServerRelativeUrl?: string): Promise<ISPFolders> {
return SPFolderPickerMockHttpClient.getFolders(this.context.pageContext.web.absoluteUrl).then(() => {
const listData: ISPFolders = {
value:
[
{ Name: 'Mock Folder One', ServerRelativeUrl: '/mockfolderone' },
{ Name: 'Mock Folder Two', ServerRelativeUrl: '/mockfoldertwo' },
{ Name: 'Mock Folder Three', ServerRelativeUrl: '/mockfolderthree' }
]
};
return listData;
}) as Promise<ISPFolders>;
}
}
/**
* @class
* Defines a http client to request mock data to use the web part with the local workbench
*/
class SPFolderPickerMockHttpClient {
/**
* @var
* Mock SharePoint result sample
*/
private static _results: ISPFolders = { value: []};
/**
* @function
* Mock get folders method
*/
public static getFolders(restUrl: string, options?: any): Promise<ISPFolders> {
return new Promise<ISPFolders>((resolve) => {
resolve(SPFolderPickerMockHttpClient._results);
});
}
} | the_stack |
import { Globals } from './../../../utils/globals';
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild, SimpleChanges } from '@angular/core';
import { MessageModel } from '../../../../chat21-core/models/message';
import { isPopupUrl, popupUrl, stripTags } from '../../../../chat21-core/utils/utils';
import { MSG_STATUS_SENT, MSG_STATUS_RETURN_RECEIPT, MSG_STATUS_SENT_SERVER, MAX_WIDTH_IMAGES} from '../../../utils/constants';
import { strip_tags } from '../../../utils/utils';
import { isInfo, isMine, messageType } from '../../../../chat21-core/utils/utils-message';
import { MESSAGE_TYPE_INFO, MESSAGE_TYPE_MINE, MESSAGE_TYPE_OTHERS } from '../../../../chat21-core/utils/constants';
import { UploadService } from '../../../../chat21-core/providers/abstract/upload.service';
import { LoggerInstance } from '../../../../chat21-core/providers/logger/loggerInstance';
import { LoggerService } from '../../../../chat21-core/providers/abstract/logger.service';
@Component({
selector: 'chat-conversation-content',
templateUrl: './conversation-content.component.html',
styleUrls: ['./conversation-content.component.scss']
})
export class ConversationContentComponent implements OnInit {
@ViewChild('scrollMe') public scrollMe: ElementRef;
@Input() messages: MessageModel[]
@Input() senderId: string;
@Input() baseLocation: string;
@Input() isConversationArchived: boolean;
@Input() translationMap: Map< string, string>;
@Input() stylesMap: Map<string, string>;
@Output() onBeforeMessageRender = new EventEmitter();
@Output() onAfterMessageRender = new EventEmitter();
@Output() onMenuOptionShow = new EventEmitter();
@Output() onAttachmentButtonClicked = new EventEmitter();
@Output() onScrollContent = new EventEmitter();
// ========= begin:: gestione scroll view messaggi ======= //
startScroll = true; // indica lo stato dello scroll: true/false -> è in movimento/ è fermo
idDivScroll = 'c21-contentScroll'; // id div da scrollare
isScrolling = false;
isIE = /msie\s|trident\//i.test(window.navigator.userAgent);
firstScroll = true;
// ========= end:: gestione scroll view messaggi ======= //
// ========= begin:: dichiarazione funzioni ======= //
isPopupUrl = isPopupUrl;
popupUrl = popupUrl;
// ========= end:: dichiarazione funzioni ======= //
// ========== begin:: set icon status message ======= //
MSG_STATUS_SENT = MSG_STATUS_SENT;
MSG_STATUS_SENT_SERVER = MSG_STATUS_SENT_SERVER;
MSG_STATUS_RETURN_RECEIPT = MSG_STATUS_RETURN_RECEIPT;
// ========== end:: icon status message ======= //
// ========== begin:: check message type functions ======= //
isMine = isMine;
isInfo = isInfo;
messageType = messageType;
MESSAGE_TYPE_INFO = MESSAGE_TYPE_INFO;
MESSAGE_TYPE_MINE = MESSAGE_TYPE_MINE;
MESSAGE_TYPE_OTHERS = MESSAGE_TYPE_OTHERS;
// ========== end:: check message type functions ======= //
tooltipOptions = {
'show-delay': 1500,
'tooltip-class': 'chat-tooltip',
'theme': 'light',
'shadow': false,
'hide-delay-mobile': 0,
'hideDelayAfterClick': 3000,
'hide-delay': 200
};
urlBOTImage = 'https://s3.eu-west-1.amazonaws.com/tiledesk-widget/dev/2.0.4-beta.7/assets/images/avatar_bot_tiledesk.svg'
uploadProgress: number;
showUploadProgress: boolean = false;
fileType: string;
private logger: LoggerService = LoggerInstance.getInstance();
constructor(private cdref: ChangeDetectorRef,
private uploadService: UploadService) { }
ngOnInit() {
this.listenToUploadFileProgress();
}
ngAfterContentChecked() {
this.cdref.detectChanges();
}
/**
*
* @param message
*/
getMetadataSize(metadata): any {
if(metadata.width === undefined){
metadata.width= '100%'
}
if(metadata.height === undefined){
metadata.height = MAX_WIDTH_IMAGES
}
// const MAX_WIDTH_IMAGES = 300;
const sizeImage = {
width: metadata.width,
height: metadata.height
};
// that.g.wdLog(['message::: ', metadata);
if (metadata.width && metadata.width > MAX_WIDTH_IMAGES) {
const rapporto = (metadata['width'] / metadata['height']);
sizeImage.width = MAX_WIDTH_IMAGES;
sizeImage.height = MAX_WIDTH_IMAGES / rapporto;
}
return sizeImage; // h.toString();
}
// ENABLE HTML SECTION 'FILE PENDING UPLOAD'
listenToUploadFileProgress() {
this.uploadService.BSStateUpload.subscribe((data: any) => {
this.logger.debug('[CONV-CONTENT] BSStateUpload', data);
// && data.type.startsWith("application")
if (data) {
data.upload === 100 || isNaN(data.upload)? this.showUploadProgress = false : this.showUploadProgress = true
this.uploadProgress = data.upload
this.fileType = 'file'
this.scrollToBottom()
}
});
}
// ========= begin:: functions scroll position ======= //
// LISTEN TO SCROLL POSITION
onScroll(event): void {
// console.log('************** SCROLLLLLLLLLL *****************');
this.startScroll = false;
if (this.scrollMe) {
const divScrollMe = this.scrollMe.nativeElement;
const checkContentScrollPositionIsEnd = this.checkContentScrollPosition(divScrollMe);
if (checkContentScrollPositionIsEnd) {
this.onScrollContent.emit(true)
//this.showBadgeScroollToBottom = false;
//this.NUM_BADGES = 0;
} else {
this.onScrollContent.emit(false)
//this.showBadgeScroollToBottom = true;
}
}
}
/**
*
*/
checkContentScrollPosition(divScrollMe?): boolean {
if(!divScrollMe){
divScrollMe = this.scrollMe.nativeElement
}
if (divScrollMe.scrollHeight - divScrollMe.scrollTop <= (divScrollMe.clientHeight + 40)) {
this.logger.debug('[CONV-CONTENT] - SONO ALLA FINE');
return true;
} else {
this.logger.debug('[CONV-CONTENT] - NON SONO ALLA FINE');
return false;
}
}
/**
* scrollo la lista messaggi all'ultimo
* chiamato in maniera ricorsiva sino a quando non risponde correttamente
*/
// scrollToBottomStart() {
// const that = this;
// if ( this.isScrolling === false ) {
// setTimeout(function () {
// try {
// that.isScrolling = true;
// const objDiv = document.getElementById(that.idDivScroll);
// setTimeout(function () {
// that.g.wdLog(['objDiv::', objDiv.scrollHeight]);
// //objDiv.scrollIntoView(false);
// objDiv.style.opacity = '1';
// }, 200);
// that.isScrolling = false;
// } catch (err) {
// that.g.wdLog(['> Error :' + err]);
// }
// }, 0);
// }
// }
/**
* scrollo la lista messaggi all'ultimo
* chiamato in maniera ricorsiva sino a quando non risponde correttamente
*/
scrollToBottom(withoutAnimation?: boolean) {
const that = this;
try {
that.isScrolling = true;
const objDiv = document.getElementById(that.idDivScroll) as HTMLElement;
// const element = objDiv[0] as HTMLElement;
setTimeout(function () {
if (that.isIE === true || withoutAnimation === true || that.firstScroll === true) {
objDiv.parentElement.classList.add('withoutAnimation');
} else {
objDiv.parentElement.classList.remove('withoutAnimation');
}
objDiv.parentElement.scrollTop = objDiv.scrollHeight;
objDiv.style.opacity = '1';
that.firstScroll = false;
}, 0);
} catch (err) {
this.logger.error('[CONV-CONTENT] scrollToBottom > Error :' + err);
}
that.isScrolling = false;
}
// ========= END:: functions scroll position ======= //
/**
* function customize tooltip
*/
handleTooltipEvents() {
const that = this;
const showDelay = this.tooltipOptions['showDelay'];
// console.log(this.tooltipOptions);
setTimeout(function () {
try {
const domRepresentation = document.getElementsByClassName('chat-tooltip');
if (domRepresentation) {
const item = domRepresentation[0] as HTMLInputElement;
// console.log(item);
if (!item.classList.contains('tooltip-show')) {
item.classList.add('tooltip-show');
}
setTimeout(function () {
if (item.classList.contains('tooltip-show')) {
item.classList.remove('tooltip-show');
}
}, that.tooltipOptions['hideDelayAfterClick']);
}
} catch (err) {
this.logger.error('[CONV-CONTENT] handleTooltipEvents > Error :' + err);
}
}, showDelay);
}
isLastMessage(idMessage: string) {
// console.log('idMessage: ' + idMessage + 'id LAST Message: ' + this.messages[this.messages.length - 1].uid);
if (idMessage === this.messages[this.messages.length - 1].uid) {
return true;
}
return false;
}
isSameSender(senderId, index){
if(senderId && this.messages[index - 1] && (senderId === this.messages[index - 1].sender)){
return true;
}
return false;
}
hideMenuOption(){
this.onMenuOptionShow.emit(false)
}
// ========= begin:: event emitter function ============//
returnOnAttachmentButtonClicked(event: any){
this.onAttachmentButtonClicked.emit(event)
}
returnOnBeforeMessageRender(event){
//decommentare se in html c'è solamente component tiledesk-text
//const messageOBJ = { message: this.message, sanitizer: this.sanitizer, messageEl: event.messageEl, component: event.component}
this.onBeforeMessageRender.emit(event)
}
returnOnAfterMessageRender(event){
this.onAfterMessageRender.emit(event)
}
onImageRenderedFN(event){
const imageRendered = event;
if (imageRendered && this.scrollMe) {
const divScrollMe = this.scrollMe.nativeElement;
const checkContentScrollPosition = this.checkContentScrollPosition(divScrollMe);
this.scrollToBottom() // SCROLLO SEMPRE
// if (!checkContentScrollPosition) { // SE NON SONO ALLA FINE, SCROLLO CONTENT
// }
}
}
// printMessage(message, messageEl, component) {
// const messageOBJ = { message: message, sanitizer: this.sanitizer, messageEl: messageEl, component: component}
// this.onBeforeMessageRender.emit(messageOBJ)
// const messageText = message.text;
// this.onAfterMessageRender.emit(messageOBJ)
// // this.triggerBeforeMessageRender(message, messageEl, component);
// // const messageText = message.text;
// // this.triggerAfterMessageRender(message, messageEl, component);
// return messageText;
// }
// ========= END:: event emitter function ============//
} | the_stack |
import { Emitter, CompositeDisposable } from 'atom'
import { WebContents, remote } from 'electron'
import { handlePromise, shellOpen, packagePath } from '../util'
import {
RequestReplyMap,
ChannelMap,
ReplyMap,
TDiffMethod,
} from '../../src-client/ipc'
import { ClientStyle, getPreviewStyles } from './util'
import { ImageWatcher } from '../image-watch-helper'
import * as path from 'path'
export type ReplyCallbackStruct<
T extends keyof RequestReplyMap = keyof RequestReplyMap,
> = {
[K in keyof RequestReplyMap]: {
request: K
callback: (reply: RequestReplyMap[K]) => void
}
}[T]
interface PrintToPDFOptionsReal {
/**
* Specifies the type of margins to use. Uses 0 for default margin, 1 for no
* margin, and 2 for minimum margin.
*/
marginsType?: number
/**
* Specify page size of the generated PDF. Can be A3, A4, A5, Legal, Letter,
* Tabloid or an Object containing height and width in microns.
*/
pageSize?:
| { width: number; height: number }
| 'A3'
| 'A4'
| 'A5'
| 'Legal'
| 'Letter'
| 'Tabloid'
/**
* Whether to print CSS backgrounds.
*/
printBackground?: boolean
/**
* Whether to print selection only.
*/
printSelectionOnly?: boolean
/**
* true for landscape, false for portrait.
*/
landscape?: boolean
}
export abstract class WebContentsHandler {
private static _id: number = 0
public readonly emitter = new Emitter<
{ 'did-destroy': void },
{
'did-scroll-preview': { min: number; max: number }
}
>()
public readonly imageWatcher: ImageWatcher
protected destroyed = false
protected readonly disposables = new CompositeDisposable()
private zoomLevel = 0
private replyCallbackId = 0
private lastSearchText?: string
private readonly replyCallbacks = new Map<number, ReplyCallbackStruct>()
private readonly id: number = ++WebContentsHandler._id
private readonly listeners: {
[key: string]: (evt: unknown, id: number, ...args: any) => void
} = {}
private readonly contents: Promise<WebContents>
private stylesReady = false
constructor(
contents: Promise<WebContents>,
showContextMenu: () => void,
private clientStyle: ClientStyle,
private readonly initCont: () => void | Promise<void>,
) {
this.addListeners({
'atom-markdown-preview-plus-ipc-zoom-in': this.zoomIn.bind(this),
'atom-markdown-preview-plus-ipc-zoom-out': this.zoomOut.bind(this),
'atom-markdown-preview-plus-ipc-did-scroll-preview': (minmax) => {
this.emitter.emit('did-scroll-preview', minmax)
},
'atom-markdown-preview-plus-ipc-uncaught-error': (err) => {
const newErr = new Error()
atom.notifications.addFatalError(
`Uncaught error ${err.name} in markdown-preview-plus webview client`,
{
dismissable: true,
stack: newErr.stack,
detail: `${err.message}\n\nstack:\n${err.stack}`,
},
)
},
'atom-markdown-preview-plus-ipc-show-context-menu': () => {
showContextMenu()
},
'atom-markdown-preview-plus-ipc-request-reply': ({
id,
request,
result,
}) => {
const cb = this.replyCallbacks.get(id)
if (cb && request === cb.request) {
const callback: (r: any) => void = cb.callback
callback(result)
}
},
'atom-markdown-preview-plus-ipc-key': (data) => {
const evt = new KeyboardEvent(data.type, data)
if (this.element) this.element.dispatchEvent(evt)
},
})
this.disposables.add(
atom.styles.onDidAddStyleElement(() => {
handlePromise(this.updateStyles())
}),
atom.styles.onDidRemoveStyleElement(() => {
handlePromise(this.updateStyles())
}),
atom.styles.onDidUpdateStyleElement(() => {
handlePromise(this.updateStyles())
}),
atom.config.onDidChange('markdown-preview-plus.useGitHubStyle', () => {
handlePromise(this.updateStyles())
}),
atom.config.onDidChange('markdown-preview-plus.syntaxThemeName', () => {
handlePromise(this.updateStyles())
}),
atom.config.onDidChange(
'markdown-preview-plus.importPackageStyles',
() => {
handlePromise(this.updateStyles())
},
),
)
this.contents = contents.then(this.initializeContents)
this.disposables.add(
(this.imageWatcher = new ImageWatcher(this.updateImages.bind(this))),
)
}
public async setClientStyle(style: ClientStyle) {
this.clientStyle = style
return this.updateStyles()
}
public abstract get element(): HTMLElement
public abstract registerViewEvents(_view: object): void
public async runJS<T>(js: string) {
const contents = await this.contents
return contents.executeJavaScript(js, false) as Promise<T>
}
public destroy() {
if (this.destroyed) return
this.destroyed = true
for (const [channel, handler] of Object.entries(this.listeners)) {
remote.ipcMain.removeListener(channel, handler)
delete this.listeners[channel]
}
this.emitter.emit('did-destroy')
this.disposables.dispose()
this.emitter.dispose()
}
public onDidDestroy(callback: () => void) {
return this.emitter.on('did-destroy', callback)
}
public async update(
html: string,
renderLaTeX: boolean,
diffMethod: TDiffMethod = 'none',
map?: { [line: number]: { tag: string; index: number }[] },
scrollSyncParams?: ChannelMap['scroll-sync'],
) {
if (this.destroyed) return undefined
return this.runRequest('update-preview', {
html,
renderLaTeX,
map,
diffMethod,
scrollSyncParams,
})
}
public async fullyReady() {
if (this.destroyed) return
return this.runRequest('await-fully-ready', {})
}
public async setBasePath(path?: string) {
return this.send<'set-base-path'>('set-base-path', { path })
}
public async setNativeKeys(val: boolean) {
return this.send<'set-native-keys'>('set-native-keys', val)
}
public async init(params: ChannelMap['init']) {
return this.send<'init'>('init', params)
}
public async updateImages(oldSource: string, version: number | undefined) {
return this.send<'update-images'>('update-images', {
oldsrc: oldSource,
v: version,
})
}
public async printToPDF(opts: PrintToPDFOptionsReal) {
const contents = await this.contents
return contents.printToPDF(opts)
}
public async sync(line: number, flash: boolean) {
return this.send<'sync'>('sync', { line, flash })
}
public async syncSource() {
return this.runRequest('sync-source', {})
}
public async scrollSync(firstLine: number, lastLine: number) {
return this.send<'scroll-sync'>('scroll-sync', { firstLine, lastLine })
}
public async zoomIn() {
this.zoomLevel += 0.1
;(await this.contents).setZoomLevel(this.zoomLevel)
}
public async zoomOut() {
this.zoomLevel -= 0.1
;(await this.contents).setZoomLevel(this.zoomLevel)
}
public async resetZoom() {
this.zoomLevel = 0
;(await this.contents).setZoomLevel(this.zoomLevel)
}
public async print() {
;(await this.contents).print()
}
public async openDevTools() {
;(await this.contents).openDevTools()
}
public async reload() {
await this.runRequest('reload', {})
;(await this.contents).reload()
}
public async error(msg: string) {
return this.send<'error'>('error', { msg })
}
public async getTeXConfig() {
return this.runRequest('get-tex-config', {})
}
public async getSelection() {
return this.runRequest('get-selection', {})
}
public async search(text: string) {
const c = await this.contents
c.findInPage(text)
this.lastSearchText = text
}
public async findNext() {
if (!this.lastSearchText) return
const c = await this.contents
c.findInPage(this.lastSearchText, { findNext: true })
}
public hasSearch() {
return !!this.lastSearchText
}
public async stopSearch() {
const c = await this.contents
this.lastSearchText = undefined
c.stopFindInPage('keepSelection')
}
protected async updateStyles() {
if (!this.stylesReady) return
return this.send<'style'>('style', {
styles: getPreviewStyles(true, this.clientStyle),
})
}
protected async runRequest<T extends keyof RequestReplyMap>(
request: T,
args: { [K in Exclude<keyof ChannelMap[T], 'id'>]: ChannelMap[T][K] },
) {
const id = this.replyCallbackId++
const result = new Promise<RequestReplyMap[T]>((resolve) => {
this.replyCallbacks.set(id, {
request: request,
callback: (result: RequestReplyMap[T]) => {
this.replyCallbacks.delete(id)
resolve(result)
},
} as unknown as ReplyCallbackStruct<T>)
})
const newargs = Object.assign({ id }, args)
await this.send<T>(request, newargs as ChannelMap[T])
return result
}
protected async send<T extends keyof ChannelMap>(
channel: T,
value: ChannelMap[T],
): Promise<void> {
;(await this.contents).send<T>(channel, value)
}
private addListeners<T extends keyof ReplyMap>(
listeners: {
[K in T]: (...args: ReplyMap[K]) => void
},
): void {
for (const [channel, handler] of Object.entries(listeners)) {
this.listeners[channel] = (
_event: any,
id: number,
...args: ReplyMap[typeof channel]
) => {
if (this.id !== id) {
return
}
handler(...args)
}
remote.ipcMain.on(channel, this.listeners[channel])
}
}
private initializeContents = async (
contents: WebContents,
): Promise<WebContents> => {
contents.once('destroyed', () => this.destroy())
contents.on('will-navigate', async (e, url) => {
e.preventDefault()
shellOpen(url)
})
if (!contents.getURL().includes('client/template.html')) {
await contents.loadFile(
path.join(packagePath(), 'client', 'template.html'),
{ hash: atom.inDevMode() ? 'dev' : undefined },
)
}
const onload = async () => {
if (this.destroyed) return
contents.send<'set-id'>('set-id', this.id)
contents.setZoomLevel(this.zoomLevel)
this.stylesReady = true
handlePromise(this.updateStyles().then(this.initCont))
}
await onload()
contents.on('dom-ready', onload)
return contents
}
} | the_stack |
declare const OK: 0;
declare const ERR_NOT_OWNER: -1;
declare const ERR_NO_PATH: -2;
declare const ERR_NAME_EXISTS: -3;
declare const ERR_BUSY: -4;
declare const ERR_NOT_FOUND: -5;
declare const ERR_NOT_ENOUGH_RESOURCES: -6;
declare const ERR_NOT_ENOUGH_ENERGY: -6;
declare const ERR_INVALID_TARGET: -7;
declare const ERR_FULL: -8;
declare const ERR_NOT_IN_RANGE: -9;
declare const ERR_INVALID_ARGS: -10;
declare const ERR_TIRED: -11;
declare const ERR_NO_BODYPART: -12;
declare const ERR_NOT_ENOUGH_EXTENSIONS: -6;
declare const ERR_RCL_NOT_ENOUGH: -14;
declare const ERR_GCL_NOT_ENOUGH: -15;
declare const FIND_EXIT_TOP: 1;
declare const FIND_EXIT_RIGHT: 3;
declare const FIND_EXIT_BOTTOM: 5;
declare const FIND_EXIT_LEFT: 7;
declare const FIND_EXIT: 10;
declare const FIND_CREEPS: 101;
declare const FIND_MY_CREEPS: 102;
declare const FIND_HOSTILE_CREEPS: 103;
declare const FIND_SOURCES_ACTIVE: 104;
declare const FIND_SOURCES: 105;
declare const FIND_DROPPED_RESOURCES: 106;
declare const FIND_DROPPED_ENERGY: 106; // Yup, it's 106.
declare const FIND_STRUCTURES: 107;
declare const FIND_MY_STRUCTURES: 108;
declare const FIND_HOSTILE_STRUCTURES: 109;
declare const FIND_FLAGS: 110;
declare const FIND_CONSTRUCTION_SITES: 111;
declare const FIND_MY_SPAWNS: 112;
declare const FIND_HOSTILE_SPAWNS: 113;
declare const FIND_MY_CONSTRUCTION_SITES: 114;
declare const FIND_HOSTILE_CONSTRUCTION_SITES: 115;
declare const FIND_MINERALS: 116;
declare const FIND_NUKES: 117;
declare const TOP: 1;
declare const TOP_RIGHT: 2;
declare const RIGHT: 3;
declare const BOTTOM_RIGHT: 4;
declare const BOTTOM: 5;
declare const BOTTOM_LEFT: 6;
declare const LEFT: 7;
declare const TOP_LEFT: 8;
declare const COLOR_RED: 1;
declare const COLOR_PURPLE: 2;
declare const COLOR_BLUE: 3;
declare const COLOR_CYAN: 4;
declare const COLOR_GREEN: 5;
declare const COLOR_YELLOW: 6;
declare const COLOR_ORANGE: 7;
declare const COLOR_BROWN: 8;
declare const COLOR_GREY: 9;
declare const COLOR_WHITE: 10;
declare const COLORS_ALL: number[];
declare const CREEP_SPAWN_TIME: 3;
declare const CREEP_LIFE_TIME: 1500;
declare const CREEP_CLAIM_LIFE_TIME: 500;
declare const CREEP_CORPSE_RATE: 0.2;
declare const OBSTACLE_OBJECT_TYPES: string[];
declare const ENERGY_REGEN_TIME: 300;
declare const ENERGY_DECAY: 1000;
declare const REPAIR_COST: 0.01;
declare const RAMPART_DECAY_AMOUNT: 300;
declare const RAMPART_DECAY_TIME: 100;
declare const RAMPART_HITS: 1;
declare const RAMPART_HITS_MAX: {
2: 300000,
3: 1000000,
4: 3000000,
5: 10000000,
6: 30000000,
7: 100000000,
8: 300000000
};
declare const SPAWN_HITS: 5000;
declare const SPAWN_ENERGY_START: 300;
declare const SPAWN_ENERGY_CAPACITY: 300;
declare const SOURCE_ENERGY_CAPACITY: 3000;
declare const SOURCE_ENERGY_NEUTRAL_CAPACITY: 1500;
declare const SOURCE_ENERGY_KEEPER_CAPACITY: 4000;
declare const WALL_HITS: 1;
declare const WALL_HITS_MAX: 300000000;
declare const EXTENSION_HITS: 1000;
declare const EXTENSION_ENERGY_CAPACITY: {
0: 50,
1: 50,
2: 50,
3: 50,
4: 50,
5: 50,
6: 50,
7: 100,
8: 200
};
declare const ROAD_HITS: 5000;
declare const ROAD_WEAROUT: 1;
declare const ROAD_DECAY_AMOUNT: 100;
declare const ROAD_DECAY_TIME: 1000;
declare const LINK_HITS: 1000;
declare const LINK_HITS_MAX: 1000;
declare const LINK_CAPACITY: 800;
declare const LINK_COOLDOWN: 1;
declare const LINK_LOSS_RATIO: 0.03;
declare const STORAGE_CAPACITY: 1000000;
declare const STORAGE_HITS: 10000;
declare const BODYPART_COST: {
[part: string]: number;
move: 50;
work: 100;
attack: 80;
carry: 50;
heal: 250;
ranged_attack: 150;
tough: 10;
claim: 600;
};
declare const BODYPARTS_ALL: string[];
declare const CARRY_CAPACITY: 50;
declare const HARVEST_POWER: 2;
declare const HARVEST_MINERAL_POWER: 1;
declare const REPAIR_POWER: 100;
declare const DISMANTLE_POWER: 50;
declare const BUILD_POWER: 5;
declare const ATTACK_POWER: 30;
declare const UPGRADE_CONTROLLER_POWER: 1;
declare const RANGED_ATTACK_POWER: 10;
declare const HEAL_POWER: 12;
declare const RANGED_HEAL_POWER: 4;
declare const DISMANTLE_COST: 0.005;
declare const MOVE: "move";
declare const WORK: "work";
declare const CARRY: "carry";
declare const ATTACK: "attack";
declare const RANGED_ATTACK: "ranged_attack";
declare const TOUGH: "tough";
declare const HEAL: "heal";
declare const CLAIM: "claim";
declare const CONSTRUCTION_COST: {
spawn: 15000,
extension: 3000,
road: 300,
constructedWall: 1,
rampart: 1,
link: 5000,
storage: 30000,
tower: 5000,
observer: 8000,
powerSpawn: 100000,
extractor: 5000,
lab: 50000,
terminal: 100000,
container: 5000,
nuker: 100000
};
declare const CONSTRUCTION_COST_ROAD_SWAMP_RATIO: 5;
declare const STRUCTURE_EXTENSION: "extension";
declare const STRUCTURE_RAMPART: "rampart";
declare const STRUCTURE_ROAD: "road";
declare const STRUCTURE_SPAWN: "spawn";
declare const STRUCTURE_LINK: "link";
declare const STRUCTURE_WALL: "wall";
declare const STRUCTURE_KEEPER_LAIR: "keeperLair";
declare const STRUCTURE_CONTROLLER: "controller";
declare const STRUCTURE_STORAGE: "storage";
declare const STRUCTURE_TOWER: "tower";
declare const STRUCTURE_OBSERVER: "observer";
declare const STRUCTURE_POWER_BANK: "powerBank";
declare const STRUCTURE_POWER_SPAWN: "powerSpawn";
declare const STRUCTURE_EXTRACTOR: "extractor";
declare const STRUCTURE_LAB: "lab";
declare const STRUCTURE_TERMINAL: "terminal";
declare const STRUCTURE_CONTAINER: "container";
declare const STRUCTURE_NUKER: "nuker";
declare const STRUCTURE_PORTAL: "portal";
declare const RESOURCE_ENERGY: "energy";
declare const RESOURCE_POWER: "power";
declare const RESOURCE_UTRIUM: "U";
declare const RESOURCE_LEMERGIUM: "L";
declare const RESOURCE_KEANIUM: "K";
declare const RESOURCE_GHODIUM: "G";
declare const RESOURCE_ZYNTHIUM: "Z";
declare const RESOURCE_OXYGEN: "O";
declare const RESOURCE_HYDROGEN: "H";
declare const RESOURCE_CATALYST: "X";
declare const RESOURCE_HYDROXIDE: "OH";
declare const RESOURCE_ZYNTHIUM_KEANITE: "ZK";
declare const RESOURCE_UTRIUM_LEMERGITE: "UL";
declare const RESOURCE_UTRIUM_HYDRIDE: "UH";
declare const RESOURCE_UTRIUM_OXIDE: "UO";
declare const RESOURCE_KEANIUM_HYDRIDE: "KH";
declare const RESOURCE_KEANIUM_OXIDE: "KO";
declare const RESOURCE_LEMERGIUM_HYDRIDE: "LH";
declare const RESOURCE_LEMERGIUM_OXIDE: "LO";
declare const RESOURCE_ZYNTHIUM_HYDRIDE: "ZH";
declare const RESOURCE_ZYNTHIUM_OXIDE: "ZO";
declare const RESOURCE_GHODIUM_HYDRIDE: "GH";
declare const RESOURCE_GHODIUM_OXIDE: "GO";
declare const RESOURCE_UTRIUM_ACID: "UH2O";
declare const RESOURCE_UTRIUM_ALKALIDE: "UHO2";
declare const RESOURCE_KEANIUM_ACID: "KH2O";
declare const RESOURCE_KEANIUM_ALKALIDE: "KHO2";
declare const RESOURCE_LEMERGIUM_ACID: "LH2O";
declare const RESOURCE_LEMERGIUM_ALKALIDE: "LHO2";
declare const RESOURCE_ZYNTHIUM_ACID: "ZH2O";
declare const RESOURCE_ZYNTHIUM_ALKALIDE: "ZHO2";
declare const RESOURCE_GHODIUM_ACID: "GH2O";
declare const RESOURCE_GHODIUM_ALKALIDE: "GHO2";
declare const RESOURCE_CATALYZED_UTRIUM_ACID: "XUH2O";
declare const RESOURCE_CATALYZED_UTRIUM_ALKALIDE: "XUHO2";
declare const RESOURCE_CATALYZED_KEANIUM_ACID: "XKH2O";
declare const RESOURCE_CATALYZED_KEANIUM_ALKALIDE: "XKHO2";
declare const RESOURCE_CATALYZED_LEMERGIUM_ACID: "XLH2O";
declare const RESOURCE_CATALYZED_LEMERGIUM_ALKALIDE: "XLHO2";
declare const RESOURCE_CATALYZED_ZYNTHIUM_ACID: "XZH2O";
declare const RESOURCE_CATALYZED_ZYNTHIUM_ALKALIDE: "ZXHO2";
declare const RESOURCE_CATALYZED_GHODIUM_ACID: "XGH2O";
declare const RESOURCE_CATALYZED_GHODIUM_ALKALIDE: "XGHO2";
declare const RESOURCES_ALL: string[];
declare const SUBSCRIPTION_TOKEN: string;
declare const CONTROLLER_LEVELS: {[level: number]: number};
declare const CONTROLLER_STRUCTURES: {[structure: string]: {[level: number]: number}};
declare const CONTROLLER_DOWNGRADE: {[level: number]: number};
declare const CONTROLLER_CLAIM_DOWNGRADE: number;
declare const CONTROLLER_RESERVE: number;
declare const CONTROLLER_RESERVE_MAX: number;
declare const CONTROLLER_MAX_UPGRADE_PER_TICK: number;
declare const CONTROLLER_ATTACK_BLOCKED_UPGRADE: number;
declare const TOWER_HITS: number;
declare const TOWER_CAPACITY: number;
declare const TOWER_ENERGY_COST: number;
declare const TOWER_POWER_ATTACK: number;
declare const TOWER_POWER_HEAL: number;
declare const TOWER_POWER_REPAIR: number;
declare const TOWER_OPTIMAL_RANGE: number;
declare const TOWER_FALLOFF_RANGE: number;
declare const TOWER_FALLOFF: number;
declare const OBSERVER_HITS: number;
declare const OBSERVER_RANGE: number;
declare const POWER_BANK_HITS: number;
declare const POWER_BANK_CAPACITY_MAX: number;
declare const POWER_BANK_CAPACITY_MIN: number;
declare const POWER_BANK_CAPACITY_CRIT: number;
declare const POWER_BANK_DECAY: number;
declare const POWER_BANK_HIT_BACK: number;
declare const POWER_SPAWN_HITS: number;
declare const POWER_SPAWN_ENERGY_CAPACITY: number;
declare const POWER_SPAWN_POWER_CAPACITY: number;
declare const POWER_SPAWN_ENERGY_RATIO: number;
declare const EXTRACTOR_HITS: number;
declare const LAB_HITS: number;
declare const LAB_MINERAL_CAPACITY: number;
declare const LAB_ENERGY_CAPACITY: number;
declare const LAB_BOOST_ENERGY: number;
declare const LAB_BOOST_MINERAL: number;
declare const LAB_COOLDOWN: number;
declare const LAB_REACTION_AMOUNT: number;
declare const GCL_POW: number;
declare const GCL_MULTIPLY: number;
declare const GCL_NOVICE: number;
declare const MODE_SIMULATION: string;
declare const MODE_SURVIVAL: string;
declare const MODE_WORLD: string;
declare const MODE_ARENA: string;
declare const TERRAIN_MASK_WALL: number;
declare const TERRAIN_MASK_SWAMP: number;
declare const TERRAIN_MASK_LAVA: number;
declare const MAX_CONSTRUCTION_SITES: number;
declare const MAX_CREEP_SIZE: number;
declare const MINERAL_REGEN_TIME: number;
declare const MINERAL_MIN_AMOUNT: {
H: number,
O: number,
L: number,
K: number,
Z: number,
U: number,
X: number
}
declare const MINERAL_RANDOM_FACTOR: number;
declare const MINERAL_DENSITY: {
1: number,
2: number,
3: number,
4: number
}
declare const MINERAL_DENSITY_PROBABILITY: {
1: number,
2: number,
3: number,
4: number
}
declare const MINERAL_DENSITY_CHANGE: number;
declare const DENSITY_LOW: number;
declare const DENSITY_MODERATE: number;
declare const DENSITY_HIGH: number;
declare const DENSITY_ULTRA: number;
declare const TERMINAL_CAPACITY: number;
declare const TERMINAL_HITS: number;
declare const TERMINAL_SEND_COST: number;
declare const TERMINAL_MIN_SEND: number;
declare const TERMINAL_COOLDOWN: number;
declare const CONTAINER_HITS: number;
declare const CONTAINER_CAPACITY: number;
declare const CONTAINER_DECAY: number;
declare const CONTAINER_DECAY_TIME: number;
declare const CONTAINER_DECAY_TIME_OWNED: number;
declare const NUKER_HITS: number;
declare const NUKER_COOLDOWN: number;
declare const NUKER_ENERGY_CAPACITY: number;
declare const NUKER_GHODIUM_CAPACITY: number;
declare const NUKE_LAND_TIME: number;
declare const NUKE_RANGE: number;
declare const NUKE_DAMAGE: {
0: number,
1: number,
4: number
}
declare const REACTIONS: {
[reagent: string]: {
[reagent: string]: string
}
}
declare const BOOSTS: {
[part: string]: {
[boost: string]: {
[action: string]: number
}
}
}
declare const LOOK_CREEPS: "creep";
declare const LOOK_ENERGY: "energy";
declare const LOOK_RESOURCES: "resource";
declare const LOOK_SOURCES: "source";
declare const LOOK_MINERALS: "mineral";
declare const LOOK_STRUCTURES: "structure";
declare const LOOK_FLAGS: "flag";
declare const LOOK_CONSTRUCTION_SITES: "constructionSite";
declare const LOOK_NUKES: "nuke";
declare const LOOK_TERRAIN: "terrain";
declare const ORDER_SELL: "sell";
declare const ORDER_BUY: "buy"; | the_stack |
'use strict';
import * as vscode from 'vscode';
import { UserInputUtil, IBlockchainQuickPickItem } from './UserInputUtil';
import { VSCodeBlockchainOutputAdapter } from '../logging/VSCodeBlockchainOutputAdapter';
import * as fs from 'fs-extra';
import * as https from 'https';
import * as path from 'path';
import { FabricEnvironmentRegistryEntry, FabricNode, LogType, FabricEnvironment, FabricNodeType, FabricEnvironmentRegistry, EnvironmentType, EnvironmentFlags } from 'ibm-blockchain-platform-common';
import { ExtensionCommands } from '../../ExtensionCommands';
import { FabricEnvironmentManager } from '../fabric/environments/FabricEnvironmentManager';
import { EnvironmentFactory } from '../fabric/environments/EnvironmentFactory';
import Axios from 'axios';
import { ExtensionsInteractionUtil } from '../util/ExtensionsInteractionUtil';
import { ExtensionUtil } from '../util/ExtensionUtil';
import { SecureStore } from '../util/SecureStore';
import { SecureStoreFactory } from '../util/SecureStoreFactory';
export async function importNodesToEnvironment(environmentRegistryEntry: FabricEnvironmentRegistryEntry, fromAddEnvironment: boolean = false, createMethod?: string, informOfChanges: boolean = false, showSuccess: boolean = true, fromConnectEnvironment: boolean = false): Promise<boolean | Error> {
const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance();
const methodMessageString: string = createMethod !== UserInputUtil.ADD_ENVIRONMENT_FROM_OPS_TOOLS ? 'import' : 'filter';
if (showSuccess) {
if (createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_NODES) {
outputAdapter.log(LogType.INFO, undefined, 'Import nodes to environment');
} else {
outputAdapter.log(LogType.INFO, undefined, 'Edit node filters');
}
}
try {
let justUpdate: boolean = false;
let chosenEnvironment: IBlockchainQuickPickItem<FabricEnvironmentRegistryEntry>;
if (!environmentRegistryEntry) {
if (createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_OPS_TOOLS) {
chosenEnvironment = await UserInputUtil.showFabricEnvironmentQuickPickBox('Choose an OpsTool environment to filter nodes', false, true, [EnvironmentFlags.OPS_TOOLS]) as IBlockchainQuickPickItem<FabricEnvironmentRegistryEntry>;
} else {
chosenEnvironment = await UserInputUtil.showFabricEnvironmentQuickPickBox('Choose an environment to import nodes to', false, true, [], [EnvironmentFlags.OPS_TOOLS, EnvironmentFlags.LOCAL]) as IBlockchainQuickPickItem<FabricEnvironmentRegistryEntry>;
}
if (!chosenEnvironment) {
return;
}
environmentRegistryEntry = chosenEnvironment.data;
}
const connectedRegistryEntry: FabricEnvironmentRegistryEntry = FabricEnvironmentManager.instance().getEnvironmentRegistryEntry();
// need to stop it refreshing if we are editting the one we are connected to
if (connectedRegistryEntry && connectedRegistryEntry.name === environmentRegistryEntry.name) {
FabricEnvironmentManager.instance().stopEnvironmentRefresh();
}
if (!fromAddEnvironment) {
if (environmentRegistryEntry.environmentType && (environmentRegistryEntry.environmentType === EnvironmentType.OPS_TOOLS_ENVIRONMENT || environmentRegistryEntry.environmentType === EnvironmentType.SAAS_OPS_TOOLS_ENVIRONMENT)) {
createMethod = UserInputUtil.ADD_ENVIRONMENT_FROM_OPS_TOOLS;
} else {
createMethod = UserInputUtil.ADD_ENVIRONMENT_FROM_NODES;
}
}
const environment: FabricEnvironment = EnvironmentFactory.getEnvironment(environmentRegistryEntry);
const environmentBaseDir: string = path.resolve(environment.getPath());
const allNodes: FabricNode[] = await environment.getNodes(false, true);
const oldNodes: FabricNode[] = allNodes.filter((_node: FabricNode) => !_node.hidden);
let nodesToUpdate: FabricNode[] = [];
let nodesToDelete: FabricNode[] = [];
let addedAllNodes: boolean = true;
if (createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_NODES) {
const openDialogOptions: vscode.OpenDialogOptions = {
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: true,
openLabel: 'Select',
filters: {
'Node Files': ['json']
}
};
const nodeUris: vscode.Uri[] = [];
let addMore: boolean = true;
do {
const selectedNodeUris: vscode.Uri[] = await UserInputUtil.browse('Select all the Fabric node (JSON) files you want to import', UserInputUtil.BROWSE_LABEL, openDialogOptions, true) as vscode.Uri[];
if (selectedNodeUris) {
nodeUris.push(...selectedNodeUris);
}
if (!nodeUris || nodeUris.length === 0) {
return;
}
const addMoreString: string = await UserInputUtil.addMoreNodes(`${nodeUris.length} JSON file(s) added successfully`);
if (addMoreString === UserInputUtil.ADD_MORE_NODES) {
addMore = true;
} else if (addMoreString === UserInputUtil.DONE_ADDING_NODES) {
addMore = false;
} else {
// cancelled so exit
return;
}
} while (addMore);
for (const nodeUri of nodeUris) {
try {
let nodes: FabricNode | Array<FabricNode> = await fs.readJson(nodeUri.fsPath);
if (!Array.isArray(nodes)) {
nodes = [nodes];
}
for (const node of nodes) {
if (node.display_name) {
node.name = node.display_name;
delete node.display_name;
}
if (node.type === 'fabric-ca') {
if (node.tls_cert) {
node.pem = node.tls_cert;
delete node.tls_cert;
}
} else {
if (node.tls_ca_root_cert) {
node.pem = node.tls_ca_root_cert;
delete node.tls_ca_root_cert;
} else if (node.tls_ca_root_certs) {
node.pem = node.tls_ca_root_certs.join('\n');
delete node.tls_ca_root_certs;
}
}
}
nodesToUpdate.push(...nodes);
} catch (error) {
addedAllNodes = false;
outputAdapter.log(LogType.ERROR, `Error importing node file ${nodeUri.fsPath}: ${error.message}`, `Error importing node file ${nodeUri.fsPath}: ${error.toString()}`);
}
}
} else {
const GET_ALL_COMPONENTS: string = '/ak/api/v2/components';
const api: string = environmentRegistryEntry.url.replace(/\/$/, '') + GET_ALL_COMPONENTS;
let response: any;
let requestOptions: any;
// establish connection to Ops Tools
try {
if (environmentRegistryEntry.environmentType === EnvironmentType.SAAS_OPS_TOOLS_ENVIRONMENT) {
let askUserInput: boolean;
if (fromConnectEnvironment) {
askUserInput = ExtensionUtil.getExtensionSaasConfigUpdatesSetting();
} else {
askUserInput = true;
}
const accessToken: string = await ExtensionsInteractionUtil.cloudAccountGetAccessToken(askUserInput);
if (!accessToken) {
if (fromConnectEnvironment) {
throw new Error('User must be logged in to an IBM Cloud account');
}
return;
}
requestOptions = { headers: { Authorization: `Bearer ${accessToken}` } };
} else {
const secureStore: SecureStore = await SecureStoreFactory.getSecureStore();
const credentials: string = await secureStore.getPassword('blockchain-vscode-ext', environmentRegistryEntry.url);
const credentialsArray: string[] = credentials.split(':'); // 'API key or User ID' : 'API secret or password' : rejectUnauthorized
if (credentialsArray.length !== 3) {
throw new Error(`Unable to retrieve the stored credentials`);
}
const userAuth1: string = credentialsArray[0];
const userAuth2: string = credentialsArray[1];
const rejectUnauthorized: boolean = credentialsArray[2] === 'true';
requestOptions = {
headers: { 'Content-Type': 'application/json' },
auth: { username: userAuth1, password: userAuth2 }
};
requestOptions.httpsAgent = new https.Agent({ rejectUnauthorized: rejectUnauthorized });
}
// retrieve json file
response = await Axios.get(api, requestOptions);
// process node data
const data: any = response.data;
const components: any[] = data.components;
let filteredData: FabricNode[] = [];
if (components && components.length > 0) {
filteredData = components.filter((_component: any) => _component.api_url)
.map((_component: any) => {
_component.name = _component.display_name;
delete _component.display_name;
if (_component.tls_cert) {
_component.pem = _component.tls_cert;
delete _component.tls_cert;
}
if (_component.type !== 'fabric-ca') {
if (_component.tls_ca_root_cert) {
_component.pem = _component.tls_ca_root_cert;
delete _component.tls_ca_root_cert;
} else if (_component.tls_ca_root_certs) {
_component.pem = _component.tls_ca_root_certs.join('\n');
delete _component.tls_ca_root_certs;
}
}
return FabricNode.pruneNode(_component);
});
let chosenNodes: IBlockchainQuickPickItem<FabricNode>[];
chosenNodes = await UserInputUtil.showNodesQuickPickBox('Edit filters: Which nodes would you like to include?', filteredData, true, allNodes, informOfChanges) as IBlockchainQuickPickItem<FabricNode>[];
let chosenNodesNames: string[] = [];
let chosenNodesUrls: string[] = [];
if (chosenNodes === undefined) {
if (fromAddEnvironment) {
return;
}
justUpdate = true;
chosenNodesNames = oldNodes.map((_node: FabricNode) => _node.type === FabricNodeType.ORDERER && _node.cluster_name ? _node.cluster_name : _node.name);
chosenNodesUrls = oldNodes.map((_node: FabricNode) => _node.api_url);
} else {
if (!Array.isArray(chosenNodes)) {
chosenNodes = [chosenNodes];
}
if (chosenNodes.length > 0) {
chosenNodesNames = chosenNodes.map((_chosenNode: IBlockchainQuickPickItem<FabricNode>) => _chosenNode.label);
chosenNodesUrls = chosenNodes.map((_chosenNode: IBlockchainQuickPickItem<FabricNode>) => _chosenNode.data.api_url);
}
}
filteredData.forEach((node: FabricNode) => {
if (node.type === FabricNodeType.ORDERER && node.cluster_name) {
node.hidden = chosenNodesNames.indexOf(node.cluster_name) === -1;
} else if (chosenNodesUrls.indexOf(node.api_url) === -1) {
node.hidden = true;
}
});
}
if (allNodes.length > 0) {
const filteredNodesUrls: string[] = filteredData.map((_node: FabricNode) => _node.api_url);
nodesToDelete = allNodes.filter((_node: FabricNode) => filteredNodesUrls.indexOf(_node.api_url) === -1);
}
nodesToUpdate.push(...filteredData);
} catch (error) {
if (fromConnectEnvironment) {
const newError: Error = new Error(`Nodes in ${environmentRegistryEntry.name} might be out of date. Unable to connect to the IBM Blockchain Platform Console with error: ${error.message}`);
outputAdapter.log(LogType.ERROR, undefined, error.toString());
outputAdapter.log(LogType.WARNING, newError.message, newError.toString());
throw newError;
} else {
outputAdapter.log(LogType.ERROR, `Failed to acquire nodes from ${environmentRegistryEntry.url}, with error ${error.message}`, `Failed to acquire nodes from ${environmentRegistryEntry.url}, with error ${error.toString()}`);
throw error;
}
}
}
// only need the orderer, peer and CA.. other node types can exist
nodesToUpdate = nodesToUpdate.filter((node: FabricNode) => {
const validType: boolean = (node.type === 'fabric-orderer' || node.type === 'fabric-peer' || node.type === 'fabric-ca');
if (!validType) {
outputAdapter.log(LogType.INFO, `Ignoring Node of type ${node.type}`);
return false;
}
return true;
}).map((node: FabricNode) => {
if (node.hidden === undefined) {
node.hidden = false;
}
return node;
});
const environmentNodesPath: string = path.join(environmentBaseDir, 'nodes');
await fs.ensureDir(environmentNodesPath);
for (const node of nodesToUpdate) {
try {
const alreadyExists: boolean = oldNodes.some((_node: FabricNode) => _node.name === node.name);
if (alreadyExists && createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_NODES) {
throw new Error(`Node with name ${node.name} already exists`);
}
FabricNode.validateNode(node);
await environment.updateNode(node, createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_OPS_TOOLS);
} catch (error) {
addedAllNodes = false;
if (!node.name) {
outputAdapter.log(LogType.ERROR, `Error ${methodMessageString}ing node: ${error.message}`, `Error ${methodMessageString}ing node: ${error.toString()}`);
} else {
outputAdapter.log(LogType.ERROR, `Error ${methodMessageString}ing node ${node.name}: ${error.message}`, `Error ${methodMessageString}ing node ${node.name}: ${error.toString()}`);
}
}
}
if (createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_OPS_TOOLS && (nodesToDelete.length > 0 || nodesToUpdate.length === 0)) {
for (const node of nodesToDelete) {
try {
await vscode.commands.executeCommand(ExtensionCommands.DELETE_NODE, node, false);
} catch (error) {
if (!node.name) {
outputAdapter.log(LogType.ERROR, `Error deleting node: ${error.message}`, `Error deleting node: ${error.toString()}`);
} else {
outputAdapter.log(LogType.ERROR, `Error deletinging node ${node.name}: ${error.message}`, `Error deleting node ${node.name}: ${error.toString()}`);
}
}
}
if (nodesToUpdate.length === 0 && !fromAddEnvironment) {
const deleteEnvironment: boolean = await UserInputUtil.showConfirmationWarningMessage(`There are no nodes in ${environment.getName()}. Do you want to delete this environment?`);
if (deleteEnvironment) {
await vscode.commands.executeCommand(ExtensionCommands.DELETE_ENVIRONMENT, environmentRegistryEntry, true);
}
} else if (nodesToUpdate.length === 0) {
const addEnvironment: string = await UserInputUtil.showQuickPickYesNo(`There are no nodes in ${environment.getName()}. Do you still want to add this environment?`);
if (addEnvironment !== UserInputUtil.YES) {
return;
}
}
const currentEnvironents: Array<FabricEnvironmentRegistryEntry> = await FabricEnvironmentRegistry.instance().getAll([], [EnvironmentFlags.LOCAL]);
const stillExists: boolean = currentEnvironents.some((_env: FabricEnvironmentRegistryEntry) => _env.name === environment.getName());
if (!stillExists) {
return;
}
}
// check if any nodes were added
const newEnvironment: FabricEnvironment = EnvironmentFactory.getEnvironment(environmentRegistryEntry);
const newNodes: FabricNode[] = await newEnvironment.getNodes();
if (newNodes.length === oldNodes.length && createMethod === UserInputUtil.ADD_ENVIRONMENT_FROM_NODES) {
throw new Error('no nodes were added');
}
if (justUpdate) {
return;
} else if (addedAllNodes) {
outputAdapter.log(LogType.SUCCESS, `Successfully ${methodMessageString}ed nodes`);
} else {
outputAdapter.log(LogType.WARNING, `Finished ${methodMessageString}ing nodes but some nodes could not be ${methodMessageString}ed`);
}
if (connectedRegistryEntry && connectedRegistryEntry.name === environmentRegistryEntry.name && !informOfChanges) {
// only do this if we run the command if we are connected to the one we are updating
if (newNodes.length > 0) {
await vscode.commands.executeCommand(ExtensionCommands.CONNECT_TO_ENVIRONMENT, environmentRegistryEntry);
} else {
await vscode.commands.executeCommand(ExtensionCommands.DISCONNECT_ENVIRONMENT);
}
}
return addedAllNodes;
} catch (error) {
if (fromConnectEnvironment) {
return error;
}
outputAdapter.log(LogType.ERROR, `Error ${methodMessageString}ing nodes: ${error.message}`);
if (fromAddEnvironment) {
return error;
}
}
} | the_stack |
require('module-alias/register');
import * as ABIDecoder from 'abi-decoder';
import * as chai from 'chai';
import { BigNumber } from 'bignumber.js';
import * as setProtocolUtils from 'set-protocol-utils';
import { Address } from 'set-protocol-utils';
import ChaiSetup from '@utils/chaiSetup';
import { BigNumberSetup } from '@utils/bigNumberSetup';
import {
CoreContract,
RebalancingSetIssuanceModuleContract,
RebalancingSetTokenContract,
RebalancingSetTokenFactoryContract,
SetTokenContract,
SetTokenFactoryContract,
StandardTokenMockContract,
TransferProxyContract,
VaultContract,
WethMockContract,
} from '@utils/contracts';
import { Blockchain } from '@utils/blockchain';
import { getWeb3, getGasUsageInEth } from '@utils/web3Helper';
import {
DEFAULT_GAS,
DEFAULT_REBALANCING_NATURAL_UNIT,
ONE_DAY_IN_SECONDS,
} from '@utils/constants';
import { ether } from '@utils/units';
import { CoreHelper } from '@utils/helpers/coreHelper';
import { ERC20Helper } from '@utils/helpers/erc20Helper';
import { RebalancingHelper } from '@utils/helpers/rebalancingHelper';
BigNumberSetup.configure();
ChaiSetup.configure();
const web3 = getWeb3();
const { expect } = chai;
const blockchain = new Blockchain(web3);
const { SetProtocolUtils: SetUtils } = setProtocolUtils;
const { ZERO } = SetUtils.CONSTANTS;
contract('RebalancingSetIssuanceModule:Scenarios', accounts => {
const [
ownerAccount,
functionCaller,
whitelist,
] = accounts;
let core: CoreContract;
let transferProxy: TransferProxyContract;
let vault: VaultContract;
let rebalancingSetTokenFactory: RebalancingSetTokenFactoryContract;
let setTokenFactory: SetTokenFactoryContract;
let rebalancingTokenIssuanceModule: RebalancingSetIssuanceModuleContract;
let wethMock: WethMockContract;
const coreHelper = new CoreHelper(ownerAccount, ownerAccount);
const erc20Helper = new ERC20Helper(ownerAccount);
const rebalancingHelper = new RebalancingHelper(
ownerAccount,
coreHelper,
erc20Helper,
blockchain
);
before(async () => {
ABIDecoder.addABI(CoreContract.getAbi());
ABIDecoder.addABI(RebalancingSetIssuanceModuleContract.getAbi());
transferProxy = await coreHelper.deployTransferProxyAsync();
vault = await coreHelper.deployVaultAsync();
core = await coreHelper.deployCoreAsync(transferProxy, vault);
wethMock = await erc20Helper.deployWrappedEtherAsync(ownerAccount);
setTokenFactory = await coreHelper.deploySetTokenFactoryAsync(core.address);
await coreHelper.setDefaultStateAndAuthorizationsAsync(core, vault, transferProxy, setTokenFactory);
rebalancingSetTokenFactory = await coreHelper.deployRebalancingSetTokenFactoryAsync(core.address, whitelist);
await coreHelper.addFactoryAsync(core, rebalancingSetTokenFactory);
rebalancingTokenIssuanceModule = await coreHelper.deployRebalancingSetIssuanceModuleAsync(
core,
vault,
transferProxy,
wethMock,
);
await coreHelper.addModuleAsync(core, rebalancingTokenIssuanceModule.address);
});
after(async () => {
ABIDecoder.removeABI(CoreContract.getAbi());
ABIDecoder.removeABI(RebalancingSetIssuanceModuleContract.getAbi());
});
beforeEach(async () => {
await blockchain.saveSnapshotAsync();
});
afterEach(async () => {
await blockchain.revertAsync();
});
describe('Issue ETH Simulated MACO Rebalancing Set with Ether', async () => {
let subjectCaller: Address;
let subjectRebalancingSetAddress: Address;
let subjectRebalancingSetQuantity: BigNumber;
let subjectKeepChangeInVault: boolean;
let subjectWethQuantity: BigNumber;
let baseSetWethComponent: WethMockContract;
let baseSetToken: SetTokenContract;
let baseSetNaturalUnit: BigNumber;
let rebalancingSetToken: RebalancingSetTokenContract;
let rebalancingUnitShares: BigNumber;
let baseSetComponentUnit: BigNumber;
let baseSetIssueQuantity: BigNumber;
beforeEach(async () => {
subjectCaller = functionCaller;
baseSetWethComponent = wethMock;
// Create the Set (1 component)
const componentAddresses = [baseSetWethComponent.address];
baseSetComponentUnit = new BigNumber(10 ** 6);
const componentUnits = [baseSetComponentUnit];
baseSetNaturalUnit = new BigNumber(10 ** 6);
baseSetToken = await coreHelper.createSetTokenAsync(
core,
setTokenFactory.address,
componentAddresses,
componentUnits,
baseSetNaturalUnit,
);
// Create the Rebalancing Set
rebalancingUnitShares = new BigNumber(10 ** 6);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
core,
rebalancingSetTokenFactory.address,
ownerAccount,
baseSetToken.address,
ONE_DAY_IN_SECONDS,
rebalancingUnitShares,
);
subjectRebalancingSetAddress = rebalancingSetToken.address;
subjectRebalancingSetQuantity = new BigNumber(10 ** 6);
baseSetIssueQuantity =
subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT);
subjectWethQuantity = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit);
subjectKeepChangeInVault = false;
});
async function subject(): Promise<string> {
return rebalancingTokenIssuanceModule.issueRebalancingSetWrappingEther.sendTransactionAsync(
subjectRebalancingSetAddress,
subjectRebalancingSetQuantity,
subjectKeepChangeInVault,
{
from: subjectCaller,
gas: DEFAULT_GAS,
value: subjectWethQuantity.toNumber(),
},
);
}
it('issues the rebalancing Set', async () => {
const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(subjectRebalancingSetQuantity);
await subject();
const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance);
});
it('uses the correct amount of ETH from the caller', async () => {
const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller));
const txHash = await subject();
const totalGasInEth = await getGasUsageInEth(txHash);
const expectedEthBalance = previousEthBalance
.sub(subjectWethQuantity)
.sub(totalGasInEth);
const ethBalance = new BigNumber(await web3.eth.getBalance(subjectCaller));
expect(ethBalance).to.bignumber.equal(expectedEthBalance);
});
});
describe('#Issue USDC Simulated MACO Rebalancing Set with USDC', async () => {
let subjectCaller: Address;
let subjectRebalancingSetAddress: Address;
let subjectRebalancingSetQuantity: BigNumber;
let subjectKeepChangeInVault: boolean;
let usdcComponent: StandardTokenMockContract;
let baseSetToken: SetTokenContract;
let baseSetNaturalUnit: BigNumber;
let rebalancingSetToken: RebalancingSetTokenContract;
let rebalancingUnitShares: BigNumber;
let usdcComponentUnit: BigNumber;
let baseSetIssueQuantity: BigNumber;
beforeEach(async () => {
subjectCaller = functionCaller;
usdcComponent = await erc20Helper.deployTokenAsync(subjectCaller, 6);
await erc20Helper.approveTransferAsync(usdcComponent, transferProxy.address, subjectCaller);
// Create the Set (1 component)
const componentAddresses = [usdcComponent.address];
usdcComponentUnit = new BigNumber(300); // Price of ETH
const componentUnits = [usdcComponentUnit];
baseSetNaturalUnit = new BigNumber(10 ** 12);
baseSetToken = await coreHelper.createSetTokenAsync(
core,
setTokenFactory.address,
componentAddresses,
componentUnits,
baseSetNaturalUnit,
);
// Create the Rebalancing Set
rebalancingUnitShares = new BigNumber(10 ** 6);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
core,
rebalancingSetTokenFactory.address,
ownerAccount,
baseSetToken.address,
ONE_DAY_IN_SECONDS,
rebalancingUnitShares,
);
subjectRebalancingSetAddress = rebalancingSetToken.address;
subjectRebalancingSetQuantity = ether(1);
baseSetIssueQuantity =
subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT);
subjectKeepChangeInVault = false;
});
async function subject(): Promise<string> {
return rebalancingTokenIssuanceModule.issueRebalancingSet.sendTransactionAsync(
subjectRebalancingSetAddress,
subjectRebalancingSetQuantity,
subjectKeepChangeInVault,
{
from: subjectCaller,
gas: DEFAULT_GAS,
},
);
}
it('issues the rebalancing Set', async () => {
const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
const expectedRBSetTokenBalance = previousRBSetTokenBalance.add(subjectRebalancingSetQuantity);
await subject();
const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance);
});
it('uses the correct amount of component tokens', async () => {
const previousComponentBalance = await usdcComponent.balanceOf.callAsync(subjectCaller);
const expectedComponentUsed = baseSetIssueQuantity.mul(usdcComponentUnit).div(baseSetNaturalUnit);
const expectedComponentBalance = previousComponentBalance.sub(expectedComponentUsed);
await subject();
const componentBalance = await usdcComponent.balanceOf.callAsync(subjectCaller);
expect(expectedComponentBalance).to.bignumber.equal(componentBalance);
});
});
describe('Redeem ETH Simulated MACO Rebalancing Set into Ether', async () => {
let subjectCaller: Address;
let subjectRebalancingSetAddress: Address;
let subjectRebalancingSetQuantity: BigNumber;
let subjectKeepChangeInVault: boolean;
let baseSetIssueQuantity: BigNumber;
let baseSetComponentUnit: BigNumber;
let baseSetWethComponent: WethMockContract;
let baseSetToken: SetTokenContract;
let baseSetNaturalUnit: BigNumber;
let rebalancingSetToken: RebalancingSetTokenContract;
let rebalancingUnitShares: BigNumber;
let wethRequiredToMintSet: BigNumber;
beforeEach(async () => {
subjectCaller = functionCaller;
baseSetWethComponent = wethMock;
await erc20Helper.approveTransferAsync(baseSetWethComponent, transferProxy.address);
// Create the Set (1 component)
const componentAddresses = [baseSetWethComponent.address];
baseSetComponentUnit = new BigNumber(10 ** 6);
const componentUnits = [baseSetComponentUnit];
baseSetNaturalUnit = new BigNumber(10 ** 6);
baseSetToken = await coreHelper.createSetTokenAsync(
core,
setTokenFactory.address,
componentAddresses,
componentUnits,
baseSetNaturalUnit,
);
await erc20Helper.approveTransferAsync(baseSetToken, transferProxy.address);
// Create the Rebalancing Set
rebalancingUnitShares = new BigNumber(10 ** 6);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
core,
rebalancingSetTokenFactory.address,
ownerAccount,
baseSetToken.address,
ONE_DAY_IN_SECONDS,
rebalancingUnitShares,
);
subjectRebalancingSetAddress = rebalancingSetToken.address;
subjectRebalancingSetQuantity = new BigNumber(10 ** 6);
baseSetIssueQuantity =
subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT);
// Wrap WETH
wethRequiredToMintSet = baseSetIssueQuantity.mul(baseSetComponentUnit).div(baseSetNaturalUnit);
await wethMock.deposit.sendTransactionAsync(
{ from: ownerAccount, gas: DEFAULT_GAS, value: wethRequiredToMintSet.toString() }
);
await coreHelper.issueSetTokenAsync(
core,
baseSetToken.address,
baseSetIssueQuantity,
);
const rebalancingSetIssueQuantity = subjectRebalancingSetQuantity;
// Issue the rebalancing Set Token
await core.issueTo.sendTransactionAsync(
functionCaller,
rebalancingSetToken.address,
rebalancingSetIssueQuantity,
);
subjectKeepChangeInVault = false;
});
async function subject(): Promise<string> {
return rebalancingTokenIssuanceModule.redeemRebalancingSetUnwrappingEther.sendTransactionAsync(
subjectRebalancingSetAddress,
subjectRebalancingSetQuantity,
subjectKeepChangeInVault,
{
from: subjectCaller,
gas: DEFAULT_GAS,
},
);
}
it('redeems the rebalancing Set', async () => {
const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity);
await subject();
const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance);
});
it('attributes the correct amount of ETH to the caller', async () => {
const previousEthBalance: BigNumber = new BigNumber(await web3.eth.getBalance(subjectCaller));
const txHash = await subject();
const totalGasInEth = await getGasUsageInEth(txHash);
const expectedEthBalance = previousEthBalance
.add(wethRequiredToMintSet)
.sub(totalGasInEth);
const ethBalance = new BigNumber(await web3.eth.getBalance(subjectCaller));
expect(ethBalance).to.bignumber.equal(expectedEthBalance);
});
});
describe('Redeem USDC Simulated MACO Rebalancing Set into USDC', async () => {
let subjectCaller: Address;
let subjectRebalancingSetAddress: Address;
let subjectRebalancingSetQuantity: BigNumber;
let subjectKeepChangeInVault: boolean;
let baseSetIssueQuantity: BigNumber;
let usdcUnit: BigNumber;
let usdc: StandardTokenMockContract;
let baseSetToken: SetTokenContract;
let baseSetNaturalUnit: BigNumber;
let rebalancingSetToken: RebalancingSetTokenContract;
let rebalancingUnitShares: BigNumber;
beforeEach(async () => {
subjectCaller = functionCaller;
usdc = await erc20Helper.deployTokenAsync(ownerAccount, 6);
await erc20Helper.approveTransferAsync(usdc, transferProxy.address);
// Create the Set (1 component)
const componentAddresses = [usdc.address];
usdcUnit = new BigNumber(300); // Price of Eth
const componentUnits = [usdcUnit];
baseSetNaturalUnit = new BigNumber(10 ** 12);
baseSetToken = await coreHelper.createSetTokenAsync(
core,
setTokenFactory.address,
componentAddresses,
componentUnits,
baseSetNaturalUnit,
);
await erc20Helper.approveTransferAsync(baseSetToken, transferProxy.address);
// Create the Rebalancing Set
rebalancingUnitShares = new BigNumber(10 ** 6);
rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenAsync(
core,
rebalancingSetTokenFactory.address,
ownerAccount,
baseSetToken.address,
ONE_DAY_IN_SECONDS,
rebalancingUnitShares,
);
subjectRebalancingSetAddress = rebalancingSetToken.address;
subjectRebalancingSetQuantity = ether(1);
baseSetIssueQuantity =
subjectRebalancingSetQuantity.mul(rebalancingUnitShares).div(DEFAULT_REBALANCING_NATURAL_UNIT);
await coreHelper.issueSetTokenAsync(
core,
baseSetToken.address,
baseSetIssueQuantity,
);
const rebalancingSetIssueQuantity = subjectRebalancingSetQuantity;
// Issue the rebalancing Set Token
await core.issueTo.sendTransactionAsync(
functionCaller,
rebalancingSetToken.address,
rebalancingSetIssueQuantity,
);
subjectKeepChangeInVault = false;
});
async function subject(): Promise<string> {
return rebalancingTokenIssuanceModule.redeemRebalancingSet.sendTransactionAsync(
subjectRebalancingSetAddress,
subjectRebalancingSetQuantity,
subjectKeepChangeInVault,
{
from: subjectCaller,
gas: DEFAULT_GAS,
},
);
}
it('redeems the rebalancing Set', async () => {
const previousRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
const expectedRBSetTokenBalance = previousRBSetTokenBalance.sub(subjectRebalancingSetQuantity);
await subject();
const currentRBSetTokenBalance = await rebalancingSetToken.balanceOf.callAsync(subjectCaller);
expect(expectedRBSetTokenBalance).to.bignumber.equal(currentRBSetTokenBalance);
});
it('redeems the base Set', async () => {
await subject();
const currentSaseSetTokenBalance = await baseSetToken.balanceOf.callAsync(subjectCaller);
expect(currentSaseSetTokenBalance).to.bignumber.equal(ZERO);
});
});
}); | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class Route53RecoveryReadiness extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Route53RecoveryReadiness.Types.ClientConfiguration)
config: Config & Route53RecoveryReadiness.Types.ClientConfiguration;
/**
* Creates a new Cell.
*/
createCell(params: Route53RecoveryReadiness.Types.CreateCellRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateCellResponse) => void): Request<Route53RecoveryReadiness.Types.CreateCellResponse, AWSError>;
/**
* Creates a new Cell.
*/
createCell(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateCellResponse) => void): Request<Route53RecoveryReadiness.Types.CreateCellResponse, AWSError>;
/**
* Create a new cross account readiness authorization.
*/
createCrossAccountAuthorization(params: Route53RecoveryReadiness.Types.CreateCrossAccountAuthorizationRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateCrossAccountAuthorizationResponse) => void): Request<Route53RecoveryReadiness.Types.CreateCrossAccountAuthorizationResponse, AWSError>;
/**
* Create a new cross account readiness authorization.
*/
createCrossAccountAuthorization(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateCrossAccountAuthorizationResponse) => void): Request<Route53RecoveryReadiness.Types.CreateCrossAccountAuthorizationResponse, AWSError>;
/**
* Creates a new Readiness Check.
*/
createReadinessCheck(params: Route53RecoveryReadiness.Types.CreateReadinessCheckRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateReadinessCheckResponse) => void): Request<Route53RecoveryReadiness.Types.CreateReadinessCheckResponse, AWSError>;
/**
* Creates a new Readiness Check.
*/
createReadinessCheck(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateReadinessCheckResponse) => void): Request<Route53RecoveryReadiness.Types.CreateReadinessCheckResponse, AWSError>;
/**
* Creates a new Recovery Group.
*/
createRecoveryGroup(params: Route53RecoveryReadiness.Types.CreateRecoveryGroupRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateRecoveryGroupResponse) => void): Request<Route53RecoveryReadiness.Types.CreateRecoveryGroupResponse, AWSError>;
/**
* Creates a new Recovery Group.
*/
createRecoveryGroup(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateRecoveryGroupResponse) => void): Request<Route53RecoveryReadiness.Types.CreateRecoveryGroupResponse, AWSError>;
/**
* Creates a new Resource Set.
*/
createResourceSet(params: Route53RecoveryReadiness.Types.CreateResourceSetRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateResourceSetResponse) => void): Request<Route53RecoveryReadiness.Types.CreateResourceSetResponse, AWSError>;
/**
* Creates a new Resource Set.
*/
createResourceSet(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.CreateResourceSetResponse) => void): Request<Route53RecoveryReadiness.Types.CreateResourceSetResponse, AWSError>;
/**
* Deletes an existing Cell.
*/
deleteCell(params: Route53RecoveryReadiness.Types.DeleteCellRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes an existing Cell.
*/
deleteCell(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Delete cross account readiness authorization
*/
deleteCrossAccountAuthorization(params: Route53RecoveryReadiness.Types.DeleteCrossAccountAuthorizationRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.DeleteCrossAccountAuthorizationResponse) => void): Request<Route53RecoveryReadiness.Types.DeleteCrossAccountAuthorizationResponse, AWSError>;
/**
* Delete cross account readiness authorization
*/
deleteCrossAccountAuthorization(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.DeleteCrossAccountAuthorizationResponse) => void): Request<Route53RecoveryReadiness.Types.DeleteCrossAccountAuthorizationResponse, AWSError>;
/**
* Deletes an existing Readiness Check.
*/
deleteReadinessCheck(params: Route53RecoveryReadiness.Types.DeleteReadinessCheckRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes an existing Readiness Check.
*/
deleteReadinessCheck(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes an existing Recovery Group.
*/
deleteRecoveryGroup(params: Route53RecoveryReadiness.Types.DeleteRecoveryGroupRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes an existing Recovery Group.
*/
deleteRecoveryGroup(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes an existing Resource Set.
*/
deleteResourceSet(params: Route53RecoveryReadiness.Types.DeleteResourceSetRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Deletes an existing Resource Set.
*/
deleteResourceSet(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Returns a collection of recommendations to improve resilliance and readiness check quality for a Recovery Group.
*/
getArchitectureRecommendations(params: Route53RecoveryReadiness.Types.GetArchitectureRecommendationsRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetArchitectureRecommendationsResponse) => void): Request<Route53RecoveryReadiness.Types.GetArchitectureRecommendationsResponse, AWSError>;
/**
* Returns a collection of recommendations to improve resilliance and readiness check quality for a Recovery Group.
*/
getArchitectureRecommendations(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetArchitectureRecommendationsResponse) => void): Request<Route53RecoveryReadiness.Types.GetArchitectureRecommendationsResponse, AWSError>;
/**
* Returns information about a Cell.
*/
getCell(params: Route53RecoveryReadiness.Types.GetCellRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetCellResponse) => void): Request<Route53RecoveryReadiness.Types.GetCellResponse, AWSError>;
/**
* Returns information about a Cell.
*/
getCell(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetCellResponse) => void): Request<Route53RecoveryReadiness.Types.GetCellResponse, AWSError>;
/**
* Returns information about readiness of a Cell.
*/
getCellReadinessSummary(params: Route53RecoveryReadiness.Types.GetCellReadinessSummaryRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetCellReadinessSummaryResponse) => void): Request<Route53RecoveryReadiness.Types.GetCellReadinessSummaryResponse, AWSError>;
/**
* Returns information about readiness of a Cell.
*/
getCellReadinessSummary(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetCellReadinessSummaryResponse) => void): Request<Route53RecoveryReadiness.Types.GetCellReadinessSummaryResponse, AWSError>;
/**
* Returns information about a ReadinessCheck.
*/
getReadinessCheck(params: Route53RecoveryReadiness.Types.GetReadinessCheckRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetReadinessCheckResponse) => void): Request<Route53RecoveryReadiness.Types.GetReadinessCheckResponse, AWSError>;
/**
* Returns information about a ReadinessCheck.
*/
getReadinessCheck(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetReadinessCheckResponse) => void): Request<Route53RecoveryReadiness.Types.GetReadinessCheckResponse, AWSError>;
/**
* Returns detailed information about the status of an individual resource within a Readiness Check's Resource Set.
*/
getReadinessCheckResourceStatus(params: Route53RecoveryReadiness.Types.GetReadinessCheckResourceStatusRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetReadinessCheckResourceStatusResponse) => void): Request<Route53RecoveryReadiness.Types.GetReadinessCheckResourceStatusResponse, AWSError>;
/**
* Returns detailed information about the status of an individual resource within a Readiness Check's Resource Set.
*/
getReadinessCheckResourceStatus(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetReadinessCheckResourceStatusResponse) => void): Request<Route53RecoveryReadiness.Types.GetReadinessCheckResourceStatusResponse, AWSError>;
/**
* Returns information about the status of a Readiness Check.
*/
getReadinessCheckStatus(params: Route53RecoveryReadiness.Types.GetReadinessCheckStatusRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetReadinessCheckStatusResponse) => void): Request<Route53RecoveryReadiness.Types.GetReadinessCheckStatusResponse, AWSError>;
/**
* Returns information about the status of a Readiness Check.
*/
getReadinessCheckStatus(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetReadinessCheckStatusResponse) => void): Request<Route53RecoveryReadiness.Types.GetReadinessCheckStatusResponse, AWSError>;
/**
* Returns information about a Recovery Group.
*/
getRecoveryGroup(params: Route53RecoveryReadiness.Types.GetRecoveryGroupRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetRecoveryGroupResponse) => void): Request<Route53RecoveryReadiness.Types.GetRecoveryGroupResponse, AWSError>;
/**
* Returns information about a Recovery Group.
*/
getRecoveryGroup(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetRecoveryGroupResponse) => void): Request<Route53RecoveryReadiness.Types.GetRecoveryGroupResponse, AWSError>;
/**
* Returns information about a Recovery Group.
*/
getRecoveryGroupReadinessSummary(params: Route53RecoveryReadiness.Types.GetRecoveryGroupReadinessSummaryRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetRecoveryGroupReadinessSummaryResponse) => void): Request<Route53RecoveryReadiness.Types.GetRecoveryGroupReadinessSummaryResponse, AWSError>;
/**
* Returns information about a Recovery Group.
*/
getRecoveryGroupReadinessSummary(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetRecoveryGroupReadinessSummaryResponse) => void): Request<Route53RecoveryReadiness.Types.GetRecoveryGroupReadinessSummaryResponse, AWSError>;
/**
* Returns information about a Resource Set.
*/
getResourceSet(params: Route53RecoveryReadiness.Types.GetResourceSetRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetResourceSetResponse) => void): Request<Route53RecoveryReadiness.Types.GetResourceSetResponse, AWSError>;
/**
* Returns information about a Resource Set.
*/
getResourceSet(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.GetResourceSetResponse) => void): Request<Route53RecoveryReadiness.Types.GetResourceSetResponse, AWSError>;
/**
* Returns a collection of Cells.
*/
listCells(params: Route53RecoveryReadiness.Types.ListCellsRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListCellsResponse) => void): Request<Route53RecoveryReadiness.Types.ListCellsResponse, AWSError>;
/**
* Returns a collection of Cells.
*/
listCells(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListCellsResponse) => void): Request<Route53RecoveryReadiness.Types.ListCellsResponse, AWSError>;
/**
* Returns a collection of cross account readiness authorizations.
*/
listCrossAccountAuthorizations(params: Route53RecoveryReadiness.Types.ListCrossAccountAuthorizationsRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListCrossAccountAuthorizationsResponse) => void): Request<Route53RecoveryReadiness.Types.ListCrossAccountAuthorizationsResponse, AWSError>;
/**
* Returns a collection of cross account readiness authorizations.
*/
listCrossAccountAuthorizations(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListCrossAccountAuthorizationsResponse) => void): Request<Route53RecoveryReadiness.Types.ListCrossAccountAuthorizationsResponse, AWSError>;
/**
* Returns a collection of Readiness Checks.
*/
listReadinessChecks(params: Route53RecoveryReadiness.Types.ListReadinessChecksRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListReadinessChecksResponse) => void): Request<Route53RecoveryReadiness.Types.ListReadinessChecksResponse, AWSError>;
/**
* Returns a collection of Readiness Checks.
*/
listReadinessChecks(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListReadinessChecksResponse) => void): Request<Route53RecoveryReadiness.Types.ListReadinessChecksResponse, AWSError>;
/**
* Returns a collection of Recovery Groups.
*/
listRecoveryGroups(params: Route53RecoveryReadiness.Types.ListRecoveryGroupsRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListRecoveryGroupsResponse) => void): Request<Route53RecoveryReadiness.Types.ListRecoveryGroupsResponse, AWSError>;
/**
* Returns a collection of Recovery Groups.
*/
listRecoveryGroups(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListRecoveryGroupsResponse) => void): Request<Route53RecoveryReadiness.Types.ListRecoveryGroupsResponse, AWSError>;
/**
* Returns a collection of Resource Sets.
*/
listResourceSets(params: Route53RecoveryReadiness.Types.ListResourceSetsRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListResourceSetsResponse) => void): Request<Route53RecoveryReadiness.Types.ListResourceSetsResponse, AWSError>;
/**
* Returns a collection of Resource Sets.
*/
listResourceSets(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListResourceSetsResponse) => void): Request<Route53RecoveryReadiness.Types.ListResourceSetsResponse, AWSError>;
/**
* Returns a collection of rules that are applied as part of Readiness Checks.
*/
listRules(params: Route53RecoveryReadiness.Types.ListRulesRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListRulesResponse) => void): Request<Route53RecoveryReadiness.Types.ListRulesResponse, AWSError>;
/**
* Returns a collection of rules that are applied as part of Readiness Checks.
*/
listRules(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListRulesResponse) => void): Request<Route53RecoveryReadiness.Types.ListRulesResponse, AWSError>;
/**
* Returns a list of the tags assigned to the specified resource.
*/
listTagsForResources(params: Route53RecoveryReadiness.Types.ListTagsForResourcesRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListTagsForResourcesResponse) => void): Request<Route53RecoveryReadiness.Types.ListTagsForResourcesResponse, AWSError>;
/**
* Returns a list of the tags assigned to the specified resource.
*/
listTagsForResources(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.ListTagsForResourcesResponse) => void): Request<Route53RecoveryReadiness.Types.ListTagsForResourcesResponse, AWSError>;
/**
* Adds tags to the specified resource. You can specify one or more tags to add.
*/
tagResource(params: Route53RecoveryReadiness.Types.TagResourceRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.TagResourceResponse) => void): Request<Route53RecoveryReadiness.Types.TagResourceResponse, AWSError>;
/**
* Adds tags to the specified resource. You can specify one or more tags to add.
*/
tagResource(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.TagResourceResponse) => void): Request<Route53RecoveryReadiness.Types.TagResourceResponse, AWSError>;
/**
* Removes tags from the specified resource. You can specify one or more tags to remove.
*/
untagResource(params: Route53RecoveryReadiness.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Removes tags from the specified resource. You can specify one or more tags to remove.
*/
untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>;
/**
* Updates an existing Cell.
*/
updateCell(params: Route53RecoveryReadiness.Types.UpdateCellRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateCellResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateCellResponse, AWSError>;
/**
* Updates an existing Cell.
*/
updateCell(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateCellResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateCellResponse, AWSError>;
/**
* Updates an exisiting Readiness Check.
*/
updateReadinessCheck(params: Route53RecoveryReadiness.Types.UpdateReadinessCheckRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateReadinessCheckResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateReadinessCheckResponse, AWSError>;
/**
* Updates an exisiting Readiness Check.
*/
updateReadinessCheck(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateReadinessCheckResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateReadinessCheckResponse, AWSError>;
/**
* Updates an existing Recovery Group.
*/
updateRecoveryGroup(params: Route53RecoveryReadiness.Types.UpdateRecoveryGroupRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateRecoveryGroupResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateRecoveryGroupResponse, AWSError>;
/**
* Updates an existing Recovery Group.
*/
updateRecoveryGroup(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateRecoveryGroupResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateRecoveryGroupResponse, AWSError>;
/**
* Updates an existing Resource Set.
*/
updateResourceSet(params: Route53RecoveryReadiness.Types.UpdateResourceSetRequest, callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateResourceSetResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateResourceSetResponse, AWSError>;
/**
* Updates an existing Resource Set.
*/
updateResourceSet(callback?: (err: AWSError, data: Route53RecoveryReadiness.Types.UpdateResourceSetResponse) => void): Request<Route53RecoveryReadiness.Types.UpdateResourceSetResponse, AWSError>;
}
declare namespace Route53RecoveryReadiness {
export interface CellOutput {
/**
* The arn for the Cell
*/
CellArn: __stringMax256;
/**
* The name of the Cell
*/
CellName: __stringMax64PatternAAZAZ09Z;
/**
* A list of Cell arns
*/
Cells: __listOf__string;
/**
* A list of Cell ARNs and/or RecoveryGroup ARNs
*/
ParentReadinessScopes: __listOf__string;
Tags?: Tags;
}
export interface CreateCellRequest {
/**
* The name of the Cell to create
*/
CellName: __string;
/**
* A list of Cell arns contained within this Cell (for use in nested Cells, e.g. regions within which AZs)
*/
Cells?: __listOf__string;
Tags?: Tags;
}
export interface CreateCellResponse {
/**
* The arn for the Cell
*/
CellArn?: __stringMax256;
/**
* The name of the Cell
*/
CellName?: __stringMax64PatternAAZAZ09Z;
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* A list of Cell ARNs and/or RecoveryGroup ARNs
*/
ParentReadinessScopes?: __listOf__string;
Tags?: Tags;
}
export interface CreateCrossAccountAuthorizationRequest {
/**
* The cross account authorization
*/
CrossAccountAuthorization: CrossAccountAuthorization;
}
export interface CreateCrossAccountAuthorizationResponse {
/**
* The cross account authorization
*/
CrossAccountAuthorization?: CrossAccountAuthorization;
}
export interface CreateReadinessCheckRequest {
/**
* The name of the ReadinessCheck to create
*/
ReadinessCheckName: __string;
/**
* The name of the ResourceSet to check
*/
ResourceSetName: __string;
Tags?: Tags;
}
export interface CreateReadinessCheckResponse {
/**
* Arn associated with ReadinessCheck
*/
ReadinessCheckArn?: __stringMax256;
/**
* Name for a ReadinessCheck
*/
ReadinessCheckName?: __stringMax64PatternAAZAZ09Z;
/**
* Name of the ResourceSet to be checked
*/
ResourceSet?: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface CreateRecoveryGroupRequest {
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* The name of the RecoveryGroup to create
*/
RecoveryGroupName: __string;
Tags?: Tags;
}
export interface CreateRecoveryGroupResponse {
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* The arn for the RecoveryGroup
*/
RecoveryGroupArn?: __stringMax256;
/**
* The name of the RecoveryGroup
*/
RecoveryGroupName?: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface CreateResourceSetRequest {
/**
* The name of the ResourceSet to create
*/
ResourceSetName: __string;
/**
* AWS Resource type of the resources in the ResourceSet
*/
ResourceSetType: __stringPatternAWSAZaZ09AZaZ09;
/**
* A list of Resource objects
*/
Resources: __listOfResource;
Tags?: Tags;
}
export interface CreateResourceSetResponse {
/**
* The arn for the ResourceSet
*/
ResourceSetArn?: __stringMax256;
/**
* The name of the ResourceSet
*/
ResourceSetName?: __stringMax64PatternAAZAZ09Z;
/**
* AWS Resource Type of the resources in the ResourceSet
*/
ResourceSetType?: __stringPatternAWSAZaZ09AZaZ09;
/**
* A list of Resource objects
*/
Resources?: __listOfResource;
Tags?: Tags;
}
export type CrossAccountAuthorization = string;
export interface DNSTargetResource {
/**
* The DNS Name that acts as ingress point to a portion of application
*/
DomainName?: __string;
/**
* The Hosted Zone ARN that contains the DNS record with the provided name of target resource.
*/
HostedZoneArn?: __string;
/**
* The R53 Set Id to uniquely identify a record given a Name and a Type
*/
RecordSetId?: __string;
/**
* The Type of DNS Record of target resource
*/
RecordType?: __string;
TargetResource?: TargetResource;
}
export interface DeleteCellRequest {
/**
* The Cell to delete
*/
CellName: __string;
}
export interface DeleteCrossAccountAuthorizationRequest {
/**
* The cross account authorization
*/
CrossAccountAuthorization: __string;
}
export interface DeleteCrossAccountAuthorizationResponse {
}
export interface DeleteReadinessCheckRequest {
/**
* The ReadinessCheck to delete
*/
ReadinessCheckName: __string;
}
export interface DeleteRecoveryGroupRequest {
/**
* The RecoveryGroup to delete
*/
RecoveryGroupName: __string;
}
export interface DeleteResourceSetRequest {
/**
* The ResourceSet to delete
*/
ResourceSetName: __string;
}
export interface GetArchitectureRecommendationsRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* Name of RecoveryGroup (top level resource) to be analyzed.
*/
RecoveryGroupName: __string;
}
export interface GetArchitectureRecommendationsResponse {
/**
* The time a Recovery Group was last assessed for recommendations in UTC ISO-8601 format.
*/
LastAuditTimestamp?: LastAuditTimestamp;
/**
* A token that can be used to resume pagination from the end of the collection
*/
NextToken?: __string;
/**
* A list of recommendations for the customer's application
*/
Recommendations?: __listOfRecommendation;
}
export interface GetCellReadinessSummaryRequest {
/**
* The name of the Cell
*/
CellName: __string;
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
}
export interface GetCellReadinessSummaryResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* The readiness at Cell level.
*/
Readiness?: Readiness;
/**
* Summaries for the ReadinessChecks making up the Cell
*/
ReadinessChecks?: __listOfReadinessCheckSummary;
}
export interface GetCellRequest {
/**
* The Cell to get
*/
CellName: __string;
}
export interface GetCellResponse {
/**
* The arn for the Cell
*/
CellArn?: __stringMax256;
/**
* The name of the Cell
*/
CellName?: __stringMax64PatternAAZAZ09Z;
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* A list of Cell ARNs and/or RecoveryGroup ARNs
*/
ParentReadinessScopes?: __listOf__string;
Tags?: Tags;
}
export interface GetReadinessCheckRequest {
/**
* The ReadinessCheck to get
*/
ReadinessCheckName: __string;
}
export interface GetReadinessCheckResourceStatusRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
/**
* The ReadinessCheck to get
*/
ReadinessCheckName: __string;
/**
* The resource ARN or component Id to get
*/
ResourceIdentifier: __string;
}
export interface GetReadinessCheckResourceStatusResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* The readiness at rule level.
*/
Readiness?: Readiness;
/**
* Details of the rules's results
*/
Rules?: __listOfRuleResult;
}
export interface GetReadinessCheckResponse {
/**
* Arn associated with ReadinessCheck
*/
ReadinessCheckArn?: __stringMax256;
/**
* Name for a ReadinessCheck
*/
ReadinessCheckName?: __stringMax64PatternAAZAZ09Z;
/**
* Name of the ResourceSet to be checked
*/
ResourceSet?: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface GetReadinessCheckStatusRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
/**
* The ReadinessCheck to get
*/
ReadinessCheckName: __string;
}
export interface GetReadinessCheckStatusResponse {
/**
* Top level messages for readiness check status
*/
Messages?: __listOfMessage;
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* The readiness at rule level.
*/
Readiness?: Readiness;
/**
* Summary of resources's readiness
*/
Resources?: __listOfResourceResult;
}
export interface GetRecoveryGroupReadinessSummaryRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
/**
* The name of the RecoveryGroup
*/
RecoveryGroupName: __string;
}
export interface GetRecoveryGroupReadinessSummaryResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* The readiness at RecoveryGroup level.
*/
Readiness?: Readiness;
/**
* Summaries for the ReadinessChecks making up the RecoveryGroup
*/
ReadinessChecks?: __listOfReadinessCheckSummary;
}
export interface GetRecoveryGroupRequest {
/**
* The RecoveryGroup to get
*/
RecoveryGroupName: __string;
}
export interface GetRecoveryGroupResponse {
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* The arn for the RecoveryGroup
*/
RecoveryGroupArn?: __stringMax256;
/**
* The name of the RecoveryGroup
*/
RecoveryGroupName?: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface GetResourceSetRequest {
/**
* The ResourceSet to get
*/
ResourceSetName: __string;
}
export interface GetResourceSetResponse {
/**
* The arn for the ResourceSet
*/
ResourceSetArn?: __stringMax256;
/**
* The name of the ResourceSet
*/
ResourceSetName?: __stringMax64PatternAAZAZ09Z;
/**
* AWS Resource Type of the resources in the ResourceSet
*/
ResourceSetType?: __stringPatternAWSAZaZ09AZaZ09;
/**
* A list of Resource objects
*/
Resources?: __listOfResource;
Tags?: Tags;
}
export type LastAuditTimestamp = Date;
export interface ListCellsRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
}
export interface ListCellsResponse {
/**
* A list of Cells
*/
Cells?: __listOfCellOutput;
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
}
export interface ListCrossAccountAuthorizationsRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
}
export interface ListCrossAccountAuthorizationsResponse {
/**
* A list of CrossAccountAuthorizations
*/
CrossAccountAuthorizations?: __listOfCrossAccountAuthorization;
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
}
export interface ListReadinessChecksRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
}
export interface ListReadinessChecksResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* A list of ReadinessCheck associated with the account
*/
ReadinessChecks?: __listOfReadinessCheckOutput;
}
export interface ListRecoveryGroupsRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
}
export interface ListRecoveryGroupsResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* A list of RecoveryGroups
*/
RecoveryGroups?: __listOfRecoveryGroupOutput;
}
export interface ListResourceSetsRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
}
export interface ListResourceSetsResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* A list of ResourceSets associated with the account
*/
ResourceSets?: __listOfResourceSetOutput;
}
export interface ListRulesOutput {
/**
* The resource type the rule applies to.
*/
ResourceType: __stringMax64;
/**
* A description of the rule
*/
RuleDescription: __stringMax256;
/**
* The Rule's ID.
*/
RuleId: __stringMax64;
}
export interface ListRulesRequest {
/**
* Upper bound on number of records to return.
*/
MaxResults?: MaxResults;
/**
* A token used to resume pagination from the end of a previous request.
*/
NextToken?: __string;
/**
* Filter parameter which specifies the rules to return given a resource type.
*/
ResourceType?: __string;
}
export interface ListRulesResponse {
/**
* A token that can be used to resume pagination from the end of the collection.
*/
NextToken?: __string;
/**
* A list of rules
*/
Rules?: __listOfListRulesOutput;
}
export interface ListTagsForResourcesRequest {
/**
* The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource.
*/
ResourceArn: __string;
}
export interface ListTagsForResourcesResponse {
Tags?: Tags;
}
export type MaxResults = number;
export interface Message {
/**
* The text of a readiness check message
*/
MessageText?: __string;
}
export interface NLBResource {
/**
* An NLB resource arn
*/
Arn?: __string;
}
export interface R53ResourceRecord {
/**
* The DNS target name
*/
DomainName?: __string;
/**
* The Resource Record set id
*/
RecordSetId?: __string;
}
export type Readiness = "READY"|"NOT_READY"|"UNKNOWN"|"NOT_AUTHORIZED"|string;
export interface ReadinessCheckOutput {
/**
* Arn associated with ReadinessCheck
*/
ReadinessCheckArn: __stringMax256;
/**
* Name for a ReadinessCheck
*/
ReadinessCheckName?: __stringMax64PatternAAZAZ09Z;
/**
* Name of the ResourceSet to be checked
*/
ResourceSet: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface ReadinessCheckSummary {
/**
* The readiness of this ReadinessCheck
*/
Readiness?: Readiness;
/**
* The name of a ReadinessCheck which is part of the given RecoveryGroup or Cell
*/
ReadinessCheckName?: __string;
}
export type ReadinessCheckTimestamp = Date;
export interface Recommendation {
/**
* Guidance text for recommendation
*/
RecommendationText: __string;
}
export interface RecoveryGroupOutput {
/**
* A list of Cell arns
*/
Cells: __listOf__string;
/**
* The arn for the RecoveryGroup
*/
RecoveryGroupArn: __stringMax256;
/**
* The name of the RecoveryGroup
*/
RecoveryGroupName: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface Resource {
/**
* The component id of the resource, generated by the service when dnsTargetResource is used
*/
ComponentId?: __string;
DnsTargetResource?: DNSTargetResource;
/**
* A list of RecoveryGroup ARNs and/or Cell ARNs that this resource is contained within.
*/
ReadinessScopes?: __listOf__string;
/**
* The ARN of the AWS resource, can be skipped if dnsTargetResource is used
*/
ResourceArn?: __string;
}
export interface ResourceResult {
/**
* The component id of the resource
*/
ComponentId?: __string;
/**
* The time the resource was last checked for readiness, in ISO-8601 format, UTC.
*/
LastCheckedTimestamp: ReadinessCheckTimestamp;
/**
* The readiness of the resource.
*/
Readiness: Readiness;
/**
* The ARN of the resource
*/
ResourceArn?: __string;
}
export interface ResourceSetOutput {
/**
* The arn for the ResourceSet
*/
ResourceSetArn: __stringMax256;
/**
* The name of the ResourceSet
*/
ResourceSetName: __stringMax64PatternAAZAZ09Z;
/**
* AWS Resource Type of the resources in the ResourceSet
*/
ResourceSetType: __stringPatternAWSAZaZ09AZaZ09;
/**
* A list of Resource objects
*/
Resources: __listOfResource;
Tags?: Tags;
}
export interface RuleResult {
/**
* The time the resource was last checked for readiness, in ISO-8601 format, UTC.
*/
LastCheckedTimestamp: ReadinessCheckTimestamp;
/**
* Details about the resource's readiness
*/
Messages: __listOfMessage;
/**
* The readiness at rule level.
*/
Readiness: Readiness;
/**
* The identifier of the rule.
*/
RuleId: __string;
}
export interface TagResourceRequest {
/**
* The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource.
*/
ResourceArn: __string;
Tags: Tags;
}
export interface TagResourceResponse {
}
export type Tags = {[key: string]: __string};
export interface TargetResource {
NLBResource?: NLBResource;
R53Resource?: R53ResourceRecord;
}
export interface UntagResourceRequest {
/**
* The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource.
*/
ResourceArn: __string;
/**
* A comma-separated list of the tag keys to remove from the resource.
*/
TagKeys: __listOf__string;
}
export interface UpdateCellRequest {
/**
* The Cell to update
*/
CellName: __string;
/**
* A list of Cell arns, completely replaces previous list
*/
Cells: __listOf__string;
}
export interface UpdateCellResponse {
/**
* The arn for the Cell
*/
CellArn?: __stringMax256;
/**
* The name of the Cell
*/
CellName?: __stringMax64PatternAAZAZ09Z;
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* A list of Cell ARNs and/or RecoveryGroup ARNs
*/
ParentReadinessScopes?: __listOf__string;
Tags?: Tags;
}
export interface UpdateReadinessCheckRequest {
/**
* The ReadinessCheck to update
*/
ReadinessCheckName: __string;
/**
* The name of the ResourceSet to check
*/
ResourceSetName: __string;
}
export interface UpdateReadinessCheckResponse {
/**
* Arn associated with ReadinessCheck
*/
ReadinessCheckArn?: __stringMax256;
/**
* Name for a ReadinessCheck
*/
ReadinessCheckName?: __stringMax64PatternAAZAZ09Z;
/**
* Name of the ResourceSet to be checked
*/
ResourceSet?: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface UpdateRecoveryGroupRequest {
/**
* A list of Cell arns, completely replaces previous list
*/
Cells: __listOf__string;
/**
* The RecoveryGroup to update
*/
RecoveryGroupName: __string;
}
export interface UpdateRecoveryGroupResponse {
/**
* A list of Cell arns
*/
Cells?: __listOf__string;
/**
* The arn for the RecoveryGroup
*/
RecoveryGroupArn?: __stringMax256;
/**
* The name of the RecoveryGroup
*/
RecoveryGroupName?: __stringMax64PatternAAZAZ09Z;
Tags?: Tags;
}
export interface UpdateResourceSetRequest {
/**
* The ResourceSet to update
*/
ResourceSetName: __string;
/**
* AWS Resource Type of the resources in the ResourceSet
*/
ResourceSetType: __stringPatternAWSAZaZ09AZaZ09;
/**
* A list of Resource objects
*/
Resources: __listOfResource;
}
export interface UpdateResourceSetResponse {
/**
* The arn for the ResourceSet
*/
ResourceSetArn?: __stringMax256;
/**
* The name of the ResourceSet
*/
ResourceSetName?: __stringMax64PatternAAZAZ09Z;
/**
* AWS Resource Type of the resources in the ResourceSet
*/
ResourceSetType?: __stringPatternAWSAZaZ09AZaZ09;
/**
* A list of Resource objects
*/
Resources?: __listOfResource;
Tags?: Tags;
}
export type __listOfCellOutput = CellOutput[];
export type __listOfCrossAccountAuthorization = CrossAccountAuthorization[];
export type __listOfListRulesOutput = ListRulesOutput[];
export type __listOfMessage = Message[];
export type __listOfReadinessCheckOutput = ReadinessCheckOutput[];
export type __listOfReadinessCheckSummary = ReadinessCheckSummary[];
export type __listOfRecommendation = Recommendation[];
export type __listOfRecoveryGroupOutput = RecoveryGroupOutput[];
export type __listOfResource = Resource[];
export type __listOfResourceResult = ResourceResult[];
export type __listOfResourceSetOutput = ResourceSetOutput[];
export type __listOfRuleResult = RuleResult[];
export type __listOf__string = __string[];
export type __string = string;
export type __stringMax256 = string;
export type __stringMax64 = string;
export type __stringMax64PatternAAZAZ09Z = string;
export type __stringPatternAWSAZaZ09AZaZ09 = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2019-12-02"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Route53RecoveryReadiness client.
*/
export import Types = Route53RecoveryReadiness;
}
export = Route53RecoveryReadiness; | the_stack |
import * as fs from "fs";
import * as path from "path";
import * as chalk from "chalk";
import { Config, ConfigAppTest, ConfigBuild, ConfigFuzz, ConfigRun, ConfigTest, Package, parsePackage, parseURIPath, parseURIPathGlob, URIPath, URIPathGlob } from "./package_load";
import { cleanCommentsStringsFromFileContents } from "../ast/parser";
type CmdTag = "run" | "symrun" | "build" | "test" | "apptest" | "fuzz" | "morphir-chk";
function help(cmd: CmdTag | undefined) {
if(cmd === "run" || cmd === undefined) {
process.stdout.write("Run Application:\n");
process.stdout.write("bosque run|debug [package_path.json] [--entrypoint fname] [--config cname]\n");
process.stdout.write("bosque run|debug [package_path.json] [--entrypoint fname] [--config cname] --args \"[...]\"\n");
process.stdout.write("bosque run|debug entryfile.bsqapi [--entrypoint fname] --files ...\n");
process.stdout.write("bosque run|debug entryfile.bsqapi [--entrypoint fname] --files ... --args \"[...]\"\n\n");
}
if(cmd === "symrun" || cmd === undefined) {
process.stdout.write("Symbolic Run Application:\n");
process.stdout.write("bosque symrun [package_path.json] [--entrypoint fname] [--config cname]\n");
process.stdout.write("bosque symrun [package_path.json] [--entrypoint fname] [--config cname] --args \"[...]\"\n\n");
}
if(cmd === "build" || cmd === undefined) {
process.stdout.write("Build Application:\n");
process.stdout.write("bosque build node [package_path.json] [--config cname] [out]\n");
process.stdout.write("bosque build bytecode [package_path.json] [--config cname] [out]\n");
process.stdout.write("bosque build sym chk|eval --smtlib [package_path.json] [--entrypoint fname] [--config cname] [out]\n");
process.stdout.write("bosque build morphir [morphir_path.json] [out]\n\n");
}
if(cmd === "test" || cmd === undefined) {
process.stdout.write("Unit-Test Application:\n");
process.stdout.write("bosque test [package_path.json] [--config cname]\n");
process.stdout.write("bosque test testfile.bsqtest ... --files ... [--flavors (sym | icpp | err | chk)*]\n\n");
}
if(cmd === "apptest" || cmd === undefined) {
process.stdout.write("EntryPoint Test Application:\n");
process.stdout.write("bosque apptest [package_path.json] [--config cname]\n");
process.stdout.write("bosque apptest testfile.bsqtest ... --files ... [--flavors (sym | icpp | err | chk)*]\n\n");
}
if(cmd === "fuzz" || cmd === undefined) {
process.stdout.write("Fuzz Application:\n");
process.stdout.write("bosque fuzz [package_path.json] [--config cname]\n");
process.stdout.write("bosque fuzz testfile.bsqapi ... --files ...\n\n");
}
if(cmd === "morphir-chk" || cmd === undefined) {
process.stdout.write("Check a Morphir (elm) Application:\n");
process.stdout.write("bosque morphir-chk [morphir.json]\n\n");
}
}
function generateRunConfigDefault(): ConfigRun {
return {
args: undefined,
main: "Main::main"
};
}
function generateBuildConfigDefault(workingdir: string): ConfigBuild {
return {
out: {
scheme: "file",
authority: undefined,
port: undefined,
path: path.join(workingdir, "bin"),
extension: undefined
}
};
}
function generateTestConfigDefault(): ConfigTest {
return {
flavors: ["sym", "icpp", "chk", "err"],
dirs: "*"
};
}
function generateAppTestConfigDefault(): ConfigAppTest {
return {
flavors: ["sym", "icpp", "err"],
dirs: "*"
};
}
function generateFuzzConfigDefault(): ConfigFuzz {
return {
dirs: "*"
};
}
function tryLoadPackage(pckgpath: string): Package | undefined {
if(path.extname(pckgpath) !== ".json") {
return undefined;
}
if(path.basename(pckgpath) !== "package.json") {
process.stderr.write(chalk.red(`Invalid package file name (expected 'package.json')-- ${pckgpath}\n`));
process.exit(1);
}
let contents: string = "EMPTY";
try {
contents = fs.readFileSync(pckgpath).toString();
}
catch(exl) {
process.stderr.write(chalk.red(`Could not load package file -- ${pckgpath}\n`));
process.exit(1);
}
let jpckg: any = undefined;
try {
jpckg = JSON.parse(contents);
}
catch(exj) {
process.stderr.write(chalk.red(`Package file does not have a vaild JSON config -- ${pckgpath}\n`));
process.exit(1);
}
const pckg = parsePackage(jpckg);
if(typeof(pckg) === "string") {
process.stderr.write(chalk.red(`Package file format error -- ${pckg}\n`));
process.exit(1);
}
return pckg;
}
function checkEntrypointMatch(contents: string, ns: string, fname: string): boolean {
const okns = contents.includes(`namespace ${ns};`);
const okfname = contents.includes(`entrypoint function ${fname}(`);
return okns && okfname;
}
function extractEntryPointKnownFile(args: string[], workingdir: string, appfile: string): {filename: string, name: string, fkey: string} | undefined {
const epidx = args.indexOf("--entrypoint");
let epname = "Main::main";
if(epidx !== -1) {
if(epidx === args.length - 1) {
return undefined;
}
epname = args[epidx] + 1;
}
const ccidx = epname.indexOf("::");
if(ccidx === -1) {
return undefined;
}
return {
filename: path.resolve(workingdir, appfile),
name: epname.slice(ccidx + 2),
fkey: "__i__" + epname
}
}
function extractEntryPointsAll(workingdir: string, appuris: URIPathGlob[]): {filename: string, names: string[], fkeys: string[]} | undefined {
if(appuris.length !== 1) {
return undefined;
}
const appuri = appuris[0];
try {
if (appuri.scheme === "file") {
const fullpath = path.resolve(workingdir, appuri.path);
if (appuri.selection === undefined) {
const contents = cleanCommentsStringsFromFileContents(fs.readFileSync(fullpath).toString());
const namespacere = /namespace([ \t]+)(?<nsstr>(([A-Z][_a-zA-Z0-9]+)::)*([A-Z][_a-zA-Z0-9]+));/;
const entryre = /(entrypoint|chktest|errtest|__chktest)(\s+)function(\s+)(?<fname>([_a-z]|([_a-z][_a-zA-Z0-9]*[a-zA-Z0-9])))(\s*)\(/g;
const ns = namespacere.exec(contents);
if (ns === null || ns.groups === undefined || ns.groups.nsstr === undefined) {
return undefined;
}
const nsstr = ns.groups.nsstr;
let names: string[] = [];
let mm: RegExpExecArray | null = null;
entryre.lastIndex = 0;
mm = entryre.exec(contents);
while (mm !== null) {
if (mm.groups === undefined || mm.groups.fname === undefined) {
return undefined;
}
if (mm[0].startsWith("entrypoint")) {
names.push(mm.groups.fname);
}
entryre.lastIndex += mm[0].length;
mm = entryre.exec(contents);
}
return {
filename: fullpath,
names: names,
fkeys: names.map((fname) => "__i__" + nsstr + "::" + fname)
};
}
else {
return undefined;
}
}
else {
return undefined;
}
}
catch (ex) {
return undefined;
}
}
function extractEntryPoint(args: string[], workingdir: string, appfiles: URIPathGlob[]): {filename: string, name: string, fkey: string} | undefined {
const epidx = args.indexOf("--entrypoint");
let epname = "Main::main";
if(epidx !== -1) {
if(epidx === args.length - 1) {
return undefined;
}
epname = args[epidx + 1];
}
const ccidx = epname.indexOf("::");
if(ccidx === -1) {
return undefined;
}
const ns = epname.slice(0, ccidx);
const fname = epname.slice(ccidx + 2);
try {
for (let i = 0; i < appfiles.length; ++i) {
if(appfiles[i].scheme === "file") {
const fullpath = path.resolve(workingdir, appfiles[i].path);
if(appfiles[i].selection === undefined) {
const contents = cleanCommentsStringsFromFileContents(fs.readFileSync(fullpath).toString());
if(checkEntrypointMatch(contents, ns, fname)) {
return {
filename: fullpath,
name: epname.slice(ccidx + 2),
fkey: "__i__" + epname
};
}
}
else if(appfiles[i].selection === "*") {
const subfiles = fs.readdirSync(fullpath);
for(let j = 0; j < subfiles.length; ++j) {
const fullsubpath = path.resolve(fullpath, subfiles[j]);
const fext = path.extname(fullsubpath);
if ((fext === appfiles[i].filter || appfiles[i].filter === undefined) && fext === ".bsqapi") {
const contents = cleanCommentsStringsFromFileContents(fs.readFileSync(fullsubpath).toString());
if (checkEntrypointMatch(contents, ns, fname)) {
return {
filename: fullsubpath,
name: epname.slice(ccidx + 2),
fkey: "__i__" + epname
};
}
}
}
}
else {
process.stderr.write(chalk.red("** glob pattern not implemented yet!!!\n"));
process.exit(1);
}
}
else {
return undefined;
}
}
return undefined;
}
catch (ex) {
return undefined;
}
}
function isStdInArgs(args: string[]): boolean {
return args.indexOf("--args") === -1;
}
function extractArgs(args: string[]): any[] | undefined {
const argsidx = args.indexOf("--args");
if(argsidx === -1 || argsidx === args.length - 1) {
return undefined;
}
let rargs: any = undefined;
try {
rargs = JSON.parse(args[argsidx + 1]);
if(!Array.isArray(rargs)) {
return undefined;
}
}
catch {
;
}
return rargs;
}
function extractOutput(workingdir: string, args: string[]): URIPath | undefined {
const argsidx = args.indexOf("--output");
if(argsidx === -1 || argsidx === args.length - 1) {
return {
scheme: "file",
authority: undefined,
port: undefined,
path: path.join(workingdir, "bin"),
extension: undefined
};
}
return parseURIPath(args[argsidx + 1]);
}
function extractFiles(workingdir: string, args: string[]): URIPathGlob[] | undefined {
const fidx = args.indexOf("--files");
if(fidx === -1) {
return undefined;
}
let ii = fidx + 1;
let files: string[] = [];
while(ii < args.length && !args[ii].startsWith("--")) {
if(path.extname(args[ii]) !== ".bsq") {
return undefined;
}
files.push(args[ii]);
}
let urifiles: URIPathGlob[] = [];
for(let i = 0; i < files.length; ++i) {
const fullfd = path.join(workingdir, files[i]);
if(!fs.existsSync(fullfd)) {
return undefined;
}
const furi = parseURIPathGlob(fullfd);
if(furi === undefined) {
return undefined;
}
urifiles.push(furi);
}
return urifiles;
}
function extractConfig<T>(args: string[], pckg: Package, workingdir: string, cmd: CmdTag): Config<T> | undefined {
const cfgidx = args.indexOf("--config");
if(cfgidx !== -1) {
if(cfgidx === args.length - 1) {
return undefined;
}
const cfgname = args[cfgidx + 1];
if(cmd === "run") {
return (pckg.configs.run.find((cfg) => cfg.name === cfgname) as any) as Config<T>;
}
else if(cmd === "build") {
return (pckg.configs.build.find((cfg) => cfg.name === cfgname) as any) as Config<T>;
}
else if(cmd === "test") {
return (pckg.configs.test.find((cfg) => cfg.name === cfgname) as any) as Config<T>;
}
else if(cmd === "apptest") {
return (pckg.configs.apptest.find((cfg) => cfg.name === cfgname) as any) as Config<T>;
}
else {
return (pckg.configs.run.find((cfg) => cfg.name === cfgname) as any) as Config<T>;
}
}
else {
if(cmd === "run") {
const rcfg = generateRunConfigDefault() as any;
return {
name: "_run_",
macros: [],
globalmacros: [],
buildlevel: "test",
params: rcfg as T
};
}
else if(cmd === "build") {
const rcfg = generateBuildConfigDefault(workingdir) as any;
return {
name: "_build_",
macros: [],
globalmacros: [],
buildlevel: "test",
params: rcfg as T
};
}
else if(cmd === "test") {
const rcfg = generateTestConfigDefault() as any;
return {
name: "_test_",
macros: [],
globalmacros: [],
buildlevel: "test",
params: rcfg as T
};
}
else if(cmd === "apptest") {
const rcfg = generateAppTestConfigDefault() as any;
return {
name: "_apptest_",
macros: [],
globalmacros: [],
buildlevel: "test",
params: rcfg as T
};
}
else {
const rcfg = generateFuzzConfigDefault() as any;
return {
name: "_fuzz_",
macros: [],
globalmacros: [],
buildlevel: "test",
params: rcfg as T
};
}
}
}
function extractTestFlags(args: string[], cmd: CmdTag): ("sym" | "icpp" | "err" | "chk")[] | undefined {
const fidx = args.indexOf("--flavors");
if(fidx === -1 || fidx === args.length - 1) {
if(cmd === "test") {
return ["sym", "icpp", "chk", "err"];
}
else {
return ["sym", "icpp", "err"];
}
}
if(fidx === args.length - 1) {
return undefined;
}
let ii = fidx + 1;
let flavors: ("sym" | "icpp" | "err" | "chk")[] = [];
while(ii < args.length && !args[ii].startsWith("--")) {
const flavor = args[ii];
if(flavor !== "sym" && flavor !== "icpp" && flavor !== "err" && flavor !== "chk") {
return undefined;
}
flavors.push(flavor);
}
return flavors;
}
function loadUserSrc(workingdir: string, files: URIPathGlob[]): string[] | undefined {
try {
let code: string[] = [];
for (let i = 0; i < files.length; ++i) {
if(files[i].scheme === "file") {
const fullpath = path.resolve(workingdir, files[i].path);
if(files[i].selection === undefined) {
code.push(fullpath);
}
else if(files[i].selection === "*") {
const subfiles = fs.readdirSync(fullpath);
for(let j = 0; j < subfiles.length; ++j) {
const fullsubpath = path.resolve(fullpath, subfiles[j]);
const fext = path.extname(fullsubpath);
if((fext === files[i].filter || files[i].filter === undefined) && fext === ".bsq") {
code.push(fullsubpath);
}
if((fext === files[i].filter || files[i].filter === undefined) && fext === ".bsqapi") {
code.push(fullsubpath);
}
if((fext === files[i].filter || files[i].filter === undefined) && fext === ".bsqtest") {
code.push(fullsubpath);
}
}
}
else {
process.stderr.write(chalk.red("** glob pattern not implemented yet!!!\n"));
process.exit(1);
}
}
else {
return undefined;
}
}
return code;
}
catch (ex) {
return undefined;
}
}
export {
CmdTag,
help,
tryLoadPackage, extractEntryPointKnownFile, extractEntryPointsAll, extractEntryPoint, isStdInArgs, extractArgs, extractOutput, extractFiles, extractConfig, extractTestFlags, loadUserSrc
}; | the_stack |
import * as _ from 'lodash';
import { Type2DMatrix } from '../types';
import { ValidationError, ValidationInconsistentShape } from './Errors';
import { inferShape } from './tensors';
/**
* Return the number of elements along a given axis.
* @param {any} X: Array like input data
* @param {any} axis
* @ignore
*/
const size = (X, axis = 0) => {
const rows = _.size(X);
if (rows === 0) {
throw new ValidationError('Invalid input array of size 0!');
}
if (axis === 0) {
return rows;
} else if (axis === 1) {
return _.flowRight(_.size, (a) => _.get(a, '[0]'))(X);
}
throw new ValidationError(`Invalid axis value ${axis} was given`);
};
/**
* Just a dumb version of subset, which is sufficient enough for now.
* It can only handle range of rows with a single column.
*
* TODO: Improve.
* @param X
* @param rowsRange
* @param colsRange
* @ignore
*/
const subset = (X, rowsRange: number[], colsRange: number[], replacement = null): any[][] => {
// console.log('checking subset', X, rowsRange, colsRange, replacement);
if (replacement) {
const _X = _.cloneDeep(X);
for (let i = 0; i < rowsRange.length; i++) {
const rowIndex = rowsRange[i];
colsRange.forEach((col) => {
_X[rowIndex][col] = replacement[i];
});
}
return _X;
} else {
const result = [];
// TODO: Replace it with a proper matrix subset method. e.g. http://mathjs.org/docs/reference/functions/subset.html
for (let i = 0; i < rowsRange.length; i++) {
const rowIndex = rowsRange[i];
const subSection = [];
colsRange.forEach((col) => {
subSection.push(X[rowIndex][col]);
});
// result.push([X[rowIndex][col]]);
result.push(subSection);
}
return result;
}
};
/**
* Get range of values
* @param start
* @param stop
* @ignore
*/
const range = (start: number, stop: number) => {
if (!_.isNumber(start) || !_.isNumber(stop)) {
throw new ValidationError('start and stop arguments need to be numbers');
}
return _.range(start, stop);
};
/**
* Checking the maxtrix is a matrix of a certain data type (e.g. number)
* The function also performs isMatrix against the passed in dataset
* @param matrix
* @param {string} _type
* @ignore
*/
const isMatrixOf = (matrix, _type = 'number') => {
if (!isMatrix(matrix)) {
throw new ValidationError(`Cannot perform isMatrixOf ${_type} unless the data is matrix`);
}
// Checking each elements inside the matrix is not number
// Returns an array of result per row
const vectorChecks = matrix.map((arr) =>
arr.some((x) => {
// Checking type of each element
if (_type === 'number') {
return !_.isNumber(x);
} else {
throw Error('Cannot check matrix of an unknown type');
}
}),
);
// All should be false
return vectorChecks.indexOf(true) === -1;
};
/**
* Checking the matrix is a data of multiple rows
* @param matrix
* @returns {boolean}
* @ignore
*/
const isMatrix = (matrix) => {
if (!Array.isArray(matrix)) {
return false;
}
if (_.size(matrix) === 0) {
return false;
}
const isAllArray = matrix.map((arr) => _.isArray(arr));
return isAllArray.indexOf(false) === -1;
};
/**
* Checking the array is a type of X
* @param arr
* @param {string} _type
* @returns {boolean}
* @ignore
*/
const isArrayOf = (arr, _type = 'number') => {
if (_type === 'number') {
return !arr.some(isNaN);
} else if (_type === 'string') {
return !arr.some((x) => !_.isString(x));
}
throw new ValidationError(`Failed to check the array content of type ${_type}`);
};
/**
*
* @param {number[]} v1
* @param {number[]} v2
* @returns {number}
* @ignore
*/
const euclideanDistance = (v1: number[], v2: number[]): number => {
const v1Range = _.range(0, v1.length);
const initialTotal = 0;
const total = _.reduce(
v1Range,
(sum, i) => {
return sum + Math.pow(v2[i] - v1[i], 2);
},
initialTotal,
);
return Math.sqrt(total);
};
/**
*
* @param {number[]} v1
* @param {number[]} v2
* @returns {number}
* @ignore
*/
const manhattanDistance = (v1: number[], v2: number[]): number => {
const v1Range = _.range(0, v1.length);
const initialTotal = 0;
return _.reduce(
v1Range,
(total, i) => {
return total + Math.abs(v2[i] - v1[i]);
},
initialTotal,
);
};
/**
* Subtracts two matrices
* @param X
* @param y
* @ignore
*/
const subtract = (X, y) => {
const _X = _.clone(X);
for (let rowIndex = 0; rowIndex < _X.length; rowIndex++) {
const row = X[rowIndex];
for (let colIndex = 0; colIndex < row.length; colIndex++) {
const column = row[colIndex];
// Supports y.length === 1 or y.length === row.length
if (y.length === 1) {
const subs = y[0];
_X[rowIndex][colIndex] = column - subs;
} else if (y.length === row.length) {
const subs = y[colIndex];
_X[rowIndex][colIndex] = column - subs;
} else {
throw Error(`Dimension of y ${y.length} and row ${row.length} are not compatible`);
}
}
}
return _X;
};
/**
* Calculates covariance
* @param X
* @param xMean
* @param y
* @param yMean
* @returns {number}
* @ignore
*/
const covariance = (X, xMean, y, yMean) => {
if (_.size(X) !== _.size(y)) {
throw new ValidationError('X and y should match in size');
}
let covar = 0.0;
for (let i = 0; i < _.size(X); i++) {
covar += (X[i] - xMean) * (y[i] - yMean);
}
return covar;
};
/**
* Calculates the variance
* needed for linear regression
* @param X
* @param mean
* @returns {number}
* @ignore
*/
const variance = (X, mean) => {
if (!Array.isArray(X)) {
throw new ValidationError('X must be an array');
}
let result = 0.0;
for (let i = 0; i < _.size(X); i++) {
result += Math.pow(X[i] - mean, 2);
}
return result;
};
/**
* Stack arrays in sequence horizontally (column wise).
* This is equivalent to concatenation along the second axis, except for 1-D
* arrays where it concatenates along the first axis. Rebuilds arrays divided by hsplit.
*
* @example
* hstack([[1], [1]], [[ 0, 1, 2 ], [ 1, 0, 3 ]])
* returns [ [ 1, 0, 1, 2 ], [ 1, 1, 0, 3 ] ]
* @param X
* @param y
* @ignore
*/
const hstack = (X, y) => {
let stack = [];
if (isMatrix(X) && isMatrix(y)) {
for (let i = 0; i < X.length; i++) {
const xEntity = X[i];
const yEntity = y[i];
stack.push(hstack(xEntity, yEntity));
}
} else if (Array.isArray(X) && Array.isArray(y)) {
stack = _.concat(X, y);
stack = _.flatten(stack);
} else {
throw new ValidationError('Input should be either matrix or Arrays');
}
return stack;
};
/**
* Validating the left input is an array, and the right input is a pure number.
* @param a
* @param b
* @ignore
*/
const isArrayNumPair = (a, b) => Array.isArray(a) && _.isNumber(b);
/**
* Inner product of two arrays.
* Ordinary inner product of vectors for 1-D arrays (without complex conjugation),
* in higher dimensions a sum product over the last axes.
* @param a
* @param b
* @ignore
*/
const inner = (a, b) => {
/**
* Internal methods to process the inner product
* @param a - First vector
* @param b - Second vector or a number
*/
// 1. If a and b are both pure numbers
if (_.isNumber(a) && _.isNumber(b)) {
return a * b;
}
// If a is a vector and b is a pure number
if (isArrayNumPair(a, b)) {
return a.map((x) => x * b);
}
// If b is a vector and a is a pure number
if (isArrayNumPair(b, a)) {
return b.map((x) => x * a);
}
// If a and b are both vectors with an identical size
if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) {
let result = 0;
for (let i = 0; i < a.length; i++) {
result += a[i] * b[i];
}
return result;
} else if (Array.isArray(a) && Array.isArray(b) && a.length !== b.length) {
throw new ValidationInconsistentShape(`Dimensions (${a.length},) and (${b.length},) are not aligned`);
}
throw new ValidationError(`Cannot process with the invalid inputs ${a} and ${b}`);
};
/**
* Generates a random set of indices of a set of a given size.
* @param setSize - Size of set we are generating subset for
* @param maxSamples - Controls the size of the subset.
* Is used in conjunction with @param maxSamplesIsFloat
* If @param maxSamplesIsFloat is true, the size of the subset is equal to
* floor(maxSamples*setSize).
* If @param maxSamplesIsFloat is false, the size of the subset is equal to
* floor(maxSamples).
* @param bootstrap - Whether samples are drawn with replacement
* @returns Returns an array of numbers in [0, setSize) range
* with size calculated according to an algorithm described above
* @ignore
*/
const generateRandomSubset = (
setSize: number,
maxSamples: number,
bootstrap: boolean,
maxSamplesIsFloat: boolean = true,
): number[] => {
if (maxSamples < 0) {
throw new ValidationError("maxSamples can't be negative");
}
if (!maxSamplesIsFloat && maxSamples > setSize) {
throw new ValidationError('maxSamples must be in [0, n_samples]');
}
if (maxSamplesIsFloat && maxSamples > 1) {
throw new ValidationError('maxSamplesIsFloat is true but number bigger than 1 was passed');
}
const sampleSize = maxSamplesIsFloat ? Math.floor(setSize * maxSamples) : Math.floor(maxSamples);
const indices = [];
if (bootstrap) {
for (let i = 0; i < sampleSize; ++i) {
indices.push(genRandomIndex(setSize));
}
} else {
// O(n) algorithm for non-bootstrap sampling as described in this paper
// https://sci-hub.se/10.1080/00207168208803304
const nums = range(0, setSize);
for (let i = 0; i < sampleSize; ++i) {
const index = genRandomIndex(setSize - i);
indices.push(nums[index]);
const tmp = nums[index];
nums[index] = nums[setSize - i - 1];
nums[setSize - i - 1] = tmp;
}
}
return indices;
};
/**
* Generates a random subset of a given matrix.
* @param X - source matrix
* @param maxSamples - The number of samples to draw from X to train each base estimator.
* Is used in conjunction with @param maxSamplesIsFloating.
* If @param maxSamplesIsFloating is false, then draw maxSamples samples.
* If @param maxSamplesIsFloating is true, then draw max_samples * shape(X)[0] samples.
* @param maxFeatures - The number of features to draw from X to train each base estimator.
* Is used in conjunction with @param maxFeaturesIsFloating
* If @param maxFeaturesIsFloating is false, then draw max_features features.
* If @param maxFeaturesIsFloating is true, then draw max_features * shape(X)[1] features.
* @param bootstrapSamples - Whether samples are drawn with replacement. If false, sampling without replacement is performed.
* @param bootstrapFeatures - Whether features are drawn with replacement.
* @ignore
*/
const generateRandomSubsetOfMatrix = <T>(
X: Type2DMatrix<T>,
maxSamples: number = 1.0,
maxFeatures: number = 1.0,
bootstrapSamples: boolean,
bootstrapFeatures: boolean,
maxSamplesIsFloating: boolean = true,
maxFeaturesIsFloating: boolean = true,
): [Type2DMatrix<T>, number[], number[]] => {
const [numRows, numColumns] = inferShape(X);
const rowIndices = generateRandomSubset(numRows, maxSamples, bootstrapSamples, maxSamplesIsFloating);
const columnIndices = generateRandomSubset(numColumns, maxFeatures, bootstrapFeatures, maxFeaturesIsFloating);
const result = [];
rowIndices.forEach((i) => {
const curRow = [];
columnIndices.forEach((j) => {
curRow.push(X[i][j]);
});
result.push(curRow);
});
return [result, rowIndices, columnIndices];
};
/**
* Generates a random integer in [0, upperBound) range.
* @ignore
*/
const genRandomIndex = (upperBound: number): number => Math.floor(Math.random() * upperBound);
const math = {
covariance,
euclideanDistance,
genRandomIndex,
generateRandomSubset,
generateRandomSubsetOfMatrix,
hstack,
isArrayOf,
inner,
isMatrix,
isMatrixOf,
manhattanDistance,
range,
subset,
size,
subtract,
variance,
};
export default math; | the_stack |
import { connect } from 'react-redux'
import { push } from 'connected-react-router'
import { withRouter } from 'react-router-dom'
import { withStyles } from '@material-ui/core/styles'
import Button from '@material-ui/core/Button'
import Card from '@material-ui/core/Card'
import CardContent from '@material-ui/core/CardContent'
import CardMedia from '@material-ui/core/CardMedia'
import Grid from '@material-ui/core/Grid'
import Hidden from '@material-ui/core/Hidden'
import Paper from '@material-ui/core/Paper'
import React, { Component } from 'react'
import classNames from 'classnames'
import LayoutBody from 'src/components/layoutBody'
import Typography from 'src/components/typography'
import { IProductHowItWorksComponentProps } from './IProductHowItWorksComponentProps'
import { IProductHowItWorksComponentState } from './IProductHowItWorksComponentState'
// - Import API
// - Import actions
const styles = (theme: any) => ({
root: {
backgroundColor: '#f7f7f7',
overflow: 'hidden',
padding: '35px',
[theme.breakpoints.down('xs')]: {
padding: '20px'
}
},
layoutBody: {
position: 'relative',
marginLeft: 0,
marginRight: 0,
marginBottom: '20px'
},
item: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: theme.spacing(0, 5),
},
itemimage: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
padding: theme.spacing(0, 5),
[theme.breakpoints.down('sm')]: {
padding: theme.spacing(0)
},
},
productwrapper: {
display: 'flex',
[theme.breakpoints.down('sm')]: {
justifyContent: 'center'
},
},
productitem: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
padding: theme.spacing(5, 5, 0, 0),
[theme.breakpoints.down('sm')]: {
alignItems: 'center',
padding: theme.spacing(0),
},
},
productimages: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
cursor: 'Pointer'
},
productimagesleft: {
display: 'flex',
flexDirection: 'column',
alignItems: 'flex-start',
cursor: 'Pointer',
[theme.breakpoints.down('md')]: {
flexDirection: 'row',
},
},
title: {
marginBottom: theme.spacing(14),
},
number: {
fontSize: 24,
fontFamily: theme.typography.fontFamily,
color: theme.palette.secondary.main,
fontWeight: theme.typography.fontWeightMedium,
},
image: {
height: 55,
marginTop: theme.spacing(4),
marginBottom: theme.spacing(4),
},
curvyLines: {
pointerEvents: 'none',
position: 'absolute',
top: -180,
opacity: 0.7,
},
button: {
textTransform: 'capitalize',
borderRadius: 30,
padding: `${15}px ${45}px`,
boxShadow: 'none'
},
paperroot: {
width: '100%',
marginTop: 16
},
producttitle: {
fontSize: 24,
fontFamily: '"Montserrat", sans-serif',
lineHeight: '150%',
color: '#2e2e2e',
textTransform: 'inherit',
fontWeight: 'bold',
marginBottom: '2rem'
},
productcontent: {
fontSize: 16,
fontFamily: '"Montserrat", sans-serif',
lineHeight: '150%',
color: '#2e2e2e',
textTransform: 'inherit',
marginBottom: '2rem',
[theme.breakpoints.down('sm')]: {
textAlign: 'center',
padding: '5px'
},
},
sectionimage: {
marginTop: 15
},
card: {
width: '100%',
boxShadow: 'none',
borderRadius: 0,
},
cardleft: {
width: '100%',
boxShadow: 'none',
borderRadius: 0,
[theme.breakpoints.down('sm')]: {
width: '49.5%',
},
[theme.breakpoints.only('md')]: {
width: '49.5%',
}
},
cardImage: {
marginBottom: 15,
[theme.breakpoints.down('sm')]: {
marginBottom: 0,
marginRight: '1rem'
},
[theme.breakpoints.only('md')]: {
marginBottom: 0,
marginRight: '1rem'
}
},
leftMedia: {
height: 0,
paddingTop: '93.8%', // 16:9
},
media: {
height: 0,
paddingTop: '59.8%', // 16:9
backgroundPosition: 'top center'
},
sideproducttitle: {
fontSize: 60,
fontFamily: '"Playfair Display", sans-serif',
lineHeight: '150%',
color: '#2e2e2e',
textTransform: 'inherit',
letterSpacing: '3px',
[theme.breakpoints.down('xs')]: {
fontSize: 30
}
},
sideproductcontent: {
fontSize: 24,
fontFamily: '"Montserrat", sans-serif',
lineHeight: '150%',
color: '#2e2e2e',
textTransform: 'inherit',
marginBottom: '2rem',
fontWeight: 'bold',
[theme.breakpoints.down('xs')]: {
fontSize: 12
}
},
registerbutton: {
textTransform: 'capitalize',
borderRadius: 30,
padding: `${17}px ${80}px`,
boxShadow: 'none'
},
registerbuttonwrapper: {
marginBottom: '2.3rem'
}
})
/**
* Create component class
*/
export class ProductHowItWorksComponent extends Component<IProductHowItWorksComponentProps,IProductHowItWorksComponentState> {
static propTypes = {
}
/**
* Component constructor
* @param {object} props is an object properties of component
*/
constructor (props: IProductHowItWorksComponentProps) {
super(props)
// Defaul state
this.state = {
}
// Binding functions to `this`
}
/**
* Reneder component DOM
* @return {react element} return the DOM which rendered by component
*/
render () {
const { classes, goTo } = this.props
return (
<section className={classes.root}>
<LayoutBody className={classes.layoutBody} width='full'>
<Paper className={classes.paperroot} elevation={1}>
<Grid container spacing={4}>
<Grid item sm={12} md={6} xs={12} className={classes.productwrapper} >
<div className={classes.itemimage}>
<Hidden xsDown implementation='css'>
<img src={'/public/bag-big.png'}/>
</Hidden>
<Hidden smUp implementation='css'>
<img src={'/public/bag-small.png'}/>
</Hidden>
</div>
</Grid>
<Grid item sm={12} md={6} xs={12} className={classes.productwrapper} >
<div className={classes.productitem}>
<Typography variant='h1' className={classes.producttitle}>
Vera Bradley
</Typography>
<Typography variant='body1' className={classes.productcontent} >
Carry the day in style with this extra-large tote crafted in our chic B.B. Colloction textured PVC. Featuring colorful faux leather trim, this tote offers a roomy interior plus just engough perfectly placed.
</Typography>
<Button
variant='contained'
color='secondary'
className={classes.button}
onClick={(evt: any) => {
evt.preventDefault()
goTo!(`/products`)
}}
>
Shop Now
</Button>
</div>
</Grid>
</Grid>
</Paper>
</LayoutBody>
<LayoutBody className={classes.layoutBody} width='full'>
<Grid container spacing={4}>
<Grid item xs={12} lg={4} >
<div className={classes.productimagesleft}>
<Card className={classNames(classes.cardleft,classes.cardImage)}>
<CardMedia
className={classes.leftMedia}
image={require('src/styles/images/wow.png')}
title='Wow'
/>
</Card>
<Card className={classes.cardleft}>
<CardMedia
className={classes.leftMedia}
image={require('src/styles/images/men-size-full.png')}
title='Men Clothings'
/>
</Card>
</div>
</Grid>
<Grid item xs={12} lg={8}>
<div className={classes.productimages}>
<Card className={classes.card}>
<CardMedia
className={classes.media}
image={require('src/styles/images/sidemainfull.png')}
title='Paella dish'
/>
<CardContent>
<Typography variant='h6' align='center' className={classes.sideproducttitle}>
Let the Game begin
</Typography>
<Typography component='p' align='center' className={classes.sideproductcontent}>
Registration is on - get ready for the Open
</Typography>
<Typography component='p' align='center' className={classes.registerbuttonwrapper}>
<Button
variant='contained'
color='secondary'
className={classes.registerbutton}
onClick={(evt: any) => {
evt.preventDefault()
goTo!('/signup')
}}
>
Register
</Button>
</Typography>
</CardContent>
</Card>
</div>
</Grid>
</Grid>
</LayoutBody>
</section>
)
}
}
/**
* Map dispatch to props
* @param {func} dispatch is the function to dispatch action to reducers
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapDispatchToProps = (dispatch: Function, ownProps: IProductHowItWorksComponentProps) => {
return {
goTo: (url: string) => dispatch(push(url)),
}
}
/**
* Map state to props
* @param {object} state is the obeject from redux store
* @param {object} ownProps is the props belong to component
* @return {object} props of component
*/
const mapStateToProps = (state: any, ownProps: IProductHowItWorksComponentProps) => {
const uid = state.getIn(['authorize', 'uid'], 0)
return {
uid
}
}
export default withRouter<any>(connect(mapStateToProps, mapDispatchToProps)(withStyles(styles as any, { withTheme: true })(ProductHowItWorksComponent as any) as any)) as typeof ProductHowItWorksComponent | the_stack |
import {
ChevronLeftIcon,
ChevronRightIcon,
HamburgerMenuIcon,
} from '@modulz/radix-icons';
import cn from 'classnames';
import clsx from 'clsx';
import fs from 'fs';
import glob from 'glob';
import matter from 'gray-matter';
import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { MDXRemote } from 'next-mdx-remote';
import { serialize } from 'next-mdx-remote/serialize';
import path from 'path';
import { useState } from 'react';
import { renderToString } from 'react-dom/server';
import _slugify from 'slugify';
import Code from '../components/code';
import {
GithubCircleIcon,
GithubIcon,
NpmIcon,
TwitterIcon,
} from '../components/icons';
import SocialHead from '../components/social-head';
import toc, { TocLink } from '../content/toc';
import { absoluteUrl } from '../lib/absolute-url';
export function slugify(name) {
name = renderToString(name)
.replace(/<[^>]*>/g, '')
.replace(/[<>]/g, '');
return _slugify(`${name}`.replace(/\./g, '-'), {
lower: true,
remove: /[^\w\s\-]/g,
});
}
function CustomLink({ href, children }) {
const onClick = (event) => {
if (!href.startsWith('#')) return;
event.preventDefault();
history.pushState(null, document.title, href);
document.body.querySelector(href)?.scrollIntoView({
behavior: 'smooth',
});
};
return (
<Link href={href}>
<a onClick={onClick} className="!text-blue-600 !font-normal underline">
{children}
</a>
</Link>
);
}
function WrapCode({ className, children }) {
const language = (className || '').split('-')[1];
return (
<Code size="md" language={language}>
{children}
</Code>
);
}
function H({ tag, children }) {
const Tag = tag;
const slug = slugify(children);
const onClick = (event) => {
event.preventDefault();
history.pushState(null, document.title, `#${slug}`);
event.currentTarget?.scrollIntoView({
behavior: 'smooth',
});
};
return (
<Tag id={slug} className="relative group">
<Link href={`#${slug}`}>
<a className="!no-underline" onClick={onClick}>
<div className="absolute -translate-x-2 group-hover:-translate-x-6 opacity-0 group-hover:opacity-100 transition">
#
</div>
{children}
</a>
</Link>
</Tag>
);
}
function Note({ children }) {
return <p className="bg-blue">{children}</p>;
}
// Custom components/renderers to pass to MDX.
// Since the MDX files aren't loaded by webpack, they have no knowledge of how
// to handle import statements. Instead, you must include components in scope
// here.
const components = {
a: CustomLink,
h1: ({ children }) => <H tag="h1">{children}</H>,
h2: ({ children }) => <H tag="h2">{children}</H>,
h3: ({ children }) => <H tag="h3">{children}</H>,
h4: ({ children }) => <H tag="h4">{children}</H>,
h5: ({ children }) => <H tag="h5">{children}</H>,
ul: ({ children }) => <ul className="list-disc list-outside">{children}</ul>,
code: WrapCode,
note: ({ children }) => (
<p className="bg-blue-50 border-l-4 border-blue-600 p-4 rounded">
<strong>note: </strong>
{children}
</p>
),
Head,
};
function NavLink({ href, children, active }) {
return (
<div
className={cn(
'hover:border-blue-600 w-full group border-l-4 transition',
{
'border-blue-600 bg-blue-50 text-black': active,
'hover:bg-blue-50 border-transparent': !active,
},
)}
>
<Link href={href}>
<a className="block w-full h-full p-4">{children}</a>
</Link>
</div>
);
}
function NavCaption({ children, className = '' }) {
return (
<div
className={clsx(
'p-4 flex-auto flex items-center text-xs font-medium text-gray-500 uppercase tracking-wider',
className,
)}
>
{children}
</div>
);
}
function SocialBar() {
return (
<div className="flex w-full px-4 space-x-4 py-2">
<a
title="GitHub"
target="_blank"
href="https://github.com/smeijer/next-runtime"
>
<GithubIcon className="" />
</a>
<a title="npm" target="_blank" href="https://npmjs.com/next-runtime">
<NpmIcon className="" />
</a>
<a title="Twitter" target="_blank" href="https://twitter.com/meijer_s">
<TwitterIcon className="" />
</a>
</div>
);
}
function Sidebar({ selected }) {
const [menuOpen, setMenuOpen] = useState(false);
return (
<div className="w-0 lg:w-80">
<div
className={cn(
'flex-none z-10 fixed top-0 left-0 bottom-0 lg:w-80 flex bg-opacity-25 bg-black',
{
'w-full': menuOpen,
'w-0': !menuOpen,
},
)}
onClick={() => {
setMenuOpen(false);
}}
>
<aside
className={cn(
'flex-none flex flex-col w-80 bg-white border-r border-gray-200 h-screen transition lg:translate-x-0',
{
'-translate-x-80': !menuOpen,
'translate-x-0': menuOpen,
},
)}
>
<h1 className="w-full mt-8 px-4 py-2 text-2xl font-light flex-none">
<Link href="/">next-runtime</Link>
</h1>
<div className="flex-none mb-4">
<SocialBar />
</div>
{/* be sure to add enough bottom padding for mobile 100vh trouble */}
<div className="flex-auto overflow-y-scroll pt-4 pb-20 relative">
{toc.map((entry, idx) =>
'caption' in entry ? (
<NavCaption
key={`${idx}-${entry.caption}`}
className={idx > 0 ? 'mt-8' : ''}
>
{entry.caption}
</NavCaption>
) : (
<NavLink
key={`${idx}-${entry.slug}`}
href={`/${entry.slug}`}
active={entry.slug === selected.slug}
>
{entry.title}
</NavLink>
),
)}
</div>
</aside>
</div>
<button
onClick={() => setMenuOpen((open) => !open)}
className="z-50 lg:hidden bg-gray-800 hover:bg-gray-900 text-white fixed w-16 h-16 shadow-lg rounded-full bottom-6 right-6 flex items-center justify-center focus:outline-none"
>
<HamburgerMenuIcon width="20" height="20" />
</button>
</div>
);
}
export default function DocsPage({ source, frontMatter, next, prev, page }) {
return (
<>
<SocialHead
title={`next-runtime — ${
frontMatter.pageTitle || frontMatter.title
}`.toLowerCase()}
description="All you need to handle POST requests, file uploads, and api requests, in Next.js getServerSideProps."
url={absoluteUrl(page.slug)}
/>
<div className="flex flex-col min-h-screen">
<div className="flex flex-auto w-full max-w-6xl mx-auto">
<Sidebar selected={page} />
<div className="overflow-x-hidden px-8 pb-16 mx-auto w-full max-w-[80ch]">
<h1 className="text-5xl tracking-tight font-light mt-8 mb-6 relative text-gray-900">
{frontMatter.title}
</h1>
<main className="flex-auto w-full prose mdx">
{frontMatter.description && (
<p className="pb-">{frontMatter.description}</p>
)}
<MDXRemote {...source} components={components} />
</main>
<div className="mt-16 pt-8 flex justify-between items-center text-blue-600">
{prev ? (
<Link href={`/${prev.slug}`}>
<a className="flex items-center px-4 py-2 rounded-lg hover:bg-blue-50">
<ChevronLeftIcon className="mr-2" />
{prev.title}
</a>
</Link>
) : (
<div />
)}
{next ? (
<Link href={`/${next.slug}`}>
<a className="flex items-center px-4 py-2 rounded-lg hover:bg-blue-50">
{next.title}
<ChevronRightIcon className="ml-2" />
</a>
</Link>
) : (
<div />
)}
</div>
<div className="mt-12 pt-8 flex justify-end items-center text-gray-700 border-t border-gray-200">
<a
className="flex items-center px-4 py-2 rounded-lg hover:opacity-60"
href={`https://github.com/smeijer/next-runtime/edit/main/docs/content/${page.slug}.mdx`}
>
<GithubCircleIcon className="w-5 h-5 mr-2" /> Edit on GitHub
</a>
</div>
</div>
</div>
</div>
</>
);
}
export const getStaticProps = async ({ params }) => {
const file = ['content', ...params.slug].join('/');
const source = fs.existsSync(file + '.mdx')
? fs.readFileSync(file + '.mdx')
: fs.readFileSync(path.join(file, 'index.mdx'));
const { content, data } = matter(source);
const mdxSource = await serialize(content, {
mdxOptions: {
remarkPlugins: [],
rehypePlugins: [],
},
scope: data,
});
const slug = params.slug.join('/');
const pages: Array<TocLink & { section: string }> = [];
let section;
for (const entry of toc) {
if ('caption' in entry) {
section = entry.caption;
continue;
}
pages.push({ ...entry, section });
}
const idx = pages.findIndex((entry) => entry.slug === slug);
const prev = pages[idx - 1] || null;
const page = pages[idx] || null;
const next = pages[idx + 1] || null;
// add sections
if (prev && prev.section !== page.section) {
prev.title = `${prev.section}: ${prev.title}`;
}
if (next && next.section !== page.section) {
next.title = `${next.section}: ${next.title}`;
}
return {
props: {
source: mdxSource,
frontMatter: data,
prev,
page,
next,
},
};
};
export const getStaticPaths = async () => {
const files = glob.sync('**/*.mdx', {
cwd: path.join(process.cwd(), 'content'),
});
const paths = files.map((path) => ({
params: {
slug: path
.replace(/\.mdx?$/, '')
.split('/')
.filter((x) => x !== 'index'),
},
}));
return {
paths,
fallback: false,
};
}; | the_stack |
import type { ScaleIdentity } from 'd3-scale';
import type { Axis } from 'd3-axis';
import type { Selection } from 'd3-selection';
// To be eventually replaced by type from @d3fc/d3fc-axis
interface AxisD3fc<Domain> extends Axis<Domain> {
tickCenterLabel(): boolean;
tickCenterLabel(tickCenterLabel: boolean): this;
}
export type Functor<T> = ((...args: any[]) => T);
type TypeOrFunctor<T> = T | Functor<T>;
type AnyFunction = (...args: any[]) => any;
export interface WebglPlotAreaComponent {
(d: any): any;
context(canvas: HTMLCanvasElement): this;
pixelRatio(pixelRatio: number): this;
xScale(scale: any): this;
yScale(scale: any): this;
}
export interface CanvasPlotAreaComponent {
(d: any): any;
context(canvas: HTMLCanvasElement): this;
xScale(scale: any): this;
yScale(scale: any): this;
}
export interface SvgPlotAreaComponent {
(d: any): any;
xScale(scale: any): this;
yScale(scale: any): this;
}
type Decorator = (container: Selection<any, any, any, any>, data: any, index: number) => void;
type PrefixProperties<T, Prefix extends string> = {
[Property in keyof T as `${Prefix}${Capitalize<string & Property>}`]: T[Property]
};
type AnyMethods<T> = {
[Property in keyof T]: T[Property] extends AnyFunction ? AnyFunction : T[Property]
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type NotStartsWith<K, TPrefix extends string> = K extends `${TPrefix}${infer _}` ? never : K;
type OmitPrefixes<T> = {[K in keyof T as NotStartsWith<K, 'range' | 'tickFormat'> ]: T[K]};
type XOrient = 'top' | 'bottom' | 'none';
type YOrient = 'left' | 'right' | 'none';
/**
* Cartesian Chart
*/
export type CartesianChart<XScale, YScale> = {
(selection: Selection<any, any, any, any>): void;
/**
* Returns the existing component.
*/
canvasPlotArea(): CanvasPlotAreaComponent | null;
/**
* Sets the component to render onto the canvas, and returns the Cartesian chart.
* For series that contain a very high number of data-points, rendering to canvas can reduce the rendering time and improve performance.
* For `canvasPlotArea` and `webglPlotArea`, the relevant context is automatically applied to the chart.
* @param component
*/
canvasPlotArea(component: CanvasPlotAreaComponent): CartesianChart<XScale, YScale>;
/**
* Returns a function that returns chartLabel.
*/
chartLabel(): Functor<string>;
/**
* If `label` is specified, sets the text for the given label, and returns the Cartesian chart.
* The `label` value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
* This can be useful if you are rendering multiple charts using a data join.
* @param label
*/
chartLabel(label: TypeOrFunctor<string>): CartesianChart<XScale, YScale>;
/**
* Returns the current decorator function.
*/
decorate(): Decorator;
/**
* Sets the decorator function to the specified, and returns the Cartesian chart.
* @param decorateFunc
*/
decorate(decorateFunc: Decorator): CartesianChart<XScale, YScale>;
/**
* Returns the existing component.
*/
svgPlotArea(): SvgPlotAreaComponent | null;
/**
* Sets the component to render onto the SVG, and returns the Cartesian chart.
* For components that require user-interaction, rendering to SVG can simplify their implementation.
* @param component
*/
svgPlotArea(component: SvgPlotAreaComponent): CartesianChart<XScale, YScale>;
/**
* Returns the current useDevicePixelRatio value.
*/
useDevicePixelRatio(): boolean;
/**
* Sets whether the Canvas / WebGL should be scaled based on the resolution of the display device, and returns the Cartesian chart.
* @param useDevicePixelRatio
*/
useDevicePixelRatio(useDevicePixelRatio: boolean): CartesianChart<XScale, YScale>;
/**
* Returns the existing component.
*/
webglPlotArea(): WebglPlotAreaComponent | null;
/**
* Sets the component to render, and returns the Cartesian chart.
* For `canvasPlotArea` and `webglPlotArea`, the relevant context is automatically applied to the chart.
* @param component
*/
webglPlotArea(component: WebglPlotAreaComponent): CartesianChart<XScale, YScale>;
/**
* Returns the x-axis height or null if not set.
*/
xAxisHeight(): Functor<string>;
/**
* If `height` is specified, sets the height for the x-axis, and returns the Cartesian chart.
* The value should be a string with units (e.g. "2em").
*
* The `height` value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
*
* This can be useful if you are rendering multiple charts using a data join.
* @param height
*/
xAxisHeight(height: TypeOrFunctor<string>): CartesianChart<XScale, YScale>;
/**
* Returns the current decorator function.
*/
xDecorate(): Decorator;
/**
* Sets the decorator function to the specified, and returns the Cartesian chart.
* @param decorateFunc
*/
xDecorate(decorateFunc: Decorator): CartesianChart<XScale, YScale>;
/**
* Returns a function that returns xLabel.
*/
xLabel(): Functor<string>;
/**
* If `label` is specified, sets the text for the given label, and returns the Cartesian chart.
* The `label` value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
* This can be useful if you are rendering multiple charts using a data join.
* @param label
*/
xLabel(label: TypeOrFunctor<string>): CartesianChart<XScale, YScale>;
/**
* Returns a function that returns the orientation.
*/
xOrient(): Functor<XOrient>;
/**
* Sets the orientation for the axis in the given direction, and returns the Cartesian chart.
* Valid values for `xOrient` are `"top"`, `"bottom"` or `"none"`.
* The value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
* This can be useful if you are rendering multiple charts using a data join.
* @param orient
*/
xOrient(orient: TypeOrFunctor<XOrient>): CartesianChart<XScale, YScale>;
/**
* Returns the y-axis width or null if not set.
*/
yAxisWidth(): Functor<string>;
/**
* If `width` is specified, sets the width for the y-axis, and returns the Cartesian chart.
* The value should be a string with units (e.g. "2em").
*
* The `width` value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
*
* This can be useful if you are rendering multiple charts using a data join.
* @param width
*/
yAxisWidth(width: TypeOrFunctor<string>): CartesianChart<XScale, YScale>;
/**
* Returns the current decorator function.
*/
yDecorate(): Decorator;
/**
* Sets the decorator function to the specified, and returns the Cartesian chart.
* @param decorateFunc
*/
yDecorate(decorateFunc: Decorator): CartesianChart<XScale, YScale>;
/**
* Returns a function that returns yLabel.
*/
yLabel(): Functor<string>;
/**
* If `label` is specified, sets the text for the given label, and returns the Cartesian chart.
* The `label` value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
* This can be useful if you are rendering multiple charts using a data join.
* @param label
*/
yLabel(label: TypeOrFunctor<string>): CartesianChart<XScale, YScale>;
/**
* Returns a function that returns the orientation.
*/
yOrient(): Functor<YOrient>;
/**
* Sets the orientation for the axis in the given direction, and returns the Cartesian chart.
* Valid values for `yOrient` are `"left"`, `"right"` or `"none"`.
* The value can either be a string, or a function that returns a string.
* If it is a function, it will be invoked with the data that is 'bound' to the chart.
* This can be useful if you are rendering multiple charts using a data join.
* @param orient
*/
yOrient(orient: TypeOrFunctor<YOrient>): CartesianChart<XScale, YScale>;
}
& AnyMethods<PrefixProperties<OmitPrefixes<XScale>, 'x'>>
& AnyMethods<PrefixProperties<OmitPrefixes<YScale>, 'y'>>
& AnyMethods<PrefixProperties<AxisD3fc<any>, 'x'>>
& AnyMethods<PrefixProperties<AxisD3fc<any>, 'y'>>;
export type Fallback<T> = T extends undefined ? ScaleIdentity : T;
export interface Scale {
range: any;
domain: any;
}
export interface CartesianChartConfigurationParameter<XScale, YScale> {
xScale?: XScale;
yScale?: YScale;
xAxis?: {
top?: any;
bottom?: any;
};
yAxis?: {
left?: any;
right?: any;
};
}
// -------------------------------------------------------------------------------
// Cartesian Chart Factory
// -------------------------------------------------------------------------------
/**
* Constructs a new Cartesian chart with the given scales and axis components.
* If xAxis is specified, it must be an object with the required x-axis factory function (top if xOrient="top" or bottom if xOrient="bottom").
* If yAxis is specified, it must be an object with the required y-axis factory function (left if yOrient="left" or right if yOrient="right").
* @param configuration
*/
export default function Cartesian<XScale extends Scale | undefined, YScale extends Scale | undefined>(configuration: CartesianChartConfigurationParameter<XScale, YScale>)
: CartesianChart<Fallback<XScale>, Fallback<YScale>>;
/**
* Constructs a new Cartesian chart with the given scales.
* @param xScale
* @param yScale
*/
export default function Cartesian<XScale extends Scale | undefined, YScale extends Scale | undefined>(xScale?: XScale, yScale?: YScale)
: CartesianChart<Fallback<XScale>, Fallback<YScale>>;
export { }; | the_stack |
import * as path from "path";
import * as fs from "fs";
import {toHex, isWordReg, isByteReg, Flag} from "z80-base";
/**
* Params that qualify as "byte-sized".
*/
const BYTE_PARAMS = new Set(["a", "b", "c", "d", "e", "h", "l", "nn", "ixh", "ixl", "iyh", "iyl"]);
/**
* Params that qualify as "word-sized".
*/
const WORD_PARAMS = new Set(["af", "bc", "de", "hl", "nnnn", "ix", "iy", "sp"]);
/**
* Indentation for generate blocks.
*/
const TAB = " ";
/**
* The two possible param sizes.
*/
enum DataWidth {
BYTE, WORD
}
/**
* Track the indentation level of code currently being generated.
*/
let indent = "";
function enter(): void {
indent += TAB;
}
function exit(): void {
indent = indent.substr(0, indent.length - TAB.length);
}
function addLine(output: string[], line: string): void {
if (line.length === 0) {
output.push("");
} else {
output.push(indent + line);
}
}
/**
* Some operations have conditions (e.g., "Z" to mean "if the value is zero").
* Generate the TypeScript "if" statement for it, or none if there's no condition.
*/
function addCondIf(output: string[], cond: string | undefined): void {
if (cond !== undefined) {
let not = cond.startsWith("n");
let flag = (not ? cond.substr(1) : cond).toUpperCase();
if (cond === "po") {
not = true;
flag = "P";
} else if (cond === "pe") {
not = false;
flag = "P";
} else if (cond === "p") {
not = true;
flag = "S";
} else if (cond === "m") {
not = false;
flag = "S";
}
addLine(output, "if ((z80.regs.f & Flag." + flag + ") " + (not ? "===" : "!==") + " 0) {");
enter();
}
}
/**
* Generate else statement for condition code. Returns whether there's a condition code.
*/
function addCondElse(output: string[], cond: string | undefined): boolean {
if (cond !== undefined) {
exit();
addLine(output, "} else {");
enter();
return true;
}
return false;
}
/**
* Finish the "if" block for a condition code.
*/
function addCondEndIf(output: string[], cond: string | undefined): void {
if (cond !== undefined) {
exit();
addLine(output, "}");
}
}
/**
* Given a parameter, determine its width, or undefined if it can't be determined
* (e.g., "(nnnn)").
*/
function determineParamWidth(param: string): DataWidth | undefined {
if (BYTE_PARAMS.has(param)) {
return DataWidth.BYTE;
}
if (WORD_PARAMS.has(param)) {
return DataWidth.WORD;
}
return undefined;
}
/**
* Given two parameters, determines the data width of the pair. At least one
* of them must indicate the width, and if both do, they must match.
*/
function determineDataWidth(param1: string, param2: string): DataWidth {
let dataWidth1 = determineParamWidth(param1);
let dataWidth2 = determineParamWidth(param2);
if (dataWidth1 === undefined) {
if (dataWidth2 === undefined) {
throw new Error(`Can't determine data width from "${param1}" and "${param2}"`);
}
return dataWidth2;
}
if (dataWidth2 !== undefined && dataWidth1 !== dataWidth2) {
throw new Error(`Mismatch of data width between "${param1}" and "${param2}"`);
}
return dataWidth1;
}
/**
* Generate 8-bit arithmetic code for the opcode and "A". The operand
* must already be in "value".
*/
function emitArith8(output: string[], opcode: "add" | "adc" | "sub" | "sbc"): void {
let addition = opcode.startsWith("a");
let op = addition ? "add" : "sub";
let opCap = addition ? "Add" : "Sub";
let carry = opcode.endsWith("c");
addLine(output, "let result = " + op + "16(z80.regs.a, value);");
if (carry) {
addLine(output, "if ((z80.regs.f & Flag.C) !== 0) {");
enter();
addLine(output, "result = " + (addition ? "inc" : "dec") + "16(result);");
exit();
addLine(output, "}");
}
addLine(output, "const lookup = (((z80.regs.a & 0x88) >> 3) |");
addLine(output, " ((value & 0x88) >> 2) |");
addLine(output, " ((result & 0x88) >> 1)) & 0xFF;");
addLine(output, "z80.regs.a = result & 0xFF;");
addLine(output, "z80.regs.f = (((result & 0x100) !== 0) ? Flag.C : 0) " +
(addition ? "" : "| Flag.N ") +
"| halfCarry" + opCap + "Table[lookup & 0x07] " + "" +
"| overflow" + opCap + "Table[lookup >> 4] " +
"| z80.sz53Table[z80.regs.a];");
}
/**
* Generate 16-bit arithmetic code for the opcode and "dest". The operand
* must already be in "value".
*/
function emitArith16(output: string[], opcode: "add" | "adc" | "sbc", dest: string): void {
let addition = opcode.startsWith("a");
let op = addition ? "+" : "-";
let carry = opcode.endsWith("c");
let mask = carry ? "0x8800" : "0x0800";
addLine(output, "let result = z80.regs." + dest + " " + op + " value;");
if (carry) {
addLine(output, "if ((z80.regs.f & Flag.C) !== 0) {");
enter();
addLine(output, "result " + op + "= 1;");
exit();
addLine(output, "}");
}
addLine(output, "const lookup = (((z80.regs." + dest + " & " + mask + ") >> 11) |");
addLine(output, " ((value & " + mask + ") >> 10) |");
addLine(output, " ((result & " + mask + ") >> 9)) & 0xFF;");
addLine(output, "z80.regs.memptr = inc16(z80.regs." + dest + ");");
addLine(output, "z80.regs." + dest + " = result & 0xFFFF;");
// Flags are set differently based on operation.
switch (opcode) {
case "add":
addLine(output, "z80.regs.f = (z80.regs.f & (Flag.V | Flag.Z | Flag.S)) | ((result & 0x10000) !== 0 ? Flag.C : 0) | ((result >> 8) & (Flag.X3 | Flag.X5)) | halfCarryAddTable[lookup];");
break;
case "adc":
addLine(output, "z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | overflowAddTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarryAddTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z);");
break;
case "sbc":
addLine(output, "z80.regs.f = ((result & 0x10000) !== 0 ? Flag.C : 0) | Flag.N | overflowSubTable[lookup >> 4] | ((result >> 8) & (Flag.X3 | Flag.X5 | Flag.S)) | halfCarrySubTable[lookup & 0x07] | (result !== 0 ? 0 : Flag.Z);");
break;
}
}
/**
* Handle 8-bit and 16-bit arithmetic operations.
*/
function handleArith(output: string[], opcode: "add" | "adc" | "sub" | "sbc", dest: string, src: string): void {
addLine(output, "let value: number;");
if (determineDataWidth(dest, src) == DataWidth.BYTE) {
if (src.startsWith("(") && src.endsWith(")")) {
const addr = src.substr(1, src.length - 2);
if (isWordReg(addr)) {
addLine(output, "value = z80.readByte(z80.regs." + addr + ");");
} else if (addr.endsWith("+dd")) {
const reg = addr.substr(0, addr.length - 3);
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = (z80.regs." + reg + " + signedByte(value)) & 0xFFFF;");
addLine(output, "value = z80.readByte(z80.regs.memptr);");
} else {
throw new Error("Unknown src address type: " + addr);
}
} else if (src === "nn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
} else {
addLine(output, "value = z80.regs." + src + ";");
}
if (dest === "a") {
emitArith8(output, opcode);
} else {
throw new Error("8-bit " + opcode + " must have A as destination");
}
} else {
// DataWidth.WORD.
if (opcode === "sub") {
throw new Error("SUB is not supported with 16 bits");
}
addLine(output, "z80.incTStateCount(7);");
if (isWordReg(src)) {
addLine(output, "value = z80.regs." + src + ";");
} else {
throw new Error("Unknown src type: " + src);
}
if (isWordReg(dest)) {
emitArith16(output, opcode, dest);
} else {
throw new Error("Unknown dest type: " + dest);
}
}
}
function handleCp(output: string[], src: string): void {
addLine(output, "let value: number;");
if (src.startsWith("(") && src.endsWith(")")) {
const addr = src.substr(1, src.length - 2);
if (isWordReg(addr)) {
addLine(output, "value = z80.readByte(z80.regs." + addr + ");");
} else if (addr.endsWith("+dd")) {
const reg = addr.substr(0, addr.length - 3);
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = (z80.regs." + reg + " + signedByte(value)) & 0xFFFF;");
addLine(output, "value = z80.readByte(z80.regs.memptr);");
} else {
throw new Error("Unknown src address type: " + addr);
}
} else if (src === "nn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
} else if (isByteReg(src)) {
addLine(output, "value = z80.regs." + src + ";");
} else {
throw new Error("Unknown src type: " + src);
}
addLine(output, "const diff = (z80.regs.a - value) & 0xFFFF;");
addLine(output, "const lookup = (((z80.regs.a & 0x88) >> 3) |");
addLine(output, " ((value & 0x88) >> 2) |");
addLine(output, " ((diff & 0x88) >> 1)) & 0xFF;");
addLine(output, "let f = Flag.N;");
addLine(output, "if ((diff & 0x100) != 0) f |= Flag.C;");
addLine(output, "if (diff == 0) f |= Flag.Z;");
addLine(output, "f |= halfCarrySubTable[lookup & 0x07];");
addLine(output, "f |= overflowSubTable[lookup >> 4];");
addLine(output, "f |= value & (Flag.X3 | Flag.X5);");
addLine(output, "f |= diff & Flag.S;");
addLine(output, "z80.regs.af = word(z80.regs.a, f);")
}
function handleEx(output: string[], op1: string, op2: string): void {
if (op2 === "af'") {
op2 = "afPrime";
}
addLine(output, "const rightValue = z80.regs." + op2 + ";");
if (op1 === "(sp)") {
addLine(output, "const leftValueL = z80.readByte(z80.regs.sp);");
addLine(output, "const leftValueH = z80.readByte(inc16(z80.regs.sp));");
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.writeByte(inc16(z80.regs.sp), hi(rightValue));");
addLine(output, "z80.writeByte(z80.regs.sp, lo(rightValue));");
addLine(output, "z80.incTStateCount(2);");
addLine(output, "z80.regs.memptr = word(leftValueH, leftValueL);");
addLine(output, "z80.regs." + op2 + " = word(leftValueH, leftValueL);");
} else {
addLine(output, "z80.regs." + op2 + " = z80.regs." + op1 + ";");
addLine(output, "z80.regs." + op1 + " = rightValue;");
}
}
function handleJpJrCall(output: string[], opcode: string, cond: string | undefined, dest: string): void {
if (dest === "nnnn") {
addLine(output, "z80.regs.memptr = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = word(z80.readByte(z80.regs.pc), z80.regs.memptr);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
}
addCondIf(output, cond);
if (opcode === "jr") {
addLine(output, "const offset = z80.readByte(z80.regs.pc);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = add16(z80.regs.pc, signedByte(offset));");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = z80.regs.pc;");
if (addCondElse(output, cond)) {
addLine(output, "z80.incTStateCount(3);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
}
} else {
if (opcode === "call") {
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.pushWord(z80.regs.pc);");
}
if (dest === "nnnn") {
addLine(output, "z80.regs.pc = z80.regs.memptr;");
} else if (isWordReg(dest)) {
addLine(output, "z80.regs.pc = z80.regs." + dest + ";");
} else {
throw new Error("Unknown " + opcode + " dest: " + dest);
}
}
addCondEndIf(output, cond);
}
function handleLd(output: string[], dest: string, src: string): void {
if (dest.includes("dd")) {
// Must fetch this first, before possible "nn" in src.
addLine(output, "const dd = z80.readByte(z80.regs.pc);");
if (isByteReg(src)) {
addLine(output, "z80.incTStateCount(5);");
}
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
}
addLine(output, "let value: number;");
if (determineDataWidth(dest, src) == DataWidth.BYTE) {
if (src.startsWith("(") && src.endsWith(")")) {
const addr = src.substr(1, src.length - 2);
if (isWordReg(addr)) {
if (addr === "bc" || addr === "de") {
addLine(output, "z80.regs.memptr = inc16(z80.regs." + addr + ");");
}
addLine(output, "value = z80.readByte(z80.regs." + addr + ");");
} else if (addr === "nnnn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "value = word(z80.readByte(z80.regs.pc), value);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = inc16(value);");
addLine(output, "value = z80.readByte(value);");
} else if (addr.endsWith("+dd")) {
const reg = addr.substr(0, addr.length - 3);
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = (z80.regs." + reg + " + signedByte(value)) & 0xFFFF;");
addLine(output, "value = z80.readByte(z80.regs.memptr);");
} else {
throw new Error("Unknown src address type: " + addr);
}
} else {
if (src === "nn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
if (dest.includes("dd")) {
addLine(output, "z80.incTStateCount(2);");
}
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
} else if (src === "r") {
addLine(output, "value = z80.regs.rCombined;");
} else {
addLine(output, "value = z80.regs." + src + ";");
}
}
if (src === "r" || src === "i" || dest === "r" || dest === "i") {
addLine(output, "z80.incTStateCount(1);");
}
if (dest.startsWith("(") && dest.endsWith(")")) {
const addr = dest.substr(1, dest.length - 2);
if (isWordReg(addr)) {
if (addr === "bc" || addr === "de") {
addLine(output, "z80.regs.memptr = word(z80.regs.a, inc16(z80.regs." + addr + "));");
}
addLine(output, "z80.writeByte(z80.regs." + addr + ", value);");
} else if (addr === "nnnn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "value = word(z80.readByte(z80.regs.pc), value);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = word(z80.regs.a, inc16(value));");
addLine(output, "z80.writeByte(value, z80.regs.a);");
} else if (addr.endsWith("+dd")) {
const reg = addr.substr(0, addr.length - 3);
// Value of "dd" is already in "dd" variable.
addLine(output, "z80.regs.memptr = (z80.regs." + reg + " + signedByte(dd)) & 0xFFFF;");
addLine(output, "z80.writeByte(z80.regs.memptr, value);")
} else {
throw new Error("Unknown dest address type: " + addr);
}
} else {
addLine(output, "z80.regs." + dest + " = value;");
if (src === "r" || src === "i") {
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53Table[z80.regs.a] | (z80.regs.iff2 ? Flag.V : 0);");
// TODO: Must clear the P flag on NMOS Z80s. See "iff2_read" in Fuse.
}
}
} else {
// DataWidth.WORD.
if (src.startsWith("(") && src.endsWith(")")) {
const addr = src.substr(1, src.length - 2);
if (addr === "nnnn") {
addLine(output, "let addr = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "addr = word(z80.readByte(z80.regs.pc), addr);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "value = z80.readByte(addr);");
addLine(output, "z80.regs.memptr = inc16(addr);");
addLine(output, "value = word(z80.readByte(z80.regs.memptr), value);");
} else {
throw new Error("Unknown src address type: " + addr);
}
} else {
if (src === "nnnn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "value = word(z80.readByte(z80.regs.pc), value);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
} else if (isWordReg(src)) {
addLine(output, "value = z80.regs." + src + ";");
if (isWordReg(dest) && (src === "hl" || src === "ix" || src === "iy")) {
addLine(output, "z80.incTStateCount(2);");
}
} else {
throw new Error("Unknown src type: " + src);
}
}
if (dest.startsWith("(") && dest.endsWith(")")) {
const addr = dest.substr(1, dest.length - 2);
if (addr === "nnnn") {
addLine(output, "let addr = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "addr = word(z80.readByte(z80.regs.pc), addr);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.writeByte(addr, lo(value));");
addLine(output, "addr = inc16(addr);");
addLine(output, "z80.regs.memptr = addr;");
addLine(output, "z80.writeByte(addr, hi(value));");
} else {
throw new Error("Unknown dest address type: " + addr);
}
} else {
if (isWordReg(dest)) {
addLine(output, "z80.regs." + dest + " = value;");
} else {
throw new Error("Unknown dest type: " + dest);
}
}
}
}
function handleLogic(output: string[], opcode: string, operand: string): void {
addLine(output, "let value: number;");
if (operand === "nn") {
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
} else if (operand === "(hl)") {
addLine(output, "value = z80.readByte(z80.regs.hl);");
} else if (operand === "(ix+dd)" || operand === "(iy+dd)") {
const reg = operand.substr(1, 2);
addLine(output, "value = z80.readByte(z80.regs.pc);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = (z80.regs." + reg + " + signedByte(value)) & 0xFFFF;");
addLine(output, "value = z80.readByte(z80.regs.memptr);");
} else if (isByteReg(operand)) {
addLine(output, "value = z80.regs." + operand + ";");
} else {
throw new Error("Unknown " + opcode + " operand " + operand);
}
const operator = opcode === "and" ? "&" : opcode === "or" ? "|" : "^";
addLine(output, "z80.regs.a " + operator + "= value;");
addLine(output, "z80.regs.f = z80.sz53pTable[z80.regs.a];");
if (opcode === "and") {
addLine(output, "z80.regs.f |= Flag.H;");
}
}
function handleOutiOutd(output: string[], decrement: boolean, repeat: boolean): void {
addLine(output, "z80.incTStateCount(1);");
addLine(output, "const value = z80.readByte(z80.regs.hl);");
addLine(output, "z80.regs.b = dec8(z80.regs.b);");
addLine(output, "z80.regs.memptr = " + (decrement ? "dec" : "inc") + "16(z80.regs.bc);");
addLine(output, "z80.writePort(z80.regs.bc, value);");
addLine(output, "z80.regs.hl = " + (decrement ? "dec" : "inc") + "16(z80.regs.hl);");
addLine(output, "const other = add8(value, z80.regs.l);");
addLine(output, "z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b];");
if (repeat) {
addLine(output, "if (z80.regs.b > 0) {");
enter();
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = add16(z80.regs.pc, -2);");
exit();
addLine(output, "}");
}
}
function handleIniInd(output: string[], decrement: boolean, repeat: boolean): void {
addLine(output, "z80.incTStateCount(1);");
addLine(output, "const value = z80.readPort(z80.regs.bc);");
addLine(output, "z80.writeByte(z80.regs.hl, value);");
addLine(output, "z80.regs.memptr = " + (decrement ? "dec" : "inc") + "16(z80.regs.bc);");
addLine(output, "z80.regs.b = dec8(z80.regs.b);");
addLine(output, "const other = " + (decrement ? "dec" : "inc") + "8(add8(value, z80.regs.c));");
addLine(output, "z80.regs.f = (value & 0x80 ? Flag.N : 0 ) | (other < value ? Flag.H | Flag.C : 0) | (z80.parityTable[(other & 0x07) ^ z80.regs.b] ? Flag.P : 0) | z80.sz53Table[z80.regs.b];");
if (repeat) {
addLine(output, "if (z80.regs.b > 0) {");
enter();
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = add16(z80.regs.pc, -2);");
exit();
addLine(output, "}");
}
addLine(output, "z80.regs.hl = " + (decrement ? "dec" : "inc") + "16(z80.regs.hl);");
}
function handleCpiCpd(output: string[], decrement: boolean, repeat: boolean): void {
addLine(output, "const value = z80.readByte(z80.regs.hl);");
addLine(output, "let diff = (z80.regs.a - value) & 0xFF;");
addLine(output, "const lookup = ((z80.regs.a & 0x08) >> 3) | ((value & 0x08) >> 2) | ((diff & 0x08) >> 1);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.bc = dec16(z80.regs.bc);");
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | (z80.regs.bc !== 0 ? Flag.V : 0) | Flag.N | halfCarrySubTable[lookup] | (diff !== 0 ? 0 : Flag.Z) | (diff & Flag.S);");
addLine(output, "if ((z80.regs.f & Flag.H) !== 0) diff = dec8(diff);");
addLine(output, "z80.regs.f |= (diff & Flag.X3) | (((diff & 0x02) !== 0) ? Flag.X5 : 0);");
if (repeat) {
addLine(output, "if ((z80.regs.f & (Flag.V | Flag.Z)) === Flag.V) {");
enter();
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = add16(z80.regs.pc, -2);");
addLine(output, "z80.regs.memptr = add16(z80.regs.pc, 1);");
exit();
addLine(output, "} else {");
enter();
addLine(output, "z80.regs.memptr = " + (decrement ? "dec" : "inc") + "16(z80.regs.memptr);");
exit();
addLine(output, "}");
} else {
addLine(output, "z80.regs.memptr = " + (decrement ? "dec" : "inc") + "16(z80.regs.memptr);");
}
addLine(output, "z80.regs.hl = " + (decrement ? "dec" : "inc") + "16(z80.regs.hl);");
}
function handleLdiLdd(output: string[], decrement: boolean, repeat: boolean): void {
addLine(output, "let value = z80.readByte(z80.regs.hl);");
addLine(output, "z80.writeByte(z80.regs.de, value);");
addLine(output, "z80.incTStateCount(2);");
addLine(output, "z80.regs.bc = dec16(z80.regs.bc);");
addLine(output, "value = add16(value, z80.regs.a);");
addLine(output, "z80.regs.f = (z80.regs.f & (Flag.C | Flag.Z | Flag.S)) | (z80.regs.bc !== 0 ? Flag.V : 0) | (value & Flag.X3) | ((value & 0x02) !== 0 ? Flag.X5 : 0)");
if (repeat) {
addLine(output, "if (z80.regs.bc !== 0) {");
enter();
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = add16(z80.regs.pc, -2);");
addLine(output, "z80.regs.memptr = add16(z80.regs.pc, 1);");
exit();
addLine(output, "}");
}
addLine(output, "z80.regs.hl = " + (decrement ? "dec" : "inc") + "16(z80.regs.hl);");
addLine(output, "z80.regs.de = " + (decrement ? "dec" : "inc") + "16(z80.regs.de);");
}
function handlePop(output: string[], reg: string): void {
addLine(output, "z80.regs." + reg + " = z80.popWord();");
}
function handlePush(output: string[], reg: string): void {
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.pushWord(z80.regs." + reg + ");");
}
function handleRet(output: string[], cond: string | undefined): void {
if (cond !== undefined) {
addLine(output, "z80.incTStateCount(1);");
}
addCondIf(output, cond);
addLine(output, "z80.regs.pc = z80.popWord();");
addLine(output, "z80.regs.memptr = z80.regs.pc;");
addCondEndIf(output, cond);
}
function handleRst(output: string[], rst: number): void {
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.pushWord(z80.regs.pc);");
addLine(output, "z80.regs.pc = 0x" + toHex(rst, 4)+ ";");
addLine(output, "z80.regs.memptr = z80.regs.pc;");
}
// Value to subtract is already in "value".
function emitSub(output: string[]): void {
addLine(output, "const diff = sub16(z80.regs.a, value);");
addLine(output, "const lookup = (((z80.regs.a & 0x88) >> 3) |");
addLine(output, " ((value & 0x88) >> 2) |");
addLine(output, " ((diff & 0x88) >> 1)) & 0xFF;");
addLine(output, "z80.regs.a = diff;");
addLine(output, "let f = Flag.N;");
addLine(output, "if ((diff & 0x100) != 0) f |= Flag.C;");
addLine(output, "f |= halfCarrySubTable[lookup & 0x07];");
addLine(output, "f |= overflowSubTable[lookup >> 4];");
addLine(output, "f |= z80.sz53Table[z80.regs.a];");
addLine(output, "z80.regs.f = f;");
}
function handleOut(output: string[], port: string, src: string): void {
if (port === "(nn)") {
if (src !== "a") {
throw new Error("When OUT to (nn), source must be A");
}
addLine(output, "const port = z80.readByte(z80.regs.pc);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = word(z80.regs.a, inc8(port));");
addLine(output, "z80.writePort(word(z80.regs.a, port), z80.regs.a);");
} else if (port === "(c)") {
let value: string;
if (src === "0") {
// TODO: apparently it's 0xFF if the Z80 is CMOS?!
value = "0x00";
} else if (isByteReg(src)) {
value = "z80.regs." + src;
} else {
throw new Error("Unknown source for OUT: " + src);
}
addLine(output, "z80.writePort(z80.regs.bc, " + value + ");");
addLine(output, "z80.regs.memptr = inc16(z80.regs.bc);");
} else {
throw new Error("Unknown port for OUT: " + port);
}
}
function handleIn(output: string[], dest: string, port: string): void {
if (port === "(nn)") {
if (dest !== "a") {
throw new Error("When IN from (nn), destination must be A");
}
addLine(output, "const port = word(z80.regs.a, z80.readByte(z80.regs.pc));");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.a = z80.readPort(port);");
addLine(output, "z80.regs.memptr = inc16(port);");
} else if (port === "(c)") {
if (!isByteReg(dest)) {
throw new Error("Unknown dest for IN: " + dest);
}
addLine(output, "z80.regs.memptr = inc16(z80.regs.bc);");
addLine(output, "z80.regs." + dest + " = z80.readPort(z80.regs.bc);");
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs." + dest + "];");
} else {
throw new Error("Unknown port for OUT: " + port);
}
}
// Return a tuple of bit value, C bitwise operator, and hex string to compare to.
// E.g., "set 5" would return [0x20, "|", "0x20"].
function getSetRes(opcode: "bit" | "set" | "res", bit: string): [number, string, string] {
let bitValue = 1 << parseInt(bit, 10);
let operator: string;
switch (opcode) {
case "bit":
operator = "&";
break;
case "set":
operator = "|";
break;
case "res":
operator = "&";
bitValue ^= 0xFF;
break;
}
let hexBit = "0x" + toHex(bitValue, 2);
return [bitValue, operator, hexBit];
}
function handleSetResBit(output: string[], opcode:"bit" | "set" | "res", bit: string, operand: string): void {
const [bitValue, operator, hexBit] = getSetRes(opcode, bit);
if (opcode === "bit") {
if (isByteReg(operand)) {
addLine(output, "const value = z80.regs." + operand + ";");
addLine(output, "const hiddenValue = value;");
} else if (operand === "(hl)") {
addLine(output, "const value = z80.readByte(z80.regs.hl);");
addLine(output, "const hiddenValue = hi(z80.regs.memptr);");
addLine(output, "z80.incTStateCount(1);");
} else if (operand.endsWith("+dd)")) {
const reg = operand.substr(1, 2);
addLine(output, "const value = z80.readByte(z80.regs.memptr);");
addLine(output, "const hiddenValue = hi(z80.regs.memptr);");
addLine(output, "z80.incTStateCount(1);");
}
addLine(output, "let f = (z80.regs.f & Flag.C) | Flag.H | (hiddenValue & (Flag.X3 | Flag.X5));");
addLine(output, "if ((value & " + hexBit + ") === 0) {");
enter();
addLine(output, "f |= Flag.P | Flag.Z;");
exit();
addLine(output, "}");
if (bitValue === 0x80) {
addLine(output, "if ((value & " + hexBit + ") !== 0) {");
enter();
addLine(output, "f |= Flag.S;");
exit();
addLine(output, "}");
}
addLine(output, "z80.regs.f = f;");
} else {
// set or res.
if (isByteReg(operand)) {
addLine(output, "z80.regs." + operand + " " + operator + "= " + hexBit + ";");
} else if (operand === "(hl)") {
addLine(output, "const value = z80.readByte(z80.regs.hl);");
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.writeByte(z80.regs.hl, value " + operator + " " + hexBit + ");");
} else if (operand.endsWith("+dd)")) {
addLine(output, "const value = z80.readByte(z80.regs.memptr);");
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.writeByte(z80.regs.memptr, value " + operator + " " + hexBit + ");");
}
}
}
function handleRotateShiftIncDec(output: string[], opcode: string, operand: string):void {
// Read operand.
addLine(output, "let value: number;");
if (isByteReg(operand) || isWordReg(operand)) {
addLine(output, "value = z80.regs." + operand + ";");
} else if (operand === "(hl)") {
addLine(output, "value = z80.readByte(z80.regs.hl);");
addLine(output, "z80.incTStateCount(1);");
} else if (operand.endsWith("+dd)")) {
if (opcode === "inc" || opcode === "dec") {
const reg = operand.substr(1, 2);
addLine(output, "const offset = z80.readByte(z80.regs.pc);");
addLine(output, "z80.incTStateCount(5);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
addLine(output, "z80.regs.memptr = add16(z80.regs." + reg + ", signedByte(offset));");
}
addLine(output, "value = z80.readByte(z80.regs.memptr);");
addLine(output, "z80.incTStateCount(1);");
} else {
throw new Error("Unknown operand for " + opcode + ": " + operand);
}
// Perform operation.
addLine(output, "const oldValue = value;");
switch (opcode) {
case "rl":
addLine(output, "value = ((value << 1) | ((z80.regs.f & Flag.C) !== 0 ? 1 : 0)) & 0xFF;");
break;
case "rlc":
addLine(output, "value = ((value << 1) | (value >> 7)) & 0xFF;");
break;
case "rr":
addLine(output, "value = (value >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0);");
break;
case "rrc":
addLine(output, "value = ((value >> 1) | (value << 7)) & 0xFF;");
break;
case "sla":
addLine(output, "value = (value << 1) & 0xFF;");
break;
case "sll":
addLine(output, "value = ((value << 1) | 0x01) & 0xFF;");
break;
case "sra":
addLine(output, "value = (value & 0x80) | (value >> 1);");
break;
case "srl":
addLine(output, "value = value >> 1;");
break;
case "inc":
case "dec":
if (isWordReg(operand)) {
addLine(output, "z80.incTStateCount(2);");
addLine(output, "value = " + opcode + "16(value);");
} else {
addLine(output, "value = " + opcode + "8(value);");
if (opcode === "dec") {
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x7F ? Flag.V : 0) | ((oldValue & 0x0F) !== 0 ? 0 : Flag.H) | Flag.N | z80.sz53Table[value];");
} else {
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | (value === 0x80 ? Flag.V : 0) | ((value & 0x0F) !== 0 ? 0 : Flag.H) | z80.sz53Table[value];");
}
}
break;
}
if (opcode !== "inc" && opcode !== "dec") {
// Which bit goes into the carry flag.
const bitIntoCarry = opcode.substr(1, 1) === "l" ? "0x80" : "0x01";
addLine(output, "z80.regs.f = ((oldValue & " + bitIntoCarry + ") !== 0 ? Flag.C : 0) | z80.sz53pTable[value];");
}
// Write operand.
if (isByteReg(operand) || isWordReg(operand)) {
addLine(output, "z80.regs." + operand + " = value;");
} else if (operand === "(hl)") {
addLine(output, "z80.writeByte(z80.regs.hl, value);");
} else if (operand.endsWith("+dd)")) {
addLine(output, "z80.writeByte(z80.regs.memptr, value);");
}
}
function handleDaa(output: string[]): void {
addLine(output, "let value = 0;");
addLine(output, "let carry = z80.regs.f & Flag.C;");
addLine(output, "if ((z80.regs.f & Flag.H) !== 0 || ((z80.regs.a & 0x0F) > 9)) {");
enter();
addLine(output, "value = 6; // Skip over hex digits in lower nybble.");
exit();
addLine(output, "}");
addLine(output, "if (carry !== 0 || z80.regs.a > 0x99) {");
enter();
addLine(output, "value |= 0x60; // Skip over hex digits in upper nybble.");
exit();
addLine(output, "}");
addLine(output, "if (z80.regs.a > 0x99) {");
enter();
addLine(output, "carry = Flag.C;");
exit();
addLine(output, "}");
addLine(output, "if ((z80.regs.f & Flag.N) !== 0) {");
enter();
emitArith8(output, "sub");
exit();
addLine(output, "} else {");
enter();
emitArith8(output, "add");
exit();
addLine(output, "}");
addLine(output, "z80.regs.f = (z80.regs.f & ~(Flag.C | Flag.P)) | carry | z80.parityTable[z80.regs.a];");
}
function handleRotateA(output: string[], opcode: string): void {
// Can't use "rr" etc. code here, the flags are set differently.
addLine(output, "const oldA = z80.regs.a;");
switch (opcode) {
case "rla":
addLine(output, "z80.regs.a = ((z80.regs.a << 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x01 : 0)) & 0xFF;");
break;
case "rra":
addLine(output, "z80.regs.a = (z80.regs.a >> 1) | ((z80.regs.f & Flag.C) !== 0 ? 0x80 : 0);");
break;
case "rlca":
addLine(output, "z80.regs.a = ((z80.regs.a >> 7) | (z80.regs.a << 1)) & 0xFF;");
break;
case "rrca":
addLine(output, "z80.regs.a = ((z80.regs.a >> 1) | (z80.regs.a << 7)) & 0xFF;");
break;
}
// Which bit goes into the carry flag.
const bitIntoCarry = opcode.substr(1, 1) === "l" ? "0x80" : "0x01";
addLine(output, "z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | ((oldA & " + bitIntoCarry + ") !== 0 ? Flag.C : 0);");
}
function generateDispatch(pathname: string, prefix: string): string {
const output: string[] = [];
// There are groups of opcodes that map to the same behavior. In the input
// file these are listed first, so we keep track of them in this list
// and created aliases after the real opcode has been generated.
let fallthroughOpcodes: number[] = [];
// Name of the TypeScript map to insert into.
const mapName = "decodeMap" + prefix.toUpperCase();
fs.readFileSync(pathname, "utf-8").split(/\r?\n/).forEach((line: string) => {
line = line.trim();
if (line.length === 0 || line.startsWith("#")) {
// Comment or empty line.
return;
}
const fields = line.split(/\s+/);
const numberString = fields.length >= 1 ? fields[0] : undefined;
const opcode = fields.length >= 2 ? fields[1].toLowerCase() : undefined;
const params = fields.length >= 3 ? fields[2].toLowerCase() : undefined;
const extra = fields.length >= 4 ? fields[3] : undefined;
if (fields.length > 4) {
throw new Error("Invalid opcode line: " + line);
}
if (numberString === undefined || numberString.length == 0 || !numberString.startsWith("0x")) {
throw new Error("Invalid number: " + line);
}
const number = parseInt(numberString, 16);
if (opcode === undefined) {
fallthroughOpcodes.push(number);
return;
}
addLine(output, mapName + ".set(0x" + toHex(number, 2) + ", (z80: Z80) => { // " + ((opcode || "") + " " + (params || "")).trim());
enter();
if (extra !== undefined) {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
const [reg, newOpcode] = params.split(",");
if (newOpcode === "set" || newOpcode === "res") {
const bit = extra.split(",")[0];
const [bitValue, operator, hexBit] = getSetRes(newOpcode, bit);
addLine(output, "z80.regs." + reg + " = z80.readByte(z80.regs.memptr) " + operator + " " + hexBit + ";");
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.writeByte(z80.regs.memptr, z80.regs." + reg + ");");
} else {
addLine(output, "z80.regs." + reg + " = z80.readByte(z80.regs.memptr);");
addLine(output, "z80.incTStateCount(1);");
addLine(output, "{");
enter();
handleRotateShiftIncDec(output, newOpcode, reg);
exit();
addLine(output, "}");
addLine(output, "z80.writeByte(z80.regs.memptr, z80.regs." + reg + ");");
}
} else {
switch (opcode) {
case "nop": {
// Nothing to do.
break;
}
case "add":
case "adc":
case "sub":
case "sbc": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
const parts = params.split(",");
if (parts.length !== 2) {
throw new Error(opcode + " requires two params: " + line);
}
const [dest, src] = parts;
handleArith(output, opcode, dest, src);
break;
}
case "cp": {
if (params === undefined) {
throw new Error("CP requires params: " + line);
}
const parts = params.split(",");
if (parts.length !== 1) {
throw new Error("CP requires one param: " + line);
}
handleCp(output, parts[0]);
break;
}
case "di": {
addLine(output, "z80.regs.iff1 = 0;");
addLine(output, "z80.regs.iff2 = 0;");
break;
}
case "ex": {
if (params === undefined) {
throw new Error("EX requires params: " + line);
}
const parts = params.split(",");
if (parts.length !== 2) {
throw new Error("EX requires two params: " + line);
}
const [op1, op2] = parts;
handleEx(output, op1, op2);
break;
}
case "ei": {
// TODO Wait another instruction before enabling interrupts.
addLine(output, "z80.regs.iff1 = 1;");
addLine(output, "z80.regs.iff2 = 1;");
break;
}
case "im": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
addLine(output, "z80.regs.im = " + parseInt(params, 10) + ";");
break;
}
case "reti":
case "retn": {
addLine(output, "z80.regs.iff1 = z80.regs.iff2;");
addLine(output, "z80.regs.pc = z80.popWord();");
addLine(output, "z80.regs.memptr = z80.regs.pc;");
break;
}
case "neg": {
addLine(output, "const value = z80.regs.a;");
addLine(output, "z80.regs.a = 0;");
emitSub(output);
break;
}
case "jr":
case "call":
case "jp": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
const parts = params.split(",");
let cond: string | undefined;
let dest: string;
if (parts.length == 2) {
cond = parts[0];
dest = parts[1];
} else {
cond = undefined;
dest = parts[0];
}
handleJpJrCall(output, opcode, cond, dest)
break;
}
case "ld": {
if (params === undefined) {
throw new Error("LD requires params: " + line);
}
const parts = params.split(",");
if (parts.length !== 2) {
throw new Error("LD requires two params: " + line);
}
const [dest, src] = parts;
handleLd(output, dest, src);
break;
}
case "or":
case "and":
case "xor": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
let operand: string;
const parts = params.split(",");
if (parts.length === 2) {
if (parts[0] === "a") {
operand = parts[1];
} else {
throw new Error("First operand of " + opcode + " must be A");
}
} else if (parts.length === 1) {
operand = parts[0];
} else {
throw new Error("LD requires two params: " + line);
}
handleLogic(output, opcode, operand);
break;
}
case "outi":
case "outd":
case "otir":
case "otdr": {
handleOutiOutd(output, opcode === "otdr" || opcode === "outd", opcode.endsWith("r"));
break;
}
case "ini":
case "ind":
case "inir":
case "indr": {
handleIniInd(output, opcode.startsWith("ind"), opcode.endsWith("r"));
break;
}
case "cpi":
case "cpd":
case "cpir":
case "cpdr": {
handleCpiCpd(output, opcode.startsWith("cpd"), opcode.endsWith("r"));
break;
}
case "ldi":
case "ldd":
case "ldir":
case "lddr": {
handleLdiLdd(output, opcode.startsWith("ldd"), opcode.endsWith("r"));
break;
}
case "pop": {
if (params === undefined) {
throw new Error("POP requires params: " + line);
}
const parts = params.split(",");
if (parts.length !== 1) {
throw new Error("POP requires one param: " + line);
}
handlePop(output, parts[0]);
break;
}
case "push": {
if (params === undefined) {
throw new Error("PUSH requires params: " + line);
}
const parts = params.split(",");
if (parts.length !== 1) {
throw new Error("PUSH requires one param: " + line);
}
handlePush(output, parts[0]);
break;
}
case "ret": {
handleRet(output, params);
break;
}
case "rst": {
if (params === undefined) {
throw new Error("RST requires params: " + line);
}
handleRst(output, parseInt(params, 16));
break;
}
case "out": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
const [port, src] = params.split(",");
handleOut(output, port, src);
break;
}
case "in": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
const [dest, port] = params.split(",");
handleIn(output, dest, port);
break;
}
case "rld": {
addLine(output, "const tmp = z80.readByte(z80.regs.hl);");
addLine(output, "z80.incTStateCount(4);");
addLine(output, "z80.writeByte(z80.regs.hl, ((tmp << 4) | (z80.regs.a & 0x0F)) & 0xFF);");
addLine(output, "z80.regs.a = (z80.regs.a & 0xF0) | (tmp >> 4);");
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.a];");
addLine(output, "z80.regs.memptr = inc16(z80.regs.hl);");
break;
}
case "rrd": {
addLine(output, "const tmp = z80.readByte(z80.regs.hl);");
addLine(output, "z80.incTStateCount(4);");
addLine(output, "z80.writeByte(z80.regs.hl, ((z80.regs.a << 4) | (tmp >> 4)) & 0xFF);");
addLine(output, "z80.regs.a = (z80.regs.a & 0xF0) | (tmp & 0x0F);");
addLine(output, "z80.regs.f = (z80.regs.f & Flag.C) | z80.sz53pTable[z80.regs.a];");
addLine(output, "z80.regs.memptr = inc16(z80.regs.hl);");
break;
}
case "exx": {
addLine(output, "let tmp: number;");
addLine(output, "tmp = z80.regs.bc; z80.regs.bc = z80.regs.bcPrime; z80.regs.bcPrime = tmp;");
addLine(output, "tmp = z80.regs.de; z80.regs.de = z80.regs.dePrime; z80.regs.dePrime = tmp;");
addLine(output, "tmp = z80.regs.hl; z80.regs.hl = z80.regs.hlPrime; z80.regs.hlPrime = tmp;");
break;
}
case "bit":
case "set":
case "res": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
const [bit, operand] = params.split(",");
handleSetResBit(output, opcode, bit, operand);
break;
}
case "rl":
case "rlc":
case "rr":
case "rrc":
case "sla":
case "sll":
case "sra":
case "srl":
case "inc":
case "dec": {
if (params === undefined) {
throw new Error(opcode + " requires params: " + line);
}
handleRotateShiftIncDec(output, opcode, params);
break;
}
case "halt": {
addLine(output, "z80.regs.halted = 1;");
addLine(output, "z80.regs.pc = dec16(z80.regs.pc);");
break;
}
case "ccf": {
addLine(output, "z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | ((z80.regs.f & Flag.C) !== 0 ? Flag.H : Flag.C) | (z80.regs.a & (Flag.X3 | Flag.X5));");
break;
}
case "scf": {
addLine(output, "z80.regs.f = (z80.regs.f & (Flag.P | Flag.Z | Flag.S)) | Flag.C | (z80.regs.a & (Flag.X3 | Flag.X5));");
break;
}
case "cpl": {
addLine(output, "z80.regs.a ^= 0xFF;");
addLine(output, "z80.regs.f = (z80.regs.f & (Flag.C | Flag.P | Flag.Z | Flag.S)) | (z80.regs.a & (Flag.X3 | Flag.X5)) | Flag.N | Flag.H;");
break;
}
case "daa": {
handleDaa(output);
break;
}
case "rla":
case "rra":
case "rlca":
case "rrca": {
handleRotateA(output, opcode);
break;
}
case "djnz": {
addLine(output, "z80.incTStateCount(1);");
addLine(output, "z80.regs.b = dec8(z80.regs.b);");
addLine(output, "if (z80.regs.b !== 0) {");
enter();
handleJpJrCall(output, "jr", undefined, "nn");
exit();
addLine(output, "} else {");
enter();
addLine(output, "z80.incTStateCount(3);");
addLine(output, "z80.regs.pc = inc16(z80.regs.pc);");
exit();
addLine(output, "}");
break;
}
case "shift":
if (params === undefined) {
throw new Error("Shift requires params: " + line);
}
addLine(output, "decode" + params.toUpperCase() + "(z80);");
break;
default:
console.log("Unhandled opcode in " + prefix + ": " + line);
break;
}
}
exit();
addLine(output, "});");
for (const fallthroughOpcode of fallthroughOpcodes) {
addLine(output, mapName + ".set(0x" + toHex(fallthroughOpcode, 2) + ", " + mapName + ".get(0x" + toHex(number, 2) + ") as OpcodeFunc);");
}
fallthroughOpcodes = [];
});
if (indent !== "") {
throw new Error("Unbalanced enter/exit");
}
return output.join("\n");
}
function generateSource(dispatchMap: Map<string, string>): void {
let template = fs.readFileSync("src/Decode.template.ts", "utf-8");
const preamble = "// Do not modify. This file was generated by GenerateOpcodes.ts.\n\n";
template = preamble + template;
for (const [prefix, dispatch] of dispatchMap.entries()) {
const key = "// DECODE_" + prefix.toUpperCase();
template = template.replace(key, dispatch);
}
fs.writeFileSync("src/Decode.ts", template);
}
function generateOpcodes(): void {
const opcodesDir = path.join(__dirname, "..");
// All the prefixes to parse.
const prefixes = ["base", "cb", "dd", "ddcb", "ed", "fd", "fdcb"];
// Map from prefix (like "ddcb") to the switch statement contents for it.
const dispatchMap = new Map<string, string>();
for (const prefix of prefixes) {
const dataPathname = path.join(opcodesDir, "opcodes_" + prefix + ".dat");
const dispatch = generateDispatch(dataPathname, prefix);
dispatchMap.set(prefix, dispatch);
}
generateSource(dispatchMap);
}
generateOpcodes(); | the_stack |
import { Scene, Mesh, Vector3, Color3, TransformNode, SceneLoader, ParticleSystem, Color4, Texture, PBRMetallicRoughnessMaterial, VertexBuffer, AnimationGroup, Sound, ExecuteCodeAction, ActionManager, Tags } from "@babylonjs/core";
import { Lantern } from "./lantern";
import { Player } from "./characterController";
export class Environment {
private _scene: Scene;
//Meshes
private _lanternObjs: Array<Lantern>; //array of lanterns that need to be lit
private _lightmtl: PBRMetallicRoughnessMaterial; // emissive texture for when lanterns are lit
//fireworks
private _fireworkObjs = [];
private _startFireworks: boolean = false;
constructor(scene: Scene) {
this._scene = scene;
this._lanternObjs = [];
//create emissive material for when lantern is lit
const lightmtl = new PBRMetallicRoughnessMaterial("lantern mesh light", this._scene);
lightmtl.emissiveTexture = new Texture("/textures/litLantern.png", this._scene, true, false);
lightmtl.emissiveColor = new Color3(0.8784313725490196, 0.7568627450980392, 0.6235294117647059);
this._lightmtl = lightmtl;
}
//What we do once the environment assets have been imported
//handles setting the necessary flags for collision and trigger meshes,
//sets up the lantern objects
//creates the firework particle systems for end-game
public async load() {
const assets = await this._loadAsset();
//Loop through all environment meshes that were imported
assets.allMeshes.forEach(m => {
m.receiveShadows = true;
m.checkCollisions = true;
if (m.name == "ground") { //dont check for collisions, dont allow for raycasting to detect it(cant land on it)
m.checkCollisions = false;
m.isPickable = false;
}
//areas that will use box collisions
if (m.name.includes("stairs") || m.name == "cityentranceground" || m.name == "fishingground.001" || m.name.includes("lilyflwr")) {
m.checkCollisions = false;
m.isPickable = false;
}
//collision meshes
if (m.name.includes("collision")) {
m.isVisible = false;
m.isPickable = true;
}
//trigger meshes
if (m.name.includes("Trigger")) {
m.isVisible = false;
m.isPickable = false;
m.checkCollisions = false;
}
});
//--LANTERNS--
assets.lantern.isVisible = false; //original mesh is not visible
//transform node to hold all lanterns
const lanternHolder = new TransformNode("lanternHolder", this._scene);
for (let i = 0; i < 22; i++) {
//Mesh Cloning
let lanternInstance = assets.lantern.clone("lantern" + i); //bring in imported lantern mesh & make clones
lanternInstance.isVisible = true;
lanternInstance.setParent(lanternHolder);
//Animation cloning
let animGroupClone = new AnimationGroup("lanternAnimGroup " + i);
animGroupClone.addTargetedAnimation(assets.animationGroups.targetedAnimations[0].animation, lanternInstance);
//Create the new lantern object
let newLantern = new Lantern(this._lightmtl, lanternInstance, this._scene, assets.env.getChildTransformNodes(false).find(m => m.name === "lantern " + i).getAbsolutePosition(), animGroupClone);
this._lanternObjs.push(newLantern);
}
//dispose of original mesh and animation group that were cloned
assets.lantern.dispose();
assets.animationGroups.dispose();
//--FIREWORKS--
for (let i = 0; i < 20; i++) {
this._fireworkObjs.push(new Firework(this._scene, i));
}
//before the scene renders, check to see if the fireworks have started
//if they have, trigger the firework sequence
this._scene.onBeforeRenderObservable.add(() => {
this._fireworkObjs.forEach(f => {
if (this._startFireworks) {
f._startFirework();
}
})
})
}
//Load all necessary meshes for the environment
public async _loadAsset() {
//loads game environment
const result = await SceneLoader.ImportMeshAsync(null, "./models/", "envSetting.glb", this._scene);
let env = result.meshes[0];
let allMeshes = env.getChildMeshes();
//loads lantern mesh
const res = await SceneLoader.ImportMeshAsync("", "./models/", "lantern.glb", this._scene);
//extract the actual lantern mesh from the root of the mesh that's imported, dispose of the root
let lantern = res.meshes[0].getChildren()[0];
lantern.parent = null;
res.meshes[0].dispose();
//--ANIMATION--
//extract animation from lantern (following demystifying animation groups video)
const importedAnims = res.animationGroups;
let animation = [];
animation.push(importedAnims[0].targetedAnimations[0].animation);
importedAnims[0].dispose();
//create a new animation group and target the mesh to its animation
let animGroup = new AnimationGroup("lanternAnimGroup");
animGroup.addTargetedAnimation(animation[0], res.meshes[1]);
return {
env: env,
allMeshes: allMeshes,
lantern: lantern as Mesh,
animationGroups: animGroup
}
}
public checkLanterns(player: Player) {
if (!this._lanternObjs[0].isLit) {
this._lanternObjs[0].setEmissiveTexture();
}
this._lanternObjs.forEach(lantern => {
player.mesh.actionManager.registerAction(
new ExecuteCodeAction(
{
trigger: ActionManager.OnIntersectionEnterTrigger,
parameter: lantern.mesh
},
() => {
//if the lantern is not lit, light it up & reset sparkler timer
if (!lantern.isLit && player.sparkLit) {
player.lanternsLit += 1;
lantern.setEmissiveTexture();
player.sparkReset = true;
player.sparkLit = true;
//SFX
player.lightSfx.play();
}
//if the lantern is lit already, reset the sparkler timer
else if (lantern.isLit) {
player.sparkReset = true;
player.sparkLit = true;
//SFX
player.sparkResetSfx.play();
}
}
)
);
});
}
}
class Firework {
private _scene:Scene;
//variables used by environment
private _emitter: Mesh;
private _rocket: ParticleSystem;
private _exploded: boolean = false;
private _height: number;
private _delay: number;
private _started: boolean;
//sounds
private _explosionSfx: Sound;
private _rocketSfx: Sound;
constructor(scene: Scene, i: number) {
this._scene = scene;
//Emitter for rocket of firework
const sphere = Mesh.CreateSphere("rocket", 4, 1, scene);
sphere.isVisible = false;
//the origin spawn point for all fireworks is determined by a TransformNode called "fireworks", this was placed in blender
let randPos = Math.random() * 10;
sphere.position = (new Vector3(scene.getTransformNodeByName("fireworks").getAbsolutePosition().x + randPos * -1, scene.getTransformNodeByName("fireworks").getAbsolutePosition().y, scene.getTransformNodeByName("fireworks").getAbsolutePosition().z));
this._emitter = sphere;
//Rocket particle system
let rocket = new ParticleSystem("rocket", 350, scene);
rocket.particleTexture = new Texture("./textures/flare.png", scene);
rocket.emitter = sphere;
rocket.emitRate = 20;
rocket.minEmitBox = new Vector3(0, 0, 0);
rocket.maxEmitBox = new Vector3(0, 0, 0);
rocket.color1 = new Color4(0.49, 0.57, 0.76);
rocket.color2 = new Color4(0.29, 0.29, 0.66);
rocket.colorDead = new Color4(0, 0, 0.2, 0.5);
rocket.minSize = 1;
rocket.maxSize = 1;
rocket.addSizeGradient(0, 1);
rocket.addSizeGradient(1, 0.01);
this._rocket = rocket;
//set how high the rocket will travel before exploding and how long it'll take before shooting the rocket
this._height = sphere.position.y + Math.random() * (15 + 4) + 4;
this._delay = (Math.random() * i + 1) * 60; //frame based
this._loadSounds();
}
private _explosions(position: Vector3): void {
//mesh that gets split into vertices
const explosion = Mesh.CreateSphere("explosion", 4, 1, this._scene);
explosion.isVisible = false;
explosion.position = position;
let emitter = explosion;
emitter.useVertexColors = true;
let vertPos = emitter.getVerticesData(VertexBuffer.PositionKind);
let vertNorms = emitter.getVerticesData(VertexBuffer.NormalKind);
let vertColors = [];
//for each vertex, create a particle system
for (let i = 0; i < vertPos.length; i += 3) {
let vertPosition = new Vector3(
vertPos[i], vertPos[i + 1], vertPos[i + 2]
)
let vertNormal = new Vector3(
vertNorms[i], vertNorms[i + 1], vertNorms[i + 2]
)
let r = Math.random();
let g = Math.random();
let b = Math.random();
let alpha = 1.0;
let color = new Color4(r, g, b, alpha);
vertColors.push(r);
vertColors.push(g);
vertColors.push(b);
vertColors.push(alpha);
//emitter for the particle system
let gizmo = Mesh.CreateBox("gizmo", 0.001, this._scene);
gizmo.position = vertPosition;
gizmo.parent = emitter;
let direction = vertNormal.normalize().scale(1); // move in the direction of the normal
//actual particle system for each exploding piece
const particleSys = new ParticleSystem("particles", 500, this._scene);
particleSys.particleTexture = new Texture("textures/flare.png", this._scene);
particleSys.emitter = gizmo;
particleSys.minEmitBox = new Vector3(1, 0, 0);
particleSys.maxEmitBox = new Vector3(1, 0, 0);
particleSys.minSize = .1;
particleSys.maxSize = .1;
particleSys.color1 = color;
particleSys.color2 = color;
particleSys.colorDead = new Color4(0, 0, 0, 0.0);
particleSys.minLifeTime = 1;
particleSys.maxLifeTime = 2;
particleSys.emitRate = 500;
particleSys.gravity = new Vector3(0, -9.8, 0);
particleSys.direction1 = direction;
particleSys.direction2 = direction;
particleSys.minEmitPower = 10;
particleSys.maxEmitPower = 13;
particleSys.updateSpeed = 0.01;
particleSys.targetStopDuration = 0.2;
particleSys.disposeOnStop = true;
particleSys.start();
}
emitter.setVerticesData(VertexBuffer.ColorKind, vertColors);
}
private _startFirework(): void {
if(this._started) { //if it's started, rocket flies up to height & then explodes
if (this._emitter.position.y >= this._height && !this._exploded) {
//--sounds--
this._explosionSfx.play();
//transition to the explosion particle system
this._exploded = !this._exploded; // don't allow for it to explode again
this._explosions(this._emitter.position);
this._emitter.dispose();
this._rocket.stop();
} else {
//move the rocket up
this._emitter.position.y += .2;
}
} else {
//use its delay to know when to shoot the firework
if(this._delay <= 0){
this._started = true;
//--sounds--
this._rocketSfx.play();
//start particle system
this._rocket.start();
} else {
this._delay--;
}
}
}
private _loadSounds(): void {
this._rocketSfx = new Sound("selection", "./sounds/fw_05.wav", this._scene, function () {
}, {
volume: 0.5,
});
this._explosionSfx = new Sound("selection", "./sounds/fw_03.wav", this._scene, function () {
}, {
volume: 0.5,
});
}
} | the_stack |
import BN from "bn.js";
import { EventData, PastEventOptions } from "web3-eth-contract";
export interface NFTTContract extends Truffle.Contract<NFTTInstance> {
"new"(meta?: Truffle.TransactionDetails): Promise<NFTTInstance>;
}
export interface Approval {
name: "Approval";
args: {
owner: string;
approved: string;
tokenId: BN;
0: string;
1: string;
2: BN;
};
}
export interface ApprovalForAll {
name: "ApprovalForAll";
args: {
owner: string;
operator: string;
approved: boolean;
0: string;
1: string;
2: boolean;
};
}
export interface OwnershipTransferred {
name: "OwnershipTransferred";
args: {
previousOwner: string;
newOwner: string;
0: string;
1: string;
};
}
export interface Transfer {
name: "Transfer";
args: {
from: string;
to: string;
tokenId: BN;
0: string;
1: string;
2: BN;
};
}
type AllEvents = Approval | ApprovalForAll | OwnershipTransferred | Transfer;
export interface NFTTInstance extends Truffle.ContractInstance {
/**
* See {IERC721-approve}.
*/
approve: {
(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* See {IERC721-balanceOf}.
*/
balanceOf(owner: string, txDetails?: Truffle.TransactionDetails): Promise<BN>;
/**
* See {IERC721-getApproved}.
*/
getApproved(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
/**
* See {IERC721-isApprovedForAll}.
*/
isApprovedForAll(
owner: string,
operator: string,
txDetails?: Truffle.TransactionDetails
): Promise<boolean>;
/**
* See {IERC721Metadata-name}.
*/
name(txDetails?: Truffle.TransactionDetails): Promise<string>;
/**
* Returns the address of the current owner.
*/
owner(txDetails?: Truffle.TransactionDetails): Promise<string>;
/**
* See {IERC721-ownerOf}.
*/
ownerOf(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
/**
* Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner.
*/
renounceOwnership: {
(txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(txDetails?: Truffle.TransactionDetails): Promise<void>;
sendTransaction(txDetails?: Truffle.TransactionDetails): Promise<string>;
estimateGas(txDetails?: Truffle.TransactionDetails): Promise<number>;
};
/**
* See {IERC721-setApprovalForAll}.
*/
setApprovalForAll: {
(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* See {IERC165-supportsInterface}.
*/
supportsInterface(
interfaceId: string,
txDetails?: Truffle.TransactionDetails
): Promise<boolean>;
/**
* See {IERC721Metadata-symbol}.
*/
symbol(txDetails?: Truffle.TransactionDetails): Promise<string>;
/**
* See {IERC721Metadata-tokenURI}.
*/
tokenURI(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
/**
* See {IERC721-transferFrom}.
*/
transferFrom: {
(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.
*/
transferOwnership: {
(newOwner: string, txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(
newOwner: string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
newOwner: string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
newOwner: string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
initialize: {
(txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(txDetails?: Truffle.TransactionDetails): Promise<void>;
sendTransaction(txDetails?: Truffle.TransactionDetails): Promise<string>;
estimateGas(txDetails?: Truffle.TransactionDetails): Promise<number>;
};
setBaseURI: {
(_newBaseURI: string, txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(
_newBaseURI: string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_newBaseURI: string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_newBaseURI: string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
getAllOnSale(
txDetails?: Truffle.TransactionDetails
): Promise<{ id: BN; price: BN; name: string; uri: string; sale: boolean }[]>;
/**
* sets maps token to its price
* @param _price unit256 token price Requirements: `tokenId` must exist `price` must be more than 0 `owner` must the msg.owner
* @param _sale bool token on sale
* @param _tokenId uint256 token ID (token number)
*/
setTokenSale: {
(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* sets maps token to its price
* @param _price uint256 token price Requirements: `tokenId` must exist `owner` must the msg.owner
* @param _tokenId uint256 token ID (token number)
*/
setTokenPrice: {
(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
tokenPrice(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<BN>;
tokenMeta(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<{ id: BN; price: BN; name: string; uri: string; sale: boolean }>;
/**
* purchase _tokenId
* @param _tokenId uint256 token ID (token number)
*/
purchaseToken: {
(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
mintCollectable: {
(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<BN>;
sendTransaction(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
methods: {
/**
* See {IERC721-approve}.
*/
approve: {
(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* See {IERC721-balanceOf}.
*/
balanceOf(
owner: string,
txDetails?: Truffle.TransactionDetails
): Promise<BN>;
/**
* See {IERC721-getApproved}.
*/
getApproved(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
/**
* See {IERC721-isApprovedForAll}.
*/
isApprovedForAll(
owner: string,
operator: string,
txDetails?: Truffle.TransactionDetails
): Promise<boolean>;
/**
* See {IERC721Metadata-name}.
*/
name(txDetails?: Truffle.TransactionDetails): Promise<string>;
/**
* Returns the address of the current owner.
*/
owner(txDetails?: Truffle.TransactionDetails): Promise<string>;
/**
* See {IERC721-ownerOf}.
*/
ownerOf(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
/**
* Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner.
*/
renounceOwnership: {
(txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(txDetails?: Truffle.TransactionDetails): Promise<void>;
sendTransaction(txDetails?: Truffle.TransactionDetails): Promise<string>;
estimateGas(txDetails?: Truffle.TransactionDetails): Promise<number>;
};
/**
* See {IERC721-setApprovalForAll}.
*/
setApprovalForAll: {
(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
operator: string,
approved: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* See {IERC165-supportsInterface}.
*/
supportsInterface(
interfaceId: string,
txDetails?: Truffle.TransactionDetails
): Promise<boolean>;
/**
* See {IERC721Metadata-symbol}.
*/
symbol(txDetails?: Truffle.TransactionDetails): Promise<string>;
/**
* See {IERC721Metadata-tokenURI}.
*/
tokenURI(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
/**
* See {IERC721-transferFrom}.
*/
transferFrom: {
(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.
*/
transferOwnership: {
(newOwner: string, txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(
newOwner: string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
newOwner: string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
newOwner: string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
initialize: {
(txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(txDetails?: Truffle.TransactionDetails): Promise<void>;
sendTransaction(txDetails?: Truffle.TransactionDetails): Promise<string>;
estimateGas(txDetails?: Truffle.TransactionDetails): Promise<number>;
};
setBaseURI: {
(_newBaseURI: string, txDetails?: Truffle.TransactionDetails): Promise<
Truffle.TransactionResponse<AllEvents>
>;
call(
_newBaseURI: string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_newBaseURI: string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_newBaseURI: string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
getAllOnSale(
txDetails?: Truffle.TransactionDetails
): Promise<
{ id: BN; price: BN; name: string; uri: string; sale: boolean }[]
>;
/**
* sets maps token to its price
* @param _price unit256 token price Requirements: `tokenId` must exist `price` must be more than 0 `owner` must the msg.owner
* @param _sale bool token on sale
* @param _tokenId uint256 token ID (token number)
*/
setTokenSale: {
(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_tokenId: number | BN | string,
_sale: boolean,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* sets maps token to its price
* @param _price uint256 token price Requirements: `tokenId` must exist `owner` must the msg.owner
* @param _tokenId uint256 token ID (token number)
*/
setTokenPrice: {
(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_tokenId: number | BN | string,
_price: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
tokenPrice(
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<BN>;
tokenMeta(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<{ id: BN; price: BN; name: string; uri: string; sale: boolean }>;
/**
* purchase _tokenId
* @param _tokenId uint256 token ID (token number)
*/
purchaseToken: {
(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
mintCollectable: {
(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<BN>;
sendTransaction(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
_owner: string,
_tokenURI: string,
_name: string,
_price: number | BN | string,
_sale: boolean,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* See {IERC721-safeTransferFrom}.
*/
"safeTransferFrom(address,address,uint256)": {
(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
from: string,
to: string,
tokenId: number | BN | string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
/**
* See {IERC721-safeTransferFrom}.
*/
"safeTransferFrom(address,address,uint256,bytes)": {
(
from: string,
to: string,
tokenId: number | BN | string,
_data: string,
txDetails?: Truffle.TransactionDetails
): Promise<Truffle.TransactionResponse<AllEvents>>;
call(
from: string,
to: string,
tokenId: number | BN | string,
_data: string,
txDetails?: Truffle.TransactionDetails
): Promise<void>;
sendTransaction(
from: string,
to: string,
tokenId: number | BN | string,
_data: string,
txDetails?: Truffle.TransactionDetails
): Promise<string>;
estimateGas(
from: string,
to: string,
tokenId: number | BN | string,
_data: string,
txDetails?: Truffle.TransactionDetails
): Promise<number>;
};
};
getPastEvents(event: string): Promise<EventData[]>;
getPastEvents(
event: string,
options: PastEventOptions,
callback: (error: Error, event: EventData) => void
): Promise<EventData[]>;
getPastEvents(event: string, options: PastEventOptions): Promise<EventData[]>;
getPastEvents(
event: string,
callback: (error: Error, event: EventData) => void
): Promise<EventData[]>;
} | the_stack |
import {Schema2Base, EntityGenerator} from './schema2base.js';
import {SchemaNode} from './schema2graph.js';
import {ParticleSpec} from '../runtime/arcs-types/particle-spec.js';
import {Type} from '../types/lib-types.js';
import {Dictionary} from '../utils/lib-utils.js';
// TODO(cypher1): Generate refinements and predicates for cpp
// https://github.com/PolymerLabs/arcs/issues/4884
// https://en.cppreference.com/w/cpp/keyword
// [...document.getElementsByClassName('wikitable')[0].getElementsByTagName('code')].map(x => x.innerHTML);
const keywords = [
'alignas', 'alignof', 'and', 'and_eq', 'asm', 'auto', 'bitand', 'bitor', 'bool', 'break', 'case',
'catch', 'char', 'char8_t', 'char16_t', 'char32_t', 'class', 'compl', 'concept', 'const',
'consteval', 'constexpr', 'const_cast', 'continue', 'co_await', 'co_return', 'co_yield',
'decltype', 'default', 'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit',
'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if', 'inline', 'int', 'long',
'mutable', 'namespace', 'new', 'noexcept', 'not', 'not_eq', 'nullptr', 'operator', 'or', 'or_eq',
'private', 'protected', 'public', 'reflexpr', 'register', 'reinterpret_cast', 'requires',
'return', 'short', 'signed', 'sizeof', 'static', 'static_assert', 'static_cast', 'struct',
'switch', 'template', 'this', 'thread_local', 'throw', 'true', 'try', 'typedef', 'typeid',
'typename', 'union', 'unsigned', 'using', 'virtual', 'void', 'volatile', 'wchar_t', 'while',
'xor', 'xor_eq'
];
function escapeIdentifier(name: string): string {
// TODO(cypher1): Check for complex keywords (e.g. cases where both 'final' and '_final' are keywords).
// TODO(cypher1): Check for name overlaps (e.g. 'final' and '_final' should not be escaped to the same identifier.
return (keywords.includes(name) ? '_' : '') + name;
}
export interface CppTypeInfo {
type: string;
defaultVal: string;
isString: boolean;
}
const typeMap: Dictionary<CppTypeInfo> = {
'Text': {type: 'std::string', defaultVal: ' = ""', isString: true},
'URL': {type: 'URL', defaultVal: ' = ""', isString: true},
'Number': {type: 'double', defaultVal: ' = 0', isString: false},
'BigInt': {type: 'long long', defaultVal: ' = 0', isString: false},
'Boolean': {type: 'bool', defaultVal: ' = false', isString: false},
'Reference': {type: '', defaultVal: ' = {}', isString: false},
};
function getTypeInfo(name: string): CppTypeInfo {
const info = typeMap[name];
if (!info) {
throw new Error(`Unhandled type '${name}' for cpp.`);
}
return info;
}
export class Schema2Cpp extends Schema2Base {
// test-CPP.file_Name.arcs -> test-cpp-file-name.h
outputName(baseName: string): string {
return baseName.toLowerCase().replace(/\.arcs$/, '').replace(/[._]/g, '-') + '.h';
}
fileHeader(outName: string): string {
const headerGuard = `_ARCS_${outName.toUpperCase().replace(/[-.]/g, '_')}`;
return `\
#ifndef ${headerGuard}
#define ${headerGuard}
// GENERATED CODE - DO NOT EDIT
#ifndef _ARCS_H
#error arcs.h must be included before entity class headers
#endif
`;
}
fileFooter(): string {
return '\n#endif\n';
}
getEntityGenerator(node: SchemaNode): EntityGenerator {
return new CppGenerator(node, this.namespace.replace(/\./g, '::'));
}
async generateParticleClass(particle: ParticleSpec): Promise<string> {
const particleName = particle.name;
const handleDecls: string[] = [];
for (const connection of particle.connections) {
const handleName = connection.name;
// Recursively compute the C++ type from the given Arcs type.
const getCppType = (type: Type, wrapEntityInSingleton: boolean = false): string => {
if (type.isCollectionType()) {
return `arcs::Collection<${getCppType(type.getContainedType())}>`;
} else if (wrapEntityInSingleton) {
return `arcs::Singleton<${getCppType(type)}>`;
} else if (type.isReference) {
return `arcs::Ref<${getCppType(type.getContainedType())}>`;
} else {
return `arcs::${particleName}_${this.upperFirst(connection.name)}`;
}
};
const handleType = getCppType(connection.type, /* wrapEntityInSingleton= */ true);
handleDecls.push(`${handleType} ${handleName}_{this, "${handleName}"};`);
}
return `
class Abstract${particleName} : public arcs::Particle {
protected:
${handleDecls.join('\n ')}
};
`;
}
async generateTestHarness(particle: ParticleSpec, nodes: SchemaNode[]): Promise<string> {
throw new Error('Test Harness generation is not available for CPP');
}
}
type AddFieldOptions = Readonly<{
field: string;
typeName: string;
isOptional?: boolean;
refClassName?: string;
refSchemaHash?: string;
listTypeInfo?: {name: string, refSchemaHash?: string, isInlineClass?: boolean};
isCollection?: boolean;
isInlineClass?: boolean;
}>;
class CppEntityDescriptor {
constructor(readonly node: SchemaNode) {
for (const [field, descriptor] of Object.entries(this.node.schema.fields)) {
// TODO(b/162033274): factor this into schema-field
if (descriptor.isPrimitive) {
if (['Text', 'URL', 'Number', 'BigInt', 'Boolean'].includes(descriptor.getType())) {
this.addField({field, typeName: descriptor.getType()});
} else {
throw new Error(`Schema type '${descriptor.getType()}' for field '${field}' is not supported`);
}
} else if (descriptor.isReference || (descriptor.isCollection && descriptor.getFieldType().isReference)) {
const schemaNode = this.node.refs.get(field);
this.addField({
field,
typeName: 'Reference',
isCollection: descriptor.isCollection,
refClassName: schemaNode.entityClassName,
refSchemaHash: schemaNode.hash,
});
} else if (descriptor.isCollection) {
const schema = descriptor.getFieldType();
if (schema.isPrimitive) {
this.addField({field, typeName: schema.getType(), isCollection: true});
} else {
throw new Error(`Schema kind '${schema.kind}' for field '${field}' is not supported`);
}
}
else {
throw new Error(`Schema kind '${descriptor.kind}' for field '${field}' is not supported`);
}
}
}
fields: string[] = [];
api: string[] = [];
ctor: string[] = [];
clone: string[] = [];
hash: string[] = [];
equals: string[] = [];
less: string[] = [];
decode: string[] = [];
encode: string[] = [];
stringify: string[] = [];
addField({field, typeName, refClassName, isOptional = false, isCollection = false}: AddFieldOptions) {
// Work around for schema2graph giving the Kotlin RefClassName.
if (refClassName !== undefined) {
refClassName = `${this.node.sources[0].fullName}_Ref`;
}
const fixed = escapeIdentifier(field);
const valid = `${field}_valid_`;
let {type, defaultVal, isString} = getTypeInfo(typeName);
if (typeName === 'Reference') {
type = `Ref<${refClassName}>`;
}
this.fields.push(`${type} ${field}_${defaultVal};`,
`bool ${valid} = false;`,
``);
if (typeName === 'Reference') {
this.api.push(`const ${type}& ${fixed}() const { return ${field}_; }`,
`void set_${field}(const ${refClassName}& value) { internal::Accessor::bind(&${field}_, value); }`);
} else {
const [r1, r2] = isString ? ['const ', '&'] : ['', ''];
this.api.push(`${r1}${type}${r2} ${fixed}() const { return ${field}_; }`,
`void set_${field}(${r1}${type}${r2} value) { ${field}_ = value; ${valid} = true; }`);
}
if (isOptional) {
this.api.push(`void clear_${field}() { ${field}_${defaultVal}; ${valid} = false; }`,
`bool has_${field}() const { return ${valid}; }`);
}
this.api.push(``);
this.ctor.push(`${field}_(other.${fixed}()), ${valid}(other.has_${field}())`);
this.clone.push(`clone.${field}_ = entity.${field}_;`,
`clone.${valid} = entity.${valid};`);
this.decode.push(`} else if (name == "${field}") {`,
` decoder.validate("${typeName[0]}");`,
` decoder.decode(entity->${field}_);`,
` entity->${valid} = true;`);
if (isOptional) {
this.equals.push(`(a.${valid} ? (b.${valid} && a.${field}_ == b.${field}_) : !b.${valid})`);
this.less.push(`if (a.${valid} != b.${valid}) {`,
` return !a.${valid};`);
} else {
this.equals.push(`(a.${field}_ == b.${field}_)`);
this.less.push(`if (0) {`);
}
if (isString) {
this.less.push(`} else if (int cmp = a.${field}_.compare(b.${field}_)) {`,
` return cmp < 0;`,
`}`);
} else {
this.less.push(`} else if (a.${field}_ != b.${field}_) {`,
` return a.${field}_ < b.${field}_;`,
`}`);
}
const ifValid = isOptional ? `if (entity.${valid}) ` : '';
this.hash.push(`${ifValid}internal::hash_combine(h, entity.${field}_);`);
this.encode.push(`${ifValid}encoder.encode("${field}:${typeName[0]}", entity.${field}_);`);
// For convenience, don't include unset required fields in the entity_to_str output.
this.stringify.push(`if (entity.${valid}) printer.add("${field}: ", entity.${field}_);`);
}
}
class CppGenerator implements EntityGenerator {
private descriptor: CppEntityDescriptor;
constructor(readonly node: SchemaNode, readonly namespace: string) {
this.descriptor = new CppEntityDescriptor(node);
}
typeFor(name: string): string {
return getTypeInfo(name).type;
}
defaultValFor(name: string): string {
return getTypeInfo(name).defaultVal;
}
generate(): string {
const name = this.node.fullEntityClassName;
const aliases = this.node.sources.map(s => s.fullName);
// Template constructor allows implicit type slicing from appropriately matching entities.
let templateCtor = '';
if (this.descriptor.ctor.length) {
templateCtor = `\
template<typename T>
${name}(const T& other) :
${this.descriptor.ctor.join(',\n ')}
{}
`;
}
// 'using' declarations for equivalent entity types.
let aliasComment = '';
let usingDecls = '';
if (aliases.length > 1) {
aliasComment = `\n// Aliased as ${aliases.join(', ')}`;
usingDecls = '\n' + aliases.map(a => `using ${a} = ${name};`).join('\n') + '\n';
}
// Schemas with no fields will always be equal.
if (this.descriptor.fields.length === 0) {
this.descriptor.equals.push('true');
}
return `\
namespace ${this.namespace} {
${aliasComment}
class ${name} {
public:
// Entities must be copied with arcs::clone_entity(), which will exclude the internal id.
// Move operations are ok (and will include the internal id).
${name}() = default;
${name}(${name}&&) = default;
${name}& operator=(${name}&&) = default;
${templateCtor}
${this.descriptor.api.join('\n ')}
// Equality ops compare internal ids and all data fields.
// Use arcs::fields_equal() to compare only the data fields.
bool operator==(const ${name}& other) const;
bool operator!=(const ${name}& other) const { return !(*this == other); }
// For STL containers.
friend bool operator<(const ${name}& a, const ${name}& b) {
if (int cmp = a._internal_id_.compare(b._internal_id_)) {
return cmp < 0;
}
${this.descriptor.less.join('\n ')}
return false;
}
protected:
// Allow private copying for use in Handles.
${name}(const ${name}&) = default;
${name}& operator=(const ${name}&) = default;
static const char* _schema_hash() { return "${this.node.hash}"; }
static const int _field_count = ${Object.entries(this.descriptor.node.schema.fields).length};
${this.descriptor.fields.join('\n ')}
std::string _internal_id_;
friend class Singleton<${name}>;
friend class Collection<${name}>;
friend class Ref<${name}>;
friend class internal::Accessor;
};
${usingDecls}
template<>
inline ${name} internal::Accessor::clone_entity(const ${name}& entity) {
${name} clone;
${this.descriptor.clone.join('\n ')}
return clone;
}
template<>
inline size_t internal::Accessor::hash_entity(const ${name}& entity) {
size_t h = 0;
internal::hash_combine(h, entity._internal_id_);
${this.descriptor.hash.join('\n ')}
return h;
}
template<>
inline bool internal::Accessor::fields_equal(const ${name}& a, const ${name}& b) {
return ${this.descriptor.equals.join(' && \n ')};
}
inline bool ${name}::operator==(const ${name}& other) const {
return _internal_id_ == other._internal_id_ && fields_equal(*this, other);
}
template<>
inline std::string internal::Accessor::entity_to_str(const ${name}& entity, const char* join, bool with_id) {
internal::StringPrinter printer;
if (with_id) {
printer.addId(entity._internal_id_);
}
${this.descriptor.stringify.join('\n ')}
return printer.result(join);
}
template<>
inline void internal::Accessor::decode_entity(${name}* entity, const char* str) {
if (str == nullptr) return;
internal::StringDecoder decoder(str);
decoder.decode(entity->_internal_id_);
decoder.validate("|");
for (int i = 0; !decoder.done() && i < ${name}::_field_count; i++) {
std::string name = decoder.upTo(':');
if (0) {
${this.descriptor.decode.join('\n ')}
} else {
// Ignore unknown fields until type slicing is fully implemented.
std::string typeChar = decoder.chomp(1);
if (typeChar == "T" || typeChar == "U") {
std::string s;
decoder.decode(s);
} else if (typeChar == "N") {
double d;
decoder.decode(d);
} else if (typeChar == "B") {
bool b;
decoder.decode(b);
}
i--;
}
decoder.validate("|");
}
}
template<>
inline std::string internal::Accessor::encode_entity(const ${name}& entity) {
internal::StringEncoder encoder;
encoder.encode("", entity._internal_id_);
${this.descriptor.encode.join('\n ')}
return encoder.result();
}
} // namespace ${this.namespace}
// For STL unordered associative containers. Entities will need to be std::move()-inserted.
template<>
struct std::hash<arcs::${name}> {
size_t operator()(const arcs::${name}& entity) const {
return arcs::hash_entity(entity);
}
};
`;
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Provides a Route53 record resource.
*
* ## Example Usage
* ### Simple routing policy
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const www = new aws.route53.Record("www", {
* zoneId: aws_route53_zone.primary.zone_id,
* name: "www.example.com",
* type: "A",
* ttl: "300",
* records: [aws_eip.lb.public_ip],
* });
* ```
* ### Weighted routing policy
* Other routing policies are configured similarly. See [AWS Route53 Developer Guide](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html) for details.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const www_dev = new aws.route53.Record("www-dev", {
* zoneId: aws_route53_zone.primary.zone_id,
* name: "www",
* type: "CNAME",
* ttl: "5",
* weightedRoutingPolicies: [{
* weight: 10,
* }],
* setIdentifier: "dev",
* records: ["dev.example.com"],
* });
* const www_live = new aws.route53.Record("www-live", {
* zoneId: aws_route53_zone.primary.zone_id,
* name: "www",
* type: "CNAME",
* ttl: "5",
* weightedRoutingPolicies: [{
* weight: 90,
* }],
* setIdentifier: "live",
* records: ["live.example.com"],
* });
* ```
* ### Alias record
* See [related part of AWS Route53 Developer Guide](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html)
* to understand differences between alias and non-alias records.
*
* TTL for all alias records is [60 seconds](https://aws.amazon.com/route53/faqs/#dns_failover_do_i_need_to_adjust),
* you cannot change this, therefore `ttl` has to be omitted in alias records.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const main = new aws.elb.LoadBalancer("main", {
* availabilityZones: ["us-east-1c"],
* listeners: [{
* instancePort: 80,
* instanceProtocol: "http",
* lbPort: 80,
* lbProtocol: "http",
* }],
* });
* const www = new aws.route53.Record("www", {
* zoneId: aws_route53_zone.primary.zone_id,
* name: "example.com",
* type: "A",
* aliases: [{
* name: main.dnsName,
* zoneId: main.zoneId,
* evaluateTargetHealth: true,
* }],
* });
* ```
* ### NS and SOA Record Management
*
* When creating Route 53 zones, the `NS` and `SOA` records for the zone are automatically created. Enabling the `allowOverwrite` argument will allow managing these records in a single deployment without the requirement for `import`.
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const exampleZone = new aws.route53.Zone("exampleZone", {});
* const exampleRecord = new aws.route53.Record("exampleRecord", {
* allowOverwrite: true,
* name: "test.example.com",
* ttl: 172800,
* type: "NS",
* zoneId: exampleZone.zoneId,
* records: [
* exampleZone.nameServers[0],
* exampleZone.nameServers[1],
* exampleZone.nameServers[2],
* exampleZone.nameServers[3],
* ],
* });
* ```
*
* ## Import
*
* Route53 Records can be imported using ID of the record, which is the zone identifier, record name, and record type, separated by underscores (`_`). e.g.
*
* ```sh
* $ pulumi import aws:route53/record:Record myrecord Z4KAPRWWNC7JR_dev.example.com_NS
* ```
*
* If the record also contains a delegated set identifier, it can be appended
*
* ```sh
* $ pulumi import aws:route53/record:Record myrecord Z4KAPRWWNC7JR_dev.example.com_NS_dev
* ```
*/
export class Record extends pulumi.CustomResource {
/**
* Get an existing Record 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?: RecordState, opts?: pulumi.CustomResourceOptions): Record {
return new Record(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:route53/record:Record';
/**
* Returns true if the given object is an instance of Record. 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 Record {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Record.__pulumiType;
}
/**
* An alias block. Conflicts with `ttl` & `records`.
* Alias record documented below.
*/
public readonly aliases!: pulumi.Output<outputs.route53.RecordAlias[] | undefined>;
/**
* Allow creation of this record to overwrite an existing record, if any. This does not affect the ability to update the record using this provider and does not prevent other resources within this provider or manual Route 53 changes outside this provider from overwriting this record. `false` by default. This configuration is not recommended for most environments.
*/
public readonly allowOverwrite!: pulumi.Output<boolean>;
/**
* A block indicating the routing behavior when associated health check fails. Conflicts with any other routing policy. Documented below.
*/
public readonly failoverRoutingPolicies!: pulumi.Output<outputs.route53.RecordFailoverRoutingPolicy[] | undefined>;
/**
* [FQDN](https://en.wikipedia.org/wiki/Fully_qualified_domain_name) built using the zone domain and `name`.
*/
public /*out*/ readonly fqdn!: pulumi.Output<string>;
/**
* A block indicating a routing policy based on the geolocation of the requestor. Conflicts with any other routing policy. Documented below.
*/
public readonly geolocationRoutingPolicies!: pulumi.Output<outputs.route53.RecordGeolocationRoutingPolicy[] | undefined>;
/**
* The health check the record should be associated with.
*/
public readonly healthCheckId!: pulumi.Output<string | undefined>;
/**
* A block indicating a routing policy based on the latency between the requestor and an AWS region. Conflicts with any other routing policy. Documented below.
*/
public readonly latencyRoutingPolicies!: pulumi.Output<outputs.route53.RecordLatencyRoutingPolicy[] | undefined>;
/**
* Set to `true` to indicate a multivalue answer routing policy. Conflicts with any other routing policy.
*/
public readonly multivalueAnswerRoutingPolicy!: pulumi.Output<boolean | undefined>;
/**
* DNS domain name for a CloudFront distribution, S3 bucket, ELB, or another resource record set in this hosted zone.
*/
public readonly name!: pulumi.Output<string>;
/**
* A string list of records. To specify a single record value longer than 255 characters such as a TXT record for DKIM, add `\"\"` inside the configuration string (e.g. `"first255characters\"\"morecharacters"`).
*/
public readonly records!: pulumi.Output<string[] | undefined>;
/**
* Unique identifier to differentiate records with routing policies from one another. Required if using `failover`, `geolocation`, `latency`, or `weighted` routing policies documented below.
*/
public readonly setIdentifier!: pulumi.Output<string | undefined>;
/**
* The TTL of the record.
*/
public readonly ttl!: pulumi.Output<number | undefined>;
/**
* `PRIMARY` or `SECONDARY`. A `PRIMARY` record will be served if its healthcheck is passing, otherwise the `SECONDARY` will be served. See http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html#dns-failover-failover-rrsets
*/
public readonly type!: pulumi.Output<string>;
/**
* A block indicating a weighted routing policy. Conflicts with any other routing policy. Documented below.
*/
public readonly weightedRoutingPolicies!: pulumi.Output<outputs.route53.RecordWeightedRoutingPolicy[] | undefined>;
/**
* Hosted zone ID for a CloudFront distribution, S3 bucket, ELB, or Route 53 hosted zone. See `resource_elb.zone_id` for example.
*/
public readonly zoneId!: pulumi.Output<string>;
/**
* Create a Record 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: RecordArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: RecordArgs | RecordState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as RecordState | undefined;
inputs["aliases"] = state ? state.aliases : undefined;
inputs["allowOverwrite"] = state ? state.allowOverwrite : undefined;
inputs["failoverRoutingPolicies"] = state ? state.failoverRoutingPolicies : undefined;
inputs["fqdn"] = state ? state.fqdn : undefined;
inputs["geolocationRoutingPolicies"] = state ? state.geolocationRoutingPolicies : undefined;
inputs["healthCheckId"] = state ? state.healthCheckId : undefined;
inputs["latencyRoutingPolicies"] = state ? state.latencyRoutingPolicies : undefined;
inputs["multivalueAnswerRoutingPolicy"] = state ? state.multivalueAnswerRoutingPolicy : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["records"] = state ? state.records : undefined;
inputs["setIdentifier"] = state ? state.setIdentifier : undefined;
inputs["ttl"] = state ? state.ttl : undefined;
inputs["type"] = state ? state.type : undefined;
inputs["weightedRoutingPolicies"] = state ? state.weightedRoutingPolicies : undefined;
inputs["zoneId"] = state ? state.zoneId : undefined;
} else {
const args = argsOrState as RecordArgs | undefined;
if ((!args || args.name === undefined) && !opts.urn) {
throw new Error("Missing required property 'name'");
}
if ((!args || args.type === undefined) && !opts.urn) {
throw new Error("Missing required property 'type'");
}
if ((!args || args.zoneId === undefined) && !opts.urn) {
throw new Error("Missing required property 'zoneId'");
}
inputs["aliases"] = args ? args.aliases : undefined;
inputs["allowOverwrite"] = args ? args.allowOverwrite : undefined;
inputs["failoverRoutingPolicies"] = args ? args.failoverRoutingPolicies : undefined;
inputs["geolocationRoutingPolicies"] = args ? args.geolocationRoutingPolicies : undefined;
inputs["healthCheckId"] = args ? args.healthCheckId : undefined;
inputs["latencyRoutingPolicies"] = args ? args.latencyRoutingPolicies : undefined;
inputs["multivalueAnswerRoutingPolicy"] = args ? args.multivalueAnswerRoutingPolicy : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["records"] = args ? args.records : undefined;
inputs["setIdentifier"] = args ? args.setIdentifier : undefined;
inputs["ttl"] = args ? args.ttl : undefined;
inputs["type"] = args ? args.type : undefined;
inputs["weightedRoutingPolicies"] = args ? args.weightedRoutingPolicies : undefined;
inputs["zoneId"] = args ? args.zoneId : undefined;
inputs["fqdn"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Record.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Record resources.
*/
export interface RecordState {
/**
* An alias block. Conflicts with `ttl` & `records`.
* Alias record documented below.
*/
aliases?: pulumi.Input<pulumi.Input<inputs.route53.RecordAlias>[]>;
/**
* Allow creation of this record to overwrite an existing record, if any. This does not affect the ability to update the record using this provider and does not prevent other resources within this provider or manual Route 53 changes outside this provider from overwriting this record. `false` by default. This configuration is not recommended for most environments.
*/
allowOverwrite?: pulumi.Input<boolean>;
/**
* A block indicating the routing behavior when associated health check fails. Conflicts with any other routing policy. Documented below.
*/
failoverRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordFailoverRoutingPolicy>[]>;
/**
* [FQDN](https://en.wikipedia.org/wiki/Fully_qualified_domain_name) built using the zone domain and `name`.
*/
fqdn?: pulumi.Input<string>;
/**
* A block indicating a routing policy based on the geolocation of the requestor. Conflicts with any other routing policy. Documented below.
*/
geolocationRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordGeolocationRoutingPolicy>[]>;
/**
* The health check the record should be associated with.
*/
healthCheckId?: pulumi.Input<string>;
/**
* A block indicating a routing policy based on the latency between the requestor and an AWS region. Conflicts with any other routing policy. Documented below.
*/
latencyRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordLatencyRoutingPolicy>[]>;
/**
* Set to `true` to indicate a multivalue answer routing policy. Conflicts with any other routing policy.
*/
multivalueAnswerRoutingPolicy?: pulumi.Input<boolean>;
/**
* DNS domain name for a CloudFront distribution, S3 bucket, ELB, or another resource record set in this hosted zone.
*/
name?: pulumi.Input<string>;
/**
* A string list of records. To specify a single record value longer than 255 characters such as a TXT record for DKIM, add `\"\"` inside the configuration string (e.g. `"first255characters\"\"morecharacters"`).
*/
records?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Unique identifier to differentiate records with routing policies from one another. Required if using `failover`, `geolocation`, `latency`, or `weighted` routing policies documented below.
*/
setIdentifier?: pulumi.Input<string>;
/**
* The TTL of the record.
*/
ttl?: pulumi.Input<number>;
/**
* `PRIMARY` or `SECONDARY`. A `PRIMARY` record will be served if its healthcheck is passing, otherwise the `SECONDARY` will be served. See http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html#dns-failover-failover-rrsets
*/
type?: pulumi.Input<string | enums.route53.RecordType>;
/**
* A block indicating a weighted routing policy. Conflicts with any other routing policy. Documented below.
*/
weightedRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordWeightedRoutingPolicy>[]>;
/**
* Hosted zone ID for a CloudFront distribution, S3 bucket, ELB, or Route 53 hosted zone. See `resource_elb.zone_id` for example.
*/
zoneId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Record resource.
*/
export interface RecordArgs {
/**
* An alias block. Conflicts with `ttl` & `records`.
* Alias record documented below.
*/
aliases?: pulumi.Input<pulumi.Input<inputs.route53.RecordAlias>[]>;
/**
* Allow creation of this record to overwrite an existing record, if any. This does not affect the ability to update the record using this provider and does not prevent other resources within this provider or manual Route 53 changes outside this provider from overwriting this record. `false` by default. This configuration is not recommended for most environments.
*/
allowOverwrite?: pulumi.Input<boolean>;
/**
* A block indicating the routing behavior when associated health check fails. Conflicts with any other routing policy. Documented below.
*/
failoverRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordFailoverRoutingPolicy>[]>;
/**
* A block indicating a routing policy based on the geolocation of the requestor. Conflicts with any other routing policy. Documented below.
*/
geolocationRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordGeolocationRoutingPolicy>[]>;
/**
* The health check the record should be associated with.
*/
healthCheckId?: pulumi.Input<string>;
/**
* A block indicating a routing policy based on the latency between the requestor and an AWS region. Conflicts with any other routing policy. Documented below.
*/
latencyRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordLatencyRoutingPolicy>[]>;
/**
* Set to `true` to indicate a multivalue answer routing policy. Conflicts with any other routing policy.
*/
multivalueAnswerRoutingPolicy?: pulumi.Input<boolean>;
/**
* DNS domain name for a CloudFront distribution, S3 bucket, ELB, or another resource record set in this hosted zone.
*/
name: pulumi.Input<string>;
/**
* A string list of records. To specify a single record value longer than 255 characters such as a TXT record for DKIM, add `\"\"` inside the configuration string (e.g. `"first255characters\"\"morecharacters"`).
*/
records?: pulumi.Input<pulumi.Input<string>[]>;
/**
* Unique identifier to differentiate records with routing policies from one another. Required if using `failover`, `geolocation`, `latency`, or `weighted` routing policies documented below.
*/
setIdentifier?: pulumi.Input<string>;
/**
* The TTL of the record.
*/
ttl?: pulumi.Input<number>;
/**
* `PRIMARY` or `SECONDARY`. A `PRIMARY` record will be served if its healthcheck is passing, otherwise the `SECONDARY` will be served. See http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html#dns-failover-failover-rrsets
*/
type: pulumi.Input<string | enums.route53.RecordType>;
/**
* A block indicating a weighted routing policy. Conflicts with any other routing policy. Documented below.
*/
weightedRoutingPolicies?: pulumi.Input<pulumi.Input<inputs.route53.RecordWeightedRoutingPolicy>[]>;
/**
* Hosted zone ID for a CloudFront distribution, S3 bucket, ELB, or Route 53 hosted zone. See `resource_elb.zone_id` for example.
*/
zoneId: pulumi.Input<string>;
} | the_stack |
import { ObjectId } from "bson";
import chalk from "chalk";
import * as path from "path";
import { TSBuffer } from 'tsbuffer';
import { Counter, Flow, getCustomObjectIdTypes, MsgHandlerManager, MsgService, ParsedServerInput, ServiceMap, ServiceMapUtil, TransportDataUtil } from 'tsrpc-base-client';
import { ApiReturn, ApiServiceDef, BaseServiceType, Logger, ServerOutputData, ServiceProto, TsrpcError, TsrpcErrorType } from 'tsrpc-proto';
import { ApiCallInner } from "../inner/ApiCallInner";
import { InnerConnection } from "../inner/InnerConnection";
import { TerminalColorLogger } from '../models/TerminalColorLogger';
import { ApiCall } from './ApiCall';
import { BaseConnection } from './BaseConnection';
import { MsgCall } from './MsgCall';
/**
* Abstract base class for TSRPC Server.
* Implement on a transportation protocol (like HTTP WebSocket) by extend it.
* @typeParam ServiceType - `ServiceType` from generated `proto.ts`
*/
export abstract class BaseServer<ServiceType extends BaseServiceType = BaseServiceType>{
abstract readonly ApiCallClass: { new(options: any): ApiCall };
abstract readonly MsgCallClass: { new(options: any): MsgCall };
/**
* Start the server
* @throws
*/
abstract start(): Promise<void>;
/**
* Stop server immediately, not waiting for the requests ending.
*/
abstract stop(): Promise<void>;
protected _status: ServerStatus = ServerStatus.Closed;
get status(): ServerStatus {
return this._status;
}
// 配置及其衍生项
readonly proto: ServiceProto<ServiceType>;
readonly options: BaseServerOptions<ServiceType>;
readonly tsbuffer: TSBuffer;
readonly serviceMap: ServiceMap;
readonly logger: Logger;
protected _connIdCounter = new Counter(1);
/**
* Flow is a specific concept created by TSRPC family.
* All pre-flow can interrupt latter behaviours.
* All post-flow can NOT interrupt latter behaviours.
*/
readonly flows = {
// Conn Flows
/** After the connection is created */
postConnectFlow: new Flow<BaseConnection<ServiceType>>(),
/** After the connection is disconnected */
postDisconnectFlow: new Flow<{ conn: BaseConnection<ServiceType>, reason?: string }>(),
// Buffer Flows
/**
* Before processing the received buffer, usually be used to encryption / decryption.
* Return `null | undefined` would ignore the buffer.
*/
preRecvBufferFlow: new Flow<{ conn: BaseConnection<ServiceType>, buf: Uint8Array }>(),
/**
* Before send out buffer to network, usually be used to encryption / decryption.
* Return `null | undefined` would not send the buffer.
*/
preSendBufferFlow: new Flow<{ conn: BaseConnection<ServiceType>, buf: Uint8Array, call?: ApiCall }>(),
// ApiCall Flows
/**
* Before a API request is send.
* Return `null | undefined` would cancel the request.
*/
preApiCallFlow: new Flow<ApiCall>(),
/**
* Before return the `ApiReturn` to the client.
* It may be used to change the return value, or return `null | undefined` to abort the request.
*/
preApiReturnFlow: new Flow<{ call: ApiCall, return: ApiReturn<any> }>(),
/**
* After the `ApiReturn` is send.
* return `null | undefined` would NOT interrupt latter behaviours.
*/
postApiReturnFlow: new Flow<{ call: ApiCall, return: ApiReturn<any> }>(),
/**
* After the api handler is executed.
* return `null | undefined` would NOT interrupt latter behaviours.
*/
postApiCallFlow: new Flow<ApiCall>(),
// MsgCall Flows
/**
* Before handle a `MsgCall`
*/
preMsgCallFlow: new Flow<MsgCall>(),
/**
* After handlers of a `MsgCall` are executed.
* return `null | undefined` would NOT interrupt latter behaviours.
*/
postMsgCallFlow: new Flow<MsgCall>(),
/**
* Before send out a message.
* return `null | undefined` would NOT interrupt latter behaviours.
*/
preSendMsgFlow: new Flow<{ conn: BaseConnection<ServiceType>, service: MsgService, msg: any }>(),
/**
* After send out a message.
* return `null | undefined` would NOT interrupt latter behaviours.
*/
postSendMsgFlow: new Flow<{ conn: BaseConnection<ServiceType>, service: MsgService, msg: any }>(),
} as const;
// Handlers
private _apiHandlers: { [apiName: string]: ApiHandler<any> | undefined } = {};
// 多个Handler将异步并行执行
private _msgHandlers: MsgHandlerManager = new MsgHandlerManager();
private static _isUncaughtExceptionProcessed = false;
/**
* It makes the `uncaughtException` and `unhandledRejection` not lead to the server stopping.
* @param logger
* @returns
*/
static processUncaughtException(logger: Logger) {
if (this._isUncaughtExceptionProcessed) {
return;
}
this._isUncaughtExceptionProcessed = true;
process.on('uncaughtException', e => {
logger.error('[uncaughtException]', e);
});
process.on('unhandledRejection', e => {
logger.error('[unhandledRejection]', e);
});
}
constructor(proto: ServiceProto<ServiceType>, options: BaseServerOptions<ServiceType>) {
this.proto = proto;
this.options = options;
this.tsbuffer = new TSBuffer({
...proto.types,
// Support mongodb/ObjectId
...getCustomObjectIdTypes(ObjectId)
}, {
strictNullChecks: this.options.strictNullChecks
});
this.serviceMap = ServiceMapUtil.getServiceMap(proto);
this.logger = this.options.logger;
// Process uncaught exception, so that Node.js process would not exit easily
BaseServer.processUncaughtException(this.logger);
// default flows onError handler
this._setDefaultFlowOnError();
}
protected _setDefaultFlowOnError() {
// API Flow Error: return [InternalServerError]
this.flows.preApiCallFlow.onError = (e, call) => {
if (e instanceof TsrpcError) {
call.error(e)
}
else {
this.onInternalServerError(e, call)
}
};
this.flows.postApiCallFlow.onError = (e, call) => {
if (!call.return) {
if (e instanceof TsrpcError) {
call.error(e)
}
else {
this.onInternalServerError(e, call)
}
}
else {
call.logger.error('postApiCallFlow Error:', e);
}
};
this.flows.preApiReturnFlow.onError = (e, last) => {
last.call['_return'] = undefined;
if (e instanceof TsrpcError) {
last.call.error(e)
}
else {
this.onInternalServerError(e, last.call)
}
}
this.flows.postApiReturnFlow.onError = (e, last) => {
if (!last.call.return) {
if (e instanceof TsrpcError) {
last.call.error(e)
}
else {
this.onInternalServerError(e, last.call)
}
}
}
}
protected _pendingApiCallNum = 0;
// #region receive buffer process flow
/**
* Process the buffer, after the `preRecvBufferFlow`.
*/
async _onRecvBuffer(conn: BaseConnection<ServiceType>, buf: Buffer) {
// 非 OPENED 状态 停止接受新的请求
if (this.status !== ServerStatus.Opened) {
return;
}
this.options.debugBuf && conn.logger.debug('[RecvBuf]', `length=${buf.length}`, buf);
// postRecvBufferFlow
let opPreRecvBuffer = await this.flows.preRecvBufferFlow.exec({ conn: conn, buf: buf }, conn.logger);
if (!opPreRecvBuffer) {
return;
}
// Parse Call
let opInput = TransportDataUtil.parseServerInput(this.tsbuffer, this.serviceMap, buf);
if (!opInput.isSucc) {
this.onInputBufferError(opInput.errMsg, conn, buf);
return;
}
let call = this._makeCall(conn, opInput.result);
if (call.type === 'api') {
await this._handleApiCall(call);
}
else {
await this._onMsgCall(call);
}
}
protected _makeCall(conn: BaseConnection<ServiceType>, input: ParsedServerInput): ApiCall | MsgCall {
if (input.type === 'api') {
return new this.ApiCallClass({
conn: conn,
service: input.service,
req: input.req,
sn: input.sn,
})
}
else {
return new this.MsgCallClass({
conn: conn,
service: input.service,
msg: input.msg
})
}
}
protected async _handleApiCall(call: ApiCall) {
++this._pendingApiCallNum;
await this._onApiCall(call);
if (--this._pendingApiCallNum === 0) {
this._gracefulStop?.rs();
}
}
protected async _onApiCall(call: ApiCall) {
let timeoutTimer = this.options.apiTimeout ? setTimeout(() => {
if (!call.return) {
call.error('Server Timeout', {
code: 'SERVER_TIMEOUT',
type: TsrpcErrorType.ServerError
})
}
timeoutTimer = undefined;
}, this.options.apiTimeout) : undefined;
// Pre Flow
let preFlow = await this.flows.preApiCallFlow.exec(call, call.logger);
if (!preFlow) {
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = undefined;
}
return;
}
call = preFlow;
// exec ApiCall
call.logger.log('[ApiReq]', this.options.logReqBody ? call.req : '');
let { handler } = await this.getApiHandler(call.service, this._delayImplementApiPath, call.logger);
// exec API handler
if (handler) {
try {
await handler(call);
}
catch (e: any) {
if (e instanceof TsrpcError) {
call.error(e);
}
else {
this.onInternalServerError(e, call);
}
}
}
// 未找到ApiHandler,且未进行任何输出
else {
call.error(`Unhandled API: ${call.service.name}`, { code: 'UNHANDLED_API', type: TsrpcErrorType.ServerError });
}
// Post Flow
await this.flows.postApiCallFlow.exec(call, call.logger);
if (timeoutTimer) {
clearTimeout(timeoutTimer);
timeoutTimer = undefined;
}
// Destroy call
// if (!call.return) {
// this.onInternalServerError({ message: 'API not return anything' }, call);
// }
}
protected async _onMsgCall(call: MsgCall) {
// 收到Msg即可断开连接(短连接)
if (call.conn.type === 'SHORT') {
call.conn.close();
}
// Pre Flow
let preFlow = await this.flows.preMsgCallFlow.exec(call, call.logger);
if (!preFlow) {
return;
}
call = preFlow;
// MsgHandler
this.options.logMsg && call.logger.log('[RecvMsg]', call.msg);
let promises = this._msgHandlers.forEachHandler(call.service.name, call.logger, call);
if (!promises.length) {
this.logger.debug('[UNHANDLED_MSG]', call.service.name);
}
else {
await Promise.all(promises);
}
// Post Flow
await this.flows.postMsgCallFlow.exec(call, call.logger);
}
// #endregion
// #region Api/Msg handler register
/**
* Associate a `ApiHandler` to a specific `apiName`.
* So that when `ApiCall` is receiving, it can be handled correctly.
* @param apiName
* @param handler
*/
implementApi<Api extends keyof ServiceType['api'], Call extends ApiCall<ServiceType['api'][Api]['req'], ServiceType['api'][Api]['res']>>(apiName: Api, handler: ApiHandler<Call>): void {
if (this._apiHandlers[apiName as string]) {
throw new Error('Already exist handler for API: ' + apiName);
}
this._apiHandlers[apiName as string] = handler;
this.logger.log(`API implemented succ: [${apiName}]`);
};
/** 用于延迟注册 API */
protected _delayImplementApiPath?: string;
/**
* Auto call `imeplementApi` by traverse the `apiPath` and find all matched `PtlXXX` and `ApiXXX`.
* It is matched by checking whether the relative path and name of an API is consistent to the service name in `serviceProto`.
* Notice that the name prefix of protocol is `Ptl`, of API is `Api`.
* For example, `protocols/a/b/c/PtlTest` is matched to `api/a/b/c/ApiTest`.
* @param apiPath Absolute path or relative path to `process.cwd()`.
* @returns
*/
async autoImplementApi(apiPath: string, delay?: boolean): Promise<{ succ: string[], fail: string[] }> {
let apiServices = Object.values(this.serviceMap.apiName2Service) as ApiServiceDef[];
let output: { succ: string[], fail: string[] } = { succ: [], fail: [] };
if (delay) {
this._delayImplementApiPath = apiPath;
return output;
}
for (let svc of apiServices) {
//get api handler
let { handler, errMsg } = await this.getApiHandler(svc, apiPath, this.logger)
if (!handler) {
output.fail.push(svc.name);
let logMsg = chalk.red(`Implement ${chalk.cyan.underline(`Api${svc.name}`)} failed:`);
logMsg += '\n |- ' + errMsg;
this.logger.error(logMsg);
continue;
}
this.implementApi(svc.name, handler);
output.succ.push(svc.name);
}
if (output.fail.length) {
this.logger.error(chalk.red(`${output.fail.length} API implemented failed: ` + output.fail.map(v => chalk.cyan.underline(v)).join(' ')))
}
return output;
}
async getApiHandler(svc: ApiServiceDef, apiPath?: string, logger?: Logger): Promise<{ handler: ApiHandler, errMsg?: undefined } | { handler?: undefined, errMsg: string }> {
if (this._apiHandlers[svc.name]) {
return { handler: this._apiHandlers[svc.name]! };
}
if (!apiPath) {
return { errMsg: `Api not implemented: ${svc.name}` };
}
// get api last name
let match = svc.name.match(/^(.+\/)*(.+)$/);
if (!match) {
logger?.error('Invalid apiName: ' + svc.name);
return { errMsg: `Invalid api name: ${svc.name}` };
}
let handlerPath = match[1] || '';
let handlerName = match[2];
// try import
let modulePath = path.resolve(apiPath, handlerPath, 'Api' + handlerName);
try {
let handlerModule = await import(modulePath);
// 优先 default,其次 ApiName 同名
let handler = handlerModule.default ?? handlerModule['Api' + handlerName];
if (handler) {
return { handler: handler };
}
else {
return { errMsg: `Cannot find export { ${'Api' + handlerName} } at: ${modulePath}` }
}
}
catch (e: any) {
if (e.code === 'MODULE_NOT_FOUND') {
return { errMsg: `Module not found: ${modulePath}` };
}
else {
return { errMsg: e.message }
}
}
}
/**
* Add a message handler,
* duplicate handlers to the same `msgName` would be ignored.
* @param msgName
* @param handler
*/
listenMsg<Msg extends keyof ServiceType['msg'], Call extends MsgCall<ServiceType['msg'][Msg]>>(msgName: Msg, handler: MsgHandler<Call>): MsgHandler<Call> {
this._msgHandlers.addHandler(msgName as string, handler);
return handler;
};
/**
* Remove a message handler
*/
unlistenMsg<Msg extends keyof ServiceType['msg'], Call extends MsgCall<ServiceType['msg'][Msg]>>(msgName: Msg, handler: Function): void {
this._msgHandlers.removeHandler(msgName as string, handler);
};
/**
* Remove all handlers from a message
*/
unlistenMsgAll<Msg extends keyof ServiceType['msg'], Call extends MsgCall<ServiceType['msg'][Msg]>>(msgName: Msg): void {
this._msgHandlers.removeAllHandlers(msgName as string);
};
// #endregion
/**
* Event when the server cannot parse input buffer to api/msg call.
* By default, it will return "Input Buffer Error" .
*/
async onInputBufferError(errMsg: string, conn: BaseConnection<ServiceType>, buf: Uint8Array) {
this.options.debugBuf && conn.logger.error(`[InputBufferError] ${errMsg} length = ${buf.length}`, buf.subarray(0, 16))
// Short conn, send apiReturn with error
if (conn.type === 'SHORT') {
// Encode
let serverOutputData: ServerOutputData = {
error: {
message: 'Invalid input buffer, please check the version of service proto.',
/**
* @defaultValue ApiError
*/
type: TsrpcErrorType.ServerError,
code: 'INPUT_BUF_ERR'
}
};
let opEncode = TransportDataUtil.tsbuffer.encode(serverOutputData, 'ServerOutputData');
if (opEncode.isSucc) {
let opSend = await conn.sendBuf(opEncode.buf);
if (opSend.isSucc) {
return;
}
}
}
conn.close('Input Buffer Error');
}
/**
* Event when a uncaught error (except `TsrpcError`) is throwed.
* By default, it will return a `TsrpcError` with message "Internal server error".
* If `returnInnerError` is `true`, the original error would be returned as `innerErr` property.
*/
onInternalServerError(err: { message: string, stack?: string, name?: string }, call: ApiCall) {
call.logger.error(err);
call.error('Internal Server Error', {
code: 'INTERNAL_ERR',
type: TsrpcErrorType.ServerError,
innerErr: call.conn.server.options.returnInnerError ? err.message : undefined
});
}
protected _gracefulStop?: {
rs: () => void
};
/**
* Stop the server gracefully.
* Wait all API requests finished and then stop the server.
* @param maxWaitTime - The max time(ms) to wait before force stop the server.
* `undefined` and `0` means unlimited time.
*/
async gracefulStop(maxWaitTime?: number) {
if (this._status !== ServerStatus.Opened) {
throw new Error(`Cannot gracefulStop when server status is '${this._status}'.`);
}
this.logger.log('[GracefulStop] Start graceful stop, waiting all ApiCall finished...')
this._status = ServerStatus.Closing;
let promiseWaitApi = new Promise<void>(rs => {
this._gracefulStop = {
rs: rs
};
});
return new Promise<void>(rs => {
let maxWaitTimer: ReturnType<typeof setTimeout> | undefined;
if (maxWaitTime) {
maxWaitTimer = setTimeout(() => {
maxWaitTimer = undefined;
if (this._gracefulStop) {
this._gracefulStop = undefined;
this.logger.log('Graceful stop timeout, stop the server directly.');
this.stop().then(() => { rs() });
}
}, maxWaitTime);
}
promiseWaitApi.then(() => {
this.logger.log('All ApiCall finished, continue stop server.');
if (maxWaitTimer) {
clearTimeout(maxWaitTimer);
maxWaitTimer = undefined;
}
if (this._gracefulStop) {
this._gracefulStop = undefined;
this.stop().then(() => { rs() });
}
})
})
}
/**
* Execute API function through the inner connection.
* It is useful when you want to customize your transport method.
* @param apiName
* @param req
* @param options
*/
callApi<T extends keyof ServiceType['api']>(apiName: T, req: ServiceType['api'][T]['req']): Promise<ApiReturn<ServiceType['api'][T]['res']>> {
return new Promise(rs => {
// 确认是哪个Service
let service = this.serviceMap.apiName2Service[apiName as string];
if (!service) {
let errMsg = `Cannot find service: ${apiName}`;
this.logger.warn(`[callApi]`, errMsg);
rs({ isSucc: false, err: new TsrpcError(errMsg, { type: TsrpcErrorType.ServerError, code: 'ERR_API_NAME' }) });
return;
}
let conn = new InnerConnection({
server: this,
id: '' + this._connIdCounter.getNext(),
ip: '',
rs: rs
});
let call = new ApiCallInner({
conn: conn,
req: req,
service: service
});
this._handleApiCall(call);
})
}
}
export interface BaseServerOptions<ServiceType extends BaseServiceType> {
// TSBuffer相关
/**
* Whether to strictly distinguish between `null` and `undefined` when encoding, decoding, and type checking.
* @defaultValue false
*/
strictNullChecks: boolean,
/**
* Timeout for processing an `ApiCall`(ms)
* `0` and `undefined` means unlimited time
* @defaultValue 30000
*/
apiTimeout: number | undefined,
// LOG相关
/**
* Logger for processing log
* @defaultValue `new TerminalColorLogger()` (print to console with color)
*/
logger: Logger;
/**
* Whethere to print API request body into log (may increase log size)
* @defaultValue `true`
*/
logReqBody: boolean;
/**
* Whethere to print API response body into log (may increase log size)
* @defaultValue `true`
*/
logResBody: boolean;
/**
* Whethere to print `[SendMsg]` and `[RecvMsg]` log into log
* @defaultValue `true`
*/
logMsg: boolean;
/**
* If `true`, all sent and received raw buffer would be print into the log.
* It may be useful when you do something for buffer encryption/decryption, and want to debug them.
*/
debugBuf?: boolean;
/**
* When uncaught error throwed,
* whether to return the original error as a property `innerErr`.
* (May include some sensitive information, suggests set to `false` in production environment.)
* @defaultValue It depends on environment variable `NODE_ENV`.
* If `NODE_ENV` equals to `production`, the default value is `false`, otherwise is `true`.
*/
returnInnerError: boolean;
}
export const defaultBaseServerOptions: BaseServerOptions<any> = {
strictNullChecks: false,
apiTimeout: 30000,
logger: new TerminalColorLogger,
logReqBody: true,
logResBody: true,
logMsg: true,
returnInnerError: process.env['NODE_ENV'] !== 'production'
}
export type ApiHandler<Call extends ApiCall = ApiCall> = (call: Call) => void | Promise<void>;
export type MsgHandler<Call extends MsgCall = MsgCall> = (call: Call) => void | Promise<void>;
export enum ServerStatus {
Opening = 'OPENING',
Opened = 'OPENED',
Closing = 'CLOSING',
Closed = 'CLOSED',
} | the_stack |
import * as babel from '@babel/types';
import * as dom5 from 'dom5/lib/index-next';
import * as parse5 from 'parse5';
import {ParsedHtmlDocument} from '../html/html-document';
import * as astValue from '../javascript/ast-value';
import {JavaScriptDocument} from '../javascript/javascript-document';
import {parseJs} from '../javascript/javascript-parser';
import {correctSourceRange, LocationOffset, Severity, SourceRange, Warning} from '../model/model';
import {ParsedDocument} from '../parser/document';
const p = dom5.predicates;
const isTemplate = p.hasTagName('template');
const isDataBindingTemplate = p.AND(
isTemplate,
p.OR(
p.hasAttrValue('is', 'dom-bind'),
p.hasAttrValue('is', 'dom-if'),
p.hasAttrValue('is', 'dom-repeat'),
p.parentMatches(p.OR(
p.hasTagName('dom-bind'),
p.hasTagName('dom-if'),
p.hasTagName('dom-repeat'),
p.hasTagName('dom-module')))));
export interface Template extends parse5.ASTNode {
content: parse5.ASTNode;
}
/**
* Given a node, return all databinding templates inside it.
*
* A template is "databinding" if polymer databinding expressions are expected
* to be evaluated inside. e.g. <template is='dom-if'> or <dom-module><template>
*
* Results include both direct and nested templates (e.g. dom-if inside
* dom-module).
*/
export function getAllDataBindingTemplates(node: parse5.ASTNode) {
return dom5.queryAll(
node, isDataBindingTemplate, dom5.childNodesIncludeTemplate) as
IterableIterator<Template>;
}
export type HtmlDatabindingExpression =
TextNodeDatabindingExpression|AttributeDatabindingExpression;
/**
* Some expressions are limited. For example, in a property declaration,
* `observer` must be the identifier of a method, and `computed` must be a
* function call expression.
*/
export type ExpressionLimitation = 'full'|'identifierOnly'|'callExpression';
export abstract class DatabindingExpression {
readonly sourceRange: SourceRange;
readonly warnings: Warning[] = [];
readonly expressionText: string;
private readonly _expressionAst: babel.Program;
private readonly locationOffset: LocationOffset;
private readonly _document: ParsedDocument;
/**
* Toplevel properties on the model that are referenced in this expression.
*
* e.g. in {{foo(bar, baz.zod)}} the properties are foo, bar, and baz
* (but not zod).
*/
properties: Array<{name: string, sourceRange: SourceRange}> = [];
constructor(
sourceRange: SourceRange, expressionText: string, ast: babel.Program,
limitation: ExpressionLimitation, document: ParsedDocument) {
this.sourceRange = sourceRange;
this.expressionText = expressionText;
this._expressionAst = ast;
this.locationOffset = {
line: sourceRange.start.line,
col: sourceRange.start.column
};
this._document = document;
this._extractPropertiesAndValidate(limitation);
}
/**
* Given an estree node in this databinding expression, give its source range.
*/
sourceRangeForNode(node: babel.Node) {
if (!node || !node.loc) {
return;
}
const databindingRelativeSourceRange = {
file: this.sourceRange.file,
// Note: estree uses 1-indexed lines, but SourceRange uses 0 indexed.
start: {line: (node.loc.start.line - 1), column: node.loc.start.column},
end: {line: (node.loc.end.line - 1), column: node.loc.end.column}
};
return correctSourceRange(
databindingRelativeSourceRange, this.locationOffset);
}
private _extractPropertiesAndValidate(limitation: ExpressionLimitation) {
if (this._expressionAst.body.length !== 1) {
this.warnings.push(this._validationWarning(
`Expected one expression, got ${this._expressionAst.body.length}`,
this._expressionAst));
return;
}
const expressionStatement = this._expressionAst.body[0]!;
if (!babel.isExpressionStatement(expressionStatement)) {
this.warnings.push(this._validationWarning(
`Expect an expression, not a ${expressionStatement.type}`,
expressionStatement));
return;
}
let expression = expressionStatement.expression;
this._validateLimitation(expression, limitation);
if (babel.isUnaryExpression(expression) && expression.operator === '!') {
expression = expression.argument;
}
this._extractAndValidateSubExpression(expression, true);
}
private _validateLimitation(
expression: babel.Expression, limitation: ExpressionLimitation) {
switch (limitation) {
case 'identifierOnly':
if (!babel.isIdentifier(expression)) {
this.warnings.push(this._validationWarning(
`Expected just a name here, not an expression`, expression));
}
break;
case 'callExpression':
if (!babel.isCallExpression(expression)) {
this.warnings.push(this._validationWarning(
`Expected a function call here.`, expression));
}
break;
case 'full':
break; // no checks needed
default:
const never: never = limitation;
throw new Error(`Got unknown limitation: ${never}`);
}
}
private _extractAndValidateSubExpression(
expression: babel.Node, callAllowed: boolean): void {
if (babel.isUnaryExpression(expression) && expression.operator === '-') {
if (!babel.isNumericLiteral(expression.argument)) {
this.warnings.push(this._validationWarning(
'The - operator is only supported for writing negative numbers.',
expression));
return;
}
this._extractAndValidateSubExpression(expression.argument, false);
return;
}
if (babel.isLiteral(expression)) {
return;
}
if (babel.isIdentifier(expression)) {
this.properties.push({
name: expression.name,
sourceRange: this.sourceRangeForNode(expression)!
});
return;
}
if (babel.isMemberExpression(expression)) {
this._extractAndValidateSubExpression(expression.object, false);
return;
}
if (callAllowed && babel.isCallExpression(expression)) {
this._extractAndValidateSubExpression(expression.callee, false);
for (const arg of expression.arguments) {
this._extractAndValidateSubExpression(arg, false);
}
return;
}
this.warnings.push(this._validationWarning(
`Only simple syntax is supported in Polymer databinding expressions. ` +
`${expression.type} not expected here.`,
expression));
}
private _validationWarning(message: string, node: babel.Node): Warning {
return new Warning({
code: 'invalid-polymer-expression',
message,
sourceRange: this.sourceRangeForNode(node)!,
severity: Severity.WARNING,
parsedDocument: this._document,
});
}
}
export class AttributeDatabindingExpression extends DatabindingExpression {
/**
* The element whose attribute/property is assigned to.
*/
readonly astNode: parse5.ASTNode;
readonly databindingInto = 'attribute';
/**
* If true, this is databinding into the complete attribute. Polymer treats
* such databindings specially, e.g. they're setting the property by default,
* not the attribute.
*
* e.g.
* foo="{{bar}}" is complete, foo="hello {{bar}} world" is not complete.
*
* An attribute may have multiple incomplete bindings. They will be separate
* AttributeDatabindingExpressions.
*/
readonly isCompleteBinding: boolean;
/** The databinding syntax used. */
readonly direction: '{'|'[';
/**
* If this is a two-way data binding, and an event name was specified
* (using ::eventName syntax), this is that event name.
*/
readonly eventName: string|undefined;
/** The attribute we're databinding into. */
readonly attribute: parse5.ASTAttribute;
constructor(
astNode: parse5.ASTNode, isCompleteBinding: boolean, direction: '{'|'[',
eventName: string|undefined, attribute: parse5.ASTAttribute,
sourceRange: SourceRange, expressionText: string, ast: babel.Program,
document: ParsedHtmlDocument) {
super(sourceRange, expressionText, ast, 'full', document);
this.astNode = astNode;
this.isCompleteBinding = isCompleteBinding;
this.direction = direction;
this.eventName = eventName;
this.attribute = attribute;
}
}
export class TextNodeDatabindingExpression extends DatabindingExpression {
/** The databinding syntax used. */
readonly direction: '{'|'[';
/**
* The HTML text node that contains this databinding.
*/
readonly astNode: parse5.ASTNode;
readonly databindingInto = 'text-node';
constructor(
direction: '{'|'[', astNode: parse5.ASTNode, sourceRange: SourceRange,
expressionText: string, ast: babel.Program,
document: ParsedHtmlDocument) {
super(sourceRange, expressionText, ast, 'full', document);
this.direction = direction;
this.astNode = astNode;
}
}
export class JavascriptDatabindingExpression extends DatabindingExpression {
readonly astNode: babel.Node;
readonly databindingInto = 'javascript';
constructor(
astNode: babel.Node, sourceRange: SourceRange, expressionText: string,
ast: babel.Program, kind: ExpressionLimitation,
document: JavaScriptDocument) {
super(sourceRange, expressionText, ast, kind, document);
this.astNode = astNode;
}
}
/**
* Find and parse Polymer databinding expressions in HTML.
*/
export function scanDocumentForExpressions(document: ParsedHtmlDocument) {
return extractDataBindingsFromTemplates(
document, getAllDataBindingTemplates(document.ast));
}
export function scanDatabindingTemplateForExpressions(
document: ParsedHtmlDocument, template: Template) {
return extractDataBindingsFromTemplates(
document,
[template].concat([...getAllDataBindingTemplates(template.content)]));
}
function extractDataBindingsFromTemplates(
document: ParsedHtmlDocument, templates: Iterable<Template>) {
const results: HtmlDatabindingExpression[] = [];
const warnings: Warning[] = [];
for (const template of templates) {
for (const node of dom5.depthFirst(template.content)) {
if (dom5.isTextNode(node) && node.value) {
extractDataBindingsFromTextNode(document, node, results, warnings);
}
if (node.attrs) {
for (const attr of node.attrs) {
extractDataBindingsFromAttr(document, node, attr, results, warnings);
}
}
}
}
return {expressions: results, warnings};
}
function extractDataBindingsFromTextNode(
document: ParsedHtmlDocument,
node: parse5.ASTNode,
results: HtmlDatabindingExpression[],
warnings: Warning[]) {
const text = node.value || '';
const dataBindings = findDatabindingInString(text);
if (dataBindings.length === 0) {
return;
}
const nodeSourceRange = document.sourceRangeForNode(node);
if (!nodeSourceRange) {
return;
}
const startOfTextNodeOffset =
document.sourcePositionToOffset(nodeSourceRange.start);
for (const dataBinding of dataBindings) {
const sourceRange = document.offsetsToSourceRange(
dataBinding.startIndex + startOfTextNodeOffset,
dataBinding.endIndex + startOfTextNodeOffset);
const parseResult =
parseExpression(dataBinding.expressionText, sourceRange);
if (!parseResult) {
continue;
}
if (parseResult.type === 'failure') {
warnings.push(
new Warning({parsedDocument: document, ...parseResult.warningish}));
} else {
const expression = new TextNodeDatabindingExpression(
dataBinding.direction,
node,
sourceRange,
dataBinding.expressionText,
parseResult.parsedFile.program,
document);
for (const warning of expression.warnings) {
warnings.push(warning);
}
results.push(expression);
}
}
}
function extractDataBindingsFromAttr(
document: ParsedHtmlDocument,
node: parse5.ASTNode,
attr: parse5.ASTAttribute,
results: HtmlDatabindingExpression[],
warnings: Warning[]) {
if (!attr.value) {
return;
}
const dataBindings = findDatabindingInString(attr.value);
const attributeValueRange =
document.sourceRangeForAttributeValue(node, attr.name, true);
if (!attributeValueRange) {
return;
}
const attributeOffset =
document.sourcePositionToOffset(attributeValueRange.start);
for (const dataBinding of dataBindings) {
const isFullAttributeBinding = dataBinding.startIndex === 2 &&
dataBinding.endIndex + 2 === attr.value.length;
let expressionText = dataBinding.expressionText;
let eventName = undefined;
if (dataBinding.direction === '{') {
const match = expressionText.match(/(.*)::(.*)/);
if (match) {
expressionText = match[1];
eventName = match[2];
}
}
const sourceRange = document.offsetsToSourceRange(
dataBinding.startIndex + attributeOffset,
dataBinding.endIndex + attributeOffset);
const parseResult = parseExpression(expressionText, sourceRange);
if (!parseResult) {
continue;
}
if (parseResult.type === 'failure') {
warnings.push(
new Warning({parsedDocument: document, ...parseResult.warningish}));
} else {
const expression = new AttributeDatabindingExpression(
node,
isFullAttributeBinding,
dataBinding.direction,
eventName,
attr,
sourceRange,
expressionText,
parseResult.parsedFile.program,
document);
for (const warning of expression.warnings) {
warnings.push(warning);
}
results.push(expression);
}
}
}
interface RawDatabinding {
readonly expressionText: string;
readonly startIndex: number;
readonly endIndex: number;
readonly direction: '{'|'[';
}
function findDatabindingInString(str: string) {
const expressions: RawDatabinding[] = [];
const openers = /{{|\[\[/g;
let match;
while (match = openers.exec(str)) {
const matchedOpeners = match[0];
const startIndex = match.index + 2;
const direction = matchedOpeners === '{{' ? '{' : '[';
const closers = matchedOpeners === '{{' ? '}}' : ']]';
const endIndex = str.indexOf(closers, startIndex);
if (endIndex === -1) {
// No closers, this wasn't an expression after all.
break;
}
const expressionText = str.slice(startIndex, endIndex);
expressions.push({startIndex, endIndex, expressionText, direction});
// Start looking for the next expression after the end of this one.
openers.lastIndex = endIndex + 2;
}
return expressions;
}
function transformPath(expression: string) {
return expression
// replace .0, .123, .kebab-case with ['0'], ['123'], ['kebab-case']
.replace(/\.([a-zA-Z_$]([\w:$*]*-+[\w:$*]*)+|[1-9][0-9]*|0)/g, '[\'$1\']')
// remove .* and .splices from the end of the paths
.replace(/\.(\*|splices)$/, '');
}
/**
* Transform polymer expression based on
* https://github.com/Polymer/polymer/blob/10aded461b1a107ed1cfc4a1d630149ad8508bda/lib/mixins/property-effects.html#L864
*/
function transformPolymerExprToJS(expression: string) {
const method = expression.match(/([^\s]+?)\(([\s\S]*)\)/);
if (method) {
const methodName = method[1];
if (method[2].trim()) {
// replace escaped commas with comma entity, split on un-escaped commas
const args = method[2].replace(/\\,/g, ',').split(',');
return methodName + '(' + args.map(transformArg).join(',') + ')';
} else {
return expression;
}
}
return transformPath(expression);
}
function transformArg(rawArg: string) {
const arg = rawArg
// replace comma entity with comma
.replace(/,/g, ',')
// repair extra escape sequences; note only commas strictly
// need escaping, but we allow any other char to be escaped
// since its likely users will do this
.replace(/\\(.)/g, '\$1');
// detect literal value (must be String or Number)
const i = arg.search(/[^\s]/);
let fc = arg[i];
if (fc === '-') {
fc = arg[i + 1];
}
if (fc >= '0' && fc <= '9') {
fc = '#';
}
switch (fc) {
case '\'':
case '"':
return arg;
case '#':
return arg;
}
if (arg.indexOf('.') !== -1) {
return transformPath(arg);
}
return arg;
}
function parseExpression(content: string, expressionSourceRange: SourceRange) {
const expressionOffset = {
line: expressionSourceRange.start.line,
col: expressionSourceRange.start.column
};
const parseResult = parseJs(
transformPolymerExprToJS(content),
expressionSourceRange.file,
expressionOffset,
'polymer-expression-parse-error');
if (parseResult.type === 'success') {
return parseResult;
}
// The polymer databinding expression language allows for foo.0 and foo.*
// formats when accessing sub properties. These aren't valid JS, but we don't
// want to warn for them either. So just return undefined for now.
if (/\.(\*|\d+)/.test(content)) {
return undefined;
}
return parseResult;
}
export function parseExpressionInJsStringLiteral(
document: JavaScriptDocument,
stringLiteral: babel.Node,
kind: 'identifierOnly'|'callExpression'|'full') {
const warnings: Warning[] = [];
const result = {
databinding: undefined as undefined | JavascriptDatabindingExpression,
warnings
};
const sourceRangeForLiteral = document.sourceRangeForNode(stringLiteral)!;
const expressionText = astValue.expressionToValue(stringLiteral);
if (expressionText === undefined) {
// Should we warn here? It's potentially valid, just unanalyzable. Maybe
// just an info that someone could escalate to a warning/error?
warnings.push(new Warning({
code: 'unanalyzable-polymer-expression',
message: `Can only analyze databinding expressions in string literals.`,
severity: Severity.INFO,
sourceRange: sourceRangeForLiteral,
parsedDocument: document
}));
return result;
}
if (typeof expressionText !== 'string') {
warnings.push(new Warning({
code: 'invalid-polymer-expression',
message: `Expected a string, got a ${typeof expressionText}.`,
sourceRange: sourceRangeForLiteral,
severity: Severity.WARNING,
parsedDocument: document
}));
return result;
}
const sourceRange: SourceRange = {
file: sourceRangeForLiteral.file,
start: {
column: sourceRangeForLiteral.start.column + 1,
line: sourceRangeForLiteral.start.line
},
end: {
column: sourceRangeForLiteral.end.column - 1,
line: sourceRangeForLiteral.end.line
}
};
const parsed = parseExpression(expressionText, sourceRange);
if (parsed && parsed.type === 'failure') {
warnings.push(
new Warning({parsedDocument: document, ...parsed.warningish}));
} else if (parsed && parsed.type === 'success') {
result.databinding = new JavascriptDatabindingExpression(
stringLiteral,
sourceRange,
expressionText,
parsed.parsedFile.program,
kind,
document);
for (const warning of result.databinding.warnings) {
warnings.push(warning);
}
}
return result;
} | the_stack |
import type { NestingInfo } from "../../utils/selectors"
import {
isNestingAtRule,
findNestingSelectors,
findNestingSelector,
hasNodesSelector,
isSelectorCombinator,
} from "../../utils/selectors"
import type {
VCSSStyleRule,
VCSSAtRule,
VCSS,
VCSSSelectorNode,
} from "../../ast"
import { VCSSSelectorCombinator } from "../../ast"
import {
CSSSelectorResolver,
ResolvedSelector,
ResolvedSelectors,
} from "./css-selector-resolver"
import type { PostCSSSPCombinatorNode } from "../../../types"
export class StylusSelectorResolver extends CSSSelectorResolver {
/**
* Resolve nesting selector
* @param {Node[]} selectorNodes the selector
* @param {ResolvedSelector[]} parentSelectors parent selectors
* @param {Node} container the container node
* @returns {ResolvedSelector[]} resolved selectors
*/
protected resolveNestingSelectors(
owner: ResolvedSelectors,
selectorNodes: VCSSSelectorNode[],
parentSelectors: ResolvedSelectors | null,
container: VCSSAtRule | VCSSStyleRule,
): ResolvedSelector[] {
if (isNestingAtRule(container)) {
return this.resolveSelectorForNestContaining(
owner,
selectorNodes,
findNestingSelector(selectorNodes),
parentSelectors,
container,
)
}
return this.resolveSelectorForStylusNesting(
owner,
selectorNodes,
parentSelectors,
container,
)
}
/**
* Resolve nesting selector for lang Stylus
* @param {Node[]} selectorNodes the selector
* @param {ResolvedSelector[]} parentSelectors parent selectors
* @param {Node} container the container node
* @returns {ResolvedSelector[]} resolved selectors
*/
private resolveSelectorForStylusNesting(
owner: ResolvedSelectors,
selectorNodes: VCSSSelectorNode[],
parentSelectors: ResolvedSelectors | null,
container: VCSSAtRule | VCSSStyleRule,
): ResolvedSelector[] {
const nesting = findNestingSelector(selectorNodes)
if (nesting != null) {
const nestingParent = parentSelectors
? this.getNestingParentSelectors(parentSelectors, nesting)
: null
let resolvedSelectors = this.resolveSelectorForNestContaining(
owner,
selectorNodes,
nesting,
nestingParent,
container,
)
let hasNesting = true
while (hasNesting) {
hasNesting = false
const nextResolvedSelectors = []
for (const resolvedSelector of resolvedSelectors) {
const nextNesting = findNextNestingSelector(
resolvedSelector,
container,
)
if (nextNesting) {
hasNesting = true
const nextNestingParent = parentSelectors
? this.getNestingParentSelectors(
parentSelectors,
nextNesting,
)
: null
nextResolvedSelectors.push(
...this.resolveSelectorForNestContaining(
owner,
resolvedSelector.selector,
nextNesting,
nextNestingParent,
container,
),
)
}
}
if (!hasNesting) {
break
}
resolvedSelectors = nextResolvedSelectors
}
return resolvedSelectors
}
const first = selectorNodes[0]
if (isSelectorCombinator(first)) {
return this.resolveSelectorForNestConcat(
owner,
selectorNodes,
parentSelectors,
container,
)
}
// create descendant combinator
const comb = new VCSSSelectorCombinator(
first.node as PostCSSSPCombinatorNode,
{
start: first.loc.start,
end: first.loc.start,
},
first.range[0],
first.range[0],
first.parent as never,
)
comb.value = " "
comb.selector = " "
return this.resolveSelectorForNestConcat(
owner,
[comb, ...selectorNodes],
parentSelectors,
container,
)
}
/**
* Gets the ResolvedSelectors that correspond to the given nesting selector.
*/
private getNestingParentSelectors(
parentSelectors: ResolvedSelectors,
nesting: NestingInfo,
): ResolvedSelectors | null {
if (nesting.node.value === "&") {
// The nestingNode is parent reference. e.g `&`
return parentSelectors
}
const partialRef = /^\^\[([\s\S]+?)\]$/u.exec(nesting.node.value)
if (partialRef) {
// The nestingNode is a partial reference. e.g. `^[0]`, `^[1]`, `^[-1]`, `^[1..-1]`
const partialRefValue = partialRef[1]
const arrayParentSelectors = toArray(parentSelectors)
const parsed = parsePartialRefValue(
partialRefValue,
arrayParentSelectors.length,
)
if (!parsed) {
return null
}
if (parsed.start === 0) {
// e.g. `^[0]`, `^[1]`, `^[-1]`
return arrayParentSelectors[parsed.end]
}
// e.g. `^[1..-1]`
return this.buildRangeResolveNestingSelectors(
arrayParentSelectors.slice(parsed.start, parsed.end + 1),
)
}
if (nesting.node.value === "~/" && nesting.nestingIndex === 0) {
// The nestingNode is initial reference. `~/`
const arrayParentSelectors = toArray(parentSelectors)
return arrayParentSelectors[0]
}
if (
/^(?:\.\.\/)+$/u.test(nesting.node.value) &&
nesting.nestingIndex === 0
) {
// The nestingNode is relative reference. e.g. `../`
const arrayParentSelectors = toArray(parentSelectors)
const index =
arrayParentSelectors.length - nesting.node.value.length / 3 - 1
return arrayParentSelectors.length > index && index >= 0
? arrayParentSelectors[index]
: null
}
if (nesting.node.value === "/" && nesting.nestingIndex === 0) {
// The nestingNode is root reference. `/`
return null
}
// unknown
return parentSelectors
}
private buildRangeResolveNestingSelectors(
range: ResolvedSelectors[],
): ResolvedSelectors {
const stack = [...range]
let resolvedSelectors: ResolvedSelectors | null = null
let next = stack.shift()
while (next != null) {
const targetResolvedSelectors: ResolvedSelectors =
new ResolvedSelectors(next.container, resolvedSelectors)
for (const selector of next.container.selectors.filter(
hasNodesSelector,
)) {
const selectors = this.resolveNestingSelectors(
targetResolvedSelectors,
selector.nodes,
resolvedSelectors,
next.container,
)
targetResolvedSelectors.selectors.push(...selectors)
}
resolvedSelectors = targetResolvedSelectors
next = stack.shift()
}
return resolvedSelectors as ResolvedSelectors
}
}
export { ResolvedSelector }
/**
* Find next nesting selector
*/
export function findNextNestingSelector(
resolved: ResolvedSelector,
container: VCSSAtRule | VCSSStyleRule,
): NestingInfo | null {
for (const nest of findNestingSelectors(resolved.selector)) {
let parent: VCSS = nest.node.parent
while (
parent &&
parent.type !== "VCSSAtRule" &&
parent.type !== "VCSSStyleRule"
) {
parent = parent.parent
}
if (parent === container) {
return nest
}
}
return null
}
/**
* Parse partial reference values
*/
function parsePartialRefValue(partialRefValue: string, length: number) {
/**
* num to index
*/
function numberToIndex(n: number, minusOffset = 0) {
if (n >= 0) {
return n
}
return length + n + minusOffset
}
const num = Number(partialRefValue)
if (Number.isInteger(num)) {
// e.g. `^[0]`, `^[1]`, `^[-1]`
const index = numberToIndex(num, -1)
if (index < 0 || length <= index) {
// out of range
return null
}
return {
start: 0,
end: index,
}
}
const rangeValues = /^([+-]?\d+)\.\.([+-]?\d+)$/u.exec(partialRefValue)
if (rangeValues) {
// The nestingNode is ranges in partial references.
const start = numberToIndex(Number(rangeValues[1]))
const end = numberToIndex(Number(rangeValues[2]))
if (
start < 0 ||
length <= start ||
end < 0 ||
length <= end ||
end < start
) {
// out of range
return null
}
return {
start,
end,
}
}
// unknown
return null
}
/**
* ResolvedSelectors to array ResolvedSelectors
*/
function toArray(selectors: ResolvedSelectors): ResolvedSelectors[] {
const array = [selectors]
let parent = selectors.parent
while (parent != null) {
array.unshift(parent)
parent = parent.parent
}
return array
} | the_stack |
import * as Clutter from 'clutter';
import * as GLib from 'glib';
import * as GObject from 'gobject';
import { App, AppSystem } from 'shell';
import { HorizontalPanel } from 'src/layout/msWorkspace/horizontalPanel/horizontalPanel';
import { MsWindow, MsWindowState } from 'src/layout/msWorkspace/msWindow';
import { MsWorkspaceCategory } from 'src/layout/msWorkspace/msWorkspaceCategory';
import { LayoutState, LayoutType } from 'src/manager/layoutManager';
import { HorizontalPanelPositionEnum } from 'src/manager/msThemeManager';
import { MsWorkspaceManager } from 'src/manager/msWorkspaceManager';
import { assert, assertNotNull, logAssert } from 'src/utils/assert';
import { Allocate, SetAllocation } from 'src/utils/compatibility';
import { registerGObjectClass, WithSignals } from 'src/utils/gjs';
import { reparentActor } from 'src/utils/index';
import { getSettings } from 'src/utils/settings';
import { MsApplicationLauncher } from 'src/widget/msApplicationLauncher';
import { layout, main as Main } from 'ui';
import Monitor = layout.Monitor;
const Signals = imports.signals;
/** Extension imports */
const Me = imports.misc.extensionUtils.getCurrentExtension();
export type Tileable = MsWindow | MsApplicationLauncher;
function isMsWindow(argument: any): argument is MsWindow {
return argument instanceof MsWindow;
}
export interface MsWorkspaceState {
// This is different from monitorIsExternal since it's used to determined if it's should be moved to an external monitor when one is plugged
external: boolean;
focusedIndex: number;
forcedCategory: string | null | undefined;
msWindowList: MsWindowState[];
layoutStateList: LayoutState[];
layoutKey: string;
}
export class MsWorkspace extends WithSignals {
msWorkspaceManager: MsWorkspaceManager;
private _state: MsWorkspaceState;
insertedMsWindow: MsWindow | null;
appLauncher: MsApplicationLauncher;
tileableList: Tileable[] = [];
msWorkspaceCategory: MsWorkspaceCategory;
precedentIndex: number;
msWorkspaceActor: MsWorkspaceActor;
// Safety: We always assign this because we call setLayoutByKey from the constructor
layout!: InstanceType<LayoutType>;
destroyed: boolean | undefined;
closing = false;
// Safety: We always assign this because we call setMonitor from the constructor
monitorIsExternal!: boolean;
// Definitely set because we call `setMonitor` in the constructor
monitor!: Monitor;
emitTileableChangedInProgress: Promise<void> | undefined;
constructor(
msWorkspaceManager: MsWorkspaceManager,
monitor: Monitor,
state: Partial<MsWorkspaceState> = {}
) {
super();
this.msWorkspaceManager = msWorkspaceManager;
this.setMonitor(monitor);
const initialState: MsWorkspaceState = Object.assign(
{
// This is different from monitorIsExternal since it's used to determined if it's should be moved to an external monitor when one is plugged
external:
this.monitor.index !== Main.layoutManager.primaryIndex,
focusedIndex: 0,
forcedCategory: null,
msWindowList: [],
layoutStateList: Me.layoutManager.defaultLayoutKeyList.map(
(layoutKey) => {
return Me.layoutManager.getLayoutByKey(layoutKey).state;
}
),
layoutKey: Me.layoutManager.defaultLayoutKey,
},
state
);
// Note: _state may be updated while some functions in the constructor run, so we keep the original state in initialState.
this._state = Object.assign({}, initialState);
this.insertedMsWindow = null;
this.appLauncher = new MsApplicationLauncher(this);
this.msWorkspaceCategory = new MsWorkspaceCategory(
this,
initialState.forcedCategory
);
this.precedentIndex = initialState.focusedIndex;
this.msWorkspaceActor = new MsWorkspaceActor(this);
// First add AppLauncher since windows are inserted before it otherwise the order is a mess.
// It's important that this is done after the workspace actor is created.
this.tileableList.push(this.appLauncher);
const appSys = AppSystem.get_default();
for (const msWindowData of initialState.msWindowList) {
let matchingInfo = msWindowData.matchingInfo;
if (
matchingInfo === undefined &&
msWindowData.metaWindowIdentifier !== null
) {
// Compatibility
const parts = msWindowData.metaWindowIdentifier.split('-');
if (
logAssert(
parts.length === 3,
'window identifier had an unknown format'
)
) {
matchingInfo = {
appId: msWindowData.appId,
title: undefined,
pid: Number(parts[1]),
wmClass: parts[0],
stableSeq: Number(parts[2]),
};
}
}
// Note: lookup_app can return null even though the type definitions don't say that.
const app: App | null = appSys.lookup_app(msWindowData.appId);
if (app) {
Me.msWindowManager.createNewMsWindow(
app,
{
msWorkspace: this,
focus: false,
insert: false,
},
msWindowData.persistent
? msWindowData.persistent
: undefined,
{
x: msWindowData.x,
y: msWindowData.y,
width: msWindowData.width,
height: msWindowData.height,
},
matchingInfo
);
}
}
this.msWorkspaceCategory.refreshCategory();
this.setLayoutByKey(initialState.layoutKey);
// Among other things, informs the TaskBar about the initial windows
this.emit('tileableList-changed', this.tileableList);
this.connect('tileableList-changed', () => {
this.msWorkspaceCategory.refreshCategory();
});
}
destroy() {
logAssert(!this.destroyed, 'Workspace is destroyed');
this.appLauncher.onDestroy();
this.layout.onDestroy();
if (this.msWorkspaceActor) {
this.msWorkspaceActor.destroy();
}
this.destroyed = true;
}
/** Index of the focused tileable.
* If there are no tileables in the workspace, this will be zero.
*/
get focusedIndex() {
return this._state.focusedIndex;
}
set focusedIndex(index) {
this._state.focusedIndex = index;
Me.stateManager.stateChanged();
}
get state(): MsWorkspaceState {
this._state.msWindowList = this.tileableList
.filter(isMsWindow)
.filter((msWindow) => {
return (
!msWindow.app.is_window_backed() &&
(msWindow.lifecycleState.type === 'app-placeholder' ||
msWindow.lifecycleState.type === 'window')
);
})
.map((msWindow) => {
return msWindow.state;
});
if (this.layout) {
this._state.layoutStateList[
this._state.layoutStateList.findIndex(
(layoutState) => layoutState.key === this.layout.state.key
)
] = this.layout.state;
this._state.layoutKey = this.layout.state.key;
}
if (this.msWorkspaceCategory) {
this._state.forcedCategory =
this.msWorkspaceCategory.forcedCategory;
}
return this._state;
}
get tileableFocused() {
logAssert(!this.destroyed, 'Workspace is destroyed');
if (!this.tileableList) return null;
return this.tileableList[this.focusedIndex] || null;
}
get msWindowList() {
return this.tileableList.filter(isMsWindow);
}
get containFullscreenWindow() {
return this.msWindowList.some((msWindow) => {
return msWindow.metaWindow
? msWindow.metaWindow.is_fullscreen()
: false;
});
}
get workspace() {
if (this.monitorIsExternal) return null;
return this.msWorkspaceManager.getWorkspaceOfMsWorkspace(this);
}
close() {
logAssert(!this.destroyed, 'Workspace is destroyed');
this.closing = true;
Promise.all(
this.msWindowList.map((msWindow) => {
return msWindow.kill();
})
).then((_params) => {
this.closing = false;
this.emit('readyToBeClosed');
});
}
async addMsWindow(msWindow: MsWindow, focus = false, insert = false) {
if (
!msWindow ||
(msWindow.msWorkspace && msWindow.msWorkspace === this)
) {
return;
}
msWindow.setMsWorkspace(this);
try {
return await this.addMsWindowUnchecked(msWindow, focus, insert);
} catch (e) {
return Me.logWithStackTrace('addMsWindowUnchecked failed');
}
}
/// Assumes that msWindow.msWorkspace == this already but that
/// it hasn't been added to this workspace.
async addMsWindowUnchecked(
msWindow: MsWindow,
focus = false,
insert = false
) {
logAssert(!this.destroyed, 'Workspace is destroyed');
if (this.msWorkspaceActor && !msWindow.dragged) {
reparentActor(msWindow, this.msWorkspaceActor.tileableContainer);
}
let insertAt = this.tileableList.length - 1;
// Do not insert tileable after App Launcher
if (insert && this.tileableFocused !== this.appLauncher) {
insertAt = this.focusedIndex + 1;
this.insertedMsWindow = msWindow;
}
this.tileableList.splice(insertAt, 0, msWindow);
if (focus) {
this.focusTileable(msWindow);
}
this.msWorkspaceActor.updateUI();
// TODO: Emitting the event after a small duration is potentially bad.
// If the window was focused the task bar will be in an invalid state
// until the 'tileableList-changed' event runs because the focus index
// will be out of bounds.
await this.emitTileableListChangedOnce();
}
async removeMsWindow(msWindow: MsWindow) {
logAssert(!this.destroyed, 'Workspace is destroyed');
if (this.msWindowList.indexOf(msWindow) === -1) return;
const tileableIsFocused = msWindow === this.tileableFocused;
const tileableIndex = this.tileableList.indexOf(msWindow);
this.tileableList.splice(tileableIndex, 1);
// Update the focusedIndex
if (
(tileableIsFocused && this.insertedMsWindow) ||
this.focusedIndex > tileableIndex
) {
this.focusedIndex--;
}
this.focusedIndex = Math.max(
0,
Math.min(this.tileableList.length - 1, this.focusedIndex)
);
await this.emitTileableListChangedOnce();
// If there's no more focused msWindow on this workspace focus the last one
if (tileableIsFocused) {
// If the window removed as just been inserted focus previous instead of next
this.focusTileable(this.tileableList[this.focusedIndex], true);
}
this.msWorkspaceActor.updateUI();
this.refreshFocus();
}
async emitTileableListChangedOnce() {
if (!this.emitTileableChangedInProgress) {
this.emitTileableChangedInProgress = new Promise<void>(
(resolve) => {
GLib.idle_add(GLib.PRIORITY_DEFAULT, () => {
delete this.emitTileableChangedInProgress;
this.emit('tileableList-changed', this.tileableList);
resolve();
return GLib.SOURCE_REMOVE;
});
}
);
}
return this.emitTileableChangedInProgress;
}
swapTileable(firstTileable: Tileable, secondTileable: Tileable) {
const firstIndex = this.tileableList.indexOf(firstTileable);
const secondIndex = this.tileableList.indexOf(secondTileable);
assert(firstIndex !== -1, 'Tileable did not exist in workspace');
assert(secondIndex !== -1, 'Tileable did not exist in workspace');
this.tileableList[firstIndex] = secondTileable;
this.tileableList[secondIndex] = firstTileable;
this.emit('tileableList-changed', this.tileableList);
}
swapTileableLeft(tileable: Tileable) {
const index = this.tileableList.indexOf(tileable);
if (index === -1) return;
if (index > 0 && tileable != this.appLauncher) {
const previousTileable = this.tileableList[index - 1];
this.swapTileable(tileable, previousTileable);
this.focusPreviousTileable();
}
}
swapTileableRight(tileable: Tileable) {
const index = this.tileableList.indexOf(tileable);
if (index === -1) return;
if (
index < this.tileableList.length - 1 &&
tileable != this.appLauncher
) {
const nextTileable = this.tileableList[index + 1];
if (nextTileable === this.appLauncher) {
return;
}
this.swapTileable(tileable, nextTileable);
this.focusNextTileable();
}
}
focusNextTileable() {
if (this.focusedIndex === this.tileableList.length - 1) {
if (this.shouldCycleTileableNavigation()) {
this.focusTileable(this.tileableList[0]);
return;
}
return;
}
this.focusTileable(this.tileableList[this.focusedIndex + 1]);
}
focusPreviousTileable() {
if (this.focusedIndex === 0) {
if (this.shouldCycleTileableNavigation()) {
this.focusTileable(
this.tileableList[this.tileableList.length - 1]
);
return;
}
return;
}
this.focusTileable(this.tileableList[this.focusedIndex - 1]);
}
focusAppLauncher() {
if (
!this.tileableList ||
this.tileableList.length < 2 ||
this.tileableFocused === this.appLauncher
) {
return;
}
this.focusTileable(this.appLauncher);
}
focusPrecedentTileable() {
if (!this.tileableList || this.tileableList.length < 2) return;
if (
this.focusedIndex !== this.precedentIndex &&
this.precedentIndex < this.tileableList.length
) {
this.focusTileable(this.tileableList[this.precedentIndex]);
}
}
focusTileable(
tileable: MsWindow | MsApplicationLauncher | null,
forced = false
) {
if (!tileable || (tileable === this.tileableFocused && !forced)) {
return;
}
if (tileable !== this.insertedMsWindow) {
this.insertedMsWindow = null;
}
const oldTileableFocused = this.tileableFocused;
if (tileable !== this.tileableFocused) {
this.precedentIndex = this.focusedIndex;
}
this.focusedIndex = Math.max(this.tileableList.indexOf(tileable), 0);
if (this.msWorkspaceManager.getActiveMsWorkspace() === this) {
tileable.grab_key_focus();
}
this.emit('tileable-focus-changed', tileable, oldTileableFocused);
}
refreshFocus(forced = false) {
if (
this.msWorkspaceManager.getActiveMsWorkspace() !== this &&
!forced
) {
return;
}
const focused = this.tileableFocused;
if (focused !== null) focused.grab_key_focus();
}
setTileableAtIndex(tileableToMove: Tileable, index: number) {
const tileableToMoveIndex = this.tileableList.indexOf(tileableToMove);
this.tileableList.splice(tileableToMoveIndex, 1);
this.tileableList.splice(index, 0, tileableToMove);
this.emit('tileableList-changed', this.tileableList);
}
nextLayout(direction: number) {
this.layout.onDestroy();
let { key } = (this.layout.constructor as LayoutType).state;
if (
!this.state.layoutStateList.find(
(layoutState) => layoutState.key === key
)
) {
key = this.state.layoutStateList[0].key;
}
let nextIndex =
this.state.layoutStateList.findIndex(
(layoutState) => layoutState.key === key
) + direction;
if (nextIndex < 0) {
nextIndex += this.state.layoutStateList.length;
}
nextIndex = nextIndex % this.state.layoutStateList.length;
// Get the next layout available
const newLayoutState = this.state.layoutStateList[nextIndex];
this.setLayoutByKey(newLayoutState.key);
}
setLayoutByKey(layoutKey: string) {
logAssert(!this.destroyed, 'Workspace is destroyed');
if (this.layout) {
this.layout.onDestroy();
}
this.layout = Me.layoutManager.createLayout(
this,
assertNotNull(
this.state.layoutStateList.find(
(layoutState) => layoutState.key === layoutKey
)
)
);
this.msWorkspaceActor.tileableContainer.set_layout_manager(this.layout);
this.emit('tiling-layout-changed');
}
shouldPanelBeVisible() {
return !this.containFullscreenWindow &&
this.msWorkspaceManager &&
Me.layout
? Me.layout.panelsVisible
: true;
}
shouldCycleTileableNavigation() {
return getSettings('tweaks').get_boolean('cycle-through-windows');
}
isDisplayed() {
if (this.monitorIsExternal) {
return true;
} else {
return (
this === this.msWorkspaceManager.getActivePrimaryMsWorkspace()
);
}
}
activate() {
const workspace = this.workspace;
if (workspace === null) return;
if (
this.tileableFocused instanceof MsWindow &&
this.tileableFocused.metaWindow &&
!this.tileableFocused.dragged
) {
workspace.activate_with_focus(
this.tileableFocused.metaWindow,
global.get_current_time()
);
} else {
workspace.activate(global.get_current_time());
}
}
setMonitor(monitor: Monitor) {
this.monitor = monitor;
this.monitorIsExternal =
monitor.index !== Main.layoutManager.primaryIndex;
this.msWindowList.forEach((msWindow) => {
msWindow.setMsWorkspace(this);
});
}
}
@registerGObjectClass
export class MsWorkspaceActor extends Clutter.Actor {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'MsWorkspaceActor',
};
tileableContainer: Clutter.Actor<
Clutter.LayoutManager,
Clutter.ContentPrototype
>;
panel: HorizontalPanel;
msWorkspace: MsWorkspace;
constructor(msWorkspace: MsWorkspace) {
super({
clip_to_allocation: true,
x_expand: true,
y_expand: true,
//background_color: new Clutter.Color({ red: 120, alpha: 255 }),
});
this.msWorkspace = msWorkspace;
this.tileableContainer = new Clutter.Actor({
//background_color: new Clutter.Color({ blue: 120, alpha: 255 }),
});
this.panel = new HorizontalPanel(msWorkspace);
this.add_child(this.tileableContainer);
this.add_child(this.panel);
this.updateUI();
}
updateUI() {
const monitorInFullScreen = global.display.get_monitor_in_fullscreen(
this.msWorkspace.monitor.index
);
if (this.panel) {
this.panel.visible =
this.msWorkspace.shouldPanelBeVisible() && !monitorInFullScreen;
}
this.visible = !monitorInFullScreen;
}
override vfunc_allocate(
box: Clutter.ActorBox,
flags?: Clutter.AllocationFlags
) {
SetAllocation(this, box, flags);
const contentBox = new Clutter.ActorBox();
contentBox.x2 = box.get_width();
contentBox.y2 = box.get_height();
const panelPosition = Me.msThemeManager.horizontalPanelPosition;
const panelHeight = (
this.panel.get_preferred_height(-1) as [number, number]
)[1];
const panelBox = new Clutter.ActorBox();
panelBox.x1 = contentBox.x1;
panelBox.x2 = contentBox.x2;
panelBox.y1 =
panelPosition === HorizontalPanelPositionEnum.TOP
? contentBox.y1
: contentBox.y2 - panelHeight;
panelBox.y2 = panelBox.y1 + panelHeight;
Allocate(this.panel, panelBox, flags);
const containerBox = new Clutter.ActorBox();
containerBox.x1 = contentBox.x1;
containerBox.x2 = contentBox.x2;
containerBox.y1 = contentBox.y1;
containerBox.y2 = contentBox.y2;
if (this.panel && this.panel.visible) {
if (panelPosition === HorizontalPanelPositionEnum.TOP) {
containerBox.y1 = containerBox.y1 + panelHeight;
} else {
containerBox.y2 = containerBox.y2 - panelHeight;
}
}
Allocate(this.tileableContainer, containerBox, flags);
this.get_children()
.filter(
(actor) =>
[this.panel, this.tileableContainer].indexOf(actor) === -1
)
.forEach((actor) => {
Allocate(actor, containerBox, flags);
});
}
} | the_stack |
declare namespace API {
/**
*
* @export
* @interface Action
*/
export interface Action {
/**
*
* @type {number}
* @memberof Action
*/
id?: number;
/**
* 项目ID
* @type {number}
* @memberof Action
*/
projectId?: number;
/**
* 名字
* @type {string}
* @memberof Action
*/
name?: string;
/**
* 操作描述
* @type {string}
* @memberof Action
*/
description?: string;
/**
* 创建人ID
* @type {number}
* @memberof Action
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof Action
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof Action
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof Action
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof Action
*/
deletedAt?: string;
}
/**
*
* @export
* @interface ActionPagination
*/
export interface ActionPagination {
/**
* json repose code
* @type {number}
* @memberof ActionPagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof ActionPagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof ActionPagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof ActionPagination
*/
limit?: number;
/**
*
* @type {Array<Action>}
* @memberof ActionPagination
*/
list?: Array<Action>;
}
/**
*
* @export
* @interface ApiResponse
*/
export interface ApiResponse {
/**
*
* @type {number}
* @memberof ApiResponse
*/
code?: number;
/**
*
* @type {string}
* @memberof ApiResponse
*/
msg?: string;
}
/**
*
* @export
* @interface Group
*/
export interface Group {
/**
*
* @type {number}
* @memberof Group
*/
id?: number;
/**
* 名字
* @type {string}
* @memberof Group
*/
name?: string;
/**
* 描述
* @type {string}
* @memberof Group
*/
description?: string;
/**
* 创建人ID
* @type {number}
* @memberof Group
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof Group
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof Group
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof Group
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof Group
*/
deletedAt?: string;
}
/**
*
* @export
* @interface GroupPagination
*/
export interface GroupPagination {
/**
* json repose code
* @type {number}
* @memberof GroupPagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof GroupPagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof GroupPagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof GroupPagination
*/
limit?: number;
/**
*
* @type {Array<Group>}
* @memberof GroupPagination
*/
list?: Array<Group>;
}
/**
*
* @export
* @interface Menu
*/
export interface Menu {
/**
*
* @type {number}
* @memberof Menu
*/
id?: number;
/**
* 项目ID
* @type {number}
* @memberof Menu
*/
projectId?: number;
/**
* 名字
* @type {string}
* @memberof Menu
*/
name?: string;
/**
* 备注
* @type {string}
* @memberof Menu
*/
desc?: string;
/**
* i18n主键
* @type {string}
* @memberof Menu
*/
i18N?: string;
/**
* 排序值
* @type {number}
* @memberof Menu
*/
sortOrder?: number;
/**
* 图标
* @type {string}
* @memberof Menu
*/
icon?: string;
/**
* 路由,link、externalLink 二选其一
* @type {string}
* @memberof Menu
*/
link?: string;
/**
* 访问路由
* @type {string}
* @memberof Menu
*/
externalLink?: string;
/**
* 链接 target
* @type {string}
* @memberof Menu
*/
target?: string;
/**
* 是否禁用菜单, 1:不禁用 2:禁用
* @type {number}
* @memberof Menu
*/
disabled?: number;
/**
* 隐藏菜单, 1:不隐藏 2:隐藏
* @type {number}
* @memberof Menu
*/
hide?: number;
/**
* 隐藏面包屑, 1:不隐藏 2:隐藏
* @type {number}
* @memberof Menu
*/
hideInBreadcrumb?: number;
/**
* 父级 ID
* @type {number}
* @memberof Menu
*/
parentId?: number;
/**
* 创建人ID
* @type {number}
* @memberof Menu
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof Menu
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof Menu
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof Menu
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof Menu
*/
deletedAt?: string;
}
/**
*
* @export
* @interface MenuPagination
*/
export interface MenuPagination {
/**
* json repose code
* @type {number}
* @memberof MenuPagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof MenuPagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof MenuPagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof MenuPagination
*/
limit?: number;
/**
*
* @type {Array<Menu>}
* @memberof MenuPagination
*/
list?: Array<Menu>;
}
/**
*
* @export
* @interface Org
*/
export interface Org {
/**
*
* @type {number}
* @memberof Org
*/
id?: number;
/**
* 组织机构代码
* @type {string}
* @memberof Org
*/
code?: string;
/**
* 名字
* @type {string}
* @memberof Org
*/
name?: string;
/**
* 备注
* @type {string}
* @memberof Org
*/
description?: string;
/**
* logo
* @type {string}
* @memberof Org
*/
logo?: string;
/**
* 创建人ID
* @type {number}
* @memberof Org
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof Org
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof Org
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof Org
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof Org
*/
deletedAt?: string;
}
/**
*
* @export
* @interface OrgNode
*/
export interface OrgNode {
/**
*
* @type {number}
* @memberof OrgNode
*/
id?: number;
/**
* 名字
* @type {string}
* @memberof OrgNode
*/
name?: string;
/**
* 备注
* @type {string}
* @memberof OrgNode
*/
description?: string;
/**
* 父级 ID
* @type {number}
* @memberof OrgNode
*/
parentId?: number;
/**
* 组织机构 ID
* @type {number}
* @memberof OrgNode
*/
orgId?: number;
/**
* 根节点 1 是, 2 否
* @type {number}
* @memberof OrgNode
*/
root?: number;
/**
* 层级数
* @type {number}
* @memberof OrgNode
*/
depth?: number;
/**
* 排序值
* @type {number}
* @memberof OrgNode
*/
order?: number;
/**
* 创建人ID
* @type {number}
* @memberof OrgNode
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof OrgNode
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof OrgNode
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof OrgNode
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof OrgNode
*/
deletedAt?: string;
/**
*
* @type {any}
* @memberof OrgNode
*/
org?: any | null;
}
/**
*
* @export
* @interface OrgNodePagination
*/
export interface OrgNodePagination {
/**
* json repose code
* @type {number}
* @memberof OrgNodePagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof OrgNodePagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof OrgNodePagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof OrgNodePagination
*/
limit?: number;
/**
*
* @type {Array<OrgNode>}
* @memberof OrgNodePagination
*/
list?: Array<OrgNode>;
}
/**
*
* @export
* @interface OrgPagination
*/
export interface OrgPagination {
/**
* json repose code
* @type {number}
* @memberof OrgPagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof OrgPagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof OrgPagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof OrgPagination
*/
limit?: number;
/**
*
* @type {Array<Org>}
* @memberof OrgPagination
*/
list?: Array<Org>;
}
/**
*
* @export
* @interface Project
*/
export interface Project {
/**
*
* @type {number}
* @memberof Project
*/
id: number;
/**
* 名字
* @type {string}
* @memberof Project
*/
name: string;
/**
* 描述
* @type {string}
* @memberof Project
*/
description?: string;
/**
* 创建人ID
* @type {number}
* @memberof Project
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof Project
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof Project
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof Project
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof Project
*/
deletedAt?: string;
}
/**
*
* @export
* @interface ProjectPagination
*/
export interface ProjectPagination {
/**
* json repose code
* @type {number}
* @memberof ProjectPagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof ProjectPagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof ProjectPagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof ProjectPagination
*/
limit?: number;
/**
*
* @type {Array<Project>}
* @memberof ProjectPagination
*/
list?: Array<Project>;
}
/**
*
* @export
* @interface Resource
*/
export interface Resource {
/**
*
* @type {number}
* @memberof Resource
*/
id?: number;
/**
* 项目ID
* @type {number}
* @memberof Resource
*/
projectId?: number;
/**
* 名字
* @type {string}
* @memberof Resource
*/
name?: string;
/**
* 资源描述
* @type {string}
* @memberof Resource
*/
description?: string;
/**
* 资源类型, 1: API 2: 菜单 3: 数据
* @type {string}
* @memberof Resource
*/
type?: string;
/**
* 资源路由,type为1时有效
* @type {string}
* @memberof Resource
*/
route?: string;
/**
* 菜单ID,type为2时有效
* @type {number}
* @memberof Resource
*/
menuId?: number;
/**
* 创建人ID
* @type {number}
* @memberof Resource
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof Resource
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof Resource
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof Resource
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof Resource
*/
deletedAt?: string;
}
/**
*
* @export
* @interface ResourcePagination
*/
export interface ResourcePagination {
/**
* json repose code
* @type {number}
* @memberof ResourcePagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof ResourcePagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof ResourcePagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof ResourcePagination
*/
limit?: number;
/**
*
* @type {Array<Resource>}
* @memberof ResourcePagination
*/
list?: Array<Resource>;
}
/**
*
* @export
* @interface User
*/
export interface User {
/**
*
* @type {number}
* @memberof User
*/
id?: number;
/**
* 名称
* @type {string}
* @memberof User
*/
username?: string;
/**
* 昵称
* @type {string}
* @memberof User
*/
nickname?: string;
/**
* 密码
* @type {string}
* @memberof User
*/
password?: string;
/**
* 手机号
* @type {string}
* @memberof User
*/
mobile?: string;
/**
* 手机号验证是否通过 1 通过, 2 未通过
* @type {number}
* @memberof User
*/
mobileVerified?: number;
/**
* 邮箱
* @type {string}
* @memberof User
*/
email?: string;
/**
* 邮箱验证是否通过 1 通过, 2 未通过
* @type {number}
* @memberof User
*/
emailVerified?: number;
/**
* 1 可用, 2 禁用, 3 注销
* @type {number}
* @memberof User
*/
status?: number;
/**
* 性别 1 男, 2 女, 3 未知
* @type {number}
* @memberof User
*/
gender?: number;
/**
* 地址
* @type {string}
* @memberof User
*/
address?: string;
/**
* 最近一次登录IP地址
* @type {string}
* @memberof User
*/
lastLoginIp?: string;
/**
* 最近一次登录时间
* @type {string}
* @memberof User
*/
lastLoginTime?: string;
/**
* 登录次数
* @type {number}
* @memberof User
*/
loginCount?: number;
/**
* 头像图片
* @type {string}
* @memberof User
*/
avatar?: string;
/**
* 创建人ID
* @type {number}
* @memberof User
*/
createBy?: number;
/**
* 修改人ID
* @type {number}
* @memberof User
*/
updateBy?: number;
/**
*
* @type {string}
* @memberof User
*/
createdAt?: string;
/**
*
* @type {string}
* @memberof User
*/
updatedAt?: string;
/**
*
* @type {string}
* @memberof User
*/
deletedAt?: string;
/**
*
* @type {Array<Group>}
* @memberof User
*/
groups?: Array<Group>;
/**
*
* @type {Array<OrgNode>}
* @memberof User
*/
orgNodes?: Array<OrgNode>;
}
/**
*
* @export
* @interface UserPagination
*/
export interface UserPagination {
/**
* json repose code
* @type {number}
* @memberof UserPagination
*/
code?: number;
/**
* total numbers
* @type {number}
* @memberof UserPagination
*/
total?: number;
/**
* offset
* @type {number}
* @memberof UserPagination
*/
offset?: number;
/**
* limit
* @type {number}
* @memberof UserPagination
*/
limit?: number;
/**
*
* @type {Array<User>}
* @memberof UserPagination
*/
list?: Array<User>;
}
} | the_stack |
* @module Zone
*/
import { PointProps } from "@itwin/appui-abstract";
import { Point, Rectangle, RectangleProps } from "@itwin/core-react";
import { NestedStagePanelKey, NestedStagePanelsManagerProps } from "../stage-panels/manager/NestedStagePanels";
import { StagePanelsManager } from "../stage-panels/manager/StagePanels";
import { StagePanelType } from "../stage-panels/StagePanel";
import { ToolSettingsWidgetMode } from "../zones/manager/Widget";
import { WidgetZoneId, ZonesManager, ZonesManagerProps } from "../zones/manager/Zones";
import { NineZoneNestedStagePanelsManager, NineZoneNestedStagePanelsManagerProps } from "./NestedStagePanels";
import { NineZoneStagePanelManager } from "./StagePanel";
/** Properties used by [[NineZoneManager]].
* @internal
*/
export interface NineZoneManagerProps {
readonly nested: NineZoneNestedStagePanelsManagerProps;
readonly zones: ZonesManagerProps;
}
/** Arguments of [[NineZoneManager.handleWidgetTabDragStart]].
* @internal
*/
export interface WidgetTabDragStartArguments {
/** Initial mouse down position. */
readonly initialPosition: PointProps;
/** Dragged tab index. */
readonly tabIndex: number;
/** Current widget bounds. */
readonly widgetBounds: RectangleProps;
/** Dragged widget index. */
readonly widgetId: WidgetZoneId;
}
/** Stage panel target used by [[NineZoneManager]].
* @internal
*/
export interface NineZoneManagerPanelTarget {
readonly panelId: string | number;
readonly panelType: StagePanelType;
}
/** Splitter pane target used by [[NineZoneManager]].
* @internal
*/
export interface NineZoneManagerPaneTarget extends NineZoneManagerPanelTarget {
readonly paneIndex: number;
}
/** @internal */
export type NineZoneManagerHiddenWidgets = { readonly [id in WidgetZoneId]: NineZoneManagerHiddenWidget };
/** @internal */
export interface NineZoneManagerHiddenWidget {
panel?: {
key: NestedStagePanelKey<NestedStagePanelsManagerProps>;
};
}
/** Class used to manage [[NineZoneStagePanelManagerProps]].
* @internal
*/
export class NineZoneManager {
private _nestedPanelsManager?: NineZoneNestedStagePanelsManager;
private _zonesManager?: ZonesManager;
private _paneTarget?: NineZoneManagerPaneTarget;
private _panelTarget?: NineZoneManagerPanelTarget;
private _hiddenWidgets?: NineZoneManagerHiddenWidgets;
private findPanelWithWidget<TProps extends NineZoneManagerProps>(widgetId: WidgetZoneId, props: TProps) {
const nestedPanelById = Object.keys(props.nested.panels).map((id) => {
return { id, panels: props.nested.panels[id] };
});
const nestedPanelsManager = this.getNestedPanelsManager();
for (const { id, panels } of nestedPanelById) {
const panelsManager = nestedPanelsManager.getPanelsManager(id);
const type = panelsManager.findWidget(widgetId, panels);
if (type !== undefined)
return {
id,
...type,
};
}
return undefined;
}
public handleWidgetTabClick<TProps extends NineZoneManagerProps>(widgetId: WidgetZoneId, tabIndex: number, props: TProps): TProps {
let zones = props.zones;
const panelWithWidget = this.findPanelWithWidget(widgetId, props);
const zonesManager = this.getZonesManager();
if (panelWithWidget) {
const panels = props.nested.panels[panelWithWidget.id];
const panel = StagePanelsManager.getPanel(panelWithWidget.type, panels);
const pane = panel.panes[panelWithWidget.paneIndex];
for (const widget of pane.widgets) {
if (widget === widgetId)
zones = zonesManager.setWidgetTabIndex(widget, tabIndex, zones);
else
zones = zonesManager.setWidgetTabIndex(widget, -1, zones);
}
} else {
zones = zonesManager.handleWidgetTabClick(widgetId, tabIndex, zones);
}
if (zones === props.zones)
return props;
return this.setZones(zones, props);
}
public handleWidgetTabDragEnd<TProps extends NineZoneManagerProps>(props: TProps): TProps {
const zonesManager = this.getZonesManager();
let zones = zonesManager.handleWidgetTabDragEnd(props.zones);
const paneTarget = this.getPaneTarget();
const targetKey = this.getTargetKey();
const paneIndex = paneTarget ? paneTarget.paneIndex : undefined;
let nested = props.nested;
const draggedWidget = props.zones.draggedWidget;
if (targetKey && draggedWidget) {
const nestedPanelsManager = this.getNestedPanelsManager();
if (paneIndex !== undefined) {
const panels = nested.panels[targetKey.id];
const panel = StagePanelsManager.getPanel(targetKey.type, panels);
const pane = panel.panes[paneIndex];
for (const widget of pane.widgets) {
zones = zonesManager.setWidgetTabIndex(widget, -1, zones);
}
}
nested = nestedPanelsManager.addWidget(draggedWidget.id, targetKey, paneIndex, props.nested);
zones = zonesManager.removeWidget(draggedWidget.id, draggedWidget.id, zones);
const horizontalAnchor = NineZoneStagePanelManager.getHorizontalAnchor(targetKey.type);
zones = zonesManager.setWidgetHorizontalAnchor(draggedWidget.id, horizontalAnchor, zones);
const verticalAnchor = NineZoneStagePanelManager.getVerticalAnchor(targetKey.type);
zones = zonesManager.setWidgetVerticalAnchor(draggedWidget.id, verticalAnchor, zones);
if (draggedWidget.id === 2)
zones = zonesManager.setToolSettingsWidgetMode(ToolSettingsWidgetMode.Tab, zones);
}
props = this.setNested(nested, props);
props = this.setZones(zones, props);
return props;
}
public handleWidgetTabDragStart<TProps extends NineZoneManagerProps>(args: WidgetTabDragStartArguments, props: TProps): TProps {
const nestedPanelsManager = this.getNestedPanelsManager();
const zonesManager = this.getZonesManager();
let nested = props.nested;
let zones = props.zones;
const panelWithWidget = this.findPanelWithWidget(args.widgetId, props);
if (panelWithWidget !== undefined) {
nestedPanelsManager.getPanelsManager(panelWithWidget.id);
nested = nestedPanelsManager.removeWidget(args.widgetId, panelWithWidget, props.nested);
zones = zonesManager.addWidget(args.widgetId, args.widgetId, zones);
const widget = props.zones.widgets[args.widgetId];
const panels = props.nested.panels[panelWithWidget.id];
const panel = StagePanelsManager.getPanel(panelWithWidget.type, panels);
const pane = panel.panes[panelWithWidget.paneIndex];
if (widget.tabIndex < 0) {
// Open dragged widget for zones manager.
zones = zonesManager.setWidgetTabIndex(args.widgetId, args.tabIndex, zones);
} else {
// Opened widget is removed, need to open next widget in a pane
for (const w of pane.widgets) {
if (w === args.widgetId) // Skip removed widget if it is first
continue;
zones = zonesManager.setWidgetTabIndex(w, 0, zones);
break;
}
}
}
zones = zonesManager.handleWidgetTabDragStart(args.widgetId, args.tabIndex, args.initialPosition, args.widgetBounds, zones);
const newZone = zones.zones[args.widgetId];
const oldZone = props.zones.zones[args.widgetId];
if (panelWithWidget && newZone.floating && oldZone.floating) {
const newBounds = Rectangle.create(newZone.floating.bounds);
const oldBounds = Rectangle.create(oldZone.floating.bounds);
const newSize = newBounds.getSize();
const oldSize = oldBounds.getSize();
let draggedWidget = zones.draggedWidget;
if (draggedWidget && panelWithWidget && panelWithWidget.type === StagePanelType.Left) {
const widthDiff = oldSize.width - newSize.width;
draggedWidget = {
...draggedWidget,
lastPosition: Point.create(draggedWidget.lastPosition).offsetX(widthDiff).toProps(),
};
}
if (draggedWidget && panelWithWidget && panelWithWidget.type === StagePanelType.Top) {
const heightDiff = oldSize.height - newSize.height;
draggedWidget = {
...draggedWidget,
lastPosition: Point.create(draggedWidget.lastPosition).offsetY(heightDiff).toProps(),
};
}
zones = {
...zones,
zones: {
...zones.zones,
[args.widgetId]: {
...zones.zones[args.widgetId],
floating: {
...zones.zones[args.widgetId].floating,
bounds: newBounds.setSize(oldSize).toProps(),
},
},
},
draggedWidget,
};
}
props = this.setNested(nested, props);
props = this.setZones(zones, props);
return props;
}
public getNestedPanelsManager(): NineZoneNestedStagePanelsManager {
if (!this._nestedPanelsManager)
this._nestedPanelsManager = new NineZoneNestedStagePanelsManager();
return this._nestedPanelsManager;
}
/** @internal */
public getHiddenWidgets(): NineZoneManagerHiddenWidgets {
if (!this._hiddenWidgets)
this._hiddenWidgets = {
1: {},
2: {},
3: {},
4: {},
6: {},
7: {},
8: {},
9: {},
};
return this._hiddenWidgets;
}
public getZonesManager(): ZonesManager {
if (!this._zonesManager)
this._zonesManager = new ZonesManager();
return this._zonesManager;
}
public setPaneTarget(target: NineZoneManagerPaneTarget | undefined) {
this._paneTarget = target;
}
public getPaneTarget(): NineZoneManagerPaneTarget | undefined {
return this._paneTarget;
}
public setPanelTarget(target: NineZoneManagerPanelTarget | undefined) {
this._panelTarget = target;
}
public getPanelTarget() {
return this._panelTarget;
}
private getTargetKey() {
const panelTarget = this.getPanelTarget();
const paneTarget = this.getPaneTarget();
return panelTarget ? {
id: panelTarget.panelId,
type: panelTarget.panelType,
} : paneTarget ? {
id: paneTarget.panelId,
type: paneTarget.panelType,
} : undefined;
}
public showWidget<TProps extends NineZoneManagerProps>(widgetId: WidgetZoneId, props: TProps): TProps {
const zonesManager = this.getZonesManager();
const hiddenWidgets = this.getHiddenWidgets();
const hiddenWidget = hiddenWidgets[widgetId];
const panel = hiddenWidget.panel;
let zones = props.zones;
let nested = props.nested;
if (panel) {
const nestedPanelsManager = this.getNestedPanelsManager();
nested = nestedPanelsManager.addWidget(widgetId, panel.key, undefined, props.nested);
} else {
zones = zonesManager.addWidget(widgetId, widgetId, props.zones);
}
zones = zonesManager.setWidgetTabIndex(widgetId, 0, zones);
props = this.setZones(zones, props);
props = this.setNested(nested, props);
return props;
}
public hideWidget<TProps extends NineZoneManagerProps>(widgetId: WidgetZoneId, props: TProps): TProps {
const zonesManager = this.getZonesManager();
const hiddenWidgets = this.getHiddenWidgets();
const hiddenWidget = hiddenWidgets[widgetId];
const zoneWithWidget = zonesManager.findZoneWithWidget(widgetId, props.zones);
if (zoneWithWidget) {
hiddenWidget.panel = undefined;
const zones = zonesManager.removeWidget(widgetId, widgetId, props.zones);
return this.setZones(zones, props);
}
const panelWithWidget = this.findPanelWithWidget(widgetId, props);
if (panelWithWidget) {
hiddenWidget.panel = {
key: {
id: panelWithWidget.id,
type: panelWithWidget.type,
},
};
let zones = props.zones;
const nestedPanelsManager = this.getNestedPanelsManager();
const panels = props.nested.panels[panelWithWidget.id];
const panel = StagePanelsManager.getPanel(panelWithWidget.type, panels);
const pane = panel.panes[panelWithWidget.paneIndex];
const isOpen = props.zones.widgets[widgetId].tabIndex > -1;
if (isOpen && pane.widgets.length > 1) {
const widgetToOpen = pane.widgets.find((w) => w !== widgetId)!;
zones = zonesManager.setWidgetTabIndex(widgetToOpen, 0, zones);
}
zones = zonesManager.setWidgetTabIndex(widgetId, -1, zones);
const nested = nestedPanelsManager.removeWidget(widgetId, panelWithWidget, props.nested);
props = this.setZones(zones, props);
props = this.setNested(nested, props);
return props;
}
return props;
}
/** @internal */
public setZones<TProps extends NineZoneManagerProps>(zones: TProps["zones"], props: TProps): TProps {
return this.setProp(zones, "zones", props);
}
/** @internal */
public setNested<TProps extends NineZoneManagerProps>(nested: TProps["nested"], props: TProps): TProps {
return this.setProp(nested, "nested", props);
}
/** @internal */
public setProp<TProps extends NineZoneManagerProps, TKey extends keyof TProps>(value: TProps[TKey], key: TKey, props: TProps): TProps {
if (value === props[key])
return props;
return {
...props,
[key]: value,
};
}
} | the_stack |
import React, { useState, useMemo, useRef } from 'react'
import { Button, Icon, Tree, Tooltip, message, Checkbox } from 'antd'
import { AntTreeNodeSelectedEvent } from 'antd/lib/tree'
import { AntTreeNodeDropEvent, AntTreeNodeMouseEvent } from 'antd/lib/tree/Tree'
import styled from 'styled-components'
import { FormattedMessage, useIntl } from 'react-intl'
import {
IPageAction,
IFullInstance,
IKey,
IFullSchema,
IFullTable,
IFullSchemas,
IFullInstances,
IFullTables,
ISourceConfig,
ITaskInfo,
IInstances
} from '../types'
import BinlogFilterModal from './BinlogFilterModal'
import { genFinalConfig } from '../utils/config-util'
import { generateConfig, downloadConfig } from '../services/api'
const { TreeNode } = Tree
const Container = styled.div`
max-width: 800px;
margin: 0 auto;
.dbtable-shuttle-container {
display: flex;
justify-content: space-around;
}
.tree-container {
position: relative;
border: 1px solid #ccc;
border-radius: 4px;
padding: 8px;
width: 300px;
min-height: 300px;
max-height: 600px;
overflow-y: scroll;
}
.shuttle-arrows {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
button {
margin-bottom: 20px;
}
}
.action-buttons {
display: flex;
justify-content: center;
button {
margin: 24px;
margin-top: 48px;
}
}
.ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected {
background: #475edd;
color: white;
}
.ant-tree-title {
display: block;
position: relative;
}
.edit-icon {
position: absolute;
color: black;
top: 5px;
right: -30px;
}
.action-icons {
position: absolute;
top: 10px;
right: 10px;
}
.auto-sync-option {
margin-top: 10px;
width: 300px;
}
`
type LastStateRef = {
lastSourceSchemas: IFullSchemas
lastAllTables: IFullTables
lastTargetSchemas: IFullSchemas
}
function existedSchemaNames(schemas: IFullSchemas) {
return Object.keys(schemas)
.map(key => schemas[key])
.map(item => item.newName)
}
function loopGenUniqueName(oriName: string, existNames: string[]): string {
if (!existNames.includes(oriName)) {
return oriName
}
return loopGenUniqueName(`${oriName}_1`, existNames)
}
function genRandSuffix() {
return `${Date.now()}_${Math.floor(Math.random() * 1000)}`
}
type Props = IPageAction<any> & {
taskInfo: ITaskInfo
instancesConfig: IInstances
sourceConfig: ISourceConfig
targetSchemas: IFullSchemas
}
function MigrateStep({ onNext, onPrev, sourceConfig, ...remainProps }: Props) {
const intl = useIntl()
const sourceInstances: IFullInstances = sourceConfig.sourceInstances
const [sourceSchemas, setSourceSchemas] = useState<IFullSchemas>(
sourceConfig.sourceSchemas
)
const [allTables, setAllTables] = useState<IFullTables>(
sourceConfig.allTables
)
const [targetSchemas, setTargetSchemas] = useState<IFullSchemas>(
remainProps.targetSchemas
)
const [selectedSourceItem, setSelectedSourceItem] = useState<IKey>({
key: ''
})
const [selectedTargetItem, setSelectedTargetItem] = useState<IKey>({
key: ''
})
// modal
const [modalVisible, setModalVisible] = useState(false)
// button loading
const [loading, setLoading] = useState(false)
// checked keys
const [sourceCheckedKeys, setSourceCheckedKeys] = useState<string[]>([])
const [targetCheckedKeys, setTargetCheckedKeys] = useState<string[]>([])
const enableMoveRight = useMemo(() => sourceCheckedKeys.length > 0, [
sourceCheckedKeys
])
const enableMoveLeft = useMemo(() => targetCheckedKeys.length > 0, [
targetCheckedKeys
])
const enableDrag = useMemo(
// schema 不可以拖动,只有 table 可以
() => selectedTargetItem.key.split(':').length > 2,
[selectedTargetItem]
)
const targetInstance: IFullInstance = useMemo(
() => ({
type: 'instance',
sourceId: 'target-instance',
key: 'target-instance',
schemas: Object.keys(targetSchemas)
}),
[targetSchemas]
)
// 左移,右移,拖拽,重命名需要记录 lastStateRef
const lastStateRef = useRef<LastStateRef | null>(null)
// 是否自动同步上游新增库和新增表的选项
const [autoSyncUpstream, setAutoSyncUpstream] = useState(false)
/////////////////////////////////
function cleanTargetInstance() {
// confirm
if (!window.confirm(intl.formatMessage({ id: 'reset_confirm' }))) {
return
}
// 将所有下游的 table 移回上游
const tableKeys = Object.keys(allTables).filter(tableKey => {
const table = allTables[tableKey]
return table.parentKey !== '' && table.type === 'table'
})
moveMultiTablesLeft(tableKeys)
// clean
setSelectedTargetItem({ key: '' })
setTargetCheckedKeys([])
// undo 不可操作
lastStateRef.current = null
}
function undo() {
// confirm
if (!window.confirm(intl.formatMessage({ id: 'undo_confirm' }))) {
return
}
console.log(lastStateRef.current)
setSourceSchemas(lastStateRef.current!.lastSourceSchemas)
setAllTables(lastStateRef.current!.lastAllTables)
setTargetSchemas(lastStateRef.current!.lastTargetSchemas)
lastStateRef.current = null
}
function recordLastState() {
// deep copy
// not elegant, need to polish later
lastStateRef.current = {
lastSourceSchemas: JSON.parse(JSON.stringify(sourceSchemas)),
lastAllTables: JSON.parse(JSON.stringify(allTables)),
lastTargetSchemas: JSON.parse(JSON.stringify(targetSchemas))
}
}
/////////////////////////////////
function onSelectSourceItem(
selectedKeys: string[],
e: AntTreeNodeSelectedEvent
) {
const { node, selected } = e
console.log(node.props.dataRef)
setSelectedSourceItem(selected ? node.props.dataRef : { key: '' })
}
function onSelectTargetItem(
selectedKeys: string[],
e: AntTreeNodeSelectedEvent
) {
const { node, selected } = e
console.log(node.props.dataRef)
setSelectedTargetItem(selected ? node.props.dataRef : { key: '' })
}
function onEditIconClick(e: any) {
e.stopPropagation()
setModalVisible(true)
}
/////////////////////////////////
function onSourceCheck(checkedKeys: any) {
console.log(checkedKeys)
setSourceCheckedKeys(checkedKeys as string[])
}
function onTargetCheck(checkedKeys: any) {
console.log(checkedKeys)
setTargetCheckedKeys(checkedKeys as string[])
}
/////////////////////////////////
function moveRight() {
recordLastState()
// 流程
// 1. 清空左侧 source checked keys
// 2. 遍历 source checked keys,过滤出 table keys,然后抽取出 table 相应的 schema key,将 table key 放到相应的 schema key 下的数组中
// 3. 对 schema key 进行遍历,对每一个 schema key 生成相应的 target schema
// 4. 修改 schema key 对应的 source schema,从 tables 中移除移到右边的 table key
// 1. 清空左侧 source checked keys
setSourceCheckedKeys([])
// 2. 遍历 source checked keys,过滤出 table keys,然后抽取出 table 相应的 schema key,将 table key 放到相应的 schema key 下的数组中
const schemaTablesMap: { [key: string]: string[] } = {}
sourceCheckedKeys.forEach(oriKey => {
const keyArr = oriKey.split(':')
// 不是 table key
if (keyArr.length !== 3) {
return
}
const schemaKey = keyArr.slice(0, 2).join(':')
if (schemaTablesMap[schemaKey] === undefined) {
schemaTablesMap[schemaKey] = []
}
schemaTablesMap[schemaKey].push(oriKey)
})
// 3. 对 schema key 进行遍历,对每一个 schema key 生成相应的 target schema
// 4. 修改 schema key 对应的 source schema,从 tables 中移除移到右边的 table key
// 5. 修改每一个 table 的 parentKey
const newSourceSchemas = { ...sourceSchemas }
const newTargetSchemas = { ...targetSchemas }
const newAllTables = { ...allTables }
Object.keys(schemaTablesMap).forEach(schemaKey => {
const sourceSchema = newSourceSchemas[schemaKey]
// 修改 source schema
sourceSchema.tables = sourceSchema.tables.filter(
t => !schemaTablesMap[schemaKey].includes(t)
)
// 创建新的 target schema
const newName = loopGenUniqueName(
sourceSchema.schema,
existedSchemaNames(newTargetSchemas)
)
const targetSchema: IFullSchema = {
...sourceSchema,
key: `${sourceSchema.key}_${genRandSuffix()}`,
newName,
tables: schemaTablesMap[schemaKey]
}
newTargetSchemas[targetSchema.key] = targetSchema
newSourceSchemas[sourceSchema.key] = { ...sourceSchema }
// 修改 table 的 parentKey
targetSchema.tables.forEach(tblKey => {
newAllTables[tblKey].parentKey = targetSchema.key
})
})
setSourceSchemas(newSourceSchemas)
setTargetSchemas(newTargetSchemas)
setAllTables(newAllTables)
}
/////////////////////////////////
function moveLeft() {
console.log('moveLeft')
console.log((selectedTargetItem as any).mergedTables)
// !! weird, their value are different in the chrome console tab, is the chrome or react's bug?
// TODO: check in other browser
// console.log(selectedTargetItem)
// console.log(JSON.stringify(selectedTargetItem))
// console.log(selectedTargetItem.toString())
// console.log('target', targetSchemas)
// 现在知道原因了,是因为打印了这个对象后马上对它进行了修改
// 在 chrome 的 inspect 窗口观察 console.log(obj) 的输出时,
// 看到的并不是对象在打印时刻的值,而是当前最新的值,因为它是一个引用
recordLastState()
// console.log('current:', lastStateRef.current)
// 1. 清空 target checked keys
setTargetCheckedKeys([])
// 2. 过虑出 table keys
const tableKeys = targetCheckedKeys
.filter(key => key.split(':').length === 3)
.filter(tblKey => allTables[tblKey].type === 'table')
// console.log(tableKeys)
moveMultiTablesLeft(tableKeys)
// console.log('current', lastStateRef.current)
}
function moveMultiTablesLeft(tableKeys: string[]) {
const newAllTables: IFullTables = { ...allTables }
const newSourceSchemas: IFullSchemas = { ...sourceSchemas }
const newTargetSchemas: IFullSchemas = { ...targetSchemas }
// 循环,依次对每一个 table 左移
tableKeys.forEach(tableKey => {
const movedTable = newAllTables[tableKey]
// 2. 将 sourceSchema 的 tables 中加入 movedTable.key
const sourceSchemaKey = `${movedTable.sourceId}:${movedTable.schema}`
const sourceSchema = newSourceSchemas[sourceSchemaKey]
sourceSchema.tables = sourceSchema.tables.concat(movedTable.key)
// 3. updateMovedTableParent
updateMovedTableParent(movedTable, newTargetSchemas, newAllTables, false)
// 1. 修改 movedTable,恢复 newName,清空 parentKey
// 为什么将这一步挪到最后,因为在 updateMovedTableParent 中要用到原始的 movedTable.parentKey
movedTable.newName = movedTable.table
movedTable.parentKey = ''
})
// setState
setAllTables(newAllTables)
setSourceSchemas(newSourceSchemas)
setTargetSchemas(newTargetSchemas)
}
/////////////////////////////////
function onDrop(info: AntTreeNodeDropEvent) {
// 所有操作最终都要调用 updateMovedTableParent()
// 所有在 updateMovedTableParent() 方法中记录 lastState
if (info.dropToGap) {
// not support
return
}
const dragItem = info.dragNode.props.dataRef
const dropItem = info.node.props.dataRef
if ((dragItem as IFullTable).type === 'table') {
// dropItem: instance, schema, merged table, table, table belongs to merged table
if ((dropItem as IFullInstance).type === 'instance') {
// 产生新的 schema
moveTableToTop(dragItem as IFullTable)
} else if ((dropItem as IFullSchema).type === 'schema') {
// 不会产生新的 schema,put it inside
moveTableToSchema(dragItem as IFullTable, dropItem as IFullSchema)
} else if ((dropItem as IFullTable).type === 'mergedTable') {
// 不会产生新的合并表,put it inside
moveTableToMergedTable(dragItem as IFullTable, dropItem as IFullTable)
} else if ((dropItem as IFullTable).type === 'table') {
// 产生新的合并表
mergeTables(dragItem as IFullTable, dropItem as IFullTable)
}
} else if ((dragItem as IFullTable).type === 'mergedTable') {
// dropItem: instance, schema, merged table, table, table belongs to merged table
if ((dropItem as IFullInstance).type === 'instance') {
moveTableToTop(dragItem as IFullTable)
// create new schema
} else if ((dropItem as IFullSchema).type === 'schema') {
// move it
moveTableToSchema(dragItem as IFullTable, dropItem as IFullSchema)
} else if ((dropItem as IFullTable).type === 'mergedTable') {
return
} else if ((dropItem as IFullTable).type === 'table') {
return
}
}
}
function updateMovedTableParent(
movedTable: IFullTable,
newTargetSchemas: IFullSchemas,
newAllTables: IFullTables,
setStateInside: boolean = true
) {
// 记录 lastState
if (setStateInside) {
recordLastState()
}
// 修改 movedTable 的 parent
//
// 如果其 parent 为 schema,从其 tables 中移除 movedTableKey,移除之后如果 tables 为空,从 targetSchemas 中删除此 schema
//
// 如果其 parent 为 mergedTable,从 mergedTables 中移除 movedTableKey,移除之后如果 mergedTables 为空,从 allTables 中删除此 mergedTable
// 并从 parent schema tables 中删除此 mergedTable,如果 parent schema tables 为空,从 targetSchemas 中删除此 schema
const parentKey = movedTable.parentKey
const keyArrLen = parentKey.split(':').length
if (keyArrLen === 2) {
// movedTable parent is schema
const tableParent = newTargetSchemas[parentKey]
tableParent.tables = tableParent.tables.filter(t => t !== movedTable.key)
if (tableParent.tables.length === 0) {
delete newTargetSchemas[parentKey]
}
} else if (keyArrLen === 3) {
// movedTable parent is mergedTable
const tableParent = newAllTables[parentKey]
tableParent.mergedTables = tableParent.mergedTables!.filter(
t => t !== movedTable.key
)
if (tableParent.mergedTables.length === 0) {
delete newAllTables[tableParent.key]
// 继续修改 schema
const tableParentParent = newTargetSchemas[tableParent.parentKey]
tableParentParent.tables = tableParentParent.tables.filter(
t => t !== tableParent.key
)
if (tableParentParent.tables.length === 0) {
delete newTargetSchemas[tableParentParent.key]
}
}
}
if (setStateInside) {
setTargetSchemas(newTargetSchemas)
setAllTables(newAllTables)
}
}
function moveTableToTop(movedTable: IFullTable) {
console.log('移动 table 到实例下,生成 newdatabase')
// 创建新的 schema,其 tables 为 movedTable
// 为新的 schema 生成 newName 和 newKey
// 修改 movedTable,其 parentKey 指向新的 schema
// ----- 以下部分可以抽成函数 - 已抽成 updateMovedTableParent()
// 修改 movedTable 的 parent
// 如果其 parent 为 schema,从 tables 中移除 movedTableKey,移除之后如果 tables 为空,从 targetSchemas 中删除此 schema
// 如果其 parent 为 mergedTable,从 mergedTables 中移除 movedTableKey,移除之后如果 mergedTables 为空,从 allTables 中删除此 mergedTable
// 并从 parent schema tables 中删除此 mergedTable,如果 parent schema tables 为空,从 targetSchemas 中删除些 schema
// 1. create new schema, gen new name and new key
const newSchema: IFullSchema = {
type: 'schema',
sourceId: 'new',
schema: 'newdatabase',
key: `new:newdatabase_${genRandSuffix()}`,
tables: [movedTable.key],
newName: 'newdatabase',
filters: []
}
const existedNames = Object.keys(targetSchemas).map(
schemaKey => targetSchemas[schemaKey].newName
)
newSchema.newName = loopGenUniqueName('newdatabase', existedNames)
const newTargetSchemas: IFullSchemas = {
...targetSchemas,
[newSchema.key]: newSchema
}
// 2. change targetTable parentKey
const newAllTables: IFullTables = {
...allTables,
[movedTable.key]: {
...movedTable,
parentKey: newSchema.key
}
}
// 看 parent 是 schema 还是 merged table
// 3. update its parent
updateMovedTableParent(movedTable, newTargetSchemas, newAllTables)
}
function moveTableToSchema(
movedTable: IFullTable,
targetSchema: IFullSchema
) {
console.log('移动 table 到 schema 下')
// 先看 table 的 parent 是 schema 还是 mergedTable
//
// 如果是 parent 是 schema,先看和目标 schema 是不是同一个,如果是同一个,直接返回,不需要操作
// 否则
// 1. 将 movedTable 放到目标 schema 中,并修改自身的 newName 和 parentKey
// 2. 目标 schema 的 tables 加上 movedTable
// 3. parent schema tables 移除 movedTable,如果 tables length 为 0,从 targetSchema 中移除 (交给 updateMovedTableParent() 方法处理)
//
// 如果 parent 是 mergedTable
// 1. 将 movedTable 放到目标 schema 中,并修改自身的 newName 和 parentKey
// 2. 将 目标 schema 的 tables 加上 movedTable
// 3. 修改 parent mergedTable,交给 updateMovedTableParent() 方法处理
//
// 以上两种情况前两步是相同的操作,可以提取出来
//
// 如此,总结一下,所有移动都可以归纳成三步:
// 1. 为 movedTable 生成 newName,修改 parentKey,指向目标 schema 或 mergedTable
// 2. 修改目标 schema 或 mergedTable,加入 movedTable.key
// 3. 调用 updateMovedTableParent() 方法
const tableParentKey = movedTable.parentKey
const keyArrLen = tableParentKey.split(':').length
if (
keyArrLen === 2 &&
targetSchemas[tableParentKey].key === targetSchema.key
) {
// parent is schema, and same as the target schema
return
}
// update targetTable: newName, parentKey
const existNames = targetSchema.tables.map(
tableKey => allTables[tableKey].newName
)
const newName = loopGenUniqueName(movedTable.newName, existNames)
const newAllTables: IFullTables = {
...allTables,
[movedTable.key]: {
...movedTable,
newName,
parentKey: targetSchema.key
}
}
const newTargetSchemas: IFullSchemas = {
...targetSchemas,
[targetSchema.key]: {
...targetSchema,
tables: targetSchema.tables.concat(movedTable.key)
}
}
updateMovedTableParent(movedTable, newTargetSchemas, newAllTables)
}
function moveTableToMergedTable(
movedTable: IFullTable,
mergedTable: IFullTable
) {
console.log('移动 table 到 mergedTable 下')
// 如果 movedTable parent 为 schema
// 1. 为 movedTable 生成 newName,parentKey 指向 mergedTable
// 2. 将 movedTable.key 加入 mergedTable 中
// 3. 调用 updateMovedTableParent() 方法
//
// 如果 movedTable parent 为 mergedTable
// 首先检查 parent 和目档 mergedTable 是不是同一个,如果是,直接返回,否则,操作和上面一样
const tableParentKey = movedTable.parentKey
const keyArrLen = tableParentKey.split(':').length
if (keyArrLen === 3 && allTables[tableParentKey].key === mergedTable.key) {
// parent is same as the target mergedTable
return
}
// 1. newName
const existNames = mergedTable.mergedTables!.map(
tableKey => allTables[tableKey].newName
)
const newName = loopGenUniqueName(movedTable.newName, existNames)
const newAllTables: IFullTables = {
...allTables,
[movedTable.key]: {
...movedTable,
newName,
parentKey: mergedTable.key
},
[mergedTable.key]: {
...mergedTable,
mergedTables: mergedTable.mergedTables!.concat(movedTable.key)
}
}
const newTargetSchemas = { ...targetSchemas }
updateMovedTableParent(movedTable, newTargetSchemas, newAllTables)
}
function mergeTables(movedTable: IFullTable, targetTable: IFullTable) {
console.log(
'将 table 移动到 table,即合并两个 table,会新建一张合并表,且明确 targetTable 不会是 mergedTable'
)
// 首先判断 targetTable 的 parent 是 schema 还是 mergedTable,如果是后者,不支持这种操作,直接返回
// 且明确 targetTable 不会是 mergedTable!其结果肯定是会新建一张合并表
// 这种情况的特殊性在于,最后需要同时修改 movedTable 和 targetTable 的 parent
//
// 如果 movedTable parent 是 schema
// 1. 新建合并表,生成 newName 和 key,parentKey 为 targetTable.parentKey,mergedTables 为 movedTable 和 targetTable,在 allTables 中插入这个新的合并表
// 2. 修改 movedTable 和 targetTable,其 parentKey 指向新建的 mergedTable,如果二者名字相同,重命名 movedTable
// 3. 修改 targetTable 的 parent schema,在其 tables 中移除 targetTable,加入 mergedTable
// 4. 调用 updateMovedTableParent()
//
// 如果 movedTable parent 是 mergedTable
// 和上面是完全一样的操作...
const targetTableParentKey = targetTable.parentKey
if (targetTableParentKey.split(':').length === 3) {
// targetTable parent is mergedTable
// 不能进行这样的操作
return
}
const targetTableParent = targetSchemas[targetTableParentKey]
// 1. 新建合并表
const newMergedTable: IFullTable = {
type: 'mergedTable',
sourceId: 'new',
schema: 'new',
table: 'newtable',
newName: 'newtable',
key: `new:new:newtable_${genRandSuffix()}`,
parentKey: targetTableParentKey,
mergedTables: [movedTable.key, targetTable.key],
filters: []
}
const existNames = targetTableParent.tables.map(
tableKey => allTables[tableKey].newName
)
newMergedTable.newName = loopGenUniqueName(
newMergedTable.newName,
existNames
)
// 2. 修改 movedTable 和 targetTable
if (movedTable.newName === targetTable.newName) {
movedTable.newName = `${movedTable.newName}_1`
}
const newAllTables: IFullTables = {
...allTables,
[newMergedTable.key]: newMergedTable,
[movedTable.key]: {
...movedTable,
parentKey: newMergedTable.key
},
[targetTable.key]: {
...targetTable,
parentKey: newMergedTable.key
}
}
// 3. 修改 targetSchema
const newTargetSchemas: IFullSchemas = {
...targetSchemas,
[targetTableParentKey]: {
...targetTableParent,
tables: targetTableParent.tables
.filter(t => t !== targetTable.key)
.concat(newMergedTable.key)
}
}
// 4. updateMovedTableParent
updateMovedTableParent(movedTable, newTargetSchemas, newAllTables)
}
/////////////////////////////////
function renameNode(options: AntTreeNodeMouseEvent) {
const targetItem = options.node.props.dataRef
if ((targetItem as IFullInstance).type === 'instance') {
return
}
const newName = prompt(
intl.formatMessage({ id: 'new_name' }),
targetItem.newName
)
if (newName === null || newName === targetItem.newName) {
// click cancel or change nothing
return
}
if (newName === '') {
alert(intl.formatMessage({ id: 'name_can_not_empty' }))
return
}
let existNames: string[] = []
if ((targetItem as IFullSchema).type === 'schema') {
existNames = Object.keys(targetSchemas).map(
schemaKey => targetSchemas[schemaKey].newName
)
} else if ((targetItem as IFullTable).type === 'mergedTable') {
const tableParent = targetSchemas[targetItem.parentKey]
existNames = tableParent.tables.map(
tableKey => allTables[tableKey].newName
)
} else if ((targetItem as IFullTable).type === 'table') {
const tableParentKey = targetItem.parentKey
if (tableParentKey.split(':').length === 2) {
// parent is schema
const tableParent = targetSchemas[targetItem.parentKey]
existNames = tableParent.tables.map(
tableKey => allTables[tableKey].newName
)
} else {
// parent is mergedTable
const tableParent = allTables[targetItem.parentKey]
existNames = tableParent.mergedTables!.map(
tableKey => allTables[tableKey].newName
)
}
}
const nameExisted = existNames.includes(newName)
if (nameExisted) {
alert(intl.formatMessage({ id: 'name_taken' }))
return
}
recordLastState()
if ((targetItem as IFullSchema).type === 'schema') {
setTargetSchemas({
...targetSchemas,
[targetItem.key]: {
...targetItem,
newName
}
})
} else {
setAllTables({
...allTables,
[targetItem.key]: {
...targetItem,
newName
}
})
}
}
/////////////////////////////////
function onUpdateItemFilters(item: IFullSchema | IFullTable) {
setSelectedSourceItem(item) // update it, because we generate a new source item object
if ((item as IFullTable).type === 'table') {
setAllTables({
...allTables,
[item.key]: item as IFullTable
})
} else if ((item as IFullSchema).type === 'schema') {
const schema = item as IFullSchema
const newSourceSchemas = {
...sourceSchemas,
[schema.key]: schema
}
// 重置所有子 table 的 filters 规则
const newAllTables = { ...allTables }
// 和 PM 沟通过了,修改 db 的 binlog 过滤规则只重置左边剩余的子 tables,不会影响已经移到右边的子 tables
// const schemaTables: IFullTable[] = Object.keys(newAllTables)
// .map(tableKey => newAllTables[tableKey])
// .filter(
// table =>
// table.sourceId === schema.sourceId && table.schema === schema.schema
// )
// schemaTables.forEach(table => (table.filters = schema.filters))
schema.tables.forEach(
tableKey => (newAllTables[tableKey].filters = schema.filters)
)
setSourceSchemas(newSourceSchemas)
setAllTables(newAllTables)
}
}
/////////////////////////////////
async function handleSubmit() {
setLoading(true)
const { taskInfo, instancesConfig } = remainProps
const finalConfig = genFinalConfig(
taskInfo,
instancesConfig,
sourceSchemas,
targetSchemas,
allTables,
autoSyncUpstream
)
let res = await generateConfig(finalConfig)
setLoading(false)
if (res.err) {
message.error(intl.formatMessage({ id: 'config_create_fail' }))
return
}
message.info(
intl.formatMessage(
{ id: 'config_create_ok' },
{ filepath: res.data.filepath }
)
)
downloadConfig(res.data.filepath)
}
/////////////////////////////////
function goHome() {
if (window.confirm(intl.formatMessage({ id: 'back_home_confirm' }))) {
onNext()
}
}
/////////////////////////////////
function renderSourceTables() {
const sourceInstancesArr: IFullInstance[] = Object.keys(
sourceInstances
).map(key => sourceInstances[key])
return (
<Tree
showLine
onSelect={onSelectSourceItem}
checkable
checkedKeys={sourceCheckedKeys}
onCheck={onSourceCheck}
>
{sourceInstancesArr.map(instance => (
<TreeNode
key={instance.key}
title={instance.sourceId}
selectable={false}
>
{instance.schemas
.filter(schemaKey => sourceSchemas[schemaKey].tables.length > 0)
.map(schemaKey => (
<TreeNode
key={sourceSchemas[schemaKey].key}
title={
selectedSourceItem.key === schemaKey ? (
<>
{sourceSchemas[schemaKey].schema}{' '}
<Icon
className="edit-icon"
type="edit"
onClick={onEditIconClick}
/>
</>
) : (
sourceSchemas[schemaKey].schema
)
}
dataRef={sourceSchemas[schemaKey]}
>
{sourceSchemas[schemaKey].tables.map(tableKey => (
<TreeNode
key={allTables[tableKey].key}
title={
selectedSourceItem.key === tableKey ? (
<>
{allTables[tableKey].table}{' '}
<Icon
className="edit-icon"
type="edit"
onClick={onEditIconClick}
/>
</>
) : (
allTables[tableKey].table
)
}
dataRef={allTables[tableKey]}
/>
))}
</TreeNode>
))}
</TreeNode>
))}
</Tree>
)
}
function renderTargetTables() {
return (
<Tree
showLine
draggable={enableDrag}
onSelect={onSelectTargetItem}
onDrop={onDrop}
onRightClick={renameNode}
checkable
checkedKeys={targetCheckedKeys}
onCheck={onTargetCheck}
>
<TreeNode
title={targetInstance.sourceId}
key={targetInstance.key}
dataRef={targetInstance}
selectable={false}
>
{targetInstance.schemas
.map(schemaKey => targetSchemas[schemaKey])
.map(schema => (
<TreeNode
title={
<Tooltip
title={`${schema.sourceId}:${schema.schema}`}
placement="right"
>
{schema.newName}
</Tooltip>
}
key={schema.key}
dataRef={schema}
>
{schema.tables
.map(tableKey => allTables[tableKey])
.map(table => (
<TreeNode
title={
<Tooltip
placement="right"
title={`${table.sourceId}:${table.schema}:${table.table}`}
>
{table.newName}
</Tooltip>
}
key={table.key}
dataRef={table}
>
{table.mergedTables &&
table
.mergedTables!.map(tbKey => allTables[tbKey])
.map(tb => (
<TreeNode
title={
<Tooltip
placement="right"
title={`${tb.sourceId}:${tb.schema}:${tb.table}`}
>
{tb.newName}
</Tooltip>
}
key={tb.key}
dataRef={tb}
/>
))}
</TreeNode>
))}
</TreeNode>
))}
</TreeNode>
</Tree>
)
}
return (
<Container>
<div className="dbtable-shuttle-container">
<div>
<h2>
<FormattedMessage id="upstream" />
</h2>
<div className="tree-container">{renderSourceTables()}</div>
<div className="auto-sync-option">
<Checkbox
checked={autoSyncUpstream}
onChange={e => setAutoSyncUpstream(e.target.checked)}
>
<FormattedMessage id="auto_sync" />
<Tooltip title={intl.formatMessage({ id: 'auto_sync_explain' })}>
<Icon type="question-circle" />
</Tooltip>
</Checkbox>
</div>
</div>
<div className="shuttle-arrows">
<Button disabled={!enableMoveRight} onClick={moveRight}>
<Icon type="arrow-right" />
</Button>
<Button disabled={!enableMoveLeft} onClick={moveLeft}>
<Icon type="arrow-left" />
</Button>
</div>
<div>
<h2>
<FormattedMessage id="downstream" />
</h2>
<div className="tree-container">
{renderTargetTables()}
<div className="action-icons">
<Tooltip title={intl.formatMessage({ id: 'go_back_tooltip' })}>
<Button onClick={undo} disabled={lastStateRef.current === null}>
<Icon type="undo" />
</Button>
</Tooltip>
<span> </span>
<Tooltip title={intl.formatMessage({ id: 'reset_tooltip' })}>
<Button
onClick={cleanTargetInstance}
disabled={targetInstance.schemas.length === 0}
>
<Icon type="delete" />
</Button>
</Tooltip>
</div>
</div>
</div>
</div>
<div className="action-buttons">
<Button onClick={() => onPrev()}>
<FormattedMessage id="pre" />
</Button>
<Button type="primary" onClick={handleSubmit} loading={loading}>
<FormattedMessage id="finish_and_download" />
</Button>
<Button onClick={goHome}>
<FormattedMessage id="go_home" />
</Button>
</div>
<BinlogFilterModal
key={selectedSourceItem.key + `${Date.now()}`}
targetItem={selectedSourceItem as any}
modalVisible={modalVisible}
onCloseModal={() => setModalVisible(false)}
onUpdateItem={onUpdateItemFilters}
/>
</Container>
)
}
export default MigrateStep | the_stack |
import React, { createRef } from 'react';
import PropTypes from 'prop-types';
import Component from '../../react-class';
import moment from 'moment';
import { Flex, Item } from '../../Flex';
import assign from '../../../common/assign';
import join from '../../../common/join';
import times from './utils/times';
import toMoment from './toMoment';
import bemFactory from './bemFactory';
import ON_KEY_DOWN from './MonthView/onKeyDown';
const ARROWS = {
prev: (
<svg width="5" height="10" viewBox="0 0 5 10">
<path
fillRule="evenodd"
d="M.262 4.738L4.368.632c.144-.144.379-.144.524 0C4.96.702 5 .796 5 .894v8.212c0 .204-.166.37-.37.37-.099 0-.193-.039-.262-.108L.262 5.262c-.145-.145-.145-.38 0-.524z"
/>
</svg>
),
next: (
<svg width="5" height="10" viewBox="0 0 5 10">
<path
fillRule="evenodd"
d="M4.738 5.262L.632 9.368c-.144.144-.379.144-.524 0C.04 9.298 0 9.204 0 9.106V.894C0 .69.166.524.37.524c.099 0 .193.039.262.108l4.106 4.106c.145.145.145.38 0 .524z"
/>
</svg>
),
};
const getDecadeStartYear = mom => {
const year = mom.get('year');
return year - (year % 10);
};
const getDecadeEndYear = mom => {
return getDecadeStartYear(mom) + 9;
};
const NAV_KEYS = {
ArrowUp(mom) {
return mom.add(-5, 'year');
},
ArrowDown(mom) {
return mom.add(5, 'year');
},
ArrowLeft(mom) {
return mom.add(-1, 'year');
},
ArrowRight(mom) {
return mom.add(1, 'year');
},
Home(mom) {
return mom.set('year', getDecadeStartYear(mom));
},
End(mom) {
return mom.set('year', getDecadeEndYear(mom));
},
PageUp(mom) {
return mom.add(-10, 'year');
},
PageDown(mom) {
return mom.add(10, 'year');
},
};
const isDateInMinMax = (timestamp, props) => {
if (props.minDate && timestamp < props.minDate) {
return false;
}
if (props.maxDate && timestamp > props.maxDate) {
return false;
}
return true;
};
const isValidActiveDate = (timestamp, props) => {
if (!props) {
throw new Error('props is mandatory in isValidActiveDate');
}
return isDateInMinMax(timestamp, props);
};
const select = function({ dateMoment, timestamp }, event) {
if (this.props.select) {
return this.props.select({ dateMoment, timestamp }, event);
}
if (!timestamp) {
timestamp = +dateMoment;
}
this.gotoViewDate({ dateMoment, timestamp });
this.onChange({ dateMoment, timestamp }, event);
return undefined;
};
const confirm = function(date, event) {
event.preventDefault();
if (this.props.confirm) {
return this.props.confirm(date, event);
}
const dateMoment = this.toMoment(date);
const timestamp = +dateMoment;
this.select({ dateMoment, timestamp }, event);
if (this.props.onConfirm) {
this.props.onConfirm({ dateMoment, timestamp });
}
return undefined;
};
const onActiveDateChange = function({ dateMoment, timestamp }) {
if (!isValidActiveDate(timestamp, this.p)) {
return;
}
if (this.props.activeDate === undefined) {
this.setState({
activeDate: timestamp,
});
}
if (this.props.onActiveDateChange) {
const dateString = this.format(dateMoment);
this.props.onActiveDateChange(dateString, {
dateMoment,
timestamp,
dateString,
});
}
};
const onViewDateChange = function({ dateMoment, timestamp }) {
if (dateMoment && timestamp === undefined) {
timestamp = +dateMoment;
}
if (this.props.constrainViewDate && !isDateInMinMax(timestamp, this.p)) {
return;
}
if (this.props.viewDate === undefined) {
this.setState({
viewDate: timestamp,
});
}
if (this.props.onViewDateChange) {
const dateString = this.format(dateMoment);
this.props.onViewDateChange(dateString, {
dateMoment,
dateString,
timestamp,
});
}
};
const onChange = function({ dateMoment, timestamp }, event) {
if (this.props.date === undefined) {
this.setState({
date: timestamp,
});
}
if (this.props.onChange) {
const dateString = this.format(dateMoment);
this.props.onChange(
dateString,
{ dateMoment, timestamp, dateString },
event
);
}
};
const navigate = function(direction, event) {
const props = this.p;
const getNavigationDate = (dir, date, dateFormat) => {
const mom = moment.isMoment(date) ? date : this.toMoment(date, dateFormat);
if (typeof dir == 'function') {
return dir(mom);
}
return mom;
};
if (props.navigate) {
return props.navigate(direction, event, getNavigationDate);
}
event.preventDefault();
if (props.activeDate) {
const nextMoment = getNavigationDate(direction, props.activeDate);
this.gotoViewDate({ dateMoment: nextMoment });
}
return undefined;
};
const gotoViewDate = function({ dateMoment, timestamp }) {
if (!timestamp) {
timestamp = dateMoment == null ? null : +dateMoment;
}
this.onViewDateChange({ dateMoment, timestamp });
this.onActiveDateChange({ dateMoment, timestamp });
};
const prepareDate = function(props, state) {
return props.date === undefined ? state.date : props.date;
};
const prepareViewDate = function(props, state) {
const viewDate =
props.viewDate === undefined ? state.viewDate : props.viewDate;
if (!viewDate && props.date) {
return props.date;
}
return viewDate;
};
const prepareActiveDate = function(props, state) {
const activeDate =
props.activeDate === undefined
? state.activeDate || prepareDate(props, state)
: props.activeDate;
return activeDate;
};
const prepareMinMax = function(props) {
const { minDate, maxDate } = props;
const result = {};
if (minDate != null) {
result.minDateMoment = toMoment(props.minDate, props).startOf(
props.adjustMinDateStartOf
);
result.minDate = +result.minDateMoment;
}
if (maxDate != null) {
result.maxDateMoment = toMoment(props.maxDate, props).endOf(
props.adjustMaxDateStartOf
);
result.maxDate = +result.maxDateMoment;
}
return result;
};
const prepareDateProps = function(props, state) {
const result = {};
assign(result, prepareMinMax(props));
result.date = prepareDate(props, state);
result.viewDate = prepareViewDate(props, state);
const activeDate = prepareActiveDate(props, state);
if (result.date != null) {
result.moment = toMoment(result.date, props);
if (props.adjustDateStartOf) {
result.moment.startOf(props.adjustDateStartOf);
}
result.timestamp = +result.moment;
}
if (activeDate) {
result.activeMoment = toMoment(activeDate, props);
if (props.adjustDateStartOf) {
result.activeMoment.startOf(props.adjustDateStartOf);
}
result.activeDate = +result.activeMoment;
}
let viewMoment = toMoment(result.viewDate, props);
if (
props.constrainViewDate &&
result.minDate != null &&
viewMoment.isBefore(result.minDate)
) {
result.minConstrained = true;
viewMoment = toMoment(result.minDate, props);
}
if (
props.constrainViewDate &&
result.maxDate != null &&
viewMoment.isAfter(result.maxDate)
) {
result.maxConstrained = true;
viewMoment = toMoment(result.maxDate, props);
}
if (props.adjustDateStartOf) {
viewMoment.startOf(props.adjustDateStartOf);
}
result.viewMoment = viewMoment;
return result;
};
const getInitialState = props => {
return {
date: props.defaultDate,
activeDate: props.defaultActiveDate,
viewDate: props.defaultViewDate,
};
};
export default class DecadeView extends Component {
constructor(props) {
super(props);
this.decadeViewRef = createRef();
this.state = getInitialState(props);
}
getYearsInDecade(value) {
const year = getDecadeStartYear(this.toMoment(value));
const start = this.toMoment(`${year}`, 'YYYY').startOf('year');
return times(10).map(i => {
return this.toMoment(start).add(i, 'year');
});
}
toMoment(date, format) {
return toMoment(date, format, this.props);
}
render() {
const props = (this.p = assign({}, this.props));
if (props.onlyCompareYear) {
}
const dateProps = prepareDateProps(props, this.state);
assign(props, dateProps);
const yearsInView = this.getYearsInDecade(props.viewMoment);
const { rootClassName } = props;
const className = join(
props.className,
rootClassName,
props.theme && `${rootClassName}--theme-${props.theme}`
);
let children = this.renderYears(props, yearsInView);
let align = 'stretch';
let column = true;
if (props.navigation) {
column = false;
align = 'center';
children = [
this.renderNav(-1),
<Flex
key="year_view"
inline
flex
column
alignItems="stretch"
children={children}
/>,
this.renderNav(1),
];
}
const flexProps = assign({}, this.props);
delete flexProps.activeDate;
delete flexProps.adjustDateStartOf;
delete flexProps.adjustMaxDateStartOf;
delete flexProps.adjustMinDateStartOf;
delete flexProps.arrows;
delete flexProps.cleanup;
delete flexProps.constrainViewDate;
delete flexProps.date;
delete flexProps.dateFormat;
delete flexProps.isDecadeView;
delete flexProps.maxDate;
delete flexProps.minDate;
delete flexProps.navigation;
delete flexProps.navKeys;
delete flexProps.onActiveDateChange;
delete flexProps.onConfirm;
delete flexProps.onlyCompareYear;
delete flexProps.onViewDateChange;
delete flexProps.perRow;
delete flexProps.theme;
delete flexProps.viewDate;
delete flexProps.yearFormat;
delete flexProps.rootClassName;
if (typeof props.cleanup == 'function') {
props.cleanup(flexProps);
}
return (
<Flex
inline
ref={this.decadeViewRef}
column={column}
alignItems={align}
tabIndex={0}
{...flexProps}
onKeyDown={this.onKeyDown}
className={className}
children={children}
/>
);
}
renderNav(dir) {
const props = this.p;
const name = dir == -1 ? 'prev' : 'next';
const navMoment = this.toMoment(props.viewMoment).add(dir * 10, 'year');
const disabled =
dir == -1
? props.minDateMoment &&
getDecadeEndYear(navMoment) < getDecadeEndYear(props.minDateMoment)
: props.maxDateMoment &&
getDecadeEndYear(navMoment) > getDecadeEndYear(props.maxDateMoment);
const { rootClassName } = props;
const className = join(
`${rootClassName}-arrow`,
`${rootClassName}-arrow--${name}`,
disabled && `${rootClassName}-arrow--disabled`
);
const arrow = props.arrows[name] || ARROWS[name];
const arrowProps = {
className,
onClick: !disabled
? () =>
this.onViewDateChange({
dateMoment: navMoment,
timestamp: this.toMoment(props.viewMoment),
})
: null,
children: arrow,
disabled,
};
if (props.renderNavigation) {
return props.renderNavigation(arrowProps, props);
}
return <div key={`nav_arrow_${dir}`} {...arrowProps} />;
}
renderYears(props, years) {
const nodes = years.map(this.renderYear);
const perRow = props.perRow;
const buckets = times(Math.ceil(nodes.length / perRow)).map(i => {
return nodes.slice(i * perRow, (i + 1) * perRow);
});
return buckets.map((bucket, i) => (
<Flex
alignItems="center"
flex
row
inline
key={`row_${i}`}
className={`${props.rootClassName}-row`}
>
{bucket}
</Flex>
));
}
renderYear(dateMoment) {
const props = this.p;
const yearText = this.format(dateMoment);
const timestamp = +dateMoment;
const isActiveDate =
props.onlyCompareYear && props.activeMoment
? dateMoment.get('year') == props.activeMoment.get('year')
: timestamp === props.activeDate;
const isValue =
props.onlyCompareYear && props.moment
? dateMoment.get('year') == props.moment.get('year')
: timestamp === props.timestamp;
const { rootClassName } = props;
const className = join(
`${rootClassName}-year`,
isActiveDate && `${rootClassName}-year--active`,
isValue && `${rootClassName}-year--value`,
props.minDate != null &&
timestamp < props.minDate &&
`${rootClassName}-year--disabled`,
props.maxDate != null &&
timestamp > props.maxDate &&
`${rootClassName}-year--disabled`
);
const onClick = this.handleClick.bind(this, {
dateMoment,
timestamp,
});
return (
<Item key={yearText} className={className} onClick={onClick}>
{yearText}
</Item>
);
}
format(mom, format) {
format = format || this.props.yearFormat;
return mom.format(format);
}
handleClick({ timestamp, dateMoment }, event) {
event.target.value = timestamp;
const props = this.p;
if (props.minDate && timestamp < props.minDate) {
return;
}
if (props.maxDate && timestamp > props.maxDate) {
return;
}
this.select({ dateMoment, timestamp }, event);
}
onKeyDown(event) {
return ON_KEY_DOWN.call(this, event);
}
confirm(date, event) {
return confirm.call(this, date, event);
}
navigate(direction, event) {
return navigate.call(this, direction, event);
}
select({ dateMoment, timestamp }, event) {
return select.call(this, { dateMoment, timestamp }, event);
}
onViewDateChange({ dateMoment, timestamp }) {
return onViewDateChange.call(this, { dateMoment, timestamp });
}
gotoViewDate({ dateMoment, timestamp }) {
return gotoViewDate.call(this, { dateMoment, timestamp });
}
onActiveDateChange({ dateMoment, timestamp }) {
return onActiveDateChange.call(this, { dateMoment, timestamp });
}
onChange({ dateMoment, timestamp }, event) {
return onChange.call(this, { dateMoment, timestamp }, event);
}
getDOMNode() {
return this.decadeViewRef.current;
}
focus() {
this.decadeViewRef.current.focus();
}
}
DecadeView.defaultProps = {
rootClassName: 'inovua-react-toolkit-calendar__decade-view',
isDecadeView: true,
arrows: {},
navigation: true,
constrainViewDate: true,
navKeys: NAV_KEYS,
theme: 'default',
yearFormat: 'YYYY',
dateFormat: 'YYYY-MM-DD',
perRow: 5,
onlyCompareYear: true,
adjustDateStartOf: 'year',
adjustMinDateStartOf: 'year',
adjustMaxDateStartOf: 'year',
};
DecadeView.propTypes = {
isDecadeView: PropTypes.bool,
rootClassName: PropTypes.string,
navigation: PropTypes.bool,
constrainViewDate: PropTypes.bool,
arrows: PropTypes.object,
navKeys: PropTypes.object,
theme: PropTypes.string,
yearFormat: PropTypes.string,
dateFormat: PropTypes.string,
perRow: PropTypes.number,
minDate: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
maxDate: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
viewDate: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
date: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
defaultDate: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
viewMoment: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
moment: PropTypes.object,
minDateMoment: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
maxDateMoment: PropTypes.oneOfType([PropTypes.number, PropTypes.object]),
onlyCompareYear: PropTypes.bool,
adjustDateStartOf: PropTypes.string,
adjustMinDateStartOf: PropTypes.string,
adjustMaxDateStartOf: PropTypes.string,
activeDate: PropTypes.number,
select: PropTypes.func,
confirm: PropTypes.func,
onConfirm: PropTypes.func,
onActiveDateChange: PropTypes.func,
onViewDateChange: PropTypes.func,
cleanup: PropTypes.func,
onChange: PropTypes.func,
renderNavigation: PropTypes.func,
navigate: PropTypes.func,
};
export {
onChange,
onViewDateChange,
onActiveDateChange,
select,
confirm,
gotoViewDate,
navigate,
ON_KEY_DOWN as onKeyDown,
prepareActiveDate,
prepareViewDate,
prepareMinMax,
prepareDateProps,
prepareDate,
isDateInMinMax,
isValidActiveDate,
getInitialState,
}; | the_stack |
import * as admin from "firebase-admin";
import { IServiceContext } from "../service";
import { getDocMetaData } from "../../utils/converter";
import { v4 as uuidv4 } from 'uuid';
import { deserializeDocumentSnapshotArray, DocumentSnapshot, serializeDocumentSnapshot, serializeQuerySnapshot } from "firestore-serializers";
import { isCollection } from "../../utils/navigator";
import { chunk, get } from "lodash";
import log from 'electron-log';
import { convertFirebaseType, isRangeFilter, parseEmulatorConnection } from "../../utils";
import axios from 'axios';
const DOCS_PER_PAGE = 200;
export default class FireStoreService implements NSFireStore.IService {
private ctx: IServiceContext;
private app: admin.app.App;
private listListeners: NSFireStore.IListenerEntity[] = [];
static addMetadata(doc: any) {
doc.metadata = {
hasPendingWrites: false,
fromCache: false,
isEqual(arg: any) {
return true;
}
}
return doc;
}
constructor(ctx: IServiceContext) {
this.ctx = ctx;
}
private fsClient() {
return admin.firestore(this.app)
}
public async init({ projectId }: NSFireStore.IFSInit): Promise<string[]> {
if (projectId.includes(':')) {
return await this.initEmulator({ projectId });
}
if (this.app?.name === projectId) {
log.warn(`${projectId} already initiated`);
const collections = await this.fsClient().listCollections();
return collections.map(collection => collection.path)
}
const cert = this.ctx.localDB.get('keys').find({ projectId }).value();
if (!cert) {
throw new Error('We do not have credentials for this project')
}
const serviceAccount = require(cert.keyPath);
this.app = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
}, projectId);
log.info("Initiated firebase app");
const collections = await this.fsClient().listCollections();
return collections.map(collection => collection.path)
}
public async initEmulator({ projectId: connection }: NSFireStore.IFSInit): Promise<string[]> {
const { host, port, projectId } = parseEmulatorConnection(connection);
try {
await axios.get(`http://${host}:${port}`);
} catch (error) {
throw new Error('Can not connect. Please check the config to emulator')
}
process.env.FIRESTORE_EMULATOR_HOST = `${host}:${port}`;
if (this.app?.name === projectId) {
log.warn(`${host} already initiated`);
const collections = await this.fsClient().listCollections();
return collections.map(collection => collection.path)
}
this.app = admin.initializeApp({
projectId,
}, projectId);
log.info("Initiated emulator firebase app");
const collections = await this.fsClient().listCollections();
return collections.map(collection => collection.path)
}
public async subscribeDoc({ path, topic }: NSFireStore.IDocSubscribe) {
log.verbose("received event fs.query.subscribe", { path, topic });
const close = this.fsClient()
.doc(path)
// .withConverter(postConverter)
.onSnapshot(
async (doc) => {
const docData = serializeDocumentSnapshot(doc as any);
this.ctx.ipc.send(topic, docData, { firestore: true });
// TODO: Consider fetch `listCollections` outsite
const collections = await doc.ref.listCollections();
this.ctx.ipc.send(
`${topic}_metadata`,
collections.map((collection) => ({
id: collection.id,
path: collection.path,
}))
);
},
(error) => {
// TODO: Handle errors here.
// Ref: https://firebase.google.com/docs/firestore/query-data/queries#compound_queries
}
);
const listenerData = {
id: uuidv4(),
topic,
close,
};
this.listListeners.push(listenerData);
return { id: listenerData.id };
}
public async subscribeCollection({ path, topic, queryOptions, sortOptions, queryVersion, startAfter, endBefore, startAt, endAt }: NSFireStore.ICollectionSubscribe) {
log.verbose("received event fs.queryCollection.subscribe", { path, topic });
log.verbose(sortOptions);
const fs = this.fsClient();
const collectionRef = fs
.collection(path);
let querier: FirebaseFirestore.Query = collectionRef;
queryOptions.forEach(({ field, operator: { type, values } }) => {
querier = querier.where(field, type, convertFirebaseType(values));
if (isRangeFilter(type) && !sortOptions.find(({ field: sortField }) => sortField === field)) {
// Auto add orderBy if query is filter by range operator
querier = querier.orderBy(field, 'asc');
}
})
sortOptions.forEach(({ field, sort }) => {
querier = querier.orderBy(field === '__id' ? admin.firestore.FieldPath.documentId() : field, sort.toLowerCase() as FirebaseFirestore.OrderByDirection);
})
if (sortOptions.length === 0) {
// Default sorting by id
querier = querier.orderBy(admin.firestore.FieldPath.documentId());
}
if (endBefore) {
querier = querier.endBefore(await fs.doc(endBefore).get());
}
if (startAfter) {
querier = querier.startAfter(await fs.doc(startAfter).get());
}
if (endAt) {
querier = querier.endAt(await fs.doc(endAt).get());
}
if (startAt) {
querier = querier.startAt(await fs.doc(startAt).get());
}
querier = querier.limit(DOCS_PER_PAGE);
const close = querier.onSnapshot(
async (querySnapshot) => {
log.verbose('Read time', querySnapshot.readTime);
const docChanges = querySnapshot.docChanges();
const addedData = serializeQuerySnapshot({
docs: docChanges.filter(changes => changes.type === 'added').map(changes => changes.doc)
})
const modifiedData = serializeQuerySnapshot({
docs: docChanges.filter(changes => changes.type === 'modified').map(changes => changes.doc)
})
const removedData = serializeQuerySnapshot({
docs: docChanges.filter(changes => changes.type === 'removed').map(changes => changes.doc)
})
log.verbose(`send to ${topic} with ${docChanges.length} changes`)
this.ctx.ipc.send(topic, {
addedData,
modifiedData,
removedData,
totalDocs: docChanges.length,
queryVersion,
isInitResult: querySnapshot.size === docChanges.filter(changes => changes.type === 'added').length
}, { firestore: true });
}, (error) => {
log.error(error)
this.ctx.ipc.send('error', { error: error.message });
}
);
// TODO: Handle error
const listenerData = {
id: uuidv4(),
topic,
close,
};
this.listListeners.push(listenerData);
log.verbose(`Create listener ${listenerData.id}`);
return {
id: listenerData.id,
queryResult: {
docsPerPage: DOCS_PER_PAGE,
startAfter,
endBefore,
}
};
};
public async subscribePathExplorer({ path, topic }: NSFireStore.IPathSubscribe) {
log.verbose("received event fs.pathExplorer", { path, topic });
// TODO: Change me to not realtime
const close = this.fsClient()
.collection(path !== '/' ? path : undefined)
.onSnapshot(
async (querySnapshot) => {
const data: any[] = [];
querySnapshot.forEach((doc) => {
data.push(getDocMetaData(doc));
});
this.ctx.ipc.send(topic, data, { firestore: true });
},
(error) => {
// TODO: Handle error
}
);
const listenerData = {
id: uuidv4(),
topic,
close,
};
this.listListeners.push(listenerData);
return { id: listenerData.id };
};
public async updateDocs({ docs }: NSFireStore.IUpdateDocs): Promise<boolean> {
const fs = this.fsClient();
const docsSnapshot = deserializeDocumentSnapshotArray(docs, admin.firestore.GeoPoint, admin.firestore.Timestamp, path => fs.doc(path))
try {
const docsTrunk = chunk(docsSnapshot, 500); // Split by 500 each chunk
// TODO: Make it parallel. I think can not since FireStore only allow about 1k write ops /sec
docsTrunk.forEach(async (chunk) => {
const batch = fs.batch();
chunk.forEach(docSnapshot => {
batch.set(fs.doc(docSnapshot.ref.path), docSnapshot.data())
})
await batch.commit();
})
log.verbose('Transaction success!');
} catch (e) {
log.error('Transaction failure:', e);
throw e;
}
// Send new docs to background
// TODO: Move data_background to another function
docsSnapshot.map(doc => {
return fs.doc(doc.ref.path).get()
});
const addedData = serializeQuerySnapshot({
docs: await Promise.all(docsSnapshot.map(doc => fs.doc(doc.ref.path).get()))
})
this.ctx.ipc.send('data_background', { docs: addedData, type: 'modified' }, { firestore: true });
return true;
};
public async unsubscribe({ id }: NSFireStore.IListenerKey) {
const dataSource = this.listListeners.filter((doc) => doc.id === id);
dataSource.forEach((source) => {
source.close();
});
this.listListeners = this.listListeners.filter((doc) => doc.id !== id);
log.verbose(`Success unsubscribe this stream ${id}`);
return true;
};
public async addDoc({ doc, path }: NSFireStore.IAddDoc): Promise<string> {
const fs = this.fsClient();
const newDoc = await fs.collection(path).add(doc);
return newDoc.path;
}
public async addDocs({ docs }: NSFireStore.IAddDocs): Promise<boolean> {
const fs = this.fsClient();
const docsSnapshot = deserializeDocumentSnapshotArray(docs, admin.firestore.GeoPoint, admin.firestore.Timestamp, path => fs.doc(path))
const docsTrunk = chunk(docsSnapshot, 500); // Split by 500 each chunk
docsTrunk.forEach(async (chunk) => {
const batch = fs.batch();
chunk.forEach((doc) => {
const newDocRef = fs.doc(doc.ref.path);
batch.set(newDocRef, doc.data())
})
await batch.commit();
});
// Send new docs to background
// TODO: Move data_background to another function
docsSnapshot.map(doc => {
return fs.doc(doc.ref.path).get()
});
const addedData = serializeQuerySnapshot({
docs: await Promise.all(docsSnapshot.map(doc => fs.doc(doc.ref.path).get()))
})
this.ctx.ipc.send('data_background', { docs: addedData, type: 'added' }, { firestore: true });
return true
}
public async deleteDocs({ docs }: NSFireStore.IRemoveDocs): Promise<boolean> {
const fs = this.fsClient();
const docsTrunk = chunk(docs, 500); // Split by 500 each chunk
docsTrunk.forEach(async (chunk) => {
const batch = fs.batch();
chunk.forEach((path) => {
const newDocRef = fs.doc(path);
batch.delete(newDocRef)
})
await batch.commit();
})
return true;
}
public async deleteCollections({ collections }: NSFireStore.IRemoveCollections): Promise<boolean> {
// TODO: Check this solution https://firebase.google.com/docs/firestore/solutions/delete-collections
const fs = this.fsClient();
await Promise.all(collections.map(collectionPath => {
const collectionRef = fs.collection(collectionPath);
const query = collectionRef.orderBy('__name__').limit(500);
return new Promise(async (resolve, reject) => {
this.deleteQueryBatch(query, resolve).catch(reject);
});
}))
return true;
}
private async deleteQueryBatch(query: FirebaseFirestore.Query<FirebaseFirestore.DocumentData>, resolve: (value: boolean) => void) {
const db = this.fsClient();
const snapshot = await query.get();
const batchSize = snapshot.size;
if (batchSize === 0) {
// When there are no documents left, we are done
resolve(true);
return;
}
// Delete documents in a batch
const batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
await batch.commit();
// Recurse on the next process tick, to avoid
// exploding the stack.
process.nextTick(() => {
this.deleteQueryBatch(query, resolve);
});
}
public async importDocs({ docs, path, option: { idField = null, autoParseJSON } }: NSFireStore.IImportDocs): Promise<boolean> {
const fs = this.fsClient();
const collection = fs.collection(path);
const docsTrunk = chunk(docs, 500); // Split by 500 each chunk
docsTrunk.forEach(async (chunk) => {
const batch = fs.batch();
chunk.forEach((doc) => {
const id = idField ? get(doc, idField) : undefined;
const newDocRef = id ? collection.doc(id) : collection.doc();
let docData = doc;
if (autoParseJSON) {
Object.keys(docData).forEach(key => {
const field = docData[key];
try {
docData[key] = JSON.parse(field);
} catch (error) {
console.warn(`Can not parse json for field ${key}. Use the original value`)
docData[key] = field;
}
})
}
delete doc.__id__;
delete doc.__path__;
batch.set(newDocRef, docData)
})
await batch.commit();
});
return true
}
public async exportCollection({ path }: NSFireStore.IExportCollection): Promise<NSFireStore.IExportCollectionResponse> {
const fs = this.fsClient();
return fs.collection(path).get().then(querySnapshot => {
const docs = serializeQuerySnapshot(querySnapshot);
return {
docs: docs
}
});
}
public async getDocs({ docs }: NSFireStore.IGetDocs): Promise<string> {
const fs = this.fsClient();
const docsSnapshot = await Promise.all(docs.map(doc => fs.doc(doc).get()))
return serializeQuerySnapshot({
docs: docsSnapshot.filter(doc => doc.exists)
});
};
public async getDocsByCollection({ path }: { path: string }): Promise<string> {
const fs = this.fsClient();
const docsSnapshot = await fs.collection(path).get()
return serializeQuerySnapshot(docsSnapshot);
};
public async pathExpander({ path }: { path: string }): Promise<string[]> {
const fs = this.fsClient();
const isCollectionPath = isCollection(path);
if (isCollectionPath) {
const docsSnapshot = await fs.collection(path).get()
return docsSnapshot.docs.map(doc => doc.ref.path);
}
const listCollections = await (path !== '/' ? fs.doc(path).listCollections() : fs.listCollections());
return listCollections.map(collection => collection.path);
}
public async getSimulatorData(): Promise<any> {
try {
const response = await axios.get(`http://localhost:4040/api/config`);
log.verbose(response.data);
return {
ok: true, data: response.data
};
} catch (error) {
return {
ok: false
};
}
}
} | the_stack |
import Web3 from "web3";
import { Account } from "web3-core";
import { v4 as uuidV4 } from "uuid";
import "jest-extended";
import {
LogLevelDesc,
IListenOptions,
Servers,
} from "@hyperledger/cactus-common";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";
import HelloWorldContractJson from "../../../../solidity/hello-world-contract/HelloWorld.json";
import { K_CACTUS_QUORUM_TOTAL_TX_COUNT } from "../../../../../main/typescript/prometheus-exporter/metrics";
import {
EthContractInvocationType,
PluginLedgerConnectorQuorum,
Web3SigningCredentialCactusKeychainRef,
Web3SigningCredentialType,
DefaultApi as QuorumApi,
} from "../../../../../main/typescript/public-api";
import {
QuorumTestLedger,
IQuorumGenesisOptions,
IAccount,
pruneDockerAllIfGithubAction,
} from "@hyperledger/cactus-test-tooling";
import { PluginRegistry } from "@hyperledger/cactus-core";
import express from "express";
import bodyParser from "body-parser";
import http from "http";
import { AddressInfo } from "net";
import { Configuration } from "@hyperledger/cactus-core-api";
const testCase = "Quorum Ledger Connector Plugin";
describe(testCase, () => {
const logLevel: LogLevelDesc = "INFO";
const contractName = "HelloWorld";
const containerImageName = "hyperledger/cactus-quorum-all-in-one";
const containerImageVersion = "2021-05-03-quorum-v21.4.1";
const ledgerOptions = { containerImageName, containerImageVersion };
const ledger = new QuorumTestLedger(ledgerOptions);
const expressApp = express();
expressApp.use(bodyParser.json({ limit: "250mb" }));
const server = http.createServer(expressApp);
let addressInfo,
rpcApiHttpHost: string,
quorumGenesisOptions: IQuorumGenesisOptions,
connector: PluginLedgerConnectorQuorum,
contractAddress: string,
address: string,
port: number,
apiHost,
apiConfig,
apiClient: QuorumApi,
web3: Web3,
testEthAccount: Account,
keychainEntryKey: string,
keychainEntryValue: string,
keychainPlugin: PluginKeychainMemory,
firstHighNetWorthAccount: string;
afterAll(async () => await Servers.shutdown(server));
beforeAll(async () => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await expect(pruning).resolves.toBeTruthy();
});
afterAll(async () => {
await ledger.stop();
await ledger.destroy();
});
afterAll(async () => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await expect(pruning).resolves.toBeTruthy();
});
beforeAll(async () => {
await ledger.start();
rpcApiHttpHost = await ledger.getRpcApiHttpHost();
expect(rpcApiHttpHost).toBeString();
quorumGenesisOptions = await ledger.getGenesisJsObject();
expect(quorumGenesisOptions).toBeTruthy();
expect(quorumGenesisOptions.alloc).toBeTruthy();
web3 = new Web3(rpcApiHttpHost);
testEthAccount = web3.eth.accounts.create(uuidV4());
keychainEntryKey = uuidV4();
keychainEntryValue = testEthAccount.privateKey;
keychainPlugin = new PluginKeychainMemory({
instanceId: uuidV4(),
keychainId: uuidV4(),
// pre-provision keychain with mock backend holding the private key of the
// test account that we'll reference while sending requests with the
// signing credential pointing to this keychain entry.
backend: new Map([[keychainEntryKey, keychainEntryValue]]),
logLevel,
});
connector = new PluginLedgerConnectorQuorum({
instanceId: uuidV4(),
rpcApiHttpHost,
logLevel,
pluginRegistry: new PluginRegistry({ plugins: [keychainPlugin] }),
});
const listenOptions: IListenOptions = {
hostname: "0.0.0.0",
port: 0,
server,
};
addressInfo = (await Servers.listen(listenOptions)) as AddressInfo;
({ address, port } = addressInfo);
apiHost = `http://${address}:${port}`;
apiConfig = new Configuration({ basePath: apiHost });
apiClient = new QuorumApi(apiConfig);
});
test("Bootsrap test ETH account with funds from genesis", async () => {
const highNetWorthAccounts: string[] = Object.keys(
quorumGenesisOptions.alloc,
).filter((address: string) => {
const anAccount: IAccount = quorumGenesisOptions.alloc[address];
const theBalance = parseInt(anAccount.balance, 10);
return theBalance > 10e7;
});
[firstHighNetWorthAccount] = highNetWorthAccounts;
keychainPlugin.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
// Instantiate connector with the keychain plugin that already has the
// private key we want to use for one of our tests
await connector.registerWebServices(expressApp);
await connector.transact({
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
transactionConfig: {
from: firstHighNetWorthAccount,
to: testEthAccount.address,
value: 10e9,
},
});
const balance = await web3.eth.getBalance(testEthAccount.address);
expect(balance).toBeTruthy();
expect(parseInt(balance, 10)).toBe(10e9);
});
test("deploys contract via .json file", async () => {
const deployOut = await connector.deployContract({
contractName: HelloWorldContractJson.contractName,
keychainId: keychainPlugin.getKeychainId(),
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
gas: 1000000,
});
expect(deployOut).toBeTruthy();
expect(deployOut.transactionReceipt).toBeTruthy();
expect(deployOut.transactionReceipt.contractAddress).toBeTruthy();
contractAddress = deployOut.transactionReceipt.contractAddress as string;
expect(typeof contractAddress).toBe("string");
const { callOutput: helloMsg } = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Call,
methodName: "sayHello",
keychainId: keychainPlugin.getKeychainId(),
params: [],
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
});
expect(helloMsg).toBeTruthy();
expect(typeof contractAddress).toBe("string");
expect(typeof helloMsg).toBe("string");
});
test("invoke Web3SigningCredentialType.GETHKEYCHAINPASSWORD", async () => {
const newName = `DrCactus${uuidV4()}`;
const setNameOut = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
keychainId: keychainPlugin.getKeychainId(),
params: [newName],
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
nonce: 2,
});
expect(setNameOut).toBeTruthy();
try {
await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
keychainId: keychainPlugin.getKeychainId(),
params: [newName],
gas: 1000000,
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
nonce: 2,
});
fail("PluginLedgerConnectorQuorum.invokeContract failed to throw error");
} catch (error) {
expect(error).not.toBe("Nonce too low");
}
const getNameOut = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "getName",
keychainId: keychainPlugin.getKeychainId(),
params: [],
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
});
expect(getNameOut.success).toBeTruthy();
const { callOutput: getNameOut2 } = await connector.getContractInfoKeychain(
{
contractName,
invocationType: EthContractInvocationType.Call,
methodName: "getName",
keychainId: keychainPlugin.getKeychainId(),
params: [],
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
},
);
expect(getNameOut2).toEqual(newName);
});
test("invoke Web3SigningCredentialType.NONE", async () => {
const testEthAccount2 = web3.eth.accounts.create(uuidV4());
const { rawTransaction } = await web3.eth.accounts.signTransaction(
{
from: testEthAccount.address,
to: testEthAccount2.address,
value: 10e6,
gas: 1000000,
},
testEthAccount.privateKey,
);
await connector.transact({
web3SigningCredential: {
type: Web3SigningCredentialType.None,
},
transactionConfig: {
rawTransaction,
},
});
const balance2 = await web3.eth.getBalance(testEthAccount2.address);
expect(balance2).toBeTruthy();
expect(parseInt(balance2, 10)).toEqual(10e6);
});
test("invoke Web3SigningCredentialType.PrivateKeyHex", async () => {
const newName = `DrCactus${uuidV4()}`;
const setNameOut = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
keychainId: keychainPlugin.getKeychainId(),
params: [newName],
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
nonce: 1,
});
expect(setNameOut).toBeTruthy();
try {
await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
keychainId: keychainPlugin.getKeychainId(),
params: [newName],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
nonce: 1,
});
fail("It should not reach here");
} catch (error) {
expect(error).not.toBe("Nonce too low");
}
const { callOutput: getNameOut } = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Call,
methodName: "getName",
keychainId: keychainPlugin.getKeychainId(),
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
expect(getNameOut).toEqual(newName);
const getNameOut2 = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "getName",
keychainId: keychainPlugin.getKeychainId(),
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: testEthAccount.address,
secret: testEthAccount.privateKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
});
expect(getNameOut2).toBeTruthy();
});
test("invoke Web3SigningCredentialType.CactusKeychainRef", async () => {
const newName = `DrCactus${uuidV4()}`;
const web3SigningCredential: Web3SigningCredentialCactusKeychainRef = {
ethAccount: testEthAccount.address,
keychainEntryKey,
keychainId: keychainPlugin.getKeychainId(),
type: Web3SigningCredentialType.CactusKeychainRef,
};
const setNameOut = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
keychainId: keychainPlugin.getKeychainId(),
params: [newName],
gas: 1000000,
web3SigningCredential,
nonce: 3,
});
expect(setNameOut).toBeTruthy();
try {
await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "setName",
keychainId: keychainPlugin.getKeychainId(),
params: [newName],
gas: 1000000,
web3SigningCredential: {
ethAccount: firstHighNetWorthAccount,
secret: "",
type: Web3SigningCredentialType.GethKeychainPassword,
},
nonce: 3,
});
fail("it should not reach here");
} catch (error) {
expect(error).not.toBe("Nonce too low");
}
const { callOutput: getNameOut } = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Call,
methodName: "getName",
keychainId: keychainPlugin.getKeychainId(),
params: [],
gas: 1000000,
web3SigningCredential,
});
expect(getNameOut).toEqual(newName);
const getNameOut2 = await connector.getContractInfoKeychain({
contractName,
invocationType: EthContractInvocationType.Send,
methodName: "getName",
keychainId: keychainPlugin.getKeychainId(),
params: [],
gas: 1000000,
web3SigningCredential,
});
expect(getNameOut2).toBeTruthy();
});
test("get prometheus exporter metrics", async () => {
const res = await apiClient.getPrometheusMetricsV1();
const promMetricsOutput =
"# HELP " +
K_CACTUS_QUORUM_TOTAL_TX_COUNT +
" Total transactions executed\n" +
"# TYPE " +
K_CACTUS_QUORUM_TOTAL_TX_COUNT +
" gauge\n" +
K_CACTUS_QUORUM_TOTAL_TX_COUNT +
'{type="' +
K_CACTUS_QUORUM_TOTAL_TX_COUNT +
'"} 5';
expect(res).toBeTruthy();
expect(res.data).toBeTruthy();
expect(res.status).toEqual(200);
expect(res.data).toContain(promMetricsOutput);
});
}); | the_stack |
import {
AfterContentInit,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
OnDestroy,
Optional,
Output,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
ValidatorFn,
Validators,
} from '@angular/forms';
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
import { DOWN_ARROW } from '@angular/cdk/keycodes';
import { ThemePalette } from '@angular/material/core';
import { MAT_INPUT_VALUE_ACCESSOR } from '@angular/material/input';
import { MatFormField } from '@angular/material/form-field';
import { Subscription } from 'rxjs';
import {
DatetimeAdapter,
MTX_DATETIME_FORMATS,
MtxDatetimeFormats,
} from '@ng-matero/extensions/core';
import { MtxDatetimepicker } from './datetimepicker';
import { createMissingDateImplError } from './datetimepicker-errors';
import { MtxDatetimepickerFilterType } from './datetimepicker-filtertype';
export const MAT_DATETIMEPICKER_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MtxDatetimepickerInput),
multi: true,
};
export const MAT_DATETIMEPICKER_VALIDATORS: any = {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => MtxDatetimepickerInput),
multi: true,
};
/**
* An event used for datetimepicker input and change events. We don't always have access to a native
* input or change event because the event may have been triggered by the user clicking on the
* calendar popup. For consistency, we always use MtxDatetimepickerInputEvent instead.
*/
export class MtxDatetimepickerInputEvent<D> {
/** The new value for the target datetimepicker input. */
value: D | null;
constructor(public target: MtxDatetimepickerInput<D>, public targetElement: HTMLElement) {
this.value = this.target.value;
}
}
/** Directive used to connect an input to a MtxDatetimepicker. */
@Directive({
selector: 'input[mtxDatetimepicker]',
providers: [
MAT_DATETIMEPICKER_VALUE_ACCESSOR,
MAT_DATETIMEPICKER_VALIDATORS,
{ provide: MAT_INPUT_VALUE_ACCESSOR, useExisting: MtxDatetimepickerInput },
],
host: {
'[attr.aria-haspopup]': 'true',
'[attr.aria-owns]': '(_datetimepicker?.opened && _datetimepicker.id) || null',
'[attr.min]': 'min ? _dateAdapter.toIso8601(min) : null',
'[attr.max]': 'max ? _dateAdapter.toIso8601(max) : null',
'[disabled]': 'disabled',
'(input)': '_onInput($event.target.value)',
'(change)': '_onChange()',
'(blur)': '_onBlur()',
'(keydown)': '_onKeydown($event)',
},
exportAs: 'mtxDatetimepickerInput',
})
export class MtxDatetimepickerInput<D>
implements AfterContentInit, ControlValueAccessor, OnDestroy, Validator
{
_datetimepicker!: MtxDatetimepicker<D>;
_dateFilter!: (date: D | null, type: MtxDatetimepickerFilterType) => boolean;
/** Emits when a `change` event is fired on this `<input>`. */
@Output() dateChange = new EventEmitter<MtxDatetimepickerInputEvent<D>>();
/** Emits when an `input` event is fired on this `<input>`. */
@Output() dateInput = new EventEmitter<MtxDatetimepickerInputEvent<D>>();
/** Emits when the value changes (either due to user input or programmatic change). */
_valueChange = new EventEmitter<D | null>();
/** Emits when the disabled state has changed */
_disabledChange = new EventEmitter<boolean>();
private _datetimepickerSubscription = Subscription.EMPTY;
private _localeSubscription = Subscription.EMPTY;
/** Whether the last value set on the input was valid. */
private _lastValueValid = false;
constructor(
private _elementRef: ElementRef,
@Optional() public _dateAdapter: DatetimeAdapter<D>,
@Optional() @Inject(MTX_DATETIME_FORMATS) private _dateFormats: MtxDatetimeFormats,
@Optional() private _formField: MatFormField
) {
if (!this._dateAdapter) {
throw createMissingDateImplError('DatetimeAdapter');
}
if (!this._dateFormats) {
throw createMissingDateImplError('MTX_DATETIME_FORMATS');
}
// Update the displayed date when the locale changes.
this._localeSubscription = _dateAdapter.localeChanges.subscribe(() => {
this.value = this._dateAdapter.deserialize(this.value);
});
}
/** The datetimepicker that this input is associated with. */
@Input()
set mtxDatetimepicker(value: MtxDatetimepicker<D>) {
this.registerDatetimepicker(value);
}
@Input()
set mtxDatetimepickerFilter(
filter: (date: D | null, type: MtxDatetimepickerFilterType) => boolean
) {
this._dateFilter = filter;
this._validatorOnChange();
}
/** The value of the input. */
@Input()
get value(): D | null {
return this._value;
}
set value(value: D | null) {
value = this._dateAdapter.deserialize(value);
this._lastValueValid = !value || this._dateAdapter.isValid(value);
value = this._dateAdapter.getValidDateOrNull(value);
const oldDate = this.value;
this._value = value;
this._formatValue(value);
// use timeout to ensure the datetimepicker is instantiated and we get the correct format
setTimeout(() => {
if (!this._dateAdapter.sameDatetime(oldDate, value)) {
this._valueChange.emit(value);
}
});
}
private _value!: D | null;
/** The minimum valid date. */
@Input()
get min(): D | null {
return this._min;
}
set min(value: D | null) {
this._min = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
this._validatorOnChange();
}
private _min!: D | null;
/** The maximum valid date. */
@Input()
get max(): D | null {
return this._max;
}
set max(value: D | null) {
this._max = this._dateAdapter.getValidDateOrNull(this._dateAdapter.deserialize(value));
this._validatorOnChange();
}
private _max!: D | null;
/** Whether the datetimepicker-input is disabled. */
@Input()
get disabled(): boolean {
return !!this._disabled;
}
set disabled(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (this._disabled !== newValue) {
this._disabled = newValue;
this._disabledChange.emit(newValue);
}
}
private _disabled!: boolean;
_onTouched = () => {};
ngAfterContentInit() {
if (this._datetimepicker) {
this._datetimepickerSubscription = this._datetimepicker.selectedChanged.subscribe(
(selected: D) => {
this.value = selected;
this._cvaOnChange(selected);
this._onTouched();
this.dateInput.emit(
new MtxDatetimepickerInputEvent(this, this._elementRef.nativeElement)
);
this.dateChange.emit(
new MtxDatetimepickerInputEvent(this, this._elementRef.nativeElement)
);
}
);
}
}
ngOnDestroy() {
this._datetimepickerSubscription.unsubscribe();
this._localeSubscription.unsubscribe();
this._valueChange.complete();
this._disabledChange.complete();
}
registerOnValidatorChange(fn: () => void): void {
this._validatorOnChange = fn;
}
validate(c: AbstractControl): ValidationErrors | null {
return this._validator ? this._validator(c) : null;
}
/**
* Gets the element that the datetimepicker popup should be connected to.
* @return The element to connect the popup to.
*/
getConnectedOverlayOrigin(): ElementRef {
return this._formField ? this._formField.getConnectedOverlayOrigin() : this._elementRef;
}
/** Gets the ID of an element that should be used a description for the calendar overlay. */
getOverlayLabelId(): string | null {
if (this._formField) {
return this._formField.getLabelId();
}
return this._elementRef.nativeElement.getAttribute('aria-labelledby');
}
// Implemented as part of ControlValueAccessor
writeValue(value: D): void {
this.value = value;
}
// Implemented as part of ControlValueAccessor
registerOnChange(fn: (value: any) => void): void {
this._cvaOnChange = fn;
}
// Implemented as part of ControlValueAccessor
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor
setDisabledState(disabled: boolean): void {
this.disabled = disabled;
}
_onKeydown(event: KeyboardEvent) {
if (event.altKey && event.keyCode === DOWN_ARROW) {
this._datetimepicker.open();
event.preventDefault();
}
}
_onInput(value: string) {
let date = this._dateAdapter.parse(value, this.getParseFormat());
this._lastValueValid = !date || this._dateAdapter.isValid(date);
date = this._dateAdapter.getValidDateOrNull(date);
this._value = date;
this._cvaOnChange(date);
this._valueChange.emit(date);
this.dateInput.emit(new MtxDatetimepickerInputEvent(this, this._elementRef.nativeElement));
}
_onChange() {
this.dateChange.emit(new MtxDatetimepickerInputEvent(this, this._elementRef.nativeElement));
}
/** Handles blur events on the input. */
_onBlur() {
// Reformat the input only if we have a valid value.
if (this.value) {
this._formatValue(this.value);
}
this._onTouched();
}
private registerDatetimepicker(value: MtxDatetimepicker<D>) {
if (value) {
this._datetimepicker = value;
this._datetimepicker._registerInput(this);
}
}
private getDisplayFormat() {
switch (this._datetimepicker.type) {
case 'date':
return this._dateFormats.display.dateInput;
case 'datetime':
return this._dateFormats.display.datetimeInput;
case 'time':
return this._dateFormats.display.timeInput;
case 'month':
return this._dateFormats.display.monthInput;
}
}
private getParseFormat() {
let parseFormat;
switch (this._datetimepicker.type) {
case 'date':
parseFormat = this._dateFormats.parse.dateInput;
break;
case 'datetime':
parseFormat = this._dateFormats.parse.datetimeInput;
break;
case 'time':
parseFormat = this._dateFormats.parse.timeInput;
break;
case 'month':
parseFormat = this._dateFormats.parse.monthInput;
break;
}
if (!parseFormat) {
parseFormat = this._dateFormats.parse.dateInput;
}
return parseFormat;
}
private _cvaOnChange: (value: any) => void = () => {};
private _validatorOnChange = () => {};
/** The form control validator for whether the input parses. */
private _parseValidator: ValidatorFn = (): ValidationErrors | null => {
return this._lastValueValid
? null
: { mtxDatetimepickerParse: { text: this._elementRef.nativeElement.value } };
};
/** The form control validator for the min date. */
private _minValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value)
);
return !this.min ||
!controlValue ||
this._dateAdapter.compareDatetime(this.min, controlValue) <= 0
? null
: { mtxDatetimepickerMin: { min: this.min, actual: controlValue } };
};
/** The form control validator for the max date. */
private _maxValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value)
);
return !this.max ||
!controlValue ||
this._dateAdapter.compareDatetime(this.max, controlValue) >= 0
? null
: { mtxDatetimepickerMax: { max: this.max, actual: controlValue } };
};
/** The form control validator for the date filter. */
private _filterValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
const controlValue = this._dateAdapter.getValidDateOrNull(
this._dateAdapter.deserialize(control.value)
);
return !this._dateFilter ||
!controlValue ||
this._dateFilter(controlValue, MtxDatetimepickerFilterType.DATE)
? null
: { mtxDatetimepickerFilter: true };
};
/** The combined form control validator for this input. */
private _validator: ValidatorFn | null = Validators.compose([
this._parseValidator,
this._minValidator,
this._maxValidator,
this._filterValidator,
]);
/** Formats a value and sets it on the input element. */
private _formatValue(value: D | null) {
this._elementRef.nativeElement.value = value
? this._dateAdapter.format(value, this.getDisplayFormat())
: '';
}
/** Returns the palette used by the input's form field, if any. */
getThemePalette(): ThemePalette {
return this._formField ? this._formField.color : undefined;
}
static ngAcceptInputType_disabled: BooleanInput;
} | the_stack |
* This is a collection object that contains items of an certain entity.
* This collection "lives" in the sense that its items are automatically
* updated, added and removed. When such a change happens, an event is triggered* you can listen on.
*/
import { ClassType, getClassName, isArray } from '@deepkit/core';
import { tearDown } from '@deepkit/core-rxjs';
import { ReplaySubject, Subject, TeardownLogic } from 'rxjs';
import { EntitySubject, IdInterface } from './model';
export type FilterParameters = { [name: string]: any | undefined };
export type QuerySelector<T> = {
// Comparison
$eq?: T;
$gt?: T;
$gte?: T;
$in?: T[];
$lt?: T;
$lte?: T;
$ne?: T;
$nin?: T[];
// Logical
$not?: T extends string ? (QuerySelector<T> | RegExp) : QuerySelector<T>;
$regex?: T extends string ? (RegExp | string) : never;
//special deepkit/type type
$parameter?: string;
};
export type RootQuerySelector<T> = {
$and?: Array<FilterQuery<T>>;
$nor?: Array<FilterQuery<T>>;
$or?: Array<FilterQuery<T>>;
// we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
// this will mark all unrecognized properties as any (including nested queries)
[key: string]: any;
};
type RegExpForString<T> = T extends string ? (RegExp | T) : T;
type MongoAltQuery<T> = T extends Array<infer U> ? (T | RegExpForString<U>) : RegExpForString<T>;
export type Condition<T> = MongoAltQuery<T> | QuerySelector<MongoAltQuery<T>>;
//should be in sync with @deepkit/orm
export type FilterQuery<T> = {
[P in keyof T & string]?: Condition<T[P]>;
} &
RootQuerySelector<T>;
//should be in sync with @deepkit/orm
export type SORT_ORDER = 'asc' | 'desc' | any;
export type Sort<T, ORDER extends SORT_ORDER = SORT_ORDER> = { [P in keyof T & string]?: ORDER };
export interface CollectionEventAdd<T> {
type: 'add';
items: T[];
}
export interface CollectionEventState {
type: 'state';
state: CollectionState;
}
export interface CollectionEventRemove {
type: 'remove';
ids: (string | number)[];
}
export interface CollectionEventSet {
type: 'set';
items: any[];
}
export interface CollectionEventUpdate {
type: 'update';
items: any[];
}
export interface CollectionSetSort {
type: 'sort';
ids: (string | number)[];
}
export type CollectionEvent<T> = CollectionEventAdd<T> | CollectionEventRemove | CollectionEventSet | CollectionEventState | CollectionEventUpdate | CollectionSetSort;
export type CollectionSortDirection = 'asc' | 'desc';
export interface CollectionSort {
field: string;
direction: CollectionSortDirection;
}
export interface CollectionEntitySubjectFetcher {
fetch<T extends IdInterface>(classType: ClassType<T>, id: string | number): EntitySubject<T>;
}
export interface CollectionQueryModelInterface<T> {
filter?: FilterQuery<T>;
skip?: number;
itemsPerPage: number;
limit?: number;
parameters: { [name: string]: any };
sort?: Sort<T>;
}
/**
* internal note: This is aligned with @deepit/orm `DatabaseQueryModel`
*/
export class CollectionQueryModel<T> implements CollectionQueryModelInterface<T> {
//filter is not used yet
filter?: FilterQuery<T>;
skip?: number;
itemsPerPage: number = 50;
limit?: number;
parameters: { [name: string]: any } = {};
sort?: Sort<T>;
public readonly change = new Subject<void>();
set(model: CollectionQueryModelInterface<any>) {
this.filter = model.filter;
this.skip = model.skip;
this.itemsPerPage = model.itemsPerPage || 50;
this.limit = model.limit;
this.sort = model.sort;
for (const [i, v] of Object.entries(model.parameters)) {
this.parameters[i] = v;
}
}
changed(): void {
this.change.next();
}
hasSort(): boolean {
return this.sort !== undefined;
}
/**
* Whether limit/skip is activated.
*/
hasPaging(): boolean {
return this.limit !== undefined || this.skip !== undefined;
}
}
export class CollectionState {
/**
* Total count in the database for the current query, regardless of paging (skip/limit) count.
*
* Use count() to get the items count on the current page (which is equal to all().length)
*/
total: number = 0;
}
/**
* @reflection never
*/
export class Collection<T extends IdInterface> extends ReplaySubject<T[]> {
public readonly event: Subject<CollectionEvent<T>> = new Subject;
public readonly removed = new Subject<T>();
public readonly added = new Subject<T>();
protected readonly teardowns: TeardownLogic[] = [];
protected items: T[] = [];
protected itemsMap = new Map<string | number, T>();
public state: CollectionState = new CollectionState();
public readonly deepChange = new Subject<T>();
protected nextChange?: Promise<void>;
protected nextChangeResolver?: () => void;
// public readonly pagination: CollectionPagination<T> = new CollectionPagination(this);
protected entitySubjectFetcher?: CollectionEntitySubjectFetcher;
public model: CollectionQueryModel<T> = new CollectionQueryModel();
public readonly entitySubjects = new Map<string | number, EntitySubject<T>>();
constructor(
public readonly classType: ClassType<T>,
) {
super(1);
}
public getTotal() {
return this.state.total;
}
public getItemsPerPage() {
return this.model.itemsPerPage;
}
public getPages() {
return Math.ceil(this.getTotal() / this.getItemsPerPage());
}
public getSort() {
return this.model.sort;
}
public getParameter(name: string) {
return this.model.parameters[name];
}
public setParameter(name: string, value: any): this {
this.model.parameters[name] = value;
return this;
}
public orderByField(name: keyof T & string, order: SORT_ORDER = 'asc') {
this.model.sort = { [name]: order } as Sort<T>;
return this;
}
public setPage(page: number) {
this.model.skip = this.getItemsPerPage() * (page - 1);
return this;
}
public getPage() {
return Math.floor((this.model.skip || 0) / this.getItemsPerPage()) + 1;
}
public apply() {
this.model.changed();
return this.nextStateChange;
}
public getEntitySubject(idOrItem: string | number | T): EntitySubject<T> | undefined {
const id: any = idOrItem instanceof this.classType ? idOrItem.id : idOrItem;
return this.entitySubjects.get(id);
}
public has(id: string | number) {
return this.itemsMap.has(id);
}
public get(id: string | number): T | undefined {
return this.itemsMap.get(id);
}
public setState(state: CollectionState) {
this.state = state;
this.event.next({ type: 'state', state });
}
public setSort(ids: (string | number)[]) {
this.items.splice(0, this.items.length);
for (const id of ids) {
const item = this.itemsMap.get(id);
if (item) this.items.push(item);
}
this.event.next({ type: 'sort', ids: ids });
this.loaded();
}
/**
* Resolves when next change happened.
*/
get nextStateChange(): Promise<void> {
if (!this.nextChange) {
this.nextChange = new Promise((resolve) => {
this.nextChangeResolver = resolve;
});
}
return this.nextChange;
}
public unsubscribe() {
super.unsubscribe();
for (const teardown of this.teardowns) tearDown(teardown);
for (const subject of this.entitySubjects.values()) {
subject.unsubscribe();
}
this.teardowns.length = 0;
}
public addTeardown(teardown: TeardownLogic) {
this.teardowns.push(teardown);
}
public index(item: T): number {
return this.items.indexOf(item);
}
/**
* Returns the page zero-based of the current item.
*/
public getPageOf(item: T, itemsPerPage = 10): number {
const index = this.index(item);
if (-1 === index) return 0;
return Math.floor(index / itemsPerPage);
}
public reset() {
this.items = [];
this.entitySubjects.clear();
this.itemsMap.clear();
}
public all(): T[] {
return this.items;
}
/**
* Count of current page if paging is used, otherwise total count.
*/
public count() {
return this.items.length;
}
public ids(): (string | number)[] {
const ids: (string | number)[] = [];
for (const i of this.items) {
ids.push(i.id);
}
return ids;
}
public empty() {
return 0 === this.items.length;
}
/**
* All items from id -> value map.
*/
public map() {
return this.itemsMap;
}
public loaded() {
if (this.isStopped) {
throw new Error('Collection already unsubscribed');
}
this.next(this.items);
if (this.nextChangeResolver) {
this.nextChangeResolver();
this.nextChangeResolver = undefined;
this.nextChange = undefined;
}
}
public set(items: T[], withEvent = true) {
for (const item of items) {
if (!this.itemsMap.has(item.id)) {
this.added.next(item);
}
this.itemsMap.delete(item.id);
}
//remaining items will be deleted
for (const deleted of this.itemsMap.values()) {
this.removed.next(deleted);
const subject = this.entitySubjects.get(deleted.id);
if (subject) {
subject.unsubscribe();
this.entitySubjects.delete(deleted.id);
}
}
this.itemsMap.clear();
this.items = items;
for (const item of items) {
this.itemsMap.set(item.id, item);
}
if (withEvent) {
this.event.next({ type: 'set', items: items });
}
}
public removeMany(ids: (string | number)[], withEvent = true) {
for (const id of ids) {
const item = this.itemsMap.get(id);
this.itemsMap.delete(id);
if (item) {
const index = this.items.indexOf(item);
if (-1 !== index) {
this.removed.next(this.items[index]);
this.items.splice(index, 1);
}
}
const subject = this.entitySubjects.get(id);
if (subject) {
subject.unsubscribe();
this.entitySubjects.delete(id);
}
}
if (withEvent) {
this.event.next({ type: 'remove', ids: ids });
}
}
public update(items: T | T[], withEvent = true) {
items = isArray(items) ? items : [items];
for (const item of items) {
if (this.itemsMap.has(item.id)) {
const index = this.items.indexOf(this.itemsMap.get(item.id) as any);
this.items[index] = item;
this.itemsMap.set(item.id, item);
} else {
this.items.push(item);
this.itemsMap.set(item.id, item);
}
}
if (withEvent) {
this.event.next({ type: 'update', items });
}
}
public add(items: T | T[], withEvent = true) {
if (!items) {
throw new Error(`Trying to insert a ${getClassName(this.classType)} collection item without value`);
}
items = isArray(items) ? items : [items];
for (const item of items) {
this.added.next(item);
if (this.itemsMap.has(item.id)) {
const index = this.items.indexOf(this.itemsMap.get(item.id) as any);
this.items[index] = item;
this.itemsMap.set(item.id, item);
} else {
this.items.push(item);
this.itemsMap.set(item.id, item);
}
}
if (withEvent) {
this.event.next({ type: 'add', items });
}
}
public remove(ids: (string | number) | (string | number)[], withEvent = true) {
ids = isArray(ids) ? ids : [ids];
for (const id of ids) {
const item = this.itemsMap.get(id);
if (!item) continue;
this.itemsMap.delete(id);
const fork = this.entitySubjects.get(id);
fork?.unsubscribe();
this.entitySubjects.delete(id);
const index = this.items.indexOf(item);
if (-1 !== index) {
this.items.splice(index, 1);
}
if (withEvent) {
this.removed.next(item);
}
}
if (withEvent) {
this.event.next({ type: 'remove', ids: ids });
}
}
} | the_stack |
import { Patcher } from "../patch";
import { WebGLRenderer } from "../renderer/webgl/WebGLRenderer";
import { C2dRenderer } from "../renderer/c2d/C2dRenderer";
import { Element } from "./Element";
import { ColorUtils } from "./ColorUtils";
import { TextureManager } from "./TextureManager";
import { CoreContext } from "./core/CoreContext";
import { RectangleTexture } from "../textures";
import { WebPlatform } from "../platforms/browser/WebPlatform";
import { Renderer } from "../renderer/Renderer";
import { Texture } from "./Texture";
import { ElementCoordinatesInfo } from "./core/ElementCore";
import { StageOptions } from "./StageOptions";
export class Stage {
private destroyed = false;
public readonly gpuPixelsMemory: number;
public readonly bufferMemory: number;
public readonly defaultFontFace: string[];
public readonly fixedTimestep: number;
public readonly useImageWorker: boolean;
public readonly autostart: boolean;
public readonly pixelRatio: number;
public readonly canvas2d: boolean;
private _usedMemory: number = 0;
private _lastGcFrame: number = 0;
public readonly platform: WebPlatform = new WebPlatform(this);
public readonly gl: WebGLRenderingContext;
public readonly c2d: CanvasRenderingContext2D;
private _renderer: Renderer;
public readonly textureManager: TextureManager;
public frameCounter: number = 0;
private startTime: number = 0;
private currentTime: number = 0;
private dt: number = 0;
public readonly rectangleTexture: RectangleTexture;
public readonly context: CoreContext;
private _updateTextures = new Set<Texture>();
public readonly root: Element;
private _updatingFrame = false;
private clearColor: null | number[] = null;
private onFrameStart?: () => void;
private onUpdate?: () => void;
private onFrameEnd?: () => void;
private canvasWidth: number = -1;
private canvasHeight: number = -1;
private idsMap = new Map<string, Element[]>();
constructor(public readonly canvas: HTMLCanvasElement, options: Partial<StageOptions> = {}) {
this.gpuPixelsMemory = options.gpuPixelsMemory || 32e6;
this.bufferMemory = options.bufferMemory || 16e6;
this.defaultFontFace = options.defaultFontFace || ["sans-serif"];
this.fixedTimestep = options.fixedTimestep || 0;
this.useImageWorker = options.useImageWorker === undefined || options.useImageWorker;
this.autostart = options.autostart !== false;
this.pixelRatio = options.pixelRatio || this.getDefaultPixelRatio() || 1;
this.canvas2d = options.canvas2d === true || !Stage.isWebglSupported();
this.destroyed = false;
this._usedMemory = 0;
this._lastGcFrame = 0;
this.platform.init();
if (this.canvas2d) {
console.log("Using canvas2d renderer");
this.c2d = this.platform.createCanvasContext();
this.gl = undefined as any;
this._renderer = new C2dRenderer(this) as any;
} else {
this.gl = this.platform.createWebGLContext();
this.c2d = undefined as any;
this._renderer = new WebGLRenderer(this);
}
this.frameCounter = 0;
this.textureManager = new TextureManager(this);
// Preload rectangle texture.
this.rectangleTexture = new RectangleTexture(this);
this.context = new CoreContext(this);
this.root = new Element(this);
this.root.setAsRoot();
this.context.root = this.root.core;
this.processClearColorOption(options.clearColor);
this.checkCanvasDimensions();
this.observeCanvasDimensions();
if (this.autostart) {
this.platform.startLoop();
}
}
private processClearColorOption(option: number | string | null | undefined) {
switch (option) {
case null:
this.setClearColor(null);
break;
case undefined:
this.setClearColor([0, 0, 0, 0]);
break;
default:
this.setClearColor(ColorUtils.getRgbaComponentsNormalized(ColorUtils.getArgbFromAny(option)));
}
}
get w() {
return this.canvas.width;
}
get h() {
return this.canvas.height;
}
get renderer() {
return this._renderer;
}
static isWebglSupported() {
try {
return !!window.WebGLRenderingContext;
} catch (e) {
return false;
}
}
destroy() {
this.destroyed = true;
this.platform.stopLoop();
this.platform.destroy();
this.context.destroy();
this.textureManager.destroy();
this._renderer.destroy();
}
stop() {
this.platform.stopLoop();
}
resume() {
this.platform.startLoop();
}
getCanvas() {
return this.canvas;
}
getPixelRatio() {
return this.pixelRatio;
}
// Marks a texture for updating it's source upon the next drawFrame.
addUpdateTexture(texture: Texture) {
if (this._updatingFrame) {
// When called from the upload loop, we must immediately load the texture in order to avoid a 'flash'.
texture._performUpdateSource();
} else {
this._updateTextures.add(texture);
}
}
removeUpdateTexture(texture: Texture) {
if (this._updateTextures) {
this._updateTextures.delete(texture);
}
}
hasUpdateTexture(texture: Texture) {
return this._updateTextures && this._updateTextures.has(texture);
}
drawFrame() {
this.startTime = this.currentTime;
this.currentTime = this.platform.getHrTime();
if (this.fixedTimestep) {
this.dt = this.fixedTimestep;
} else {
this.dt = !this.startTime ? 0.02 : 0.001 * (this.currentTime - this.startTime);
}
if (this.onFrameStart) {
this.onFrameStart();
}
if (this._updateTextures.size) {
this._updateTextures.forEach((texture) => {
texture._performUpdateSource();
});
this._updateTextures = new Set();
}
if (this.onUpdate) {
this.onUpdate();
}
const changes = this.context.hasRenderUpdates();
if (changes) {
this._updatingFrame = true;
this.context.updateAndRender();
this._updatingFrame = false;
}
this.platform.nextFrame(changes);
if (this.onFrameEnd) {
this.onFrameEnd();
}
this.frameCounter++;
}
isUpdatingFrame() {
return this._updatingFrame;
}
forceRenderUpdate() {
this.context.setRenderUpdatesFlag();
}
setClearColor(clearColor: number[] | null) {
if (clearColor === null) {
// Do not clear.
this.clearColor = null;
} else {
this.clearColor = clearColor;
}
this.forceRenderUpdate();
}
getClearColor() {
return this.clearColor;
}
createElement(settings: any) {
return Patcher.createObject(settings, Element, this);
}
createShader(settings: any) {
return Patcher.createObject(settings, undefined, this);
}
get coordsWidth() {
return this.canvasWidth / this.pixelRatio;
}
get coordsHeight() {
return this.canvasHeight / this.pixelRatio;
}
getCanvasHeight() {
return this.canvasHeight;
}
addMemoryUsage(delta: number) {
this._usedMemory += delta;
if (this._lastGcFrame !== this.frameCounter) {
if (this._usedMemory > this.gpuPixelsMemory) {
this.gc(false);
if (this._usedMemory > this.gpuPixelsMemory - 2e6) {
// Too little memory could be recovered. Aggressive cleanup.
this.gc(true);
}
}
}
}
get usedMemory() {
return this._usedMemory;
}
gc(aggressive: boolean) {
if (this._lastGcFrame !== this.frameCounter) {
this._lastGcFrame = this.frameCounter;
const memoryUsageBefore = this._usedMemory;
this.gcTextureMemory(aggressive);
this.gcRenderTextureMemory(aggressive);
this.renderer.gc(aggressive);
console.log(
`GC${aggressive ? "[aggressive]" : ""}! Frame ${this._lastGcFrame} Freed ${(
(memoryUsageBefore - this._usedMemory) /
1e6
).toFixed(2)}MP from GPU memory. Remaining: ${(this._usedMemory / 1e6).toFixed(2)}MP`,
);
const other = this._usedMemory - this.textureManager.usedMemory - this.context.usedMemory;
console.log(
` Textures: ${(this.textureManager.usedMemory / 1e6).toFixed(2)}MP, Render Textures: ${(
this.context.usedMemory / 1e6
).toFixed(2)}MP, Renderer caches: ${(other / 1e6).toFixed(2)}MP`,
);
}
}
gcTextureMemory(aggressive = false) {
if (aggressive && this.root.visible) {
// Make sure that ALL textures are cleaned;
this.root.visible = false;
this.textureManager.gc();
this.root.visible = true;
} else {
this.textureManager.gc();
}
}
gcRenderTextureMemory(aggressive = false) {
if (aggressive && this.root.visible) {
// Make sure that ALL render textures are cleaned;
this.root.visible = false;
this.context.freeUnusedRenderTextures(0);
this.root.visible = true;
} else {
this.context.freeUnusedRenderTextures(0);
}
}
getDrawingCanvas() {
return this.platform.getDrawingCanvas();
}
update() {
this.context.update();
}
isDestroyed() {
return this.destroyed;
}
private checkCanvasDimensions() {
const rect = this.canvas.getBoundingClientRect();
let changed = false;
// Prevent resize recursion in dynamic layouts (flexbox etc).
// Notice that when you would like to use dynamic resize, you should wrap the canvas element in a dynamically
// resized div, and absolutely position the canvas in it with 100% width and height.
const cssWidth = rect.width || this.canvas.width;
if (Math.round(cssWidth) !== Math.round(this.canvasWidth)) {
const newCanvasWidth = cssWidth * this.pixelRatio;
changed = changed || newCanvasWidth !== this.canvasWidth;
this.canvasWidth = newCanvasWidth;
}
const cssHeight = rect.height || this.canvas.height;
if (Math.round(cssHeight) !== Math.round(this.canvasHeight)) {
const newCanvasHeight = cssHeight * this.pixelRatio;
changed = changed || newCanvasHeight !== this.canvasHeight;
this.canvasHeight = newCanvasHeight;
}
if (changed) {
this.updateCanvasSize();
}
}
private updateCanvasSize() {
// Make sure that the canvas looks 'crisp'.
this.canvas.width = Math.round(this.canvasWidth);
this.canvas.height = Math.round(this.canvasHeight);
// Reset dimensions.
this.root.core.setupAsRoot();
this.renderer.onResizeCanvasSize();
this.drawFrame();
}
getElementsAtCoordinates<DATA = any>(worldX: number, worldY: number): ElementCoordinatesInfo<DATA>[] {
const results: ElementCoordinatesInfo[] = [];
this.root.core.update();
this.root.core.gatherElementsAtCoordinates(worldX, worldY, results);
return results.reverse();
}
private getDefaultPixelRatio() {
return Math.min(window.devicePixelRatio, 2);
}
addId(id: string, element: Element) {
let elements = this.idsMap.get(id);
if (!elements) {
elements = [];
this.idsMap.set(id, elements);
}
elements.push(element);
}
removeId(id: string, element: Element) {
const elements = this.idsMap.get(id);
if (elements) {
this.idsMap.set(
id,
elements.filter((el) => el !== element),
);
}
}
getById(id: string): Element | undefined {
const elements = this.idsMap.get(id);
return elements ? elements[0] : undefined;
}
getMaxTextureSize(): number {
if (this.gl) {
return this.gl.getParameter(this.gl.MAX_TEXTURE_SIZE);
} else {
return 2048;
}
}
private observeCanvasDimensions() {
const hasResizeObserverSupport = !!(window as any).ResizeObserver;
if (hasResizeObserverSupport) {
const viewportResizeObserver = new (window as any).ResizeObserver(() => {
this.checkCanvasDimensions();
});
viewportResizeObserver.observe(this.canvas);
}
}
} | the_stack |
import { neverCheck } from '../../helper/neverCheck'
interface Uniform {
type:
| '1i'
| '2i'
| '3i'
| '4i'
| '1ui'
| '2ui'
| '3ui'
| '4ui'
| '1f'
| '2f'
| '3f'
| '4f'
| '1iv'
| '2iv'
| '3iv'
| '4iv'
| '1fv'
| '2fv'
| '3fv'
| '4fv'
| '1uiv'
| '2uiv'
| '3uiv'
| '4uiv'
| 'matrix2fv'
| 'matrix3x2fv'
| 'matrix4x2fv'
| 'matrix2x3fv'
| 'matrix3fv'
| 'matrix4x3fv'
| 'matrix2x4fv'
| 'matrix3x4fv'
| 'matrix4fv'
value: ReadonlyArray<number>
}
const DEFAULT_VERTEX_SHADER = `
precision highp float;
attribute vec2 position;
attribute vec2 coord;
varying vec2 vTexCoord;
void main(void) {
vTexCoord = coord;
gl_Position = vec4(position, 0.0, 1.0);
}
`
export default class WebGLContext {
private glCanvas: HTMLCanvasElement
private gl: WebGL2RenderingContext
private texBufferCanvas: HTMLCanvasElement
private vertexBuffer: WebGLBuffer
private tex2DBuffer: WebGLBuffer
public constructor(private width: number, private height: number) {
// OffscreenCanvas not updated frame (bug?) so using HTMLCanvasElement
this.glCanvas = Object.assign(document.createElement('canvas'), { width, height })
this.gl = this.glCanvas.getContext('webgl2')!
this.gl.viewport(0, 0, width, height)
// texImage2D not support for OffscreenCanvas so using HTMLCanvasElement
this.texBufferCanvas = Object.assign(document.createElement('canvas'), { width, height })
this.vertexBuffer = this.gl.createBuffer()!
this.tex2DBuffer = this.gl.createBuffer()!
}
/** [DO NOT USE] This is Delir internal API */
public setSize(width: number, height: number) {
this.glCanvas.width = width
this.glCanvas.height = height
this.gl.viewport(0, 0, width, height)
this.texBufferCanvas.width = width
this.texBufferCanvas.height = height
}
public getProgram(fragmentShaderSource: string, vertexShaderSource: string = DEFAULT_VERTEX_SHADER): WebGLProgram {
const program = this.gl.createProgram()!
const vertShader = this.gl.createShader(this.gl.VERTEX_SHADER)!
this.gl.shaderSource(vertShader, vertexShaderSource)
this.gl.compileShader(vertShader)
const fragShader = this.gl.createShader(this.gl.FRAGMENT_SHADER)!
this.gl.shaderSource(fragShader, fragmentShaderSource)
this.gl.compileShader(fragShader)
this.gl.attachShader(program, vertShader)
this.gl.attachShader(program, fragShader)
this.gl.linkProgram(program)
if (!this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) {
const error = this.gl.getProgramInfoLog(program)
throw new Error(`Failed to compile shader: ${error}`)
}
return program
}
public applyProgram(
program: WebGLProgram,
uniforms: { [uniformName: string]: Uniform },
source: HTMLCanvasElement,
dest: HTMLCanvasElement,
) {
const { gl, texBufferCanvas } = this
gl.useProgram(program)
const texBufferCtx = texBufferCanvas.getContext('2d')!
texBufferCanvas.width = source.width
texBufferCanvas.height = source.height
texBufferCtx.drawImage(source, 0, 0)
gl.clearColor(0, 0, 0, 0)
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, 1, 1, -1, 1]), gl.STATIC_DRAW)
const positionAttrib = gl.getAttribLocation(program, 'position')
gl.enableVertexAttribArray(positionAttrib)
gl.vertexAttribPointer(positionAttrib, 2, gl.FLOAT, false, 0, 0)
gl.bindBuffer(gl.ARRAY_BUFFER, this.tex2DBuffer)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]), gl.STATIC_DRAW)
const coordAttrib = gl.getAttribLocation(program, 'coord')
gl.enableVertexAttribArray(coordAttrib)
gl.vertexAttribPointer(coordAttrib, 2, gl.FLOAT, false, 0, 0)
const tex = gl.createTexture()
gl.activeTexture(gl.TEXTURE0)
gl.bindTexture(gl.TEXTURE_2D, tex)
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texBufferCanvas)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
// Attach source uniform
const sourceLoc = gl.getUniformLocation(program, 'source')
gl.uniform1i(sourceLoc, 0)
// Attach uniforms
this.attachUniforms(gl, program, uniforms)
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
gl.flush()
const destCtx = dest.getContext('2d')!
destCtx.clearRect(0, 0, dest.width, dest.height)
destCtx.drawImage(this.glCanvas, 0, 0, source.width, source.height)
}
// Uniforms
public uni1i(...value: [number]): Uniform {
return { type: '1i', value }
}
public uni2i(...value: [number, number]): Uniform {
return { type: '2i', value }
}
public uni3i(...value: [number, number, number]): Uniform {
return { type: '3i', value }
}
public uni4i(...value: [number, number, number, number]): Uniform {
return { type: '4i', value }
}
public uni1ui(...value: [number]): Uniform {
return { type: '1ui', value }
}
public uni2ui(...value: [number, number]): Uniform {
return { type: '2ui', value }
}
public uni3ui(...value: [number, number, number]): Uniform {
return { type: '3ui', value }
}
public uni4ui(...value: [number, number, number, number]): Uniform {
return { type: '4ui', value }
}
public uni1f(...value: [number]): Uniform {
return { type: '1f', value }
}
public uni2f(...value: [number, number]): Uniform {
return { type: '2f', value }
}
public uni3f(...value: [number, number, number]): Uniform {
return { type: '3f', value }
}
public uni4f(...value: [number, number, number, number]): Uniform {
return { type: '4f', value }
}
public uni1iv(value: number[]): Uniform {
return { type: '1iv', value }
}
public uni2iv(value: number[]): Uniform {
return { type: '2iv', value }
}
public uni3iv(value: number[]): Uniform {
return { type: '3iv', value }
}
public uni4iv(value: number[]): Uniform {
return { type: '4iv', value }
}
public uni1fv(value: number[]): Uniform {
return { type: '1fv', value }
}
public uni2fv(value: number[]): Uniform {
return { type: '2fv', value }
}
public uni3fv(value: number[]): Uniform {
return { type: '3fv', value }
}
public uni4fv(value: number[]): Uniform {
return { type: '4fv', value }
}
public uni1uiv(value: number[]): Uniform {
return { type: '1uiv', value }
}
public uni2uiv(value: number[]): Uniform {
return { type: '2uiv', value }
}
public uni3uiv(value: number[]): Uniform {
return { type: '3uiv', value }
}
public uni4uiv(value: number[]): Uniform {
return { type: '4uiv', value }
}
public uniMatrix2fv(value: number[]): Uniform {
return { type: 'matrix2fv', value }
}
public uniMatrix3x2fv(value: number[]): Uniform {
return { type: 'matrix3x2fv', value }
}
public uniMatrix4x2fv(value: number[]): Uniform {
return { type: 'matrix4x2fv', value }
}
public uniMatrix2x3fv(value: number[]): Uniform {
return { type: 'matrix2x3fv', value }
}
public uniMatrix3fv(value: number[]): Uniform {
return { type: 'matrix3fv', value }
}
public uniMatrix4x3fv(value: number[]): Uniform {
return { type: 'matrix4x3fv', value }
}
public uniMatrix2x4fv(value: number[]): Uniform {
return { type: 'matrix2x4fv', value }
}
public uniMatrix3x4fv(value: number[]): Uniform {
return { type: 'matrix3x4fv', value }
}
public uniMatrix4fv(value: number[]): Uniform {
return { type: 'matrix4fv', value }
}
private attachUniforms(gl: WebGL2RenderingContext, program: WebGLProgram, uniforms: { [uniform: string]: Uniform }) {
for (const uni of Object.keys(uniforms)) {
const loc = gl.getUniformLocation(program, uni)
const { type, value } = uniforms[uni]
switch (type) {
case '1i': {
gl.uniform1i(loc, value[0])
}
case '2i': {
gl.uniform2i(loc, value[0], value[1])
}
case '3i': {
gl.uniform3i(loc, value[0], value[1], value[2])
}
case '4i': {
gl.uniform4i(loc, value[0], value[1], value[2], value[3])
}
case '1ui': {
gl.uniform1ui(loc, value[0])
break
}
case '2ui': {
gl.uniform2ui(loc, value[0], value[1])
break
}
case '3ui': {
gl.uniform3ui(loc, value[0], value[1], value[2])
break
}
case '4ui': {
gl.uniform4ui(loc, value[0], value[1], value[2], value[3])
break
}
case '1f': {
gl.uniform1f(loc, value[0])
break
}
case '2f': {
gl.uniform2f(loc, value[0], value[1])
break
}
case '3f': {
gl.uniform3f(loc, value[0], value[1], value[2])
break
}
case '4f': {
gl.uniform4f(loc, value[0], value[1], value[2], value[3])
break
}
case '1iv': {
gl.uniform1iv(loc, value)
break
}
case '2iv': {
gl.uniform2iv(loc, value)
break
}
case '3iv': {
gl.uniform3iv(loc, value)
break
}
case '4iv': {
gl.uniform4iv(loc, value)
break
}
case '1fv': {
gl.uniform1fv(loc, value)
break
}
case '2fv': {
gl.uniform2fv(loc, value)
break
}
case '3fv': {
gl.uniform3fv(loc, value)
break
}
case '4fv': {
gl.uniform4fv(loc, value)
break
}
case '1uiv': {
gl.uniform1uiv(loc, value)
break
}
case '2uiv': {
gl.uniform2uiv(loc, value)
break
}
case '3uiv': {
gl.uniform3uiv(loc, value)
break
}
case '4uiv': {
gl.uniform4uiv(loc, value)
break
}
case 'matrix2fv': {
gl.uniformMatrix2fv(loc, false, value)
break
}
case 'matrix3x2fv': {
gl.uniformMatrix3x2fv(loc, false, value)
break
}
case 'matrix4x2fv': {
gl.uniformMatrix4x2fv(loc, false, value)
break
}
case 'matrix2x3fv': {
gl.uniformMatrix2x3fv(loc, false, value)
break
}
case 'matrix3fv': {
gl.uniformMatrix3fv(loc, false, value)
break
}
case 'matrix4x3fv': {
gl.uniformMatrix4x3fv(loc, false, value)
break
}
case 'matrix2x4fv': {
gl.uniformMatrix2x4fv(loc, false, value)
break
}
case 'matrix3x4fv': {
gl.uniformMatrix3x4fv(loc, false, value)
break
}
case 'matrix4fv': {
gl.uniformMatrix4fv(loc, false, value)
break
}
default: {
neverCheck(type)
}
}
}
}
} | the_stack |
import { componentScope, Fragment, h, ListView } from "harmaja"
import * as L from "lonna"
import prettyMs from "pretty-ms"
import { boardReducer } from "../../../common/src/board-reducer"
import {
Board,
BoardHistoryEntry,
EventUserInfo,
findItem,
getItem,
getItemIds,
getItemText,
Id,
ISOTimeStamp,
Item,
PersistableBoardItemEvent,
} from "../../../common/src/domain"
import { Checkbox } from "../components/components"
import { HistoryIcon } from "../components/Icons"
import { Dispatch } from "../store/board-store"
import { BoardFocus, getSelectedIds } from "./board-focus"
type ParsedHistoryEntry = {
timestamp: ISOTimeStamp
itemIds: Id[]
user: EventUserInfo
kind: "added" | "moved into" | "renamed" | "deleted" | "changed"
actionText: string // TODO: this should include links to items for selecting by click.
revertAction?: PersistableBoardItemEvent
}
export const HistoryView = ({
history,
board,
focus,
dispatch,
}: {
history: L.Property<BoardHistoryEntry[]>
board: L.Property<Board>
focus: L.Property<BoardFocus>
dispatch: Dispatch
}) => {
const expanded = L.atom(false)
return (
<div className={L.view(expanded, (e) => (e ? "history expanded" : "history"))}>
<div className="history-icon-wrapper">
<span className="icon" onClick={() => expanded.modify((e) => !e)}>
<HistoryIcon />
</span>
</div>
{L.view(expanded, (e) => e && <HistoryTable />)}
</div>
)
function HistoryTable() {
// Note: parsing full history once a second may or may not prove to be a performance challenge.
// At least it's done only when the history table is visible and debounced with 1000 milliseconds.
const parsedHistory = history.pipe(L.debounce(1000, componentScope()), L.map(parseFullHistory))
const forSelectedItem = L.atom(false)
const historyFocus = L.view(focus, forSelectedItem, (f, s) => (s ? f : ({ status: "none" } as BoardFocus)))
const focusedHistory = L.combine(parsedHistory, historyFocus, focusHistory)
const clippedHistory = L.view(focusedHistory, clipHistory)
return (
<>
<h2>Change Log</h2>
<div className="selection">
<Checkbox checked={forSelectedItem} /> for selected items
</div>
<div className="scroll-container">
<table>
<ListView
observable={clippedHistory}
getKey={(i) => i.timestamp}
renderObservable={renderHistoryEntry}
/>
</table>
</div>
</>
)
}
function renderHistoryEntry(key: string, entry: L.Property<ParsedHistoryEntry>) {
return (
<tr className="row">
<td className="timestamp">{L.view(entry, (e) => renderTimestamp(e.timestamp))}</td>
<td className="action">{L.view(entry, (e) => `${e.user.nickname} ${e.actionText}`)}</td>
<td className="revert">
{L.view(entry, (e) =>
e.revertAction ? (
<a className="icon undo" title="Revert" onClick={() => dispatch(e.revertAction!)}></a>
) : null,
)}
</td>
</tr>
)
}
function renderTimestamp(timestamp: ISOTimeStamp) {
const diff = new Date().getTime() - new Date(timestamp).getTime()
if (diff < 1000) return "just now"
return prettyMs(diff, { compact: true }) + " ago"
}
function focusHistory(history: ParsedHistoryEntry[], focus: BoardFocus) {
const selectedIds = getSelectedIds(focus)
if (selectedIds.size === 0) {
return history
}
return history.filter((entry) => entry.itemIds.some((id) => selectedIds.has(id)))
}
function clipHistory(history: ParsedHistoryEntry[]) {
return history.reverse().slice(0, 100)
}
function parseFullHistory(history: BoardHistoryEntry[]): ParsedHistoryEntry[] {
// Note: the history is not necessarily full, just what we have available locally. It will always start with a bootstrapping
// action though, so it will be consistent.
const currentBoard = board.get()
const initAtSerial = (history[0]?.serial || 1) - 1
const init = {
board: { ...currentBoard, items: {}, serial: initAtSerial } as Board,
parsedHistory: [] as ParsedHistoryEntry[],
}
const { parsedHistory } = history.reduce(({ board, parsedHistory }, event) => {
const [boardAfter, revertAction] = boardReducer(board, event)
let parsedEntry = parseHistory(event, board, boardAfter)
if (
parsedEntry &&
revertAction &&
event.action === "item.delete" &&
!event.itemIds.some((id) => !!findItem(currentBoard)(id))
)
parsedEntry = { ...parsedEntry, revertAction }
const newHistory = parsedEntry !== null ? [...parsedHistory, parsedEntry] : parsedHistory
return { board: boardAfter, parsedHistory: newHistory, revertAction }
}, init)
return parsedHistory
}
function parseHistory(event: BoardHistoryEntry, boardBefore: Board, boardAfter: Board): ParsedHistoryEntry | null {
const { timestamp, user } = event
const itemIds = getItemIds(event)
switch (event.action) {
case "connection.add":
case "connection.delete":
case "connection.modify": {
const kind =
event.action === "connection.add"
? "added"
: event.action === "connection.delete"
? "deleted"
: "changed"
const id = "connectionId" in event ? event.connectionId : event.connection.id
return {
timestamp,
user,
itemIds: [id],
kind,
actionText: `${kind} connection ${id}`,
}
}
case "item.add": {
const containerIds = [...new Set(event.items.map((i) => i.containerId))]
const containerInfo =
(containerIds.length === 1 &&
containerIds[0] &&
` to ${describeItems([getItem(boardBefore)(containerIds[0])])}`) ||
""
return {
timestamp,
user,
itemIds,
kind: "added",
actionText: `added ${describeItems(event.items)}${containerInfo}`,
}
}
case "item.delete":
return {
timestamp,
user,
itemIds,
kind: "deleted",
actionText: "deleted " + describeItems(itemIds.map(getItem(boardBefore))),
}
case "item.font.decrease":
case "item.font.increase":
case "item.front":
return null
case "item.move": {
const containerChanged = event.items.some(
(i) => i.containerId !== getItem(boardBefore)(i.id).containerId,
)
const containerIds = event.items.map((i) => i.containerId)
const containerId = containerIds[0]
const sameContainer = new Set(containerIds).size === 1
if (containerId && containerChanged && sameContainer) {
return {
timestamp,
user,
itemIds,
kind: "moved into",
actionText: `moved ${describeItems(itemIds.map(getItem(boardBefore)))} to ${describeItems([
getItem(boardBefore)(containerId),
])}`,
}
} else {
return null
}
}
case "item.update": {
if (event.items.length === 1) {
const itemId = event.items[0].id
const itemBefore = getItem(boardBefore)(itemId)
const itemAfter = getItem(boardAfter)(itemId)
const textBefore = getItemText(itemBefore)
const textAfter = getItemText(itemAfter)
if (textBefore !== textAfter) {
return {
timestamp,
user,
itemIds,
kind: "renamed",
actionText: `renamed ${describeItems([itemBefore])} to ${textAfter}`,
}
} else {
return null // Ignore all the resizes, recolorings...
}
}
return {
timestamp,
user,
itemIds,
kind: "changed",
actionText: `changed ${describeItems(event.items)}`,
}
}
case "board.rename":
case "board.setAccessPolicy":
case "item.bootstrap": {
return null
}
}
}
function describeItems(items: Item[]): string | null {
if (items.length === 0) return null
if (items.length > 1) return "multiple items"
const item = items[0]
switch (item.type) {
case "note":
case "container":
case "text":
return item.text
case "image":
return "an image"
case "video":
return "a video"
}
}
} | the_stack |
import * as assert from 'assert'
import * as fc from 'fast-check'
import { isDeepStrictEqual } from 'util'
import * as B from '../src/boolean'
import * as E from '../src/Either'
import * as Eq from '../src/Eq'
import { identity, pipe, tuple } from '../src/function'
import * as M from '../src/Monoid'
import * as N from '../src/number'
import * as O from '../src/Option'
import * as Ord from '../src/Ord'
import { Predicate } from '../src/Predicate'
import * as _ from '../src/ReadonlyArray'
import { Refinement } from '../src/Refinement'
import { separated } from '../src/Separated'
import * as S from '../src/string'
import * as T from '../src/Task'
import * as U from './util'
describe('ReadonlyArray', () => {
describe('pipeables', () => {
it('traverse', () => {
const traverse = _.traverse(O.Applicative)((n: number): O.Option<number> => (n % 2 === 0 ? O.none : O.some(n)))
U.deepStrictEqual(traverse([1, 2]), O.none)
U.deepStrictEqual(traverse([1, 3]), O.some([1, 3]))
})
it('sequence', () => {
const sequence = _.sequence(O.Applicative)
U.deepStrictEqual(sequence([O.some(1), O.some(3)]), O.some([1, 3]))
U.deepStrictEqual(sequence([O.some(1), O.none]), O.none)
})
it('traverseWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'bb'],
_.traverseWithIndex(O.Applicative)((i, s) => (s.length >= 1 ? O.some(s + i) : O.none))
),
O.some(['a0', 'bb1'])
)
U.deepStrictEqual(
pipe(
['a', 'bb'],
_.traverseWithIndex(O.Applicative)((i, s) => (s.length > 1 ? O.some(s + i) : O.none))
),
O.none
)
})
it('lookup', () => {
U.deepStrictEqual(_.lookup(0, [1, 2, 3]), O.some(1))
U.deepStrictEqual(_.lookup(3, [1, 2, 3]), O.none)
U.deepStrictEqual(pipe([1, 2, 3], _.lookup(0)), O.some(1))
U.deepStrictEqual(pipe([1, 2, 3], _.lookup(3)), O.none)
})
it('elem', () => {
U.deepStrictEqual(_.elem(N.Eq)(2, [1, 2, 3]), true)
U.deepStrictEqual(_.elem(N.Eq)(0, [1, 2, 3]), false)
U.deepStrictEqual(pipe([1, 2, 3], _.elem(N.Eq)(2)), true)
U.deepStrictEqual(pipe([1, 2, 3], _.elem(N.Eq)(0)), false)
})
it('unfold', () => {
const as = _.unfold(5, (n) => (n > 0 ? O.some([n, n - 1]) : O.none))
U.deepStrictEqual(as, [5, 4, 3, 2, 1])
})
it('wither', async () => {
const wither = _.wither(T.ApplicativePar)((n: number) => T.of(n > 2 ? O.some(n + 1) : O.none))
U.deepStrictEqual(await pipe([], wither)(), [])
U.deepStrictEqual(await pipe([1, 3], wither)(), [4])
})
it('wilt', async () => {
const wilt = _.wilt(T.ApplicativePar)((n: number) => T.of(n > 2 ? E.right(n + 1) : E.left(n - 1)))
U.deepStrictEqual(await pipe([], wilt)(), separated([], []))
U.deepStrictEqual(await pipe([1, 3], wilt)(), separated([0], [4]))
})
it('map', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.map((n) => n * 2)
),
[2, 4, 6]
)
})
it('mapWithIndex', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.mapWithIndex((i, n) => n + i)
),
[1, 3, 5]
)
})
it('alt', () => {
U.deepStrictEqual(
pipe(
[1, 2],
_.alt(() => [3, 4])
),
[1, 2, 3, 4]
)
})
it('ap', () => {
U.deepStrictEqual(pipe([(x: number) => x * 2, (x: number) => x * 3], _.ap([1, 2, 3])), [2, 4, 6, 3, 6, 9])
})
it('apFirst', () => {
U.deepStrictEqual(pipe([1, 2], _.apFirst(['a', 'b', 'c'])), [1, 1, 1, 2, 2, 2])
})
it('apSecond', () => {
U.deepStrictEqual(pipe([1, 2], _.apSecond(['a', 'b', 'c'])), ['a', 'b', 'c', 'a', 'b', 'c'])
})
it('chain', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.chain((n) => [n, n + 1])
),
[1, 2, 2, 3, 3, 4]
)
})
it('chainWithIndex', () => {
const f = _.chainWithIndex((i, n: number) => [n + i])
U.deepStrictEqual(pipe([1, 2, 3], f), [1, 3, 5])
U.strictEqual(pipe(_.empty, f), _.empty)
const empty: ReadonlyArray<number> = []
U.strictEqual(pipe(empty, f), _.empty)
})
it('chainFirst', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.chainFirst((n) => [n, n + 1])
),
[1, 1, 2, 2, 3, 3]
)
})
it('extend', () => {
const sum = (as: ReadonlyArray<number>) => M.concatAll(N.MonoidSum)(as)
U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(sum)), [10, 9, 7, 4])
U.deepStrictEqual(pipe([1, 2, 3, 4], _.extend(identity)), [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]])
})
it('foldMap', () => {
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.foldMap(S.Monoid)(identity)), 'abc')
U.deepStrictEqual(pipe([], _.foldMap(S.Monoid)(identity)), '')
})
it('compact', () => {
U.deepStrictEqual(_.compact([]), [])
U.deepStrictEqual(_.compact([O.some(1), O.some(2), O.some(3)]), [1, 2, 3])
U.deepStrictEqual(_.compact([O.some(1), O.none, O.some(3)]), [1, 3])
})
it('separate', () => {
U.deepStrictEqual(_.separate([]), separated([], []))
U.deepStrictEqual(_.separate([E.left(123), E.right('123')]), separated([123], ['123']))
})
it('filter', () => {
const g = (n: number) => n % 2 === 1
U.deepStrictEqual(pipe([1, 2, 3], _.filter(g)), [1, 3])
const x = pipe([O.some(3), O.some(2), O.some(1)], _.filter(O.isSome))
assert.deepStrictEqual(x, [O.some(3), O.some(2), O.some(1)])
const y = pipe([O.some(3), O.none, O.some(1)], _.filter(O.isSome))
assert.deepStrictEqual(y, [O.some(3), O.some(1)])
})
it('filterWithIndex', () => {
const f = (n: number) => n % 2 === 0
U.deepStrictEqual(pipe(['a', 'b', 'c'], _.filterWithIndex(f)), ['a', 'c'])
})
it('filterMap', () => {
const f = (n: number) => (n % 2 === 0 ? O.none : O.some(n))
U.deepStrictEqual(pipe([1, 2, 3], _.filterMap(f)), [1, 3])
U.deepStrictEqual(pipe([], _.filterMap(f)), [])
})
it('foldMapWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.foldMapWithIndex(S.Monoid)((i, a) => i + a)
),
'0a1b'
)
})
it('filterMapWithIndex', () => {
const f = (i: number, n: number) => ((i + n) % 2 === 0 ? O.none : O.some(n))
U.deepStrictEqual(pipe([1, 2, 4], _.filterMapWithIndex(f)), [1, 2])
U.deepStrictEqual(pipe([], _.filterMapWithIndex(f)), [])
})
it('partitionMap', () => {
U.deepStrictEqual(pipe([], _.partitionMap(identity)), separated([], []))
U.deepStrictEqual(
pipe([E.right(1), E.left('foo'), E.right(2)], _.partitionMap(identity)),
separated(['foo'], [1, 2])
)
})
it('partition', () => {
U.deepStrictEqual(
pipe(
[],
_.partition((n) => n > 2)
),
separated([], [])
)
U.deepStrictEqual(
pipe(
[1, 3],
_.partition((n) => n > 2)
),
separated([1], [3])
)
})
it('partitionMapWithIndex', () => {
U.deepStrictEqual(
pipe(
[],
_.partitionMapWithIndex((_, a) => a)
),
separated([], [])
)
U.deepStrictEqual(
pipe(
[E.right(1), E.left('foo'), E.right(2)],
_.partitionMapWithIndex((i, a) =>
pipe(
a,
E.filterOrElse(
(n) => n > i,
() => 'err'
)
)
)
),
separated(['foo', 'err'], [1])
)
})
it('partitionWithIndex', () => {
U.deepStrictEqual(
pipe(
[],
_.partitionWithIndex((i, n) => i + n > 2)
),
separated([], [])
)
U.deepStrictEqual(
pipe(
[1, 2],
_.partitionWithIndex((i, n) => i + n > 2)
),
separated([1], [2])
)
})
it('reduce', () => {
U.deepStrictEqual(
pipe(
['a', 'b', 'c'],
_.reduce('', (acc, a) => acc + a)
),
'abc'
)
})
it('reduceWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.reduceWithIndex('', (i, b, a) => b + i + a)
),
'0a1b'
)
})
it('reduceRight', () => {
const as: ReadonlyArray<string> = ['a', 'b', 'c']
const b = ''
const f = (a: string, acc: string) => acc + a
U.deepStrictEqual(pipe(as, _.reduceRight(b, f)), 'cba')
const x2: ReadonlyArray<string> = []
U.deepStrictEqual(pipe(x2, _.reduceRight(b, f)), '')
})
it('reduceRightWithIndex', () => {
U.deepStrictEqual(
pipe(
['a', 'b'],
_.reduceRightWithIndex('', (i, a, b) => b + i + a)
),
'1b0a'
)
})
it('duplicate', () => {
U.deepStrictEqual(pipe(['a', 'b'], _.duplicate), [['a', 'b'], ['b']])
})
})
it('getMonoid', () => {
const M = _.getMonoid<number>()
U.deepStrictEqual(M.concat([1, 2], [3, 4]), [1, 2, 3, 4])
const x = [1, 2]
U.strictEqual(M.concat(x, M.empty), x)
U.strictEqual(M.concat(M.empty, x), x)
})
it('getEq', () => {
const O = _.getEq(S.Ord)
U.deepStrictEqual(O.equals([], []), true)
U.deepStrictEqual(O.equals(['a'], ['a']), true)
U.deepStrictEqual(O.equals(['a', 'b'], ['a', 'b']), true)
U.deepStrictEqual(O.equals(['a'], []), false)
U.deepStrictEqual(O.equals([], ['a']), false)
U.deepStrictEqual(O.equals(['a'], ['b']), false)
U.deepStrictEqual(O.equals(['a', 'b'], ['b', 'a']), false)
U.deepStrictEqual(O.equals(['a', 'a'], ['a']), false)
})
it('getOrd', () => {
const O = _.getOrd(S.Ord)
U.deepStrictEqual(O.compare([], []), 0)
U.deepStrictEqual(O.compare(['a'], ['a']), 0)
U.deepStrictEqual(O.compare(['b'], ['a']), 1)
U.deepStrictEqual(O.compare(['a'], ['b']), -1)
U.deepStrictEqual(O.compare(['a'], []), 1)
U.deepStrictEqual(O.compare([], ['a']), -1)
U.deepStrictEqual(O.compare(['a', 'a'], ['a']), 1)
U.deepStrictEqual(O.compare(['a', 'a'], ['b']), -1)
U.deepStrictEqual(O.compare(['a', 'a'], ['a', 'a']), 0)
U.deepStrictEqual(O.compare(['a', 'b'], ['a', 'b']), 0)
U.deepStrictEqual(O.compare(['a', 'a'], ['a', 'b']), -1)
U.deepStrictEqual(O.compare(['a', 'b'], ['a', 'a']), 1)
U.deepStrictEqual(O.compare(['a', 'b'], ['b', 'a']), -1)
U.deepStrictEqual(O.compare(['b', 'a'], ['a', 'a']), 1)
U.deepStrictEqual(O.compare(['b', 'a'], ['a', 'b']), 1)
U.deepStrictEqual(O.compare(['b', 'b'], ['b', 'a']), 1)
U.deepStrictEqual(O.compare(['b', 'a'], ['b', 'b']), -1)
})
it('isEmpty', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.isEmpty(as), false)
U.deepStrictEqual(_.isEmpty([]), true)
})
it('isNotEmpty', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.isNonEmpty(as), true)
U.deepStrictEqual(_.isNonEmpty([]), false)
})
it('cons', () => {
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.cons(0, [1, 2, 3]), [0, 1, 2, 3])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.cons([1], [[2]]), [[1], [2]])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(pipe([1, 2, 3], _.cons(0)), [0, 1, 2, 3])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(pipe([[2]], _.cons([1])), [[1], [2]])
})
it('snoc', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.snoc(as, 4), [1, 2, 3, 4])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.snoc([[1]], [2]), [[1], [2]])
})
it('head', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.head(as), O.some(1))
U.deepStrictEqual(_.head([]), O.none)
})
it('last', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.last(as), O.some(3))
U.deepStrictEqual(_.last([]), O.none)
})
it('tail', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.tail(as), O.some([2, 3]))
U.deepStrictEqual(_.tail([]), O.none)
})
it('takeLeft', () => {
// _.empty
U.strictEqual(_.takeLeft(0)(_.empty), _.empty)
// empty
const empty: ReadonlyArray<number> = []
U.strictEqual(_.takeLeft(0)(empty), empty)
const full: ReadonlyArray<number> = [1, 2]
// non empty
U.strictEqual(_.takeLeft(0)(full), _.empty)
U.deepStrictEqual(_.takeLeft(1)(full), [1])
// full
U.strictEqual(_.takeLeft(2)(full), full)
// out of bound
U.strictEqual(_.takeLeft(1)(_.empty), _.empty)
U.strictEqual(_.takeLeft(1)(empty), empty)
U.strictEqual(_.takeLeft(3)(full), full)
U.strictEqual(_.takeLeft(-1)(_.empty), _.empty)
U.strictEqual(_.takeLeft(-1)(empty), empty)
U.strictEqual(_.takeLeft(-1)(full), full)
})
it('takeRight', () => {
// _.empty
U.strictEqual(_.takeRight(0)(_.empty), _.empty)
// empty
const empty: ReadonlyArray<number> = []
U.strictEqual(_.takeRight(0)(empty), empty)
const full: ReadonlyArray<number> = [1, 2]
// non empty
U.strictEqual(_.takeRight(0)(full), _.empty)
U.deepStrictEqual(_.takeRight(1)(full), [2])
// full
U.strictEqual(_.takeRight(2)(full), full)
// out of bound
U.strictEqual(_.takeRight(1)(_.empty), _.empty)
U.strictEqual(_.takeRight(1)(empty), empty)
U.strictEqual(_.takeRight(3)(full), full)
U.strictEqual(_.takeRight(-1)(_.empty), _.empty)
U.strictEqual(_.takeRight(-1)(empty), empty)
U.strictEqual(_.takeRight(-1)(full), full)
})
it('spanLeft', () => {
const f = _.spanLeft((n: number) => n % 2 === 1)
const assertSpanLeft = (
input: ReadonlyArray<number>,
expectedInit: ReadonlyArray<number>,
expectedRest: ReadonlyArray<number>
) => {
const { init, rest } = f(input)
U.strictEqual(init, expectedInit)
U.strictEqual(rest, expectedRest)
}
U.deepStrictEqual(f([1, 3, 2, 4, 5]), { init: [1, 3], rest: [2, 4, 5] })
const empty: ReadonlyArray<number> = []
assertSpanLeft(empty, empty, _.empty)
assertSpanLeft(_.empty, _.empty, _.empty)
const inputAll: ReadonlyArray<number> = [1, 3]
assertSpanLeft(inputAll, inputAll, _.empty)
const inputNone: ReadonlyArray<number> = [2, 4]
assertSpanLeft(inputNone, _.empty, inputNone)
})
it('takeLeftWhile', () => {
const f = (n: number) => n % 2 === 0
U.deepStrictEqual(_.takeLeftWhile(f)([2, 4, 3, 6]), [2, 4])
const empty: ReadonlyArray<number> = []
U.strictEqual(_.takeLeftWhile(f)(empty), empty)
U.strictEqual(_.takeLeftWhile(f)(_.empty), _.empty)
U.strictEqual(_.takeLeftWhile(f)([1, 2, 4]), _.empty)
const input: ReadonlyArray<number> = [2, 4]
U.strictEqual(_.takeLeftWhile(f)(input), input)
})
it('dropLeft', () => {
// _.empty
U.strictEqual(_.dropLeft(0)(_.empty), _.empty)
// empty
const empty: ReadonlyArray<number> = []
U.strictEqual(_.dropLeft(0)(empty), empty)
const full: ReadonlyArray<number> = [1, 2]
// non empty
U.strictEqual(_.dropLeft(0)(full), full)
U.deepStrictEqual(_.dropLeft(1)(full), [2])
// full
U.strictEqual(_.dropLeft(2)(full), _.empty)
// out of bound
U.strictEqual(_.dropLeft(1)(_.empty), _.empty)
U.strictEqual(_.dropLeft(1)(empty), empty)
U.strictEqual(_.dropLeft(3)(full), _.empty)
U.strictEqual(_.dropLeft(-1)(_.empty), _.empty)
U.strictEqual(_.dropLeft(-1)(empty), empty)
U.strictEqual(_.dropLeft(-1)(full), full)
})
it('dropRight', () => {
// _.empty
U.strictEqual(_.dropRight(0)(_.empty), _.empty)
// empty
const empty: ReadonlyArray<number> = []
U.strictEqual(_.dropRight(0)(empty), empty)
const full: ReadonlyArray<number> = [1, 2]
// non empty
U.strictEqual(_.dropRight(0)(full), full)
U.deepStrictEqual(_.dropRight(1)(full), [1])
// full
U.strictEqual(_.dropRight(2)(full), _.empty)
// out of bound
U.strictEqual(_.dropRight(1)(_.empty), _.empty)
U.strictEqual(_.dropRight(1)(empty), empty)
U.strictEqual(_.dropRight(3)(full), _.empty)
U.strictEqual(_.dropRight(-1)(_.empty), _.empty)
U.strictEqual(_.dropRight(-1)(empty), empty)
U.strictEqual(_.dropRight(-1)(full), full)
})
it('dropLeftWhile', () => {
const f = _.dropLeftWhile((n: number) => n > 0)
U.strictEqual(f(_.empty), _.empty)
const empty: ReadonlyArray<number> = []
U.strictEqual(f(empty), empty)
U.strictEqual(f([1, 2]), _.empty)
const x1: ReadonlyArray<number> = [-1, -2]
U.strictEqual(f(x1), x1)
const x2: ReadonlyArray<number> = [-1, 2]
U.strictEqual(f(x2), x2)
U.deepStrictEqual(f([1, -2, 3]), [-2, 3])
})
it('init', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.init(as), O.some([1, 2]))
U.deepStrictEqual(_.init([]), O.none)
})
it('findIndex', () => {
U.deepStrictEqual(_.findIndex((x) => x === 2)([1, 2, 3]), O.some(1))
U.deepStrictEqual(_.findIndex((x) => x === 2)([]), O.none)
})
it('findFirst', () => {
U.deepStrictEqual(
pipe(
[],
_.findFirst((x: { readonly a: number }) => x.a > 1)
),
O.none
)
U.deepStrictEqual(
pipe(
[{ a: 1 }, { a: 2 }, { a: 3 }],
_.findFirst((x) => x.a > 1)
),
O.some({ a: 2 })
)
U.deepStrictEqual(
pipe(
[{ a: 1 }, { a: 2 }, { a: 3 }],
_.findFirst((x) => x.a > 3)
),
O.none
)
})
it('findFirstMap', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.findFirstMap((n) => (n > 1 ? O.some(n * 2) : O.none))
),
O.some(4)
)
U.deepStrictEqual(
pipe(
[1],
_.findFirstMap((n) => (n < 1 ? O.some(n * 2) : O.none))
),
O.none
)
})
it('findLast', () => {
U.deepStrictEqual(
pipe(
[],
_.findLast((x: { readonly a: number }) => x.a > 1)
),
O.none
)
U.deepStrictEqual(
pipe(
[{ a: 1 }, { a: 2 }, { a: 3 }],
_.findLast((x) => x.a > 1)
),
O.some({ a: 3 })
)
U.deepStrictEqual(
pipe(
[{ a: 1 }, { a: 2 }, { a: 3 }],
_.findLast((x) => x.a > 3)
),
O.none
)
})
it('findLastMap', () => {
U.deepStrictEqual(
pipe(
[1, 2, 3],
_.findLastMap((n) => (n > 1 ? O.some(n * 2) : O.none))
),
O.some(6)
)
U.deepStrictEqual(
pipe(
[1],
_.findLastMap((n) => (n > 1 ? O.some(n * 2) : O.none))
),
O.none
)
})
it('findLastIndex', () => {
interface X {
readonly a: number
readonly b: number
}
const xs: ReadonlyArray<X> = [
{ a: 1, b: 0 },
{ a: 1, b: 1 }
]
U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 1)(xs), O.some(1))
U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 4)(xs), O.none)
U.deepStrictEqual(_.findLastIndex((x: X) => x.a === 1)([]), O.none)
})
it('insertAt', () => {
U.deepStrictEqual(_.insertAt(1, 1)([]), O.none)
U.deepStrictEqual(_.insertAt(0, 1)([]), O.some([1] as const))
U.deepStrictEqual(_.insertAt(2, 5)([1, 2, 3, 4]), O.some([1, 2, 5, 3, 4] as const))
})
it('unsafeUpdateAt', () => {
const empty: ReadonlyArray<number> = []
U.strictEqual(_.unsafeUpdateAt(1, 2, empty), empty)
U.strictEqual(_.unsafeUpdateAt(1, 2, _.empty), _.empty)
// should return the same reference if nothing changed
const input: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(
pipe(_.unsafeUpdateAt(1, 2, input), (out) => out === input),
true
)
})
it('updateAt', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.updateAt(1, 1)(as), O.some([1, 1, 3]))
U.deepStrictEqual(_.updateAt(1, 1)([]), O.none)
})
it('deleteAt', () => {
const as: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(_.deleteAt(0)(as), O.some([2, 3]))
U.deepStrictEqual(_.deleteAt(1)([]), O.none)
})
it('modifyAt', () => {
U.deepStrictEqual(_.modifyAt(1, U.double)([1, 2, 3]), O.some([1, 4, 3]))
U.deepStrictEqual(_.modifyAt(1, U.double)([]), O.none)
// should return the same reference if nothing changed
const input: ReadonlyArray<number> = [1, 2, 3]
U.deepStrictEqual(
pipe(
input,
_.modifyAt(1, identity),
O.map((out) => out === input)
),
O.some(true)
)
})
it('sort', () => {
const O = pipe(
N.Ord,
Ord.contramap((x: { readonly a: number }) => x.a)
)
U.deepStrictEqual(
pipe(
[
{ a: 3, b: 'b1' },
{ a: 2, b: 'b2' },
{ a: 1, b: 'b3' }
],
_.sort(O)
),
[
{ a: 1, b: 'b3' },
{ a: 2, b: 'b2' },
{ a: 3, b: 'b1' }
]
)
U.strictEqual(_.sort(N.Ord)(_.empty), _.empty)
const as: ReadonlyArray<number> = [1]
U.strictEqual(_.sort(N.Ord)(as), as)
})
it('zipWith', () => {
U.deepStrictEqual(
_.zipWith([1, 2, 3], [], (n, s) => s + n),
[]
)
U.deepStrictEqual(
_.zipWith([], ['a', 'b', 'c', 'd'], (n, s) => s + n),
[]
)
U.deepStrictEqual(
_.zipWith([], [], (n, s) => s + n),
[]
)
U.deepStrictEqual(
_.zipWith([1, 2, 3], ['a', 'b', 'c', 'd'], (n, s) => s + n),
['a1', 'b2', 'c3']
)
})
it('zip', () => {
U.deepStrictEqual(_.zip([], ['a', 'b', 'c', 'd']), [])
U.deepStrictEqual(_.zip([1, 2, 3], []), [])
U.deepStrictEqual(_.zip([1, 2, 3], ['a', 'b', 'c', 'd']), [
[1, 'a'],
[2, 'b'],
[3, 'c']
])
U.deepStrictEqual(pipe([1, 2, 3], _.zip(['a', 'b', 'c', 'd'])), [
[1, 'a'],
[2, 'b'],
[3, 'c']
])
})
it('unzip', () => {
U.deepStrictEqual(_.unzip([]), [[], []])
U.deepStrictEqual(
_.unzip([
[1, 'a'],
[2, 'b'],
[3, 'c']
]),
[
[1, 2, 3],
['a', 'b', 'c']
]
)
})
it('rights', () => {
U.deepStrictEqual(_.rights([E.right(1), E.left('foo'), E.right(2)]), [1, 2])
U.deepStrictEqual(_.rights([]), [])
})
it('lefts', () => {
U.deepStrictEqual(_.lefts([E.right(1), E.left('foo'), E.right(2)]), ['foo'])
U.deepStrictEqual(_.lefts([]), [])
})
it('flatten', () => {
U.deepStrictEqual(_.flatten([[1], [2], [3]]), [1, 2, 3])
})
it('prependAll', () => {
const empty: ReadonlyArray<number> = []
U.strictEqual(_.prependAll(0)(empty), empty)
U.strictEqual(_.prependAll(0)(_.empty), _.empty)
U.deepStrictEqual(_.prependAll(0)([1, 2, 3]), [0, 1, 0, 2, 0, 3])
U.deepStrictEqual(_.prependAll(0)([1]), [0, 1])
U.deepStrictEqual(_.prependAll(0)([1, 2, 3, 4]), [0, 1, 0, 2, 0, 3, 0, 4])
})
it('intersperse', () => {
const empty: ReadonlyArray<number> = []
U.strictEqual(_.intersperse(0)(empty), empty)
U.strictEqual(_.intersperse(0)(_.empty), _.empty)
const singleton = [1]
U.strictEqual(_.intersperse(0)(singleton), singleton)
U.deepStrictEqual(_.intersperse(0)([1, 2, 3]), [1, 0, 2, 0, 3])
U.deepStrictEqual(_.intersperse(0)([1, 2]), [1, 0, 2])
U.deepStrictEqual(_.intersperse(0)([1, 2, 3, 4]), [1, 0, 2, 0, 3, 0, 4])
})
it('rotate', () => {
U.strictEqual(_.rotate(0)(_.empty), _.empty)
U.strictEqual(_.rotate(1)(_.empty), _.empty)
const singleton: ReadonlyArray<number> = [1]
U.strictEqual(_.rotate(1)(singleton), singleton)
U.strictEqual(_.rotate(2)(singleton), singleton)
U.strictEqual(_.rotate(-1)(singleton), singleton)
U.strictEqual(_.rotate(-2)(singleton), singleton)
const two: ReadonlyArray<number> = [1, 2]
U.strictEqual(_.rotate(2)(two), two)
U.strictEqual(_.rotate(0)(two), two)
U.strictEqual(_.rotate(-2)(two), two)
U.deepStrictEqual(_.rotate(1)([1, 2]), [2, 1])
U.deepStrictEqual(_.rotate(1)([1, 2, 3, 4, 5]), [5, 1, 2, 3, 4])
U.deepStrictEqual(_.rotate(2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
U.deepStrictEqual(_.rotate(-1)([1, 2, 3, 4, 5]), [2, 3, 4, 5, 1])
U.deepStrictEqual(_.rotate(-2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
U.deepStrictEqual(_.rotate(7)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
U.deepStrictEqual(_.rotate(-7)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
U.deepStrictEqual(_.rotate(2.2)([1, 2, 3, 4, 5]), [4, 5, 1, 2, 3])
U.deepStrictEqual(_.rotate(-2.2)([1, 2, 3, 4, 5]), [3, 4, 5, 1, 2])
})
it('reverse', () => {
const empty: ReadonlyArray<number> = []
U.strictEqual(_.reverse(empty), empty)
U.strictEqual(_.reverse(_.empty), _.empty)
const singleton: ReadonlyArray<number> = [1]
U.strictEqual(_.reverse(singleton), singleton)
U.deepStrictEqual(_.reverse([1, 2, 3]), [3, 2, 1])
})
it('foldLeft', () => {
const len: <A>(as: ReadonlyArray<A>) => number = _.foldLeft(
() => 0,
(_, tail) => 1 + len(tail)
)
U.deepStrictEqual(len([1, 2, 3]), 3)
})
it('foldRight', () => {
const len: <A>(as: ReadonlyArray<A>) => number = _.foldRight(
() => 0,
(init, _) => 1 + len(init)
)
U.deepStrictEqual(len([1, 2, 3]), 3)
})
it('scanLeft', () => {
const f = (b: number, a: number) => b - a
U.deepStrictEqual(_.scanLeft(10, f)([1, 2, 3]), [10, 9, 7, 4])
U.deepStrictEqual(_.scanLeft(10, f)([0]), [10, 10])
U.deepStrictEqual(_.scanLeft(10, f)([]), [10])
})
it('scanRight', () => {
const f = (b: number, a: number) => b - a
U.deepStrictEqual(_.scanRight(10, f)([1, 2, 3]), [-8, 9, -7, 10])
U.deepStrictEqual(_.scanRight(10, f)([0]), [-10, 10])
U.deepStrictEqual(_.scanRight(10, f)([]), [10])
})
it('uniq', () => {
interface A {
readonly a: string
readonly b: number
}
const eqA = pipe(
N.Eq,
Eq.contramap((f: A) => f.b)
)
const arrA: A = { a: 'a', b: 1 }
const arrB: A = { a: 'b', b: 1 }
const arrC: A = { a: 'c', b: 2 }
const arrD: A = { a: 'd', b: 2 }
const arrUniq: ReadonlyArray<A> = [arrA, arrC]
U.deepStrictEqual(_.uniq(eqA)(arrUniq), arrUniq)
U.deepStrictEqual(_.uniq(eqA)([arrA, arrB, arrC, arrD]), [arrA, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrB, arrA, arrC, arrD]), [arrB, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrA, arrA, arrC, arrD, arrA]), [arrA, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrA, arrC]), [arrA, arrC])
U.deepStrictEqual(_.uniq(eqA)([arrC, arrA]), [arrC, arrA])
U.deepStrictEqual(_.uniq(B.Eq)([true, false, true, false]), [true, false])
U.deepStrictEqual(_.uniq(N.Eq)([-0, -0]), [-0])
U.deepStrictEqual(_.uniq(N.Eq)([0, -0]), [0])
U.deepStrictEqual(_.uniq(N.Eq)([1]), [1])
U.deepStrictEqual(_.uniq(N.Eq)([2, 1, 2]), [2, 1])
U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 1]), [1, 2])
U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.uniq(N.Eq)([1, 1, 2, 2, 3, 3, 4, 4, 5, 5]), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.uniq(N.Eq)([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]), [1, 2, 3, 4, 5])
U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'a']), ['a', 'b'])
U.deepStrictEqual(_.uniq(S.Eq)(['a', 'b', 'A']), ['a', 'b', 'A'])
U.strictEqual(_.uniq(N.Eq)(_.empty), _.empty)
const as: ReadonlyArray<number> = [1]
U.strictEqual(_.uniq(N.Eq)(as), as)
})
it('sortBy', () => {
interface X {
readonly a: string
readonly b: number
readonly c: boolean
}
const byName = pipe(
S.Ord,
Ord.contramap((p: { readonly a: string; readonly b: number }) => p.a)
)
const byAge = pipe(
N.Ord,
Ord.contramap((p: { readonly a: string; readonly b: number }) => p.b)
)
const f = _.sortBy([byName, byAge])
const xs: ReadonlyArray<X> = [
{ a: 'a', b: 1, c: true },
{ a: 'b', b: 3, c: true },
{ a: 'c', b: 2, c: true },
{ a: 'b', b: 2, c: true }
]
U.deepStrictEqual(f(xs), [
{ a: 'a', b: 1, c: true },
{ a: 'b', b: 2, c: true },
{ a: 'b', b: 3, c: true },
{ a: 'c', b: 2, c: true }
])
const sortByAgeByName = _.sortBy([byAge, byName])
U.deepStrictEqual(sortByAgeByName(xs), [
{ a: 'a', b: 1, c: true },
{ a: 'b', b: 2, c: true },
{ a: 'c', b: 2, c: true },
{ a: 'b', b: 3, c: true }
])
U.strictEqual(f(_.empty), _.empty)
U.strictEqual(_.sortBy([])(xs), xs)
})
it('chop', () => {
const f = _.chop<number, number>((as) => [as[0] * 2, as.slice(1)])
const empty: ReadonlyArray<number> = []
U.strictEqual(f(empty), _.empty)
U.strictEqual(f(_.empty), _.empty)
U.deepStrictEqual(f([1, 2, 3]), [2, 4, 6])
})
it('splitAt', () => {
const assertSplitAt = (
input: ReadonlyArray<number>,
index: number,
expectedInit: ReadonlyArray<number>,
expectedRest: ReadonlyArray<number>
) => {
const [init, rest] = _.splitAt(index)(input)
U.strictEqual(init, expectedInit)
U.strictEqual(rest, expectedRest)
}
U.deepStrictEqual(_.splitAt(1)([1, 2]), [[1], [2]])
const two: ReadonlyArray<number> = [1, 2]
assertSplitAt(two, 2, two, _.empty)
U.deepStrictEqual(_.splitAt(2)([1, 2, 3, 4, 5]), [
[1, 2],
[3, 4, 5]
])
// zero
const empty: ReadonlyArray<number> = []
assertSplitAt(_.empty, 0, _.empty, _.empty)
assertSplitAt(empty, 0, empty, _.empty)
assertSplitAt(two, 0, _.empty, two)
// out of bounds
assertSplitAt(_.empty, -1, _.empty, _.empty)
assertSplitAt(empty, -1, empty, _.empty)
assertSplitAt(two, -1, _.empty, two)
assertSplitAt(two, 3, two, _.empty)
assertSplitAt(_.empty, 3, _.empty, _.empty)
assertSplitAt(empty, 3, empty, _.empty)
})
describe('chunksOf', () => {
it('should split a `ReadonlyArray` into length-n pieces', () => {
U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5]), [[1, 2], [3, 4], [5]])
U.deepStrictEqual(_.chunksOf(2)([1, 2, 3, 4, 5, 6]), [
[1, 2],
[3, 4],
[5, 6]
])
U.deepStrictEqual(_.chunksOf(1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])
U.deepStrictEqual(_.chunksOf(5)([1, 2, 3, 4, 5]), [[1, 2, 3, 4, 5]])
// out of bounds
U.deepStrictEqual(_.chunksOf(0)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])
U.deepStrictEqual(_.chunksOf(-1)([1, 2, 3, 4, 5]), [[1], [2], [3], [4], [5]])
const assertSingleChunk = (input: ReadonlyArray<number>, n: number) => {
const chunks = _.chunksOf(n)(input)
U.strictEqual(chunks.length, 1)
U.strictEqual(chunks[0], input)
}
// n = length
assertSingleChunk([1, 2], 2)
// n out of bounds
assertSingleChunk([1, 2], 3)
})
// #897
it('returns an empty array if provided an empty array', () => {
const empty: ReadonlyArray<number> = []
U.strictEqual(_.chunksOf(0)(empty), _.empty)
U.strictEqual(_.chunksOf(0)(_.empty), _.empty)
U.strictEqual(_.chunksOf(1)(empty), _.empty)
U.strictEqual(_.chunksOf(1)(_.empty), _.empty)
U.strictEqual(_.chunksOf(2)(empty), _.empty)
U.strictEqual(_.chunksOf(2)(_.empty), _.empty)
})
// #897
it('should respect the law: chunksOf(n)(xs).concat(chunksOf(n)(ys)) == chunksOf(n)(xs.concat(ys)))', () => {
const xs: ReadonlyArray<number> = []
const ys: ReadonlyArray<number> = [1, 2]
U.deepStrictEqual(_.chunksOf(2)(xs).concat(_.chunksOf(2)(ys)), _.chunksOf(2)(xs.concat(ys)))
fc.assert(
fc.property(
fc.array(fc.integer()).filter((xs) => xs.length % 2 === 0), // Ensures `xs.length` is even
fc.array(fc.integer()),
fc.integer(1, 1).map((x) => x * 2), // Generates `n` to be even so that it evenly divides `xs`
(xs, ys, n) => {
const as = _.chunksOf(n)(xs).concat(_.chunksOf(n)(ys))
const bs = _.chunksOf(n)(xs.concat(ys))
isDeepStrictEqual(as, bs)
}
)
)
})
})
it('prepend', () => {
U.deepStrictEqual(pipe(['a', 'b'], _.prepend('c')), ['c', 'a', 'b'])
U.deepStrictEqual(pipe(['a', 'b'], _.prependW(3)), [3, 'a', 'b'])
})
it('append', () => {
U.deepStrictEqual(pipe(['a', 'b'], _.append('c')), ['a', 'b', 'c'])
U.deepStrictEqual(pipe(['a', 'b'], _.appendW(3)), ['a', 'b', 3])
})
it('makeBy', () => {
U.deepStrictEqual(_.makeBy(5, U.double), [0, 2, 4, 6, 8])
U.strictEqual(_.makeBy(0, U.double), _.empty)
U.strictEqual(_.makeBy(-1, U.double), _.empty)
U.deepStrictEqual(_.makeBy(2.2, U.double), [0, 2])
})
it('replicate', () => {
U.strictEqual(_.replicate(0, 'a'), _.empty)
U.strictEqual(_.replicate(-1, 'a'), _.empty)
U.deepStrictEqual(_.replicate(3, 'a'), ['a', 'a', 'a'])
U.deepStrictEqual(_.replicate(2.2, 'a'), ['a', 'a'])
})
it('range', () => {
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(0, 0), [0])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(0, 1), [0, 1])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(1, 5), [1, 2, 3, 4, 5])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(10, 15), [10, 11, 12, 13, 14, 15])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(-1, 0), [-1, 0])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(-5, -1), [-5, -4, -3, -2, -1])
// out of bound
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(2, 1), [2])
// tslint:disable-next-line: deprecation
U.deepStrictEqual(_.range(-1, -2), [-1])
})
it('comprehension', () => {
U.deepStrictEqual(
_.comprehension([[1, 2, 3]], (a) => a * 2),
[2, 4, 6]
)
U.deepStrictEqual(
_.comprehension(
[
[1, 2, 3],
['a', 'b']
],
tuple
),
[
[1, 'a'],
[1, 'b'],
[2, 'a'],
[2, 'b'],
[3, 'a'],
[3, 'b']
]
)
U.deepStrictEqual(
_.comprehension(
[
[1, 2, 3],
['a', 'b']
],
tuple,
(a, b) => (a + b.length) % 2 === 0
),
[
[1, 'a'],
[1, 'b'],
[3, 'a'],
[3, 'b']
]
)
})
it('union', () => {
const concat = _.union(N.Eq)
const two: ReadonlyArray<number> = [1, 2]
U.deepStrictEqual(concat(two, [3, 4]), [1, 2, 3, 4])
U.deepStrictEqual(concat(two, [2, 3]), [1, 2, 3])
U.deepStrictEqual(concat(two, [1, 2]), [1, 2])
U.deepStrictEqual(pipe(two, concat([3, 4])), [1, 2, 3, 4])
U.deepStrictEqual(pipe(two, concat([2, 3])), [1, 2, 3])
U.deepStrictEqual(pipe(two, concat([1, 2])), [1, 2])
U.strictEqual(pipe(two, concat(_.empty)), two)
U.strictEqual(pipe(_.empty, concat(two)), two)
U.strictEqual(pipe(_.empty, concat(_.empty)), _.empty)
})
it('intersection', () => {
U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [3, 4]), [])
U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [2, 3]), [2])
U.deepStrictEqual(_.intersection(N.Eq)([1, 2], [1, 2]), [1, 2])
U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([3, 4])), [])
U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([2, 3])), [2])
U.deepStrictEqual(pipe([1, 2], _.intersection(N.Eq)([1, 2])), [1, 2])
})
it('difference', () => {
U.deepStrictEqual(_.difference(N.Eq)([1, 2], [3, 4]), [1, 2])
U.deepStrictEqual(_.difference(N.Eq)([1, 2], [2, 3]), [1])
U.deepStrictEqual(_.difference(N.Eq)([1, 2], [1, 2]), [])
U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([3, 4])), [1, 2])
U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([2, 3])), [1])
U.deepStrictEqual(pipe([1, 2], _.difference(N.Eq)([1, 2])), [])
})
it('getUnionMonoid', () => {
const M = _.getUnionMonoid(N.Eq)
const two: ReadonlyArray<number> = [1, 2]
U.deepStrictEqual(M.concat(two, [3, 4]), [1, 2, 3, 4])
U.deepStrictEqual(M.concat(two, [2, 3]), [1, 2, 3])
U.deepStrictEqual(M.concat(two, [1, 2]), [1, 2])
U.strictEqual(M.concat(two, M.empty), two)
U.strictEqual(M.concat(M.empty, two), two)
U.strictEqual(M.concat(M.empty, M.empty), M.empty)
})
it('getIntersectionSemigroup', () => {
const concat = _.getIntersectionSemigroup(N.Eq).concat
U.deepStrictEqual(concat([1, 2], [3, 4]), [])
U.deepStrictEqual(concat([1, 2], [2, 3]), [2])
U.deepStrictEqual(concat([1, 2], [1, 2]), [1, 2])
})
it('getDifferenceMagma', () => {
const concat = _.getDifferenceMagma(N.Eq).concat
U.deepStrictEqual(concat([1, 2], [3, 4]), [1, 2])
U.deepStrictEqual(concat([1, 2], [2, 3]), [1])
U.deepStrictEqual(concat([1, 2], [1, 2]), [])
})
it('should be safe when calling map with a binary function', () => {
interface Foo {
readonly bar: () => number
}
const f = (a: number, x?: Foo) => (x !== undefined ? `${a}${x.bar()}` : `${a}`)
U.deepStrictEqual(_.Functor.map([1, 2], f), ['1', '2'])
U.deepStrictEqual(pipe([1, 2], _.map(f)), ['1', '2'])
})
it('getShow', () => {
const Sh = _.getShow(S.Show)
U.deepStrictEqual(Sh.show([]), `[]`)
U.deepStrictEqual(Sh.show(['a']), `["a"]`)
U.deepStrictEqual(Sh.show(['a', 'b']), `["a", "b"]`)
})
it('fromArray', () => {
U.strictEqual(_.fromArray([]), _.empty)
// tslint:disable-next-line: readonly-array
const as = [1, 2, 3]
const bs = _.fromArray(as)
U.deepStrictEqual(bs, as)
assert.notStrictEqual(bs, as)
})
it('toArray', () => {
U.deepStrictEqual(_.toArray(_.empty), [])
assert.notStrictEqual(_.toArray(_.empty), _.empty)
// tslint:disable-next-line: readonly-array
const as = [1, 2, 3]
const bs = _.toArray(as)
U.deepStrictEqual(bs, as)
assert.notStrictEqual(bs, as)
})
it('empty', () => {
U.deepStrictEqual(_.empty.length, 0)
})
it('do notation', () => {
U.deepStrictEqual(
pipe(
_.of(1),
_.bindTo('a'),
_.bind('b', () => _.of('b'))
),
[{ a: 1, b: 'b' }]
)
})
it('apS', () => {
U.deepStrictEqual(pipe(_.of(1), _.bindTo('a'), _.apS('b', _.of('b'))), [{ a: 1, b: 'b' }])
})
it('every', () => {
const isPositive: Predicate<number> = (n) => n > 0
U.deepStrictEqual(pipe([1, 2, 3], _.every(isPositive)), true)
U.deepStrictEqual(pipe([1, 2, -3], _.every(isPositive)), false)
})
it('some', () => {
const isPositive: Predicate<number> = (n) => n > 0
U.deepStrictEqual(pipe([-1, -2, 3], _.some(isPositive)), true)
U.deepStrictEqual(pipe([-1, -2, -3], _.some(isPositive)), false)
})
it('size', () => {
U.deepStrictEqual(_.size(_.empty), 0)
U.deepStrictEqual(_.size([]), 0)
U.deepStrictEqual(_.size(['a']), 1)
})
describe('chainRec', () => {
it('depth-first', () => {
const chainRec = _.ChainRecDepthFirst.chainRec
assert.deepStrictEqual(
chainRec(1, () => []),
[]
)
assert.deepStrictEqual(
chainRec(1, () => [E.right('foo')]),
['foo']
)
assert.deepStrictEqual(
chainRec(1, (a) => {
if (a < 5) {
return [E.right(a), E.left(a + 1)]
} else {
return [E.right(a)]
}
}),
[1, 2, 3, 4, 5]
)
assert.deepStrictEqual(
chainRec(1, (a) => {
if (a < 5) {
return [E.left(a + 1), E.right(a)]
} else {
return [E.right(a)]
}
}),
[5, 4, 3, 2, 1]
)
assert.deepStrictEqual(
chainRec(1, (a) => {
if (a < 5) {
return a % 2 === 0 ? [E.right(a), E.left(a + 1)] : [E.left(a + 1), E.right(a)]
} else {
return [E.right(a)]
}
}),
[2, 4, 5, 3, 1]
)
assert.deepStrictEqual(
chainRec(0, (a) => {
if (a === 0) {
return [E.right(a), E.left(a - 1), E.left(a + 1)]
} else if (0 < a && a < 5) {
return [E.right(a), E.left(a + 1)]
} else if (-5 < a && a < 0) {
return [E.right(a), E.left(a - 1)]
} else {
return [E.right(a)]
}
}),
[0, -1, -2, -3, -4, -5, 1, 2, 3, 4, 5]
)
assert.deepStrictEqual(
chainRec(0, (a) => {
if (a === 0) {
return [E.left(a - 1), E.right(a), E.left(a + 1)]
} else if (0 < a && a < 5) {
return [E.right(a), E.left(a + 1)]
} else if (-5 < a && a < 0) {
return [E.left(a - 1), E.right(a)]
} else {
return [E.right(a)]
}
}),
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
)
})
it('breadth-first', () => {
const chainRec = _.ChainRecBreadthFirst.chainRec
assert.deepStrictEqual(
chainRec(1, () => []),
[]
)
assert.deepStrictEqual(
chainRec(1, () => [E.right('foo')]),
['foo']
)
assert.deepStrictEqual(
chainRec(1, (a) => {
if (a < 5) {
return [E.right(a), E.left(a + 1)]
} else {
return [E.right(a)]
}
}),
[1, 2, 3, 4, 5]
)
assert.deepStrictEqual(
chainRec(1, (a) => {
if (a < 5) {
return [E.left(a + 1), E.right(a)]
} else {
return [E.right(a)]
}
}),
[1, 2, 3, 4, 5]
)
assert.deepStrictEqual(
chainRec(0, (a) => {
if (a === 0) {
return [E.right(a), E.left(a - 1), E.left(a + 1)]
} else if (0 < a && a < 5) {
return [E.right(a), E.left(a + 1)]
} else if (-5 < a && a < 0) {
return [E.right(a), E.left(a - 1)]
} else {
return [E.right(a)]
}
}),
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
)
assert.deepStrictEqual(
chainRec(0, (a) => {
if (a === 0) {
return [E.left(a - 1), E.right(a), E.left(a + 1)]
} else if (0 < a && a < 5) {
return [E.right(a), E.left(a + 1)]
} else if (-5 < a && a < 0) {
return [E.left(a - 1), E.right(a)]
} else {
return [E.right(a)]
}
}),
[0, -1, 1, -2, 2, -3, 3, -4, 4, -5, 5]
)
})
})
describe('fromPredicate', () => {
it('can create an array from a Refinement', () => {
const refinement: Refinement<unknown, string> = (a): a is string => typeof a === 'string'
U.deepStrictEqual(_.fromPredicate(refinement)('hello'), ['hello'])
U.deepStrictEqual(_.fromPredicate(refinement)(null), [])
})
it('can create an array from a Predicate', () => {
const predicate = (a: string) => a.length > 0
U.deepStrictEqual(_.fromPredicate(predicate)('hi'), ['hi'])
U.deepStrictEqual(_.fromPredicate(predicate)(''), [])
})
})
it('fromOption', () => {
U.deepStrictEqual(_.fromOption(O.some('hello')), ['hello'])
U.deepStrictEqual(_.fromOption(O.none), [])
})
it('fromEither', () => {
U.deepStrictEqual(_.fromEither(E.right(1)), [1])
U.strictEqual(_.fromEither(E.left('a')), _.empty)
})
it('match', () => {
const f = _.match(
() => 'empty',
(as) => `nonEmpty ${as.length}`
)
U.deepStrictEqual(pipe(_.empty, f), 'empty')
U.deepStrictEqual(pipe([1, 2, 3], f), 'nonEmpty 3')
})
it('concatW', () => {
U.deepStrictEqual(pipe([1], _.concatW(['a'])), [1, 'a'])
const as = [1, 2, 3]
U.strictEqual(pipe(_.empty, _.concatW(as)), as)
U.strictEqual(pipe(as, _.concatW(_.empty)), as)
const empty: ReadonlyArray<string> = []
U.strictEqual(pipe(empty, _.concatW(as)), as)
U.strictEqual(pipe(as, _.concatW(empty)), as)
})
it('fromOptionK', () => {
const f = (n: number) => (n > 0 ? O.some(n) : O.none)
const g = _.fromOptionK(f)
U.strictEqual(g(0), _.empty)
U.deepStrictEqual(g(1), [1])
})
}) | the_stack |
import { CodeFileInfo, SourceInfo } from "../ast/parser";
import { MIRBody, MIRResolvedTypeKey, MIRFieldKey, MIRInvokeKey, MIRVirtualMethodKey, MIRGlobalKey } from "./mir_ops";
import { BSQRegex } from "../ast/bsqregex";
import * as assert from "assert";
enum APIEmitTypeTag
{
NoneTag = 0x0,
NothingTag,
BoolTag,
NatTag,
IntTag,
BigNatTag,
BigIntTag,
RationalTag,
FloatTag,
DecimalTag,
StringTag,
StringOfTag,
DataStringTag,
ByteBufferTag,
DataBufferTag,
DateTimeTag,
TickTimeTag,
LogicalTimeTag,
UUIDTag,
ContentHashTag,
ConstructableOfType,
TupleTag,
RecordTag,
ContainerTag,
EnumTag,
EntityTag,
UnionTag
};
enum ContainerCategory
{
List = 0x0,
Stack,
Queue,
Set,
Map
}
function jemitsinfo(sinfo: SourceInfo): object {
return { line: sinfo.line, column: sinfo.column, pos: sinfo.pos, span: sinfo.span };
}
function jparsesinfo(jobj: any): SourceInfo {
return new SourceInfo(jobj.line, jobj.column, jobj.pos, jobj.span);
}
class MIRFunctionParameter {
readonly name: string;
readonly type: MIRResolvedTypeKey;
constructor(name: string, type: MIRResolvedTypeKey) {
this.name = name;
this.type = type;
}
jemit(): object {
return { name: this.name, type: this.type };
}
static jparse(jobj: any): MIRFunctionParameter {
return new MIRFunctionParameter(jobj.name, jobj.type);
}
}
class MIRConstantDecl {
readonly enclosingDecl: MIRResolvedTypeKey | undefined;
readonly gkey: MIRGlobalKey;
readonly shortname: string;
readonly attributes: string[];
readonly sourceLocation: SourceInfo;
readonly srcFile: string;
readonly declaredType: MIRResolvedTypeKey;
readonly ivalue: MIRInvokeKey;
constructor(enclosingDecl: MIRResolvedTypeKey | undefined, gkey: MIRGlobalKey, shortname: string, attributes: string[], sinfo: SourceInfo, srcFile: string, declaredType: MIRResolvedTypeKey, ivalue: MIRInvokeKey) {
this.enclosingDecl = enclosingDecl;
this.gkey = gkey;
this.shortname = shortname;
this.attributes = attributes;
this.sourceLocation = sinfo;
this.srcFile = srcFile;
this.declaredType = declaredType;
this.ivalue = ivalue;
}
jemit(): object {
return { enclosingDecl: this.enclosingDecl, gkey: this.gkey, shortname: this.shortname, attributes: this.attributes, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, declaredType: this.declaredType, ivalue: this.ivalue };
}
static jparse(jobj: any): MIRConstantDecl {
return new MIRConstantDecl(jobj.enclosingDecl, jobj.gkey, jobj.shortname, jobj.attributes, jparsesinfo(jobj.sinfo), jobj.file, jobj.declaredType, jobj.ivalue);
}
}
abstract class MIRInvokeDecl {
readonly enclosingDecl: MIRResolvedTypeKey | undefined;
readonly bodyID: string;
readonly ikey: MIRInvokeKey;
readonly shortname: string;
readonly sinfoStart: SourceInfo;
readonly sinfoEnd: SourceInfo;
readonly srcFile: string;
readonly attributes: string[];
readonly recursive: boolean;
readonly params: MIRFunctionParameter[];
readonly resultType: MIRResolvedTypeKey;
readonly preconditions: MIRInvokeKey[] | undefined;
readonly postconditions: MIRInvokeKey[] | undefined;
readonly isUserCode: boolean;
constructor(enclosingDecl: MIRResolvedTypeKey | undefined, bodyID: string, ikey: MIRInvokeKey, shortname: string, attributes: string[], recursive: boolean, sinfoStart: SourceInfo, sinfoEnd: SourceInfo, srcFile: string, params: MIRFunctionParameter[], resultType: MIRResolvedTypeKey, preconds: MIRInvokeKey[] | undefined, postconds: MIRInvokeKey[] | undefined, isUserCode: boolean) {
this.enclosingDecl = enclosingDecl;
this.bodyID = bodyID;
this.ikey = ikey;
this.shortname = shortname;
this.sinfoStart = sinfoStart;
this.sinfoEnd = sinfoEnd;
this.srcFile = srcFile;
this.attributes = attributes;
this.recursive = recursive;
this.params = params;
this.resultType = resultType;
this.preconditions = preconds;
this.postconditions = postconds;
this.isUserCode = isUserCode;
}
abstract jemit(): object;
static jparse(jobj: any): MIRInvokeDecl {
if (jobj.body) {
return new MIRInvokeBodyDecl(jobj.enclosingDecl, jobj.bodyID, jobj.ikey, jobj.shortname, jobj.attributes, jobj.recursive, jparsesinfo(jobj.sinfoStart), jparsesinfo(jobj.sinfoEnd), jobj.file, jobj.params.map((p: any) => MIRFunctionParameter.jparse(p)), jobj.masksize, jobj.resultType, jobj.preconditions || undefined, jobj.postconditions || undefined, jobj.isUserCode, MIRBody.jparse(jobj.body));
}
else {
let binds = new Map<string, MIRResolvedTypeKey>();
jobj.binds.forEach((bind: any) => binds.set(bind[0], bind[1]));
let pcodes = new Map<string, MIRPCode>();
jobj.pcodes.forEach((pc: any) => pcodes.set(pc[0], pc[1]));
return new MIRInvokePrimitiveDecl(jobj.enclosingDecl, jobj.bodyID, jobj.ikey, jobj.shortname, jobj.attributes, jobj.recursive, jparsesinfo(jobj.sinfoStart), jparsesinfo(jobj.sinfoEnd), jobj.file, binds, jobj.params.map((p: any) => MIRFunctionParameter.jparse(p)), jobj.resultType, jobj.implkey, pcodes);
}
}
}
class MIRInvokeBodyDecl extends MIRInvokeDecl {
readonly body: MIRBody;
readonly masksize: number;
constructor(enclosingDecl: MIRResolvedTypeKey | undefined, bodyID: string, ikey: MIRInvokeKey, shortname: string, attributes: string[], recursive: boolean, sinfoStart: SourceInfo, sinfoEnd: SourceInfo, srcFile: string, params: MIRFunctionParameter[], masksize: number, resultType: MIRResolvedTypeKey, preconds: MIRInvokeKey[] | undefined, postconds: MIRInvokeKey[] | undefined, isUserCode: boolean, body: MIRBody) {
super(enclosingDecl, bodyID, ikey, shortname, attributes, recursive, sinfoStart, sinfoEnd, srcFile, params, resultType, preconds, postconds, isUserCode);
this.body = body;
this.masksize = masksize;
}
jemit(): object {
return { enclosingDecl: this.enclosingDecl, bodyID: this.bodyID, ikey: this.ikey, shortname: this.shortname, sinfoStart: jemitsinfo(this.sinfoStart), sinfoEnd: jemitsinfo(this.sinfoEnd), file: this.srcFile, attributes: this.attributes, recursive: this.recursive, params: this.params.map((p) => p.jemit()), masksize: this.masksize, resultType: this.resultType, preconditions: this.preconditions, postconditions: this.postconditions, body: this.body.jemit(), isUserCode: this.isUserCode };
}
}
type MIRPCode = {
code: MIRInvokeKey,
cargs: {cname: string, ctype: MIRResolvedTypeKey}[]
};
class MIRInvokePrimitiveDecl extends MIRInvokeDecl {
readonly implkey: string;
readonly binds: Map<string, MIRResolvedTypeKey>;
readonly pcodes: Map<string, MIRPCode>;
constructor(enclosingDecl: MIRResolvedTypeKey | undefined, bodyID: string, ikey: MIRInvokeKey, shortname: string, attributes: string[], recursive: boolean, sinfoStart: SourceInfo, sinfoEnd: SourceInfo, srcFile: string, binds: Map<string, MIRResolvedTypeKey>, params: MIRFunctionParameter[], resultType: MIRResolvedTypeKey, implkey: string, pcodes: Map<string, MIRPCode>) {
super(enclosingDecl, bodyID, ikey, shortname, attributes, recursive, sinfoStart, sinfoEnd, srcFile, params, resultType, undefined, undefined, false);
this.implkey = implkey;
this.binds = binds;
this.pcodes = pcodes;
}
jemit(): object {
return {enclosingDecl: this.enclosingDecl, bodyID: this.bodyID, ikey: this.ikey, shortname: this.shortname, sinfoStart: jemitsinfo(this.sinfoStart), sinfoEnd: jemitsinfo(this.sinfoEnd), file: this.srcFile, attributes: this.attributes, recursive: this.recursive, params: this.params.map((p) => p.jemit()), resultType: this.resultType, implkey: this.implkey, binds: [...this.binds], pcodes: [... this.pcodes] };
}
}
class MIRFieldDecl {
readonly enclosingDecl: MIRResolvedTypeKey;
readonly attributes: string[];
readonly fkey: MIRFieldKey;
readonly fname: string;
readonly sourceLocation: SourceInfo;
readonly srcFile: string;
readonly isOptional: boolean;
readonly declaredType: MIRResolvedTypeKey;
constructor(enclosingDecl: MIRResolvedTypeKey, attributes: string[], srcInfo: SourceInfo, srcFile: string, fkey: MIRFieldKey, fname: string, isOptional: boolean, dtype: MIRResolvedTypeKey) {
this.enclosingDecl = enclosingDecl;
this.attributes = attributes;
this.fkey = fkey;
this.fname = fname;
this.sourceLocation = srcInfo;
this.srcFile = srcFile;
this.isOptional = isOptional;
this.declaredType = dtype;
}
jemit(): object {
return { enclosingDecl: this.enclosingDecl, attributes: this.attributes, fkey: this.fkey, fname: this.fname, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, isOptional: this.isOptional, declaredType: this.declaredType };
}
static jparse(jobj: any): MIRFieldDecl {
return new MIRFieldDecl(jobj.enclosingDecl, jobj.attributes, jparsesinfo(jobj.sinfo), jobj.file, jobj.fkey, jobj.fname, jobj.isOptional, jobj.declaredType);
}
}
abstract class MIROOTypeDecl {
readonly tkey: MIRResolvedTypeKey;
readonly sourceLocation: SourceInfo;
readonly srcFile: string;
readonly attributes: string[];
readonly ns: string;
readonly name: string;
readonly terms: Map<string, MIRType>;
readonly provides: MIRResolvedTypeKey[];
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) {
this.tkey = tkey;
this.sourceLocation = srcInfo;
this.srcFile = srcFile;
this.attributes = attributes;
this.ns = ns;
this.name = name;
this.terms = terms;
this.provides = provides;
}
abstract jemit(): object;
jemitbase(): object {
return { tkey: this.tkey, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, attributes: this.attributes, ns: this.ns, name: this.name, terms: [...this.terms].map((t) => [t[0], t[1].jemit()]), provides: this.provides };
}
static jparsebase(jobj: any): [SourceInfo, string, MIRResolvedTypeKey, string[], string, string, Map<string, MIRType>, MIRResolvedTypeKey[]] {
let terms = new Map<string, MIRType>();
jobj.terms.forEach((t: any) => terms.set(t[0], MIRType.jparse(t[1])));
return [jparsesinfo(jobj.sinfo), jobj.file, jobj.tkey, jobj.attributes, jobj.ns, jobj.name, terms, jobj.provides];
}
static jparse(jobj: any): MIROOTypeDecl {
const tag = jobj.tag;
switch (tag) {
case "concept":
return MIRConceptTypeDecl.jparse(jobj);
case "std":
return MIRObjectEntityTypeDecl.jparse(jobj);
case "constructable":
return MIRConstructableEntityTypeDecl.jparse(jobj);
case "enum":
return MIREnumEntityTypeDecl.jparse(jobj);
case "primitive":
return MIRPrimitiveInternalEntityTypeDecl.jparse(jobj);
case "constructableinternal":
return MIRConstructableInternalEntityTypeDecl.jparse(jobj);
case "havocsequence":
return MIRHavocEntityTypeDecl.jparse(jobj);
case "list":
return MIRPrimitiveListEntityTypeDecl.jparse(jobj);
case "stack":
return MIRPrimitiveStackEntityTypeDecl.jparse(jobj);
case "queue":
return MIRPrimitiveQueueEntityTypeDecl.jparse(jobj);
case "set":
return MIRPrimitiveSetEntityTypeDecl.jparse(jobj);
default:
assert(tag === "map");
return MIRPrimitiveMapEntityTypeDecl.jparse(jobj);
}
}
}
class MIRConceptTypeDecl extends MIROOTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
}
jemit(): object {
return { tag: "concept", ...this.jemitbase() };
}
static jparse(jobj: any): MIRConceptTypeDecl {
return new MIRConceptTypeDecl(...MIROOTypeDecl.jparsebase(jobj));
}
}
abstract class MIREntityTypeDecl extends MIROOTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
}
}
class MIRObjectEntityTypeDecl extends MIREntityTypeDecl {
readonly hasconsinvariants: boolean;
readonly validatefunc: MIRInvokeKey | undefined;
readonly consfunc: MIRInvokeKey;
readonly consfuncfields: {cfkey: MIRFieldKey, isoptional: boolean}[];
readonly fields: MIRFieldDecl[];
readonly vcallMap: Map<MIRVirtualMethodKey, MIRInvokeKey> = new Map<string, MIRInvokeKey>();
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], hasconsinvariants: boolean, validatefunc: MIRInvokeKey | undefined, consfunc: MIRInvokeKey, consfuncfields: {cfkey: MIRFieldKey, isoptional: boolean}[], fields: MIRFieldDecl[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.hasconsinvariants = hasconsinvariants;
this.validatefunc = validatefunc;
this.consfunc = consfunc;
this.consfuncfields = consfuncfields;
this.fields = fields;
}
jemit(): object {
return { tag: "std", ...this.jemitbase(), hasconsinvariants: this.hasconsinvariants, validatefunc: this.validatefunc, consfunc: this.consfunc, consfuncfields: this.consfuncfields, fields: this.fields.map((f) => f.jemit()), vcallMap: [...this.vcallMap] };
}
static jparse(jobj: any): MIRConceptTypeDecl {
let entity = new MIRObjectEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.hasconsinvariants, jobj.validatefunc || undefined, jobj.consfunc, jobj.consfuncfields, jobj.fields.map((jf: any) => MIRFieldDecl.jparse(jf)));
jobj.vcallMap.forEach((vc: any) => entity.vcallMap.set(vc[0], vc[1]));
return entity;
}
}
class MIRConstructableEntityTypeDecl extends MIREntityTypeDecl {
readonly fromtype: MIRResolvedTypeKey;
readonly validatefunc: MIRInvokeKey | undefined;
readonly usingcons: MIRInvokeKey | undefined;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], fromtype: MIRResolvedTypeKey, validatefunc: MIRInvokeKey | undefined, usingcons: MIRInvokeKey | undefined) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.fromtype = fromtype;
this.validatefunc = validatefunc;
this.usingcons = usingcons;
}
jemit(): object {
return { tag: "constructable", ...this.jemitbase(), fromtype: this.fromtype, validatefunc: this.validatefunc, usingcons: this.usingcons };
}
static jparse(jobj: any): MIRConstructableEntityTypeDecl {
return new MIRConstructableEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.fromtype, jobj.validatefunc, jobj.usingcons);
}
}
class MIREnumEntityTypeDecl extends MIREntityTypeDecl {
readonly enums: string[];
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], enums: string[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.enums = enums;
}
jemit(): object {
return { tag: "enum", ...this.jemitbase(), enums: this.enums };
}
static jparse(jobj: any): MIREnumEntityTypeDecl {
return new MIREnumEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.enums);
}
}
abstract class MIRInternalEntityTypeDecl extends MIREntityTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
}
}
class MIRPrimitiveInternalEntityTypeDecl extends MIRInternalEntityTypeDecl {
//Should just be a special implemented value
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
}
jemit(): object {
return { tag: "primitive", ...this.jemitbase() };
}
static jparse(jobj: any): MIRPrimitiveInternalEntityTypeDecl {
return new MIRPrimitiveInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj));
}
}
class MIRStringOfInternalEntityTypeDecl extends MIRInternalEntityTypeDecl {
readonly validatortype: MIRResolvedTypeKey;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], validatortype: MIRResolvedTypeKey) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.validatortype = validatortype;
}
jemit(): object {
return { tag: "stringofinternal", ...this.jemitbase(), validatortype: this.validatortype };
}
static jparse(jobj: any): MIRStringOfInternalEntityTypeDecl {
return new MIRStringOfInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.validatortype);
}
}
class MIRDataStringInternalEntityTypeDecl extends MIRInternalEntityTypeDecl {
readonly fromtype: MIRResolvedTypeKey;
readonly accepts: MIRInvokeKey;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], fromtype: MIRResolvedTypeKey, accepts: MIRInvokeKey) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.fromtype = fromtype;
this.accepts = accepts;
}
jemit(): object {
return { tag: "datastringinternal", ...this.jemitbase(), fromtype: this.fromtype, optaccepts: this.accepts };
}
static jparse(jobj: any): MIRDataStringInternalEntityTypeDecl {
return new MIRDataStringInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.fromtype, jobj.accepts);
}
}
class MIRDataBufferInternalEntityTypeDecl extends MIRInternalEntityTypeDecl {
readonly fromtype: MIRResolvedTypeKey;
readonly accepts: MIRInvokeKey;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], fromtype: MIRResolvedTypeKey, accepts: MIRInvokeKey) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.fromtype = fromtype;
this.accepts = accepts;
}
jemit(): object {
return { tag: "databufferinternal", ...this.jemitbase(), fromtype: this.fromtype, accepts: this.accepts };
}
static jparse(jobj: any): MIRDataBufferInternalEntityTypeDecl {
return new MIRDataBufferInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.fromtype, jobj.accepts);
}
}
class MIRConstructableInternalEntityTypeDecl extends MIRInternalEntityTypeDecl {
readonly fromtype: MIRResolvedTypeKey;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], fromtype: MIRResolvedTypeKey) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.fromtype = fromtype;
}
jemit(): object {
return { tag: "constructableinternal", ...this.jemitbase(), fromtype: this.fromtype };
}
static jparse(jobj: any): MIRConstructableInternalEntityTypeDecl {
return new MIRConstructableInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.fromtype);
}
}
class MIRHavocEntityTypeDecl extends MIRInternalEntityTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
}
jemit(): object {
return { tag: "havocsequence", ...this.jemitbase() };
}
static jparse(jobj: any): MIRHavocEntityTypeDecl {
return new MIRHavocEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj));
}
}
abstract class MIRPrimitiveCollectionEntityTypeDecl extends MIRInternalEntityTypeDecl {
readonly binds: Map<string, MIRType>;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], binds: Map<string, MIRType>) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides);
this.binds = binds;
}
jemitcollection(): object {
const fbinds = [...this.binds].sort((a, b) => a[0].localeCompare(b[0])).map((v) => [v[0], v[1].jemit()]);
return { ...this.jemitbase(), binds: fbinds };
}
static jparsecollection(jobj: any): [SourceInfo, string, MIRResolvedTypeKey, string[], string, string, Map<string, MIRType>, MIRResolvedTypeKey[], Map<string, MIRType>] {
const bbinds = new Map<string, MIRType>();
jobj.binds.foreach((v: [string, any]) => {
bbinds.set(v[0], MIRType.jparse(v[1]));
});
return [...MIROOTypeDecl.jparsebase(jobj), bbinds];
}
}
class MIRPrimitiveListEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], binds: Map<string, MIRType>) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides, binds);
}
getTypeT(): MIRType {
return this.binds.get("T") as MIRType;
}
jemit(): object {
return { tag: "list", ...this.jemitcollection() };
}
static jparse(jobj: any): MIRPrimitiveListEntityTypeDecl {
return new MIRPrimitiveListEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj));
}
}
class MIRPrimitiveStackEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], binds: Map<string, MIRType>) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides, binds);
}
getTypeT(): MIRType {
return this.binds.get("T") as MIRType;
}
jemit(): object {
return { tag: "stack", ...this.jemitcollection() };
}
static jparse(jobj: any): MIRPrimitiveStackEntityTypeDecl {
return new MIRPrimitiveStackEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj));
}
}
class MIRPrimitiveQueueEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], binds: Map<string, MIRType>) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides, binds);
}
getTypeT(): MIRType {
return this.binds.get("T") as MIRType;
}
jemit(): object {
return { tag: "queue", ...this.jemitcollection() };
}
static jparse(jobj: any): MIRPrimitiveQueueEntityTypeDecl {
return new MIRPrimitiveQueueEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj));
}
}
class MIRPrimitiveSetEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl {
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], binds: Map<string, MIRType>) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides, binds);
}
getTypeT(): MIRType {
return this.binds.get("T") as MIRType;
}
jemit(): object {
return { tag: "set", ...this.jemitcollection() };
}
static jparse(jobj: any): MIRPrimitiveSetEntityTypeDecl {
return new MIRPrimitiveSetEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj));
}
}
class MIRPrimitiveMapEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl {
readonly tupentrytype: MIRResolvedTypeKey;
constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], binds: Map<string, MIRType>, tupentrytype: MIRResolvedTypeKey) {
super(srcInfo, srcFile, tkey, attributes, ns, name, terms, provides, binds);
this.tupentrytype = tupentrytype;
}
getTypeK(): MIRType {
return this.binds.get("K") as MIRType;
}
getTypeV(): MIRType {
return this.binds.get("V") as MIRType;
}
jemit(): object {
return { tag: "set", ...this.jemitcollection(), tupentrytype: this.tupentrytype };
}
static jparse(jobj: any): MIRPrimitiveMapEntityTypeDecl {
return new MIRPrimitiveMapEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj), jobj.tupentrytype);
}
}
abstract class MIRTypeOption {
readonly typeID: MIRResolvedTypeKey;
constructor(typeID: MIRResolvedTypeKey) {
this.typeID = typeID;
}
abstract jemit(): object;
static jparse(jobj: any): MIRTypeOption {
switch (jobj.kind) {
case "entity":
return MIREntityType.jparse(jobj);
case "concept":
return MIRConceptType.jparse(jobj);
case "tuple":
return MIRTupleType.jparse(jobj);
case "record":
return MIRRecordType.jparse(jobj);
default:
assert(jobj.kind === "ephemeral");
return MIREphemeralListType.jparse(jobj);
}
}
}
class MIREntityType extends MIRTypeOption {
private constructor(typeID: MIRResolvedTypeKey) {
super(typeID);
}
static create(typeID: MIRResolvedTypeKey): MIREntityType {
return new MIREntityType(typeID);
}
jemit(): object {
return {kind: "entity", typeID: this.typeID };
}
static jparse(jobj: any): MIREntityType {
return MIREntityType.create(jobj.typeID);
}
}
class MIRConceptType extends MIRTypeOption {
readonly ckeys: MIRResolvedTypeKey[];
private constructor(typeID: MIRResolvedTypeKey, ckeys: MIRResolvedTypeKey[]) {
super(typeID);
this.ckeys = ckeys;
}
static create(ckeys: MIRResolvedTypeKey[]): MIRConceptType {
const skeys = ckeys.sort((a, b) => a[0].localeCompare(b[0]));
return new MIRConceptType(skeys.join(" & "), skeys);
}
jemit(): object {
return {kind: "concept", ckeys: this.ckeys };
}
static jparse(jobj: any): MIRConceptType {
return MIRConceptType.create(jobj.ckeys);
}
}
class MIRTupleType extends MIRTypeOption {
readonly entries: MIRType[];
private constructor(typeID: MIRResolvedTypeKey, entries: MIRType[]) {
super(typeID);
this.entries = entries;
}
static create(entries: MIRType[]): MIRTupleType {
let cvalue = entries.map((entry) => entry.typeID).join(", ");
return new MIRTupleType(`[${cvalue}]`, [...entries]);
}
jemit(): object {
return { kind: "tuple", entries: this.entries };
}
static jparse(jobj: any): MIRTupleType {
return MIRTupleType.create(jobj.entries);
}
}
class MIRRecordType extends MIRTypeOption {
readonly entries: {pname: string, ptype: MIRType}[];
constructor(typeID: string, entries: {pname: string, ptype: MIRType}[]) {
super(typeID);
this.entries = entries;
}
static create(entries: {pname: string, ptype: MIRType}[]): MIRRecordType {
let simplifiedEntries = [...entries].sort((a, b) => a.pname.localeCompare(b.pname));
const name = simplifiedEntries.map((entry) => entry.pname + ": " + entry.ptype.typeID).join(", ");
return new MIRRecordType("{" + name + "}", simplifiedEntries);
}
jemit(): object {
return { kind: "record", entries: this.entries };
}
static jparse(jobj: any): MIRRecordType {
return MIRRecordType.create(jobj.entries);
}
}
class MIREphemeralListType extends MIRTypeOption {
readonly entries: MIRType[];
private constructor(typeID: string, entries: MIRType[]) {
super(typeID);
this.entries = entries;
}
static create(entries: MIRType[]): MIREphemeralListType {
const name = entries.map((entry) => entry.typeID).join(", ");
return new MIREphemeralListType("(|" + name + "|)", entries);
}
jemit(): object {
return { kind: "ephemeral", entries: this.entries.map((e) => e.jemit()) };
}
static jparse(jobj: any): MIREphemeralListType {
return MIREphemeralListType.create(jobj.entries.map((e: any) => MIRType.jparse(e)));
}
}
class MIRType {
readonly typeID: MIRResolvedTypeKey;
readonly options: MIRTypeOption[];
private constructor(typeID: MIRResolvedTypeKey, options: MIRTypeOption[]) {
this.typeID = typeID;
this.options = options;
}
static createSingle(option: MIRTypeOption): MIRType {
return new MIRType(option.typeID, [option]);
}
static create(options: MIRTypeOption[]): MIRType {
if (options.length === 1) {
return MIRType.createSingle(options[0]);
}
else {
const typeid = [...options].sort().map((tk) => tk.typeID).join(" | ");
return new MIRType(typeid, options);
}
}
jemit(): object {
return { options: this.options.map((opt) => opt.jemit()) };
}
static jparse(jobj: any): MIRType {
return MIRType.create(jobj.options.map((opt: any) => MIRTypeOption.jparse(opt)));
}
isTupleTargetType(): boolean {
return this.options.every((opt) => opt instanceof MIRTupleType);
}
isUniqueTupleTargetType(): boolean {
return this.isTupleTargetType() && this.options.length === 1;
}
getUniqueTupleTargetType(): MIRTupleType {
return (this.options[0] as MIRTupleType);
}
isRecordTargetType(): boolean {
return this.options.every((opt) => opt instanceof MIRRecordType);
}
isUniqueRecordTargetType(): boolean {
return this.isRecordTargetType() && this.options.length === 1;
}
getUniqueRecordTargetType(): MIRRecordType {
return (this.options[0] as MIRRecordType);
}
isUniqueCallTargetType(): boolean {
if (this.options.length !== 1) {
return false;
}
return this.options[0] instanceof MIREntityType;
}
getUniqueCallTargetType(): MIREntityType {
return this.options[0] as MIREntityType;
}
}
enum SymbolicActionMode {
EvaluateSymbolic, //Inputs will be symbolically parsed and executed and set to extract result value -- single entrypoint assumed
ErrTestSymbolic, //Inputs will symbolically generated and executed with failures reported (NO check on output) -- single entrypoint assumed
ChkTestSymbolic //Inputs will be symbolically generated and executed with failures reported and check for "true" return value -- single entrypoint assumed
}
enum RuntimeActionMode {
EvaluateConcrete, //Inputs will be parsed as concrete values and set to extract result value
ErrTestConcrete, //Inputs will be parsed as concrete values and executed with failures reported (NO check on output)
ChkTestConcrete, //Inputs will be parsed as concrete values and executed with failures reported and check for "true" return value
}
class PackageConfig {
readonly macrodefs: string[];
readonly src: CodeFileInfo[];
constructor(macrodefs: string[], src: CodeFileInfo[]) {
this.macrodefs = macrodefs;
this.src = src;
}
jemit(): object {
return { macrodefs: this.macrodefs, src: this.src };
}
static jparse(jobj: any): PackageConfig {
return new PackageConfig(jobj.macrodefs, jobj.src);
}
}
class MIRAssembly {
readonly package: PackageConfig[];
readonly srcFiles: { fpath: string, contents: string }[];
readonly srcHash: string;
readonly literalRegexs: BSQRegex[] = [];
readonly validatorRegexs: Map<MIRResolvedTypeKey, BSQRegex> = new Map<MIRResolvedTypeKey, BSQRegex>();
readonly constantDecls: Map<MIRGlobalKey, MIRConstantDecl> = new Map<MIRGlobalKey, MIRConstantDecl>();
readonly fieldDecls: Map<MIRFieldKey, MIRFieldDecl> = new Map<MIRFieldKey, MIRFieldDecl>();
readonly invokeDecls: Map<MIRInvokeKey, MIRInvokeBodyDecl> = new Map<MIRInvokeKey, MIRInvokeBodyDecl>();
readonly primitiveInvokeDecls: Map<MIRInvokeKey, MIRInvokePrimitiveDecl> = new Map<MIRInvokeKey, MIRInvokePrimitiveDecl>();
readonly virtualOperatorDecls: Map<MIRVirtualMethodKey, MIRInvokeKey[]> = new Map<MIRVirtualMethodKey, MIRInvokeKey[]>();
readonly conceptDecls: Map<MIRResolvedTypeKey, MIRConceptTypeDecl> = new Map<MIRResolvedTypeKey, MIRConceptTypeDecl>();
readonly entityDecls: Map<MIRResolvedTypeKey, MIREntityTypeDecl> = new Map<MIRResolvedTypeKey, MIREntityTypeDecl>();
readonly tupleDecls: Map<MIRResolvedTypeKey, MIRTupleType> = new Map<MIRResolvedTypeKey, MIRTupleType>();
readonly recordDecls: Map<MIRResolvedTypeKey, MIRRecordType> = new Map<MIRResolvedTypeKey, MIRRecordType>();
readonly ephemeralListDecls: Map<MIRResolvedTypeKey, MIREphemeralListType> = new Map<MIRResolvedTypeKey, MIREphemeralListType>();
readonly typeMap: Map<MIRResolvedTypeKey, MIRType> = new Map<MIRResolvedTypeKey, MIRType>();
private m_subtypeRelationMemo: Map<string, Map<string, boolean>> = new Map<string, Map<string, boolean>>();
private m_atomSubtypeRelationMemo: Map<string, Map<string, boolean>> = new Map<string, Map<string, boolean>>();
entyremaps = {namespaceremap: new Map<string, string>(), entrytypedef: new Map<string, MIRType>()};
private getConceptsProvidedByTuple(tt: MIRTupleType): MIRType {
let tci: MIRResolvedTypeKey[] = ["Tuple"];
if (tt.entries.every((ttype) => this.subtypeOf(ttype, this.typeMap.get("APIType") as MIRType))) {
tci.push("APIType");
}
else {
if (tt.entries.every((ttype) => this.subtypeOf(ttype, this.typeMap.get("TestableType") as MIRType))) {
tci.push("TestableType");
}
}
return MIRType.createSingle(MIRConceptType.create(tci));
}
private getConceptsProvidedByRecord(rr: MIRRecordType): MIRType {
let tci: MIRResolvedTypeKey[] = ["Record"];
if (rr.entries.every((entry) => this.subtypeOf(entry.ptype, this.typeMap.get("APIType") as MIRType))) {
tci.push("APIType");
}
else {
if (rr.entries.every((entry) => this.subtypeOf(entry.ptype, this.typeMap.get("TestableType") as MIRType))) {
tci.push("TestableType");
}
}
return MIRType.createSingle(MIRConceptType.create(tci));
}
private atomSubtypeOf_EntityConcept(t1: MIREntityType, t2: MIRConceptType): boolean {
const t1e = this.entityDecls.get(t1.typeID) as MIREntityTypeDecl;
const mcc = MIRType.createSingle(t2);
return t1e.provides.some((provide) => this.subtypeOf(this.typeMap.get(provide) as MIRType, mcc));
}
private atomSubtypeOf_ConceptConcept(t1: MIRConceptType, t2: MIRConceptType): boolean {
return t2.ckeys.every((c2t) => {
return t1.ckeys.some((c1t) => {
const c1 = this.conceptDecls.get(c1t) as MIRConceptTypeDecl;
const c2 = this.conceptDecls.get(c2t) as MIRConceptTypeDecl;
if (c1.ns === c2.ns && c1.name === c2.name) {
return true;
}
return c1.provides.some((provide) => this.subtypeOf(this.typeMap.get(provide) as MIRType, this.typeMap.get(c2t) as MIRType));
});
});
}
private atomSubtypeOf_TupleConcept(t1: MIRTupleType, t2: MIRConceptType): boolean {
const t2type = this.typeMap.get(t2.typeID) as MIRType;
const tcitype = this.getConceptsProvidedByTuple(t1);
return this.subtypeOf(tcitype, t2type);
}
private atomSubtypeOf_RecordConcept(t1: MIRRecordType, t2: MIRConceptType): boolean {
const t2type = this.typeMap.get(t2.typeID) as MIRType;
const tcitype = this.getConceptsProvidedByRecord(t1);
return this.subtypeOf(tcitype, t2type);
}
private atomSubtypeOf(t1: MIRTypeOption, t2: MIRTypeOption): boolean {
let memores = this.m_atomSubtypeRelationMemo.get(t1.typeID);
if (memores === undefined) {
this.m_atomSubtypeRelationMemo.set(t1.typeID, new Map<string, boolean>());
memores = this.m_atomSubtypeRelationMemo.get(t1.typeID) as Map<string, boolean>;
}
let memoval = memores.get(t2.typeID);
if (memoval !== undefined) {
return memoval;
}
let res = false;
if (t1.typeID === t2.typeID) {
res = true;
}
else if (t1 instanceof MIRConceptType && t2 instanceof MIRConceptType) {
res = this.atomSubtypeOf_ConceptConcept(t1, t2);
}
else if (t2 instanceof MIRConceptType) {
if (t1 instanceof MIREntityType) {
res = this.atomSubtypeOf_EntityConcept(t1, t2);
}
else if (t1 instanceof MIRTupleType) {
res = this.atomSubtypeOf_TupleConcept(t1, t2);
}
else if (t1 instanceof MIRRecordType) {
res = this.atomSubtypeOf_RecordConcept(t1, t2);
}
else {
//fall-through
}
}
else {
//fall-through
}
memores.set(t2.typeID, res);
return res;
}
constructor(pckge: PackageConfig[], srcFiles: { fpath: string, contents: string }[], srcHash: string) {
this.package = pckge;
this.srcFiles = srcFiles;
this.srcHash = srcHash;
}
subtypeOf(t1: MIRType, t2: MIRType): boolean {
let memores = this.m_subtypeRelationMemo.get(t1.typeID);
if (memores === undefined) {
this.m_subtypeRelationMemo.set(t1.typeID, new Map<string, boolean>());
memores = this.m_subtypeRelationMemo.get(t1.typeID) as Map<string, boolean>;
}
let memoval = memores.get(t2.typeID);
if (memoval !== undefined) {
return memoval;
}
const res = (t1.typeID === t2.typeID) || t1.options.every((t1opt) => t2.options.some((t2opt) => this.atomSubtypeOf(t1opt, t2opt)));
memores.set(t2.typeID, res);
return res;
}
jemit(): object {
return {
package: this.package.map((pc) => pc.jemit()),
srcFiles: this.srcFiles,
srcHash: this.srcHash,
literalRegexs: [...this.literalRegexs].map((lre) => lre.jemit()),
validatorRegexs: [...this.validatorRegexs].map((vre) => [vre[0], vre[1]]),
constantDecls: [...this.constantDecls].map((cd) => [cd[0], cd[1].jemit()]),
fieldDecls: [...this.fieldDecls].map((fd) => [fd[0], fd[1].jemit()]),
invokeDecls: [...this.invokeDecls].map((id) => [id[0], id[1].jemit()]),
primitiveInvokeDecls: [...this.primitiveInvokeDecls].map((id) => [id[0], id[1].jemit()]),
virtualOperatorDecls: [...this.virtualOperatorDecls],
conceptDecls: [...this.conceptDecls].map((cd) => [cd[0], cd[1].jemit()]),
entityDecls: [...this.entityDecls].map((ed) => [ed[0], ed[1].jemit()]),
typeMap: [...this.typeMap].map((t) => [t[0], t[1].jemit()]),
entyremaps: {
namespaceremap: [...this.entyremaps.namespaceremap].map((vv) => vv),
entrytypedef: [...this.entyremaps.entrytypedef].map((vv) => [vv[0], vv[1].jemit()])
}
};
}
static jparse(jobj: any): MIRAssembly {
let masm = new MIRAssembly(jobj.package.map((pc: any) => PackageConfig.jparse(pc)), jobj.srcFiles, jobj.srcHash);
jobj.literalRegexs.forEach((lre: any) => masm.literalRegexs.push(BSQRegex.jparse(lre)));
jobj.validatorRegexs.forEach((vre: any) => masm.validatorRegexs.set(vre[0], vre[1]));
jobj.constantDecls.forEach((cd: any) => masm.constantDecls.set(cd[0], MIRConstantDecl.jparse(cd[1])));
jobj.fieldDecls.forEach((fd: any) => masm.fieldDecls.set(fd[0], MIRFieldDecl.jparse(fd[1])));
jobj.invokeDecls.forEach((id: any) => masm.invokeDecls.set(id[0], MIRInvokeDecl.jparse(id[1]) as MIRInvokeBodyDecl));
jobj.primitiveInvokeDecls.forEach((id: any) => masm.primitiveInvokeDecls.set(id[0], MIRInvokeDecl.jparse(id[1]) as MIRInvokePrimitiveDecl));
jobj.virtualOperatorDecls.forEach((od: any) => masm.virtualOperatorDecls.set(od[0], od[1]));
jobj.conceptDecls.forEach((cd: any) => masm.conceptDecls.set(cd[0], MIROOTypeDecl.jparse(cd[1]) as MIRConceptTypeDecl));
jobj.entityDecls.forEach((id: any) => masm.entityDecls.set(id[0], MIROOTypeDecl.jparse(id[1]) as MIREntityTypeDecl));
jobj.typeMap.forEach((t: any) => masm.typeMap.set(t[0], MIRType.jparse(t[1])));
jobj.entyremaps.namespaceremap.forEach((vv: any) => masm.entyremaps.namespaceremap.set(vv[0], vv[1]));
jobj.entyremaps.entrytypedef.forEach((vv: any) => masm.entyremaps.entrytypedef.set(vv[0], MIRType.jparse(vv[1])));
return masm;
}
private getAPITypeForEntity(tt: MIRType, entity: MIREntityTypeDecl): object {
if(entity instanceof MIRInternalEntityTypeDecl) {
if(entity instanceof MIRPrimitiveInternalEntityTypeDecl) {
if (tt.typeID === "None") {
return {tag: APIEmitTypeTag.NoneTag};
}
else if (tt.typeID === "Nothing") {
return {tag: APIEmitTypeTag.NothingTag};
}
else if (tt.typeID === "Bool") {
return {tag: APIEmitTypeTag.BoolTag};
}
else if (tt.typeID === "Int") {
return {tag: APIEmitTypeTag.IntTag};
}
else if (tt.typeID === "Nat") {
return {tag: APIEmitTypeTag.NatTag};
}
else if (tt.typeID === "BigInt") {
return {tag: APIEmitTypeTag.BigIntTag};
}
else if (tt.typeID === "BigNat") {
return {tag: APIEmitTypeTag.BigNatTag};
}
else if (tt.typeID === "Float") {
return {tag: APIEmitTypeTag.FloatTag};
}
else if (tt.typeID === "Decimal") {
return {tag: APIEmitTypeTag.DecimalTag};
}
else if (tt.typeID === "Rational") {
return {tag: APIEmitTypeTag.RationalTag};
}
else if (tt.typeID === "String") {
return {tag: APIEmitTypeTag.StringTag};
}
else if (tt.typeID === "ByteBuffer") {
return {tag: APIEmitTypeTag.ByteBufferTag};
}
else if(tt.typeID === "DateTime") {
return {tag: APIEmitTypeTag.DateTimeTag};
}
else if(tt.typeID === "TickTime") {
return {tag: APIEmitTypeTag.TickTimeTag};
}
else if(tt.typeID === "LogicalTime") {
return {tag: APIEmitTypeTag.LogicalTimeTag};
}
else if(tt.typeID === "UUID") {
return {tag: APIEmitTypeTag.UUIDTag};
}
else if(tt.typeID === "ContentHash") {
return {tag: APIEmitTypeTag.ContentHashTag};
}
else {
assert(false);
return {tag: APIEmitTypeTag.NoneTag, name: "[UNKNOWN API TYPE]"};
}
}
else if (entity instanceof MIRConstructableInternalEntityTypeDecl) {
if (tt.typeID.startsWith("StringOf")) {
return {tag: APIEmitTypeTag.StringOfTag, name: tt.typeID, validator: (entity.fromtype as MIRResolvedTypeKey)};
}
else if (tt.typeID.startsWith("DataString")) {
return {tag: APIEmitTypeTag.DataStringTag, name: tt.typeID, oftype: (entity.fromtype as MIRResolvedTypeKey), chkinv: (entity as MIRDataStringInternalEntityTypeDecl).accepts};
}
else if (tt.typeID.startsWith("DataBuffer")) {
return {tag: APIEmitTypeTag.DataBufferTag, name: tt.typeID, oftype: (entity.fromtype as MIRResolvedTypeKey), chkinv: (entity as MIRDataBufferInternalEntityTypeDecl).accepts};
}
else if (tt.typeID.startsWith("Something")) {
return {tag: APIEmitTypeTag.ConstructableOfType, name: tt.typeID, oftype: (entity.fromtype as MIRResolvedTypeKey), validatefunc: null};
}
else if (tt.typeID.startsWith("Result::Ok")) {
return {tag: APIEmitTypeTag.ConstructableOfType, name: tt.typeID, oftype: (entity.fromtype as MIRResolvedTypeKey), validatefunc: null};
}
else {
assert(tt.typeID.startsWith("Result::Err"));
return {tag: APIEmitTypeTag.ConstructableOfType, name: tt.typeID, oftype: (entity.fromtype as MIRResolvedTypeKey), validatefunc: null};
}
}
else if (entity instanceof MIRStringOfInternalEntityTypeDecl) {
const validator = this.validatorRegexs.get(entity.validatortype) as BSQRegex;
return {tag: APIEmitTypeTag.StringOfTag, name: tt.typeID, validator: validator.jemit()};
}
else if (entity instanceof MIRDataStringInternalEntityTypeDecl) {
return {tag: APIEmitTypeTag.DataStringTag, name: tt.typeID, oftype: entity.fromtype, chkinv: entity.accepts}
}
else if (entity instanceof MIRDataBufferInternalEntityTypeDecl) {
return {tag: APIEmitTypeTag.DataStringTag, name: tt.typeID, oftype: entity.fromtype, chkinv: entity.accepts}
}
else {
assert(entity instanceof MIRPrimitiveCollectionEntityTypeDecl);
if(entity instanceof MIRPrimitiveListEntityTypeDecl) {
return {tag: APIEmitTypeTag.ContainerTag, name: tt.typeID, category: ContainerCategory.List, elemtype: entity.getTypeT().typeID};
}
else if(entity instanceof MIRPrimitiveStackEntityTypeDecl) {
return {tag: APIEmitTypeTag.ContainerTag, name: tt.typeID, category: ContainerCategory.Stack, elemtype: entity.getTypeT().typeID};
}
else if(entity instanceof MIRPrimitiveQueueEntityTypeDecl) {
return {tag: APIEmitTypeTag.ContainerTag, name: tt.typeID, category: ContainerCategory.Queue, elemtype: entity.getTypeT().typeID};
}
else if(entity instanceof MIRPrimitiveSetEntityTypeDecl) {
return {tag: APIEmitTypeTag.ContainerTag, name: tt.typeID, category: ContainerCategory.Set, elemtype: entity.getTypeT().typeID};
}
else {
const mentity = entity as MIRPrimitiveMapEntityTypeDecl;
return {tag: APIEmitTypeTag.ContainerTag, name: tt.typeID, category: ContainerCategory.Map, elemtype: mentity.tupentrytype};
}
}
}
else if(entity instanceof MIRConstructableEntityTypeDecl) {
return {tag: APIEmitTypeTag.ConstructableOfType, name: tt.typeID, oftype: entity.fromtype, validatefunc: entity.validatefunc || null};
}
else if(entity instanceof MIREnumEntityTypeDecl) {
return {tag: APIEmitTypeTag.EnumTag, name: tt.typeID, enums: entity.enums};
}
else {
const oentity = entity as MIRObjectEntityTypeDecl;
let consfields: {fkey: MIRFieldKey, fname: string}[] = [];
let ttypes: {declaredType: MIRResolvedTypeKey, isOptional: boolean}[] = [];
for(let i = 0; i < oentity.consfuncfields.length; ++i)
{
const ff = oentity.consfuncfields[i];
const mirff = this.fieldDecls.get(ff.cfkey) as MIRFieldDecl;
consfields.push({fkey: mirff.fkey, fname: mirff.fname});
ttypes.push({declaredType: mirff.declaredType, isOptional: ff.isoptional});
}
return {tag: APIEmitTypeTag.EntityTag, name: tt.typeID, consfields: consfields, ttypes: ttypes, validatefunc: oentity.validatefunc || null, consfunc: oentity.consfunc || null};
}
}
getAPITypeFor(tt: MIRType): object {
if(tt.options.length === 1 && (tt.options[0] instanceof MIRTupleType)) {
const tdecl = this.tupleDecls.get(tt.typeID) as MIRTupleType;
let ttypes: string[] = [];
for(let i = 0; i < tdecl.entries.length; ++i)
{
const mirtt = tdecl.entries[i];
ttypes.push(mirtt.typeID);
}
return {tag: APIEmitTypeTag.TupleTag, name: tt.typeID, ttypes: ttypes};
}
else if(tt.options.length === 1 && (tt.options[0] instanceof MIRRecordType)) {
const rdecl = this.recordDecls.get(tt.typeID) as MIRRecordType;
let props: string[] = [];
let ttypes: string[] = [];
for(let i = 0; i < rdecl.entries.length; ++i)
{
const prop = rdecl.entries[i].pname;
const mirtt = rdecl.entries[i].ptype;
props.push(prop);
ttypes.push(mirtt.typeID);
}
return {tag: APIEmitTypeTag.RecordTag, name: tt.typeID, props: props, ttypes: ttypes};
}
else if(tt.options.length === 1 && (tt.options[0] instanceof MIREntityType)) {
return this.getAPITypeForEntity(tt, this.entityDecls.get(tt.typeID) as MIREntityTypeDecl);
}
else if(tt.options.length === 1 && (tt.options[0] instanceof MIRConceptType)) {
const etypes = [...this.entityDecls].filter((edi) => this.subtypeOf(this.typeMap.get(edi[1].tkey) as MIRType, tt));
const opts: string[] = etypes.map((opt) => opt[1].tkey).sort((a, b) => a.localeCompare(b));
let ropts: string[] = [];
for(let i = 0; i < opts.length; ++i) {
const has = ropts.includes(opts[i]);
if(!has) {
ropts.push(opts[i]);
}
}
return {tag: APIEmitTypeTag.UnionTag, name: tt.typeID, opts: ropts};
}
else {
const etypes = [...this.entityDecls].filter((edi) => this.subtypeOf(this.typeMap.get(edi[1].tkey) as MIRType, tt));
const opts: string[] = etypes.map((opt) => opt[1].tkey).sort((a, b) => a.localeCompare(b));
let ropts: string[] = [];
for(let i = 0; i < opts.length; ++i) {
const has = ropts.includes(opts[i]);
if(!has) {
ropts.push(opts[i]);
}
}
return {tag: APIEmitTypeTag.UnionTag, name: tt.typeID, opts: ropts};
}
}
getAPIForInvoke(invk: MIRInvokeDecl): object {
return { name: invk.ikey, argnames: invk.params.map((pp) => pp.name), argtypes: invk.params.map((pp) => pp.type), restype: invk.resultType };
}
emitAPIInfo(entrypoints: MIRInvokeKey[], istestbuild: boolean): any {
const apitype = this.typeMap.get("APIType") as MIRType;
const testtype = this.typeMap.get("TestableType") as MIRType;
const apitypes = [...this.typeMap]
.filter((tp) => this.subtypeOf(this.typeMap.get(tp[0]) as MIRType, apitype) || (istestbuild && this.subtypeOf(this.typeMap.get(tp[0]) as MIRType, testtype)))
.sort((a, b) => a[0].localeCompare(b[0]))
.map((tt) => this.getAPITypeFor(tt[1]));
const typedecls = [...this.entyremaps.entrytypedef].sort((a, b) => a[0].localeCompare(b[0])).map((td) => {
return {name: td[0], type: td[1].typeID};
});
const namespacemap = [...this.entyremaps.namespaceremap].sort((a, b) => a[0].localeCompare(b[0])).map((td) => {
return {name: td[0], into: td[1]};
});
const sigs = entrypoints.sort().map((ep) => {
const epdcl = this.invokeDecls.get(ep) as MIRInvokeBodyDecl;
return this.getAPIForInvoke(epdcl);
})
return { apitypes: apitypes, typedecls: typedecls, namespacemap: namespacemap, apisig: sigs};
}
}
export {
MIRConstantDecl, MIRFunctionParameter, MIRPCode, MIRInvokeDecl, MIRInvokeBodyDecl, MIRInvokePrimitiveDecl, MIRFieldDecl,
MIROOTypeDecl, MIRConceptTypeDecl, MIREntityTypeDecl,
MIRType, MIRTypeOption,
MIREntityType, MIRObjectEntityTypeDecl, MIRConstructableEntityTypeDecl, MIREnumEntityTypeDecl, MIRInternalEntityTypeDecl, MIRPrimitiveInternalEntityTypeDecl, MIRStringOfInternalEntityTypeDecl, MIRDataStringInternalEntityTypeDecl, MIRDataBufferInternalEntityTypeDecl, MIRConstructableInternalEntityTypeDecl,
MIRHavocEntityTypeDecl,
MIRPrimitiveCollectionEntityTypeDecl, MIRPrimitiveListEntityTypeDecl, MIRPrimitiveStackEntityTypeDecl, MIRPrimitiveQueueEntityTypeDecl, MIRPrimitiveSetEntityTypeDecl, MIRPrimitiveMapEntityTypeDecl,
MIRConceptType, MIRTupleType, MIRRecordType, MIREphemeralListType,
SymbolicActionMode, RuntimeActionMode, PackageConfig, MIRAssembly
}; | the_stack |
module android.graphics{
/**
* The Paint class holds the style and color information about how to draw
* geometries, text and bitmaps.
*/
export class Paint{
private static FontMetrics_Size_Ascent = -0.9277344;
private static FontMetrics_Size_Bottom = 0.2709961;
private static FontMetrics_Size_Descent = 0.24414062;
private static FontMetrics_Size_Leading = 0;
private static FontMetrics_Size_Top = -1.05615234;
static DIRECTION_LTR:number = 0;
static DIRECTION_RTL:number = 1;
/**
* Option for getTextRunCursor to compute the valid cursor after
* offset or the limit of the context, whichever is less.
* @hide
*/
static CURSOR_AFTER:number = 0;
/**
* Option for getTextRunCursor to compute the valid cursor at or after
* the offset or the limit of the context, whichever is less.
* @hide
*/
static CURSOR_AT_OR_AFTER:number = 1;
/**
* Option for getTextRunCursor to compute the valid cursor before
* offset or the start of the context, whichever is greater.
* @hide
*/
static CURSOR_BEFORE:number = 2;
/**
* Option for getTextRunCursor to compute the valid cursor at or before
* offset or the start of the context, whichever is greater.
* @hide
*/
static CURSOR_AT_OR_BEFORE:number = 3;
/**
* Option for getTextRunCursor to return offset if the cursor at offset
* is valid, or -1 if it isn't.
* @hide
*/
static CURSOR_AT:number = 4;
/**
* Maximum cursor option value.
*/
private static CURSOR_OPT_MAX_VALUE:number = Paint.CURSOR_AT;
/**
* Paint flag that enables antialiasing when drawing.
*
* <p>Enabling this flag will cause all draw operations that support
* antialiasing to use it.</p>
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static ANTI_ALIAS_FLAG:number = 0x01;
/**
* Paint flag that enables bilinear sampling on scaled bitmaps.
*
* <p>If cleared, scaled bitmaps will be drawn with nearest neighbor
* sampling, likely resulting in artifacts. This should generally be on
* when drawing bitmaps, unless performance-bound (rendering to software
* canvas) or preferring pixelation artifacts to blurriness when scaling
* significantly.</p>
*
* <p>If bitmaps are scaled for device density at creation time (as
* resource bitmaps often are) the filtering will already have been
* done.</p>
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static FILTER_BITMAP_FLAG:number = 0x02;
/**
* Paint flag that enables dithering when blitting.
*
* <p>Enabling this flag applies a dither to any blit operation where the
* target's colour space is more constrained than the source.
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static DITHER_FLAG:number = 0x04;
/**
* Paint flag that applies an underline decoration to drawn text.
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static UNDERLINE_TEXT_FLAG:number = 0x08;
/**
* Paint flag that applies a strike-through decoration to drawn text.
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static STRIKE_THRU_TEXT_FLAG:number = 0x10;
/**
* Paint flag that applies a synthetic bolding effect to drawn text.
*
* <p>Enabling this flag will cause text draw operations to apply a
* simulated bold effect when drawing a {@link Typeface} that is not
* already bold.</p>
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static FAKE_BOLD_TEXT_FLAG:number = 0x20;
/**
* Paint flag that enables smooth linear scaling of text.
*
* <p>Enabling this flag does not actually scale text, but rather adjusts
* text draw operations to deal gracefully with smooth adjustment of scale.
* When this flag is enabled, font hinting is disabled to prevent shape
* deformation between scale factors, and glyph caching is disabled due to
* the large number of glyph images that will be generated.</p>
*
* <p>{@link #SUBPIXEL_TEXT_FLAG} should be used in conjunction with this
* flag to prevent glyph positions from snapping to whole pixel values as
* scale factor is adjusted.</p>
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static LINEAR_TEXT_FLAG:number = 0x40;
/**
* Paint flag that enables subpixel positioning of text.
*
* <p>Enabling this flag causes glyph advances to be computed with subpixel
* accuracy.</p>
*
* <p>This can be used with {@link #LINEAR_TEXT_FLAG} to prevent text from
* jittering during smooth scale transitions.</p>
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static SUBPIXEL_TEXT_FLAG:number = 0x80;
/** Legacy Paint flag, no longer used. */
static DEV_KERN_TEXT_FLAG:number = 0x100;
/** @hide bit mask for the flag enabling subpixel glyph rendering for text */
static LCD_RENDER_TEXT_FLAG:number = 0x200;
/**
* Paint flag that enables the use of bitmap fonts when drawing text.
*
* <p>Disabling this flag will prevent text draw operations from using
* embedded bitmap strikes in fonts, causing fonts with both scalable
* outlines and bitmap strikes to draw only the scalable outlines, and
* fonts with only bitmap strikes to not draw at all.</p>
*
* @see #Paint(int)
* @see #setFlags(int)
*/
static EMBEDDED_BITMAP_TEXT_FLAG:number = 0x400;
/** @hide bit mask for the flag forcing freetype's autohinter on for text */
static AUTO_HINTING_TEXT_FLAG:number = 0x800;
/** @hide bit mask for the flag enabling vertical rendering for text */
static VERTICAL_TEXT_FLAG:number = 0x1000;
// we use this when we first create a paint
static DEFAULT_PAINT_FLAGS:number = Paint.DEV_KERN_TEXT_FLAG | Paint.EMBEDDED_BITMAP_TEXT_FLAG;
private mTextStyle = Paint.Style.FILL;
private mColor:number;
private mStrokeWidth:number;
private align:Paint.Align;
private mStrokeCap:Paint.Cap;
private mStrokeJoin:Paint.Join;
private textSize:number;
private textScaleX = 1;
private mFlag = 0;
/**
* @hide
*/
hasShadow:boolean;
/**
* @hide
*/
shadowDx:number = 0;
/**
* @hide
*/
shadowDy:number = 0;
/**
* @hide
*/
shadowRadius:number = 0;
/**
* @hide
*/
shadowColor:number = 0;
drawableState:number[];
constructor(flag=0){
this.mFlag = flag;
}
/**
* Copy the fields from src into this paint. This is equivalent to calling
* get() on all of the src fields, and calling the corresponding set()
* methods on this.
*/
set(src:Paint):void {
if (this != src) {
// copy over the native settings
this.setClassVariablesFrom(src);
}
}
/**
* Set all class variables using current values from the given
* {@link Paint}.
*/
private setClassVariablesFrom(paint:Paint):void {
this.mTextStyle = paint.mTextStyle;
this.mColor = paint.mColor;
this.mStrokeWidth = paint.mStrokeWidth;
this.align = paint.align;
this.mStrokeCap = paint.mStrokeCap;
this.mStrokeJoin = paint.mStrokeJoin;
this.textSize = paint.textSize;
this.textScaleX = paint.textScaleX;
this.mFlag = paint.mFlag;
this.hasShadow = paint.hasShadow;
this.shadowDx = paint.shadowDx;
this.shadowDy = paint.shadowDy;
this.shadowRadius = paint.shadowRadius;
this.shadowColor = paint.shadowColor;
this.drawableState = paint.drawableState;
//Object.assign(this, paint);
}
/**
* Return the paint's style, used for controlling how primitives'
* geometries are interpreted (except for drawBitmap, which always assumes
* FILL_STYLE).
*
* @return the paint's style setting (Fill, Stroke, StrokeAndFill)
*/
getStyle():Paint.Style {
return this.mTextStyle;
}
/**
* Set the paint's style, used for controlling how primitives'
* geometries are interpreted (except for drawBitmap, which always assumes
* Fill).
*
* @param style The new style to set in the paint
*/
setStyle(style:Paint.Style):void {
this.mTextStyle = style;
}
/**
* Return the paint's flags. Use the Flag enum to test flag values.
*
* @return the paint's flags (see enums ending in _Flag for bit masks)
*/
getFlags():number{
return this.mFlag;
}
/**
* Set the paint's flags. Use the Flag enum to specific flag values.
*
* @param flags The new flag bits for the paint
*/
setFlags(flags:number):void{
this.mFlag = flags;
}
getTextScaleX():number {
return this.textScaleX;
}
setTextScaleX(scaleX:number):void {
this.textScaleX = scaleX;
}
/**
* Return the paint's color. Note that the color is a 32bit value
* containing alpha as well as r,g,b. This 32bit value is not premultiplied,
* meaning that its alpha can be any value, regardless of the values of
* r,g,b. See the Color class for more details.
*
* @return the paint's color (and alpha).
*/
getColor():number{
return this.mColor;
}
/**
* Set the paint's color. Note that the color is an int containing alpha
* as well as r,g,b. This 32bit value is not premultiplied, meaning that
* its alpha can be any value, regardless of the values of r,g,b.
* See the Color class for more details.
*
* @param color The new color (including alpha) to set in the paint.
*/
setColor(color:number){
this.mColor = color;
}
/**
* Helper to setColor(), that takes a,r,g,b and constructs the color int
*
* @param a The new alpha component (0..255) of the paint's color.
* @param r The new red component (0..255) of the paint's color.
* @param g The new green component (0..255) of the paint's color.
* @param b The new blue component (0..255) of the paint's color.
*/
setARGB(a:number, r:number, g:number, b:number):void {
this.setColor((a << 24) | (r << 16) | (g << 8) | b);
}
/**
* Helper to getColor() that just returns the color's alpha value. This is
* the same as calling getColor() >>> 24. It always returns a value between
* 0 (completely transparent) and 255 (completely opaque).
*
* @return the alpha component of the paint's color.
*/
getAlpha():number{
return Color.alpha(this.mColor);
}
/**
* Helper to setColor(), that only assigns the color's alpha value,
* leaving its r,g,b values unchanged. Results are undefined if the alpha
* value is outside of the range [0..255]
*
* @param alpha set the alpha component [0..255] of the paint's color.
*/
setAlpha(alpha:number){
this.setColor(Color.argb(alpha, Color.red(this.mColor), Color.green(this.mColor), Color.blue(this.mColor)));
}
/**
* Return the width for stroking.
* <p />
* A value of 0 strokes in hairline mode.
* Hairlines always draws a single pixel independent of the canva's matrix.
*
* @return the paint's stroke width, used whenever the paint's style is
* Stroke or StrokeAndFill.
*/
getStrokeWidth():number{
return this.mStrokeWidth;
}
/**
* Set the width for stroking.
* Pass 0 to stroke in hairline mode.
* Hairlines always draws a single pixel independent of the canva's matrix.
*
* @param width set the paint's stroke width, used whenever the paint's
* style is Stroke or StrokeAndFill.
*/
setStrokeWidth(width:number):void{
this.mStrokeWidth = width;
}
/**
* Return the paint's Cap, controlling how the start and end of stroked
* lines and paths are treated.
*
* @return the line cap style for the paint, used whenever the paint's
* style is Stroke or StrokeAndFill.
*/
getStrokeCap():Paint.Cap {
return this.mStrokeCap;
}
/**
* Set the paint's Cap.
*
* @param cap set the paint's line cap style, used whenever the paint's
* style is Stroke or StrokeAndFill.
*/
setStrokeCap(cap:Paint.Cap):void {
this.mStrokeCap = cap;
}
/**
* Return the paint's stroke join type.
*
* @return the paint's Join.
*/
getStrokeJoin():Paint.Join {
return this.mStrokeJoin
}
/**
* Set the paint's Join.
*
* @param join set the paint's Join, used whenever the paint's style is
* Stroke or StrokeAndFill.
*/
setStrokeJoin(join:Paint.Join):void {
this.mStrokeJoin = join;
}
setAntiAlias(enable:boolean){
//no effect on web canvas
//http://stackoverflow.com/questions/4261090/html5-canvas-and-anti-aliasing
}
isAntiAlias():boolean {
//default true on web canvas
return true;
}
/**
* This draws a shadow layer below the main layer, with the specified
* offset and color, and blur radius. If radius is 0, then the shadow
* layer is removed.
*/
setShadowLayer(radius:number, dx:number, dy:number, color:number):void {
this.hasShadow = radius > 0.0;
this.shadowRadius = radius;
this.shadowDx = dx;
this.shadowDy = dy;
this.shadowColor = color;
}
/**
* Clear the shadow layer.
*/
clearShadowLayer():void {
this.hasShadow = false;
}
/**
* Return the paint's Align value for drawing text. This controls how the
* text is positioned relative to its origin. LEFT align means that all of
* the text will be drawn to the right of its origin (i.e. the origin
* specifieds the LEFT edge of the text) and so on.
*
* @return the paint's Align value for drawing text.
*/
getTextAlign():Paint.Align {
return this.align;
}
/**
* Set the paint's text alignment. This controls how the
* text is positioned relative to its origin. LEFT align means that all of
* the text will be drawn to the right of its origin (i.e. the origin
* specifieds the LEFT edge of the text) and so on.
*
* @param align set the paint's Align value for drawing text.
*/
setTextAlign(align:Paint.Align){
this.align = align;
}
/**
* Return the paint's text size.
*
* @return the paint's text size.
*/
getTextSize():number{
return this.textSize;
}
/**
* Set the paint's text size. This value must be > 0
*
* @param textSize set the paint's text size.
*/
setTextSize(textSize:number){
this.textSize = textSize;
}
/**
* Return the distance above (negative) the baseline (ascent) based on the
* current typeface and text size.
*
* @return the distance above (negative) the baseline (ascent) based on the
* current typeface and text size.
*/
ascent():number {
return this.textSize * Paint.FontMetrics_Size_Ascent;
}
/**
* Return the distance below (positive) the baseline (descent) based on the
* current typeface and text size.
*
* @return the distance below (positive) the baseline (descent) based on
* the current typeface and text size.
*/
descent():number {
return this.textSize * Paint.FontMetrics_Size_Descent;
}
/**
* Return the font's interline spacing, given the Paint's settings for
* typeface, textSize, etc. If metrics is not null, return the fontmetric
* values in it. Note: all values have been converted to integers from
* floats, in such a way has to make the answers useful for both spacing
* and clipping. If you want more control over the rounding, call
* getFontMetrics().
*
* @return the font's interline spacing.
*/
getFontMetricsInt(fmi:Paint.FontMetricsInt):number {
if(this.textSize==null){
console.warn('call Paint.getFontMetricsInt but textSize not init');
return 0;
}
if(fmi==null){
return Math.floor((Paint.FontMetrics_Size_Descent - Paint.FontMetrics_Size_Ascent) * this.textSize);
}
fmi.ascent = Math.floor(Paint.FontMetrics_Size_Ascent * this.textSize);
fmi.bottom = Math.floor(Paint.FontMetrics_Size_Bottom * this.textSize);
fmi.descent = Math.floor(Paint.FontMetrics_Size_Descent * this.textSize);
fmi.leading = Math.floor(Paint.FontMetrics_Size_Leading * this.textSize);
fmi.top = Math.floor(Paint.FontMetrics_Size_Top * this.textSize);
return fmi.descent - fmi.ascent;
}
/**
* Return the font's recommended interline spacing, given the Paint's
* settings for typeface, textSize, etc. If metrics is not null, return the
* fontmetric values in it.
*
* @param metrics If this object is not null, its fields are filled with
* the appropriate values given the paint's text attributes.
* @return the font's recommended interline spacing.
*/
getFontMetrics(metrics:Paint.FontMetrics):number {
if(this.textSize==null){
console.warn('call Paint.getFontMetrics but textSize not init');
return 0;
}
if(metrics==null){
return (Paint.FontMetrics_Size_Descent - Paint.FontMetrics_Size_Ascent) * this.textSize;
}
metrics.ascent = Paint.FontMetrics_Size_Ascent * this.textSize;
metrics.bottom = Paint.FontMetrics_Size_Bottom * this.textSize;
metrics.descent = Paint.FontMetrics_Size_Descent * this.textSize;
metrics.leading = Paint.FontMetrics_Size_Leading * this.textSize;
metrics.top = Paint.FontMetrics_Size_Top * this.textSize;
return metrics.descent - metrics.ascent;
}
/**
* Return the width of the text.
*
* @param text The text to measure. Cannot be null.
* @param index The index of the first character to start measuring
* @param count THe number of characters to measure, beginning with start
* @return The width of the text
*/
measureText(text:string, index=0, count=text.length):number {
return Canvas.measureText(text.substr(index, count), this.textSize) * this.textScaleX;
}
/**
* Return the advance widths for the characters in the string.
*
* @param text The text to measure. Cannot be null.
* @param index The index of the first char to to measure
* @param count The number of chars starting with index to measure
* @param widths array to receive the advance widths of the characters.
* Must be at least a large as count.
* @return the actual number of widths returned.
*/
getTextWidths_count(text:string, index:number, count:number, widths:number[]):number {
return this.getTextWidths_end(text, index, index+count, widths);
}
/**
* Return the advance widths for the characters in the string.
*
* @param text The text to measure. Cannot be null.
* @param start The index of the first char to to measure
* @param end The end of the text slice to measure
* @param widths array to receive the advance widths of the characters.
* Must be at least a large as the text.
* @return the number of unichars in the specified text.
*/
getTextWidths_end(text:string, start:number, end:number, widths:number[]):number {
if (text == null) {
throw Error(`new IllegalArgumentException("text cannot be null")`);
}
if ((start | end | (end - start) | (text.length - end)) < 0) {
throw Error(`new IndexOutOfBoundsException()`);
}
if (end - start > widths.length) {
throw Error(`new ArrayIndexOutOfBoundsException()`);
}
if (text.length == 0 || start == end) {
return 0;
}
for (let i = start; i < end; i++) {
widths[i-start] = this.measureText(text[i]);
}
return end - start;
}
/**
* Return the advance widths for the characters in the string.
*
* @param text The text to measure
* @param widths array to receive the advance widths of the characters.
* Must be at least a large as the text.
* @return the number of unichars in the specified text.
*/
getTextWidths_2(text:string, widths:number[]):number {
return this.getTextWidths_end(text, 0, text.length, widths);
}
/**
* @hide
*/
getTextRunAdvances_count(chars:string, index:number, count:number, contextIndex:number, contextCount:number,
flags:number, advances:number[], advancesIndex:number):number {
return this.getTextRunAdvances_end(chars, index, index+count, contextIndex, contextCount, flags, advances, advancesIndex);
}
/**
* @hide
*/
getTextRunAdvances_end(text:string, start:number, end:number, contextStart:number, contextEnd:number,
flags:number, advances:number[], advancesIndex:number):number {
if (text == null) {
throw Error(`new IllegalArgumentException("text cannot be null")`);
}
if (flags != Paint.DIRECTION_LTR && flags != Paint.DIRECTION_RTL) {
throw Error(`new IllegalArgumentException("unknown flags value: " + flags)`);
}
if ((start | end | contextStart | contextEnd | advancesIndex | (end - start)
| (start - contextStart) | (contextEnd - end) | (text.length - contextEnd)
| (advances == null ? 0 : (advances.length - advancesIndex - (end - start)))) < 0) {
throw Error(`new IndexOutOfBoundsException()`);
}
if (text.length == 0 || start == end) {
return 0;
}
let totalAdvance = 0;
for (let i = start; i < end; i++) {
let width = this.measureText(text[i]);
if(advances) advances[i-start+advancesIndex] = width;
totalAdvance += width;
}
return totalAdvance;
}
/**
* Returns the next cursor position in the run. This avoids placing the
* cursor between surrogates, between characters that form conjuncts,
* between base characters and combining marks, or within a reordering
* cluster.
*
* <p>ContextStart and offset are relative to the start of text.
* The context is the shaping context for cursor movement, generally
* the bounds of the metric span enclosing the cursor in the direction of
* movement.
*
* <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
* cursor position, this returns -1. Otherwise this will never return a
* value before contextStart or after contextStart + contextLength.
*
* @param text the text
* @param contextStart the start of the context
* @param contextLength the length of the context
* @param flags either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR}
* @param offset the cursor position to move from
* @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
* {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
* {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
* @return the offset of the next position, or -1
* @hide
*/
getTextRunCursor_len(text:string, contextStart:number, contextLength:number, flags:number, offset:number, cursorOpt:number):number {
let contextEnd:number = contextStart + contextLength;
if (((contextStart | contextEnd | offset | (contextEnd - contextStart) | (offset - contextStart) | (contextEnd - offset)
| (text.length - contextEnd) | cursorOpt) < 0) || cursorOpt > Paint.CURSOR_OPT_MAX_VALUE) {
throw Error(`new IndexOutOfBoundsException()`);
}
const scalarArray = androidui.util.ArrayCreator.newNumberArray(contextLength);
this.getTextRunAdvances_count(text, contextStart, contextLength, contextStart, contextLength, flags, scalarArray, 0);
let pos = offset - contextStart;
switch (cursorOpt) {
case Paint.CURSOR_AFTER:
if (pos < contextLength) {
pos += 1;
}
// fall through
case Paint.CURSOR_AT_OR_AFTER:
while (pos < contextLength && scalarArray[pos] == 0) {
++pos;
}
break;
case Paint.CURSOR_BEFORE:
if (pos > 0) {
--pos;
}
// fall through
case Paint.CURSOR_AT_OR_BEFORE:
while (pos > 0 && scalarArray[pos] == 0) {
--pos;
}
break;
case Paint.CURSOR_AT:
default:
if (scalarArray[pos] == 0) {
pos = -1;
}
break;
}
if (pos != -1) {
pos += contextStart;
}
return pos;
}
/**
* Returns the next cursor position in the run. This avoids placing the
* cursor between surrogates, between characters that form conjuncts,
* between base characters and combining marks, or within a reordering
* cluster.
*
* <p>ContextStart, contextEnd, and offset are relative to the start of
* text. The context is the shaping context for cursor movement, generally
* the bounds of the metric span enclosing the cursor in the direction of
* movement.
*
* <p>If cursorOpt is {@link #CURSOR_AT} and the offset is not a valid
* cursor position, this returns -1. Otherwise this will never return a
* value before contextStart or after contextEnd.
*
* @param text the text
* @param contextStart the start of the context
* @param contextEnd the end of the context
* @param flags either {@link #DIRECTION_RTL} or {@link #DIRECTION_LTR}
* @param offset the cursor position to move from
* @param cursorOpt how to move the cursor, one of {@link #CURSOR_AFTER},
* {@link #CURSOR_AT_OR_AFTER}, {@link #CURSOR_BEFORE},
* {@link #CURSOR_AT_OR_BEFORE}, or {@link #CURSOR_AT}
* @return the offset of the next position, or -1
* @hide
*/
getTextRunCursor_end(text:string, contextStart:number, contextEnd:number, flags:number, offset:number, cursorOpt:number):number {
if (((contextStart | contextEnd | offset | (contextEnd - contextStart) | (offset - contextStart) | (contextEnd - offset)
| (text.length - contextEnd) | cursorOpt) < 0) || cursorOpt > Paint.CURSOR_OPT_MAX_VALUE) {
throw Error(`new IndexOutOfBoundsException()`);
}
let contextLen:number = contextEnd - contextStart;
return this.getTextRunCursor_len(text, 0, contextLen, flags, offset - contextStart, cursorOpt);
}
isEmpty():boolean {
return this.mColor==null
&& this.align==null
&& this.mStrokeWidth==null
&& this.mStrokeCap==null
&& this.mStrokeJoin==null
&& !this.hasShadow
&& this.textSize==null
;
}
applyToCanvas(canvas:Canvas):void {
if(this.mColor!=null) {
canvas.setColor(this.mColor, this.getStyle());
}
if(this.align!=null){
canvas.setTextAlign(Paint.Align[this.align].toLowerCase());
}
if(this.mStrokeWidth!=null){
canvas.setLineWidth(this.mStrokeWidth);
}
if(this.mStrokeCap!=null){
canvas.setLineCap(Paint.Cap[this.mStrokeCap].toLowerCase());
}
if(this.mStrokeJoin!=null){
canvas.setLineJoin(Paint.Join[this.mStrokeJoin].toLowerCase());
}
if(this.hasShadow){
canvas.setShadow(this.shadowRadius, this.shadowDx, this.shadowDy, this.shadowColor);
}
if(this.textSize!=null){
canvas.setFontSize(this.textSize);
}
if(this.textScaleX!=1){
canvas.scale(this.textScaleX, 1);
}
}
}
export module Paint{
export enum Align{
LEFT,
CENTER,
RIGHT,
}
/**
* Class that describes the various metrics for a font at a given text size.
* Remember, Y values increase going down, so those values will be positive,
* and values that measure distances going up will be negative. This class
* is returned by getFontMetrics().
*/
export class FontMetrics {
/**
* The maximum distance above the baseline for the tallest glyph in
* the font at a given text size.
*/
top:number = 0;
/**
* The recommended distance above the baseline for singled spaced text.
*/
ascent:number = 0;
/**
* The recommended distance below the baseline for singled spaced text.
*/
descent:number = 0;
/**
* The maximum distance below the baseline for the lowest glyph in
* the font at a given text size.
*/
bottom:number = 0;
/**
* The recommended additional space to add between lines of text.
*/
leading:number = 0;
}
/**
* Convenience method for callers that want to have FontMetrics values as
* integers.
*/
export class FontMetricsInt {
top:number = 0;
ascent:number = 0;
descent:number = 0;
bottom:number = 0;
leading:number = 0;
toString():string {
return "FontMetricsInt: top=" + this.top + " ascent=" + this.ascent + " descent=" + this.descent + " bottom=" + this.bottom + " leading=" + this.leading;
}
}
/**
* The Style specifies if the primitive being drawn is filled, stroked, or
* both (in the same color). The default is FILL.
*/
export enum Style {
/**
* Geometry and text drawn with this style will be filled, ignoring all
* stroke-related settings in the paint.
*/
FILL,
/**
* Geometry and text drawn with this style will be stroked, respecting
* the stroke-related fields on the paint.
*/
STROKE,
/**
* Geometry and text drawn with this style will be both filled and
* stroked at the same time, respecting the stroke-related fields on
* the paint. This mode can give unexpected results if the geometry
* is oriented counter-clockwise. This restriction does not apply to
* either FILL or STROKE.
*/
FILL_AND_STROKE
}
/**
* The Cap specifies the treatment for the beginning and ending of
* stroked lines and paths. The default is BUTT.
*/
export enum Cap {
/**
* The stroke ends with the path, and does not project beyond it.
*/
BUTT,
/**
* The stroke projects out as a semicircle, with the center at the
* end of the path.
*/
ROUND,
/**
* The stroke projects out as a square, with the center at the end
* of the path.
*/
SQUARE
}
/**
* The Join specifies the treatment where lines and curve segments
* join on a stroked path. The default is MITER.
*/
export enum Join {
/**
* The outer edges of a join meet at a sharp angle
*/
MITER,
/**
* The outer edges of a join meet in a circular arc.
*/
ROUND,
/**
* The outer edges of a join meet with a straight line
*/
BEVEL
}
}
} | the_stack |
///<reference path='typings/node/node.d.ts'/>
import ts = require("typescript");
import harness = require("./harness");
import path = require("path");
function resolvePath(rpath) {
return switchToForwardSlashes(path.resolve(rpath));
}
function switchToForwardSlashes(path: string) {
return path.replace(/\\/g, "/");
}
// some approximated subsets..
interface ReadlineHandlers {
on(event: string, listener: (event:string)=>void) : ReadlineHandlers;
close() : void;
}
interface Readline {
createInterface(options:any) : ReadlineHandlers;
}
// bypass import, we don't want to drop out of the global module;
// use fixed readline (https://github.com/joyent/node/issues/3305),
// fixed version should be in nodejs from about v0.9.9/v0.8.19?
var readline:Readline = require("./readline");
var EOL = require("os").EOL;
/** holds list of fileNames, ScriptInfos and ScriptSnapshots for LS host */
class FileCache {
public ls: ts.LanguageService;
public fileNames: string[] = [];
public snapshots:ts.Map<ts.IScriptSnapshot> = {};
public fileNameToScript:ts.Map<harness.ScriptInfo> = {};
public getFileNames() { return this.fileNames; }
/**
* @param fileName resolved name of possibly cached file
*/
public getScriptInfo(fileName) {
if (!this.fileNameToScript[fileName]) {
this.fetchFile(fileName);
}
return this.fileNameToScript[fileName];
}
/**
* @param fileName resolved name of possibly cached file
*/
public getScriptSnapshot(fileName) {
// console.log("getScriptSnapshot",fileName);
if (!this.snapshots[fileName]) {
this.fetchFile(fileName);
}
return this.snapshots[fileName];
}
/**
* @param fileName resolved file name
* @param text file contents
* @param isDefaultLib should fileName be listed first?
*/
public addFile(fileName,text,isDefaultLib=false) {
if (isDefaultLib) {
this.fileNames.push(fileName);
} else {
this.fileNames.unshift(fileName);
}
this.fileNameToScript[fileName] = new harness.ScriptInfo(fileName,text);
this.snapshots[fileName] = new harness.ScriptSnapshot(this.getScriptInfo(fileName));
}
/**
* @param fileName resolved file name
*/
public fetchFile(fileName) {
// console.log("fetchFile:",fileName);
if (ts.sys.fileExists(fileName)) {
this.addFile(fileName,ts.sys.readFile(fileName));
} else {
// console.error ("tss: cannot fetch file: "+fileName);
}
}
/**
* @param fileName resolved name of cached file
* @param line 1 based index
* @param col 1 based index
*/
public lineColToPosition(fileName: string, line: number, col: number): number {
var script: harness.ScriptInfo = this.getScriptInfo(fileName);
return ts.getPositionOfLineAndCharacter(this.ls.getSourceFile(fileName),line-1, col-1);
}
/**
* @param fileName resolved name of cached file
* @returns {line,character} 1 based indices
*/
public positionToLineCol(fileName: string, position: number): ts.LineAndCharacter {
var script: harness.ScriptInfo = this.getScriptInfo(fileName);
var lineChar = ts.getLineAndCharacterOfPosition(this.ls.getSourceFile(fileName),position);
return {line: lineChar.line+1, character: lineChar.character+1 };
}
/**
* @param fileName resolved name of cached file
* @param line 1 based index
*/
public getLineText(fileName,line) {
var source = this.ls.getSourceFile(fileName);
var lineStart = ts.getPositionOfLineAndCharacter(source,line-1,0)
var lineEnd = ts.getPositionOfLineAndCharacter(source,line,0)-1;
var lineText = source.text.substring(lineStart,lineEnd);
return lineText;
}
/**
* @param fileName resolved name of possibly cached file
* @param content new file contents
*/
public updateScript(fileName: string, content: string) {
var script = this.getScriptInfo(fileName);
if (script) {
script.updateContent(content);
this.snapshots[fileName] = new harness.ScriptSnapshot(script);
} else {
this.addFile(fileName,content);
}
}
/**
* @param fileName resolved name of cached file
* @param minChar first char of edit range
* @param limChar first char after edit range
* @param newText new file contents
*/
public editScript(fileName: string, minChar: number, limChar: number, newText: string) {
var script = this.getScriptInfo(fileName);
if (script) {
script.editContent(minChar, limChar, newText);
this.snapshots[fileName] = new harness.ScriptSnapshot(script);
return;
}
throw new Error("No script with name '" + fileName + "'");
}
}
/** TypeScript Services Server,
an interactive commandline tool
for getting info on .ts projects */
class TSS {
public compilerOptions: ts.CompilerOptions;
public compilerHost: ts.CompilerHost;
public lsHost : ts.LanguageServiceHost;
public ls : ts.LanguageService;
public rootFiles : string[];
public lastError;
constructor (public prettyJSON: boolean = false) { } // NOTE: call setup
private fileCache: FileCache;
/** collect syntactic and semantic diagnostics for all project files */
public getErrors(): ts.Diagnostic[] {
var addPhase = phase => d => {d.phase = phase; return d};
var errors = [];
this.fileCache.getFileNames().map( file=>{
if (!file.match(/^.*(\.ts)$/)) return; // exclude package.json
var syntactic = this.ls.getSyntacticDiagnostics(file);
var semantic = this.ls.getSemanticDiagnostics(file);
// this.ls.languageService.getEmitOutput(file).diagnostics;
errors = errors.concat(syntactic.map(addPhase("Syntax"))
,semantic.map(addPhase("Semantics")));
});
return errors;
}
/** flatten messageChain into string|string[] */
private messageChain(message:string|ts.DiagnosticMessageChain) {
if (typeof message==="string") {
return [message];
} else {
return [message.messageText].concat(message.next?this.messageChain(message.next):[]);
}
}
/** load file and dependencies, prepare language service for queries */
public setup(files,options) {
this.fileCache = new FileCache();
this.rootFiles = files.map(file=>resolvePath(file));
this.compilerOptions = options;
this.compilerHost = ts.createCompilerHost(options);
//TODO: diagnostics
// prime fileCache with root files and defaultLib
var seenNoDefaultLib = options.noLib;
this.rootFiles.forEach(file=>{
var source = this.compilerHost.getSourceFile(file,options.target);
if (source) {
seenNoDefaultLib = seenNoDefaultLib || source.hasNoDefaultLib;
this.fileCache.addFile(file,source.text);
} else {
throw ("tss cannot find file: "+file);
}
});
if (!seenNoDefaultLib) {
var defaultLibFileName = this.compilerHost.getDefaultLibFileName(options);
var source = this.compilerHost.getSourceFile(defaultLibFileName,options.target);
this.fileCache.addFile(defaultLibFileName,source.text);
}
// Get a language service
// internally builds programs from root files,
// chases dependencies (references and imports), ...
// (NOTE: files are processed on demand, loaded via lsHost, cached in fileCache)
this.lsHost = {
getCompilationSettings : ()=>this.compilerOptions,
getScriptFileNames : ()=>this.fileCache.getFileNames(),
getScriptVersion : (fileName: string)=>this.fileCache.getScriptInfo(fileName).version.toString(),
//getScriptIsOpen : (fileName: string)=>this.fileCache.getScriptInfo(fileName).isOpen,
getScriptSnapshot : (fileName: string)=>this.fileCache.getScriptSnapshot(fileName),
getCurrentDirectory : ()=>ts.sys.getCurrentDirectory(),
getDefaultLibFileName :
(options: ts.CompilerOptions)=>ts.getDefaultLibFileName(options),
log : (message)=>undefined, // ??
trace : (message)=>undefined, // ??
error : (message)=>console.error(message) // ??
};
this.ls = ts.createLanguageService(this.lsHost,ts.createDocumentRegistry());
this.fileCache.ls = this.ls;
}
/** output value/object as JSON, excluding irrelevant properties,
* with optional pretty-printing controlled by this.prettyJSON
* @param info thing to output
* @param excludes Array of property keys to exclude
*/
private output(info,excludes=["displayParts"]) {
var replacer = (k,v)=>excludes.indexOf(k)!==-1?undefined:v;
if (info) {
console.log(JSON.stringify(info,replacer,this.prettyJSON?" ":undefined).trim());
} else {
console.log(JSON.stringify(info,replacer));
}
}
private outputJSON(json) {
console.log(json.trim());
}
/** recursively prepare navigationBarItems for JSON output */
private handleNavBarItem(file:string,item:ts.NavigationBarItem) {
// TODO: under which circumstances can item.spans.length be other than 1?
return { info: [item.kindModifiers,item.kind,item.text].filter(s=>s!=="").join(" ")
, kindModifiers : item.kindModifiers
, kind: item.kind
, text: item.text
, min: this.fileCache.positionToLineCol(file,item.spans[0].start)
, lim: this.fileCache.positionToLineCol(file,item.spans[0].start+item.spans[0].length)
, childItems: item.childItems.map(item=>this.handleNavBarItem(file,item))
};
}
/** commandline server main routine: commands in, JSON info out */
public listen() {
var line: number;
var col: number;
var rl = readline.createInterface({input:process.stdin,output:process.stdout});
var cmd:string, pos:number, file:string, script, added:boolean, range:boolean, check:boolean
, def, refs:ts.ReferenceEntry[], locs:ts.DefinitionInfo[], info, source:ts.SourceFile
, brief, member:boolean, navbarItems:ts.NavigationBarItem[], pattern:string;
var collecting = 0, on_collected_callback:()=>void, lines:string[] = [];
var commands = {};
function match(cmd,regexp) {
commands[regexp.source] = true;
return cmd.match(regexp);
}
rl.on('line', input => { // most commands are one-liners
var m:string[];
try {
cmd = input.trim();
if (collecting>0) { // multiline input, eg, source
lines.push(input)
collecting--;
if (collecting===0) {
on_collected_callback();
}
} else if (m = match(cmd,/^signature (\d+) (\d+) (.*)$/)) { // only within call parameters?
(()=>{
line = parseInt(m[1]);
col = parseInt(m[2]);
file = resolvePath(m[3]);
pos = this.fileCache.lineColToPosition(file,line,col);
info = this.ls.getSignatureHelpItems(file,pos);
var param = p=>({name:p.name
,isOptional:p.isOptional
,type:ts.displayPartsToString(p.displayParts)||""
,docComment:ts.displayPartsToString(p.documentation)||""
});
info && (info.items = info.items
.map(item=>({prefix: ts.displayPartsToString(item.prefixDisplayParts)||""
,separator: ts.displayPartsToString(item.separatorDisplayParts)||""
,suffix: ts.displayPartsToString(item.suffixDisplayParts)||""
,parameters: item.parameters.map(param)
,docComment: ts.displayPartsToString(item.documentation)||""
}))
);
this.output(info);
})();
} else if (m = match(cmd,/^(type|quickInfo) (\d+) (\d+) (.*)$/)) { // "type" deprecated
line = parseInt(m[2]);
col = parseInt(m[3]);
file = resolvePath(m[4]);
pos = this.fileCache.lineColToPosition(file,line,col);
info = (this.ls.getQuickInfoAtPosition(file, pos)||{});
info.type = ((info&&ts.displayPartsToString(info.displayParts))||"");
info.docComment = ((info&&ts.displayPartsToString(info.documentation))||"");
this.output(info);
} else if (m = match(cmd,/^definition (\d+) (\d+) (.*)$/)) {
line = parseInt(m[1]);
col = parseInt(m[2]);
file = resolvePath(m[3]);
pos = this.fileCache.lineColToPosition(file,line,col);
locs = this.ls.getDefinitionAtPosition(file, pos); // NOTE: multiple definitions
info = locs && locs.map( def => ({
def : def,
file : def && def.fileName,
min : def && this.fileCache.positionToLineCol(def.fileName,def.textSpan.start),
lim : def && this.fileCache.positionToLineCol(def.fileName,ts.textSpanEnd(def.textSpan))
}));
// TODO: what about multiple definitions?
this.output((locs && info[0])||null);
} else if (m = match(cmd,/^(references|occurrences) (\d+) (\d+) (.*)$/)) {
line = parseInt(m[2]);
col = parseInt(m[3]);
file = resolvePath(m[4]);
pos = this.fileCache.lineColToPosition(file,line,col);
switch (m[1]) {
case "references":
refs = this.ls.getReferencesAtPosition(file, pos);
break;
case "occurrences":
refs = this.ls.getOccurrencesAtPosition(file, pos);
break;
default:
throw "cannot happen";
}
info = (refs || []).map( ref => {
var start, end, fileName, lineText;
if (ref) {
start = this.fileCache.positionToLineCol(ref.fileName,ref.textSpan.start);
end = this.fileCache.positionToLineCol(ref.fileName,ts.textSpanEnd(ref.textSpan));
fileName = resolvePath(ref.fileName);
lineText = this.fileCache.getLineText(fileName,start.line);
}
return {
ref : ref,
file : ref && ref.fileName,
lineText : lineText,
min : start,
lim : end
}} );
this.output(info);
} else if (m = match(cmd,/^navigationBarItems (.*)$/)) {
file = resolvePath(m[1]);
this.output(this.ls.getNavigationBarItems(file)
.map(item=>this.handleNavBarItem(file,item)));
} else if (m = match(cmd,/^navigateToItems (.*)$/)) {
pattern = m[1];
info = this.ls.getNavigateToItems(pattern)
.map(item=>{
item['min'] = this.fileCache.positionToLineCol(item.fileName
,item.textSpan.start);
item['lim'] = this.fileCache.positionToLineCol(item.fileName
,item.textSpan.start
+item.textSpan.length);
return item;
});
this.output(info);
} else if (m = match(cmd,/^completions(-brief)?( true| false)? (\d+) (\d+) (.*)$/)) {
brief = m[1];
line = parseInt(m[3]);
col = parseInt(m[4]);
file = resolvePath(m[5]);
pos = this.fileCache.lineColToPosition(file,line,col);
info = this.ls.getCompletionsAtPosition(file, pos) || null;
if (info) {
// fill in completion entry details, unless briefness requested
!brief && (info.entries = info.entries.map( e =>{
var d = this.ls.getCompletionEntryDetails(file,pos,e.name);
if (d) {
d["type"] =ts.displayPartsToString(d.displayParts);
d["docComment"]=ts.displayPartsToString(d.documentation);
return d;
} else {
return e;
}} ));
// NOTE: details null for primitive type symbols, see TS #1592
(()=>{ // filter entries by prefix, determined by pos
var languageVersion = this.compilerOptions.target;
var source = this.fileCache.getScriptInfo(file).content;
var startPos = pos;
var idPart = p => /[0-9a-zA-Z_$]/.test(source[p])
|| ts.isIdentifierPart(source.charCodeAt(p),languageVersion);
var idStart = p => /[a-zA-Z_$]/.test(source[p])
|| ts.isIdentifierStart(source.charCodeAt(p),languageVersion);
while ((--startPos>=0) && idPart(startPos) );
if ((++startPos < pos) && idStart(startPos)) {
var prefix = source.slice(startPos,pos);
info["prefix"] = prefix;
var len = prefix.length;
info.entries = info.entries.filter( e => e.name.substr(0,len)===prefix );
}
})();
}
this.output(info,["displayParts","documentation","sortText"]);
} else if (m = match(cmd,/^update( nocheck)? (\d+)( (\d+)-(\d+))? (.*)$/)) { // send non-saved source
file = resolvePath(m[6]);
source = this.ls.getSourceFile(file);
script = this.fileCache.getScriptInfo(file);
added = !script;
range = !!m[3]
check = !m[1]
if (!added || !range) {
collecting = parseInt(m[2]);
on_collected_callback = () => {
if (!range) {
this.fileCache.updateScript(file,lines.join(EOL));
} else {
var startLine = parseInt(m[4]);
var endLine = parseInt(m[5]);
var maxLines = source.getLineStarts().length;
var startPos = startLine<=maxLines
? (startLine<1 ? 0 : this.fileCache.lineColToPosition(file,startLine,1))
: script.content.length;
var endPos = endLine<maxLines
? (endLine<1 ? 0 : this.fileCache.lineColToPosition(file,endLine+1,1)-1) //??CHECK
: script.content.length;
this.fileCache.editScript(file, startPos, endPos, lines.join(EOL));
}
var syn:number,sem:number;
if (check) {
syn = this.ls.getSyntacticDiagnostics(file).length;
sem = this.ls.getSemanticDiagnostics(file).length;
}
on_collected_callback = undefined;
lines = [];
this.outputJSON((added ? '"added ' : '"updated ')
+(range ? 'lines'+m[3]+' in ' : '')
+file+(check ? ', ('+syn+'/'+sem+') errors' : '')+'"');
};
} else {
this.outputJSON('"cannot update line range in new file"');
}
} else if (m = match(cmd,/^showErrors$/)) { // get processing errors
info = this.ls.getProgram().getGlobalDiagnostics()
.concat(this.getErrors())
.map( d => {
if (d.file) {
var file = resolvePath(d.file.fileName);
var lc = this.fileCache.positionToLineCol(file,d.start);
var len = this.fileCache.getScriptInfo(file).content.length;
var end = Math.min(len,d.start+d.length);
// NOTE: clamped to end of file (#11)
var lc2 = this.fileCache.positionToLineCol(file,end);
return {
file: file,
start: {line: lc.line, character: lc.character},
end: {line: lc2.line, character: lc2.character},
text: this.messageChain(d.messageText).join(EOL),
code: d.code,
phase: d["phase"],
category: ts.DiagnosticCategory[d.category]
};
} else { // global diagnostics have no file
return {
text: this.messageChain(d.messageText).join(EOL),
code: d.code,
phase: d["phase"],
category: ts.DiagnosticCategory[d.category]
};
}
}
);
this.output(info);
} else if (m = match(cmd,/^files$/)) { // list files in project
info = this.lsHost.getScriptFileNames(); // TODO: files are pre-resolved
this.output(info);
} else if (m = match(cmd,/^lastError(Dump)?$/)) { // debugging only
if (this.lastError)
if (m[1]) // commandline use
console.log(JSON.parse(this.lastError).stack);
else
this.outputJSON(this.lastError);
else
this.outputJSON('"no last error"');
} else if (m = match(cmd,/^dump (\S+) (.*)$/)) { // debugging only
(()=>{
var dump = m[1];
var file = resolvePath(m[2]);
var sourceText = this.fileCache.getScriptInfo(file).content;
if (dump==="-") { // to console
console.log('dumping '+file);
console.log(sourceText);
} else { // to file
ts.sys.writeFile(dump,sourceText,false);
this.outputJSON('"dumped '+file+' to '+dump+'"');
}
})();
} else if (m = match(cmd,/^reload$/)) { // reload current project
// TODO: keep updated (in-memory-only) files?
this.setup(this.rootFiles,this.compilerOptions);
this.outputJSON(this.listeningMessage('reloaded'));
} else if (m = match(cmd,/^quit$/)) {
rl.close();
} else if (m = match(cmd,/^prettyJSON (true|false)$/)) { // useful for debugging
this.prettyJSON = m[1]==='true';
this.outputJSON('"pretty JSON: '+this.prettyJSON+'"');
} else if (m = match(cmd,/^help$/)) {
console.log(Object.keys(commands).join(EOL));
} else {
this.outputJSON('"TSS command syntax error: '+cmd+'"');
}
} catch(e) {
this.lastError = (JSON.stringify({msg:e.toString(),stack:e.stack})).trim();
this.outputJSON('"TSS command processing error: '+e+'"');
}
}).on('close', () => {
this.outputJSON('"TSS closing"');
});
this.outputJSON(this.listeningMessage('loaded'));
}
private listeningMessage(prefix) {
var count = this.rootFiles.length-1;
var more = count>0 ? ' (+'+count+' more)' : '';
return '"'+prefix+' '+this.rootFiles[0]+more+', TSS listening.."';
}
}
function extend(o1,o2) {
var o = {};
for(var p in o1) { o[p] = o1[p] }
for(var p in o2) { if(!(p in o)) o[p] = o2[p] }
return o;
}
var fileNames;
var configFile, configObject, configObjectParsed;
// NOTE: partial options support only
var commandLine = ts.parseCommandLine(ts.sys.args);
if (commandLine.options.version) {
console.log(require("../package.json").version);
process.exit(0);
}
if (commandLine.fileNames.length>0) {
fileNames = commandLine.fileNames;
} else if (commandLine.options.project) {
configFile = path.join(commandLine.options.project,"tsconfig.json");
} else {
configFile = ts.findConfigFile(path.normalize(ts.sys.getCurrentDirectory()),ts.sys.fileExists);
}
var options;
if (configFile) {
configObject = ts.readConfigFile(configFile,ts.sys.readFile);
if (!configObject) {
console.error("can't read tsconfig.json at",configFile);
process.exit(1);
}
configObjectParsed = ts.parseJsonConfigFileContent(configObject,ts.sys,path.dirname(configFile));
if (configObjectParsed.errors.length>0) {
console.error(configObjectParsed.errors);
process.exit(1);
}
fileNames = configObjectParsed.fileNames;
options = extend(commandLine.options,configObjectParsed.options);
} else {
options = extend(commandLine.options,ts.getDefaultCompilerOptions());
}
if (!fileNames) {
console.error("can't find project root");
console.error("please specify root source file");
console.error(" or --project directory (containing a tsconfig.json)");
process.exit(1);
}
var tss = new TSS();
try {
tss.setup(fileNames,options);
tss.listen();
} catch (e) {
console.error(e.toString());
process.exit(1);
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.