text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { ConnectionClosed, DataReceived } from "./Common"; import { DefaultHttpClient, HttpClient } from "./HttpClient"; import { IConnection } from "./IConnection"; import { ILogger, LogLevel } from "./ILogger"; import { LoggerFactory } from "./Loggers"; import { ITransport, LongPollingTransport, ServerSentEventsTransport, TransferFormat, TransportType, WebSocketTransport } from "./Transports"; import { Arg } from "./Utils"; export interface IHttpConnectionOptions { httpClient?: HttpClient; transport?: TransportType | ITransport; logger?: ILogger | LogLevel; accessTokenFactory?: () => string; } const enum ConnectionState { Connecting, Connected, Disconnected, } interface INegotiateResponse { connectionId: string; availableTransports: IAvailableTransport[]; } interface IAvailableTransport { transport: keyof typeof TransportType; transferFormats: Array<keyof typeof TransferFormat>; } export class HttpConnection implements IConnection { private connectionState: ConnectionState; private baseUrl: string; private url: string; private readonly httpClient: HttpClient; private readonly logger: ILogger; private readonly options: IHttpConnectionOptions; private transport: ITransport; private connectionId: string; private startPromise: Promise<void>; public readonly features: any = {}; constructor(url: string, options: IHttpConnectionOptions = {}) { Arg.isRequired(url, "url"); this.logger = LoggerFactory.createLogger(options.logger); this.baseUrl = this.resolveUrl(url); options = options || {}; options.accessTokenFactory = options.accessTokenFactory || (() => null); this.httpClient = options.httpClient || new DefaultHttpClient(this.logger); this.connectionState = ConnectionState.Disconnected; this.options = options; } public start(transferFormat: TransferFormat): Promise<void> { Arg.isRequired(transferFormat, "transferFormat"); Arg.isIn(transferFormat, TransferFormat, "transferFormat"); this.logger.log(LogLevel.Trace, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`); if (this.connectionState !== ConnectionState.Disconnected) { return Promise.reject(new Error("Cannot start a connection that is not in the 'Disconnected' state.")); } this.connectionState = ConnectionState.Connecting; this.startPromise = this.startInternal(transferFormat); return this.startPromise; } private async startInternal(transferFormat: TransferFormat): Promise<void> { try { if (this.options.transport === TransportType.WebSockets) { // No need to add a connection ID in this case this.url = this.baseUrl; this.transport = this.constructTransport(TransportType.WebSockets); // We should just call connect directly in this case. // No fallback or negotiate in this case. await this.transport.connect(this.url, transferFormat, this); } else { const token = this.options.accessTokenFactory(); let headers; if (token) { headers = { ["Authorization"]: `Bearer ${token}`, }; } const negotiateResponse = await this.getNegotiationResponse(headers); // the user tries to stop the the connection when it is being started if (this.connectionState === ConnectionState.Disconnected) { return; } await this.createTransport(this.options.transport, negotiateResponse, transferFormat, headers); } this.transport.onreceive = this.onreceive; this.transport.onclose = (e) => this.stopConnection(true, e); // only change the state if we were connecting to not overwrite // the state if the connection is already marked as Disconnected this.changeState(ConnectionState.Connecting, ConnectionState.Connected); } catch (e) { this.logger.log(LogLevel.Error, "Failed to start the connection: " + e); this.connectionState = ConnectionState.Disconnected; this.transport = null; throw e; } } private async getNegotiationResponse(headers: any): Promise<INegotiateResponse> { const negotiateUrl = this.resolveNegotiateUrl(this.baseUrl); this.logger.log(LogLevel.Trace, `Sending negotiation request: ${negotiateUrl}`); try { const response = await this.httpClient.post(negotiateUrl, { content: "", headers, }); return JSON.parse(response.content as string); } catch (e) { this.logger.log(LogLevel.Error, "Failed to complete negotiation with the server: " + e); throw e; } } private updateConnectionId(negotiateResponse: INegotiateResponse) { this.connectionId = negotiateResponse.connectionId; this.url = this.baseUrl + (this.baseUrl.indexOf("?") === -1 ? "?" : "&") + `id=${this.connectionId}`; } private async createTransport(requestedTransport: TransportType | ITransport, negotiateResponse: INegotiateResponse, requestedTransferFormat: TransferFormat, headers: any): Promise<void> { this.updateConnectionId(negotiateResponse); if (this.isITransport(requestedTransport)) { this.logger.log(LogLevel.Trace, "Connection was provided an instance of ITransport, using that directly."); this.transport = requestedTransport; await this.transport.connect(this.url, requestedTransferFormat, this); // only change the state if we were connecting to not overwrite // the state if the connection is already marked as Disconnected this.changeState(ConnectionState.Connecting, ConnectionState.Connected); return; } const transports = negotiateResponse.availableTransports; for (const endpoint of transports) { this.connectionState = ConnectionState.Connecting; const transport = this.resolveTransport(endpoint, requestedTransport, requestedTransferFormat); if (typeof transport === "number") { this.transport = this.constructTransport(transport); if (negotiateResponse.connectionId === null) { negotiateResponse = await this.getNegotiationResponse(headers); this.updateConnectionId(negotiateResponse); } try { await this.transport.connect(this.url, requestedTransferFormat, this); this.changeState(ConnectionState.Connecting, ConnectionState.Connected); return; } catch (ex) { this.logger.log(LogLevel.Error, `Failed to start the transport '${TransportType[transport]}': ${ex}`); this.connectionState = ConnectionState.Disconnected; negotiateResponse.connectionId = null; } } } throw new Error("Unable to initialize any of the available transports."); } private constructTransport(transport: TransportType) { switch (transport) { case TransportType.WebSockets: return new WebSocketTransport(this.options.accessTokenFactory, this.logger); case TransportType.ServerSentEvents: return new ServerSentEventsTransport(this.httpClient, this.options.accessTokenFactory, this.logger); case TransportType.LongPolling: return new LongPollingTransport(this.httpClient, this.options.accessTokenFactory, this.logger); default: throw new Error(`Unknown transport: ${transport}.`); } } private resolveTransport(endpoint: IAvailableTransport, requestedTransport: TransportType, requestedTransferFormat: TransferFormat): TransportType | null { const transport = TransportType[endpoint.transport]; if (transport === null || transport === undefined) { this.logger.log(LogLevel.Trace, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`); } else { const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]); if (!requestedTransport || transport === requestedTransport) { if (transferFormats.indexOf(requestedTransferFormat) >= 0) { if ((transport === TransportType.WebSockets && typeof WebSocket === "undefined") || (transport === TransportType.ServerSentEvents && typeof EventSource === "undefined")) { this.logger.log(LogLevel.Trace, `Skipping transport '${TransportType[transport]}' because it is not supported in your environment.'`); } else { this.logger.log(LogLevel.Trace, `Selecting transport '${TransportType[transport]}'`); return transport; } } else { this.logger.log(LogLevel.Trace, `Skipping transport '${TransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`); } } else { this.logger.log(LogLevel.Trace, `Skipping transport '${TransportType[transport]}' because it was disabled by the client.`); } } return null; } private isITransport(transport: any): transport is ITransport { return typeof (transport) === "object" && "connect" in transport; } private changeState(from: ConnectionState, to: ConnectionState): boolean { if (this.connectionState === from) { this.connectionState = to; return true; } return false; } public send(data: any): Promise<void> { if (this.connectionState !== ConnectionState.Connected) { throw new Error("Cannot send data if the connection is not in the 'Connected' State."); } return this.transport.send(data); } public async stop(error?: Error): Promise<void> { const previousState = this.connectionState; this.connectionState = ConnectionState.Disconnected; try { await this.startPromise; } catch (e) { // this exception is returned to the user as a rejected Promise from the start method } this.stopConnection(/*raiseClosed*/ previousState === ConnectionState.Connected, error); } private stopConnection(raiseClosed: boolean, error?: Error) { if (this.transport) { this.transport.stop(); this.transport = null; } if (error) { this.logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`); } else { this.logger.log(LogLevel.Information, "Connection disconnected."); } this.connectionState = ConnectionState.Disconnected; if (raiseClosed && this.onclose) { this.onclose(error); } } private resolveUrl(url: string): string { // startsWith is not supported in IE if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) { return url; } if (typeof window === "undefined" || !window || !window.document) { throw new Error(`Cannot resolve '${url}'.`); } const parser = window.document.createElement("a"); parser.href = url; const baseUrl = (!parser.protocol || parser.protocol === ":") ? `${window.document.location.protocol}//${(parser.host || window.document.location.host)}` : `${parser.protocol}//${parser.host}`; if (!url || url[0] !== "/") { url = "/" + url; } const normalizedUrl = baseUrl + url; this.logger.log(LogLevel.Information, `Normalizing '${url}' to '${normalizedUrl}'.`); return normalizedUrl; } private resolveNegotiateUrl(url: string): string { const index = url.indexOf("?"); let negotiateUrl = url.substring(0, index === -1 ? url.length : index); if (negotiateUrl[negotiateUrl.length - 1] !== "/") { negotiateUrl += "/"; } negotiateUrl += "negotiate"; negotiateUrl += index === -1 ? "" : url.substring(index); return negotiateUrl; } public onreceive: DataReceived; public onclose: ConnectionClosed; }
the_stack
import { ApiBlock, ApiBlockType, ApiCellBlock, ApiKeyValueEntityType, ApiKeyValueSetBlock, ApiLineBlock, ApiPageBlock, ApiRelationshipType, ApiSelectionElementBlock, ApiSelectionStatus, ApiTableBlock, ApiTextType, ApiWordBlock, } from "./api-models/document"; import { ApiDocumentMetadata, ApiResponsePage, ApiResponsePages, ApiResponseWithContent, ApiResultWarning, } from "./api-models/response"; import { ApiObjectWrapper, getIterable, modalAvg } from "./base"; import { BoundingBox, Geometry } from "./geometry"; export class ApiBlockWrapper<T extends ApiBlock> extends ApiObjectWrapper<T> { get id(): string { return this._dict.Id; } get blockType(): ApiBlockType { return this._dict.BlockType; } } // Simple constructor type for TS mixin pattern // eslint-disable-next-line @typescript-eslint/no-explicit-any type Constructor<T> = new (...args: any[]) => T; export class Word extends ApiBlockWrapper<ApiWordBlock> { _geometry: Geometry<ApiWordBlock, Word>; constructor(block: ApiWordBlock) { super(block); this._geometry = new Geometry(block.Geometry, this); } get confidence(): number { return this._dict.Confidence; } set confidence(newVal: number) { this._dict.Confidence = newVal; } get geometry(): Geometry<ApiWordBlock, Word> { return this._geometry; } get text(): string { return this._dict.Text; } get textType(): ApiTextType { return this._dict.TextType; } set textType(newVal: ApiTextType) { this._dict.TextType = newVal; } str(): string { return this.text; } } // eslint-disable-next-line @typescript-eslint/ban-types function WithWords<T extends Constructor<{}>>(SuperClass: T) { return class extends SuperClass { _words: Word[]; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(...args: any[]) { super(...args); this._words = []; } get nWords(): number { return this._words.length; } /** * Iterate through the Words in this object * @example * for (const word of line.iterWords) { * console.log(word.text); * } * @example * [...line.iterWords()].forEach( * (word) => console.log(word.text) * ); */ iterWords(): Iterable<Word> { return getIterable(() => this._words); } listWords(): Word[] { return this._words.slice(); } /** * Get a particular Word from the object by index * @param ix 0-based index in the word list * @throws if the index is out of bounds */ wordAtIndex(ix: number): Word { if (ix < 0 || ix >= this._words.length) { throw new Error(`Word index ${ix} must be >=0 and <${this._words.length}`); } return this._words[ix]; } }; } export class Line extends WithWords(ApiBlockWrapper)<ApiLineBlock> { _geometry: Geometry<ApiLineBlock, Line>; _parentPage: Page; constructor(block: ApiLineBlock, parentPage: Page) { super(block); this._parentPage = parentPage; this._words = []; this._geometry = new Geometry(block.Geometry, this); const parentDocument = parentPage.parentDocument; if (block.Relationships) { block.Relationships.forEach((rs) => { if (rs.Type == ApiRelationshipType.Child) { rs.Ids.forEach((cid) => { const wordBlock = parentDocument.getBlockById(cid); if (!wordBlock) { console.warn(`Document missing word block ${cid} referenced by line ${this.id}`); return; } if (wordBlock.BlockType == ApiBlockType.Word) this._words.push(new Word(wordBlock as ApiWordBlock)); }); } }); } } get confidence(): number { return this._dict.Confidence; } set confidence(newVal: number) { this._dict.Confidence = newVal; } get geometry(): Geometry<ApiLineBlock, Line> { return this._geometry; } get parentPage(): Page { return this._parentPage; } get text(): string { return this._dict.Text; } str(): string { return `Line\n==========\n${this._dict.Text}\nWords\n----------\n${this._words .map((word) => `[${word.str()}]`) .join("")}`; } } export class SelectionElement extends ApiBlockWrapper<ApiSelectionElementBlock> { _geometry: Geometry<ApiSelectionElementBlock, SelectionElement>; constructor(block: ApiSelectionElementBlock) { super(block); this._geometry = new Geometry(block.Geometry, this); } get confidence(): number { return this._dict.Confidence; } set confidence(newVal: number) { this._dict.Confidence = newVal; } get geometry(): Geometry<ApiSelectionElementBlock, SelectionElement> { return this._geometry; } get selectionStatus(): ApiSelectionStatus { return this._dict.SelectionStatus; } set selectionStatus(newVal: ApiSelectionStatus) { this._dict.SelectionStatus = newVal; } } export class FieldKey extends WithWords(ApiBlockWrapper)<ApiKeyValueSetBlock> { _geometry: Geometry<ApiKeyValueSetBlock, FieldKey>; _parentField: Field; constructor(block: ApiKeyValueSetBlock, parentField: Field) { super(block); this._parentField = parentField; this._words = []; this._geometry = new Geometry(block.Geometry, this); let childIds: string[] = []; (block.Relationships || []).forEach((rs) => { if (rs.Type == ApiRelationshipType.Child) { childIds = childIds.concat(rs.Ids); } }); const parentDocument = parentField.parentForm.parentPage.parentDocument; childIds .map((id) => { const block = parentDocument.getBlockById(id); if (!block) { console.warn(`Document missing child block ${id} referenced by field key ${this.id}`); } return block; }) .forEach((block) => { if (!block) return; // Already logged warning above if (block.BlockType == ApiBlockType.Word) { this._words.push(new Word(block)); } }); } get confidence(): number { return this._dict.Confidence; } get geometry(): Geometry<ApiKeyValueSetBlock, FieldKey> { return this._geometry; } get parentField(): Field { return this._parentField; } get text(): string { return this._words.map((w) => w.text).join(" "); } str(): string { return this.text; } } export class FieldValue extends ApiBlockWrapper<ApiKeyValueSetBlock> { _content: Array<SelectionElement | Word>; _geometry: Geometry<ApiKeyValueSetBlock, FieldValue>; _parentField: Field; constructor(valueBlock: ApiKeyValueSetBlock, parentField: Field) { super(valueBlock); this._content = []; this._parentField = parentField; this._geometry = new Geometry(valueBlock.Geometry, this); let childIds: string[] = []; (valueBlock.Relationships || []).forEach((rs) => { if (rs.Type == ApiRelationshipType.Child) { childIds = childIds.concat(rs.Ids); } }); const parentDocument = parentField.parentForm.parentPage.parentDocument; childIds .map((id) => { const block = parentDocument.getBlockById(id); if (!block) { console.warn(`Document missing child block ${id} referenced by field value ${this.id}`); } return block; }) .forEach((block) => { if (!block) return; // Already logged warning above if (block.BlockType == ApiBlockType.Word) { this._content.push(new Word(block)); } else if (block.BlockType == ApiBlockType.SelectionElement) { this._content.push(new SelectionElement(block)); } }); } get confidence(): number { return this._dict.Confidence; } get geometry(): Geometry<ApiKeyValueSetBlock, FieldValue> { return this._geometry; } get parentField(): Field { return this._parentField; } get text(): string { return this._content.map((c) => ("selectionStatus" in c ? c.selectionStatus : c.text)).join(" "); } listContent(): Array<SelectionElement | Word> { return this._content.slice(); } str(): string { return this.text; } } export class Field { _key: FieldKey; _parentForm: Form; _value: FieldValue | null; constructor(keyBlock: ApiKeyValueSetBlock, parentForm: Form) { this._parentForm = parentForm; this._value = null; this._key = new FieldKey(keyBlock, this); let valueBlockIds: string[] = []; (keyBlock.Relationships || []).forEach((rs) => { if (rs.Type == ApiRelationshipType.Value) { valueBlockIds = valueBlockIds.concat(rs.Ids); } }); if (valueBlockIds.length > 1) { const fieldLogName = this._key ? `field '${this._key.text}'` : "unnamed form field"; console.warn( `Got ${valueBlockIds.length} value blocks for ${fieldLogName} (Expected 0-1). Including first only.` ); } if (valueBlockIds.length) { const parentDocument = parentForm.parentPage.parentDocument; const valBlockId = valueBlockIds[0]; const valBlock = parentDocument.getBlockById(valBlockId); if (!valBlock) { console.warn( `Document missing child block ${valBlockId} referenced by value for field key ${this.key.id}` ); } else { this._value = new FieldValue(valBlock as ApiKeyValueSetBlock, this); } } } /** * Return average confidence over whichever of {key, value} are present. */ get confidence(): number { const scores = []; if (this._key) { scores.push(this._key.confidence || 0); } if (this._value) { scores.push(this._value.confidence || 0); } if (scores.length) { return scores.reduce((acc, next) => acc + next, 0) / scores.length; } else { return 0; } } get key(): FieldKey { return this._key; } get parentForm(): Form { return this._parentForm; } get value(): FieldValue | null { return this._value; } str(): string { return `\nField\n==========\nKey: ${this._key ? this._key.str() : ""}\nValue: ${ this._value ? this._value.str() : "" }`; } } export class Form { _fields: Field[]; _fieldsMap: { [keyText: string]: Field }; _parentPage: Page; constructor(keyBlocks: ApiKeyValueSetBlock[], parentPage: Page) { this._fields = []; this._fieldsMap = {}; this._parentPage = parentPage; keyBlocks.forEach((keyBlock) => { const f = new Field(keyBlock, this); this._fields.push(f); const fieldKeyText = f.key.text || ""; if (fieldKeyText) { if (fieldKeyText in this._fieldsMap) { if (f.confidence > this._fieldsMap[fieldKeyText].confidence) { this._fieldsMap[fieldKeyText] = f; } } else { this._fieldsMap[fieldKeyText] = f; } } }); } get nFields(): number { return this._fields.length; } get parentPage(): Page { return this._parentPage; } getFieldByKey(key: string): Field | null { return this._fieldsMap[key] || null; } /** * Iterate through the Fields in the Form. * @param skipFieldsWithoutKey Set `true` to skip fields with no field.key (Included by default) * @example * for (const field of form.iterFields()) { * console.log(field?.key.text); * } * @example * const fields = [...form.iterFields()]; */ iterFields(skipFieldsWithoutKey = false): Iterable<Field> { return getIterable(() => this.listFields(skipFieldsWithoutKey)); } /** * List the Fields in the Form. * @param skipFieldsWithoutKey Set `true` to skip fields with no field.key (Included by default) */ listFields(skipFieldsWithoutKey = false): Field[] { return skipFieldsWithoutKey ? this._fields.filter((f) => f.key) : this._fields.slice(); } /** * List the Fields in the Form with key text containing (case-insensitive) `key` * @param key The text to search for in field keys */ searchFieldsByKey(key: string): Field[] { const searchKey = key.toLowerCase(); return this._fields.filter((field) => field.key && field.key.text.toLowerCase().indexOf(searchKey) >= 0); } str(): string { return this._fields.map((f) => f.str()).join("\n"); } } export class Cell extends ApiBlockWrapper<ApiCellBlock> { _geometry: Geometry<ApiCellBlock, Cell>; _content: Array<SelectionElement | Word>; _parentTable: Table; _text: string; constructor(block: ApiCellBlock, parentTable: Table) { super(block); const parentDocument = parentTable.parentPage.parentDocument; this._geometry = new Geometry(block.Geometry, this); this._content = []; this._parentTable = parentTable; this._text = ""; (block.Relationships || []).forEach((rs) => { if (rs.Type == ApiRelationshipType.Child) { rs.Ids.forEach((cid) => { const childBlock = parentDocument.getBlockById(cid); if (!childBlock) { console.warn(`Document missing child block ${cid} referenced by table cell ${this.id}`); return; } const blockType = childBlock.BlockType; if (blockType == ApiBlockType.Word) { const w = new Word(childBlock as ApiWordBlock); this._content.push(w); this._text += w.text + " "; } else if (blockType == ApiBlockType.SelectionElement) { const se = new SelectionElement(childBlock as ApiSelectionElementBlock); this._content.push(se); this._text += se.selectionStatus + ", "; } }); } }); } get columnIndex(): number { return this._dict.ColumnIndex; } get columnSpan(): number { return this._dict.ColumnSpan || 1; } get confidence(): number { return this._dict.Confidence; } set confidence(newVal: number) { this._dict.Confidence = newVal; } get geometry(): Geometry<ApiCellBlock, Cell> { return this._geometry; } get parentTable(): Table { return this._parentTable; } get rowIndex(): number { return this._dict.RowIndex; } get rowSpan(): number { return this._dict.RowSpan || 1; } get text(): string { return this._text; } listContent(): Array<SelectionElement | Word> { return this._content.slice(); } str(): string { return this._text; } } export class Row { _cells: Cell[]; _parentTable: Table; constructor(cells: Cell[] = [], parentTable: Table) { this._cells = cells; this._parentTable = parentTable; } get nCells(): number { return this._cells.length; } get parentTable(): Table { return this._parentTable; } /** * Iterate through the cells in this row * @example * for (const cell of row.iterCells()) { * console.log(cell.text); * } * @example * [...row.iterCells()].forEach( * (cell) => console.log(cell.text) * ); */ iterCells(): Iterable<Cell> { return getIterable(() => this._cells); } listCells(): Cell[] { return this._cells.slice(); } str(): string { return this._cells.map((cell) => `[${cell.str()}]`).join(""); } } export class Table extends ApiBlockWrapper<ApiTableBlock> { _cells: Cell[]; _geometry: Geometry<ApiTableBlock, Table>; _nCols: number; _nRows: number; _parentPage: Page; constructor(block: ApiTableBlock, parentPage: Page) { super(block); this._parentPage = parentPage; this._geometry = new Geometry(block.Geometry, this); const parentDocument = parentPage.parentDocument; this._cells = ([] as Cell[]).concat( ...(block.Relationships || []) .filter((rs) => rs.Type == ApiRelationshipType.Child) .map( (rs) => rs.Ids.map((cid) => { const cellBlock = parentDocument.getBlockById(cid); if (!cellBlock) { console.warn(`Document missing child block ${cid} referenced by table cell ${this.id}`); return; } return new Cell(cellBlock as ApiCellBlock, this); }).filter((cell) => cell) as Cell[] ) ); // This indexing could be moved to a utility function if supporting more mutation operations in future: this._cells.sort((a, b) => a.rowIndex - b.rowIndex || a.columnIndex - b.columnIndex); this._nCols = this._cells.reduce((acc, next) => Math.max(acc, next.columnIndex + next.columnSpan - 1), 0); this._nRows = this._cells.reduce((acc, next) => Math.max(acc, next.rowIndex + next.rowSpan - 1), 0); } /** * Get the Cell at a particular Y, X coordinate in the table. * @param rowIndex 1-based index of the target row in the table * @param columnIndex 1-based index of the target column in the table * @param strict Set `true` to exclude cells rowspan/colspan cells which don't *start* at the target indices. * @returns Cell at the specified row & column, or undefined if none is present. */ cellAt(rowIndex: number, columnIndex: number, strict = false): Cell | undefined { if (strict) { return this._cells.find((c) => c.columnIndex === columnIndex && c.rowIndex === rowIndex); } else { return this._cells.find( (c) => c.columnIndex <= columnIndex && c.columnIndex + c.columnSpan > columnIndex && c.rowIndex <= rowIndex && c.rowIndex + c.rowSpan > rowIndex ); } } /** * List the cells at a particular {row, column, or combination} in the table * @param rowIndex 1-based index of the target row in the table * @param columnIndex 1-based index of the target column in the table * @param strict Set `true` to exclude cells rowspan/colspan cells which don't *start* at the target indices. * @returns Cell at the specified row & column, or undefined if none is present. */ cellsAt(rowIndex: number | null, columnIndex: number | null, strict = false): Cell[] { return this._cells.filter( (c) => (rowIndex == null || (strict ? c.rowIndex === rowIndex : c.rowIndex <= rowIndex && c.rowIndex + c.rowSpan > rowIndex)) && (columnIndex == null || (strict ? c.columnIndex === columnIndex : c.columnIndex <= columnIndex && c.columnIndex + c.columnSpan > columnIndex)) ); } /** * Iterate through the rows of the table * @param repeatMultiRowCells Set `true` to include rowspan>1 cells in every `Row` they intersect with. * @example * for (const row of table.iterRows()) { * for (const cell of row.iterCells()) { * console.log(cell.text); * } * } * @example * [...table.iterRows()].forEach( * (row) => [...row.iterCells()].forEach( * (cell) => console.log(cell.text) * ) * ); */ iterRows(repeatMultiRowCells = false): Iterable<Row> { const getIterator = (): Iterator<Row> => { let ixRow = 0; return { next: (): IteratorResult<Row> => { return ixRow < this._nRows ? { done: false, value: new Row(this.cellsAt(++ixRow, null, !repeatMultiRowCells), this), } : { done: true, value: undefined, }; }, }; }; return { [Symbol.iterator]: getIterator, }; } /** * List the rows of the table * @param repeatMultiRowCells Set `true` to include rowspan>1 cells in every `Row` they intersect with. */ listRows(repeatMultiRowCells = false): Row[] { return [...Array(this._nRows).keys()].map( (ixRow) => new Row(this.cellsAt(++ixRow, null, !repeatMultiRowCells), this) ); } get confidence(): number { return this._dict.Confidence; } set confidence(newVal: number) { this._dict.Confidence = newVal; } get geometry(): Geometry<ApiTableBlock, Table> { return this._geometry; } get nCells(): number { return this._cells.length; } get nColumns(): number { return this._nCols; } get nRows(): number { return this._nRows; } get parentPage(): Page { return this._parentPage; } str(): string { return ( "Table\n==========\n" + this.listRows() .map((row) => `Row\n==========\n${row.str()}`) .join("\n") ); } } export class Page extends ApiBlockWrapper<ApiPageBlock> { _blocks: ApiBlock[]; _content: Array<Line | Table | Field>; _form: Form; _geometry: Geometry<ApiPageBlock, Page>; _lines: Line[]; _parentDocument: TextractDocument; _tables: Table[]; constructor(pageBlock: ApiPageBlock, blocks: ApiBlock[], parentDocument: TextractDocument) { super(pageBlock); this._blocks = blocks; this._parentDocument = parentDocument; this._geometry = new Geometry(pageBlock.Geometry, this); // Placeholders pre-parsing to keep TypeScript happy: this._content = []; this._lines = []; this._tables = []; this._form = new Form([], this); // Parse the content: this._parse(blocks); } _parse(blocks: ApiBlock[]): void { this._content = []; this._lines = []; this._tables = []; const formKeyBlocks: ApiKeyValueSetBlock[] = []; blocks.forEach((item) => { if (item.BlockType == ApiBlockType.Line) { const l = new Line(item, this); this._lines.push(l); this._content.push(l); } else if (item.BlockType == ApiBlockType.Table) { const t = new Table(item, this); this._tables.push(t); this._content.push(t); } else if (item.BlockType == ApiBlockType.KeyValueSet) { if (item.EntityTypes.indexOf(ApiKeyValueEntityType.Key) >= 0) { formKeyBlocks.push(item); } } }); this._form = new Form(formKeyBlocks, this); } /** * Calculate the most common orientation (in whole degrees) of 'WORD' content in the page. */ getModalWordOrientationDegrees(): number | null { const wordDegreesByLine = this.listLines().map((line) => line.listWords().map((word) => word.geometry.orientationDegrees()) ); const wordDegrees = ([] as Array<number | null>) .concat(...wordDegreesByLine) .filter((n) => n != null) as number[]; return modalAvg(wordDegrees.map((n) => Math.round(n))); } /** * List lines in reading order, grouped by 'cluster' (heuristically, almost a paragraph) */ getLineClustersInReadingOrder(): Line[][] { const colBoxes: BoundingBox<ApiLineBlock, ApiObjectWrapper<ApiLineBlock>>[] = []; const colLines: Line[][] = []; const colTotalLineHeight: number[] = []; const lineHCenters = this._lines.map((l) => l.geometry.boundingBox.hCenter); this._lines.forEach((line, ixLine) => { const lineBox = line.geometry.boundingBox; const lineHCenter = lineHCenters[ixLine]; let ixColumn: number | null = null; for (let ixCol = 0; ixCol < colBoxes.length; ++ixCol) { const colBox = colBoxes[ixCol]; const colHCenter = colBox.hCenter; const newTotalLineHeight = colTotalLineHeight[ixCol] + lineBox.height; const newAvgLineHeight = newTotalLineHeight / (colLines[ixCol].length + 1); // These distances can't both be >0, and will both be <0 if they overlap const vDist = Math.max(0, lineBox.top - colBox.bottom, colBox.top - lineBox.bottom); if ( ((lineHCenter > colBox.left && lineHCenter < colBox.right) || (colHCenter > lineBox.left && colHCenter < lineBox.right)) && vDist < newAvgLineHeight && Math.abs((newAvgLineHeight - lineBox.height) / newAvgLineHeight) < 0.3 ) { ixColumn = ixCol; colBoxes[ixCol] = colBox.union(lineBox); colLines[ixCol].push(line); colTotalLineHeight[ixCol] = newTotalLineHeight; break; } } if (ixColumn == null) { colBoxes.push(new BoundingBox(lineBox.dict)); colLines.push([line]); colTotalLineHeight.push(lineBox.height); } }); return colLines; } getTextInReadingOrder(): string { return this.getLineClustersInReadingOrder() .map((lines) => lines.map((l) => l.text).join("\n")) .join("\n\n"); } /** * Iterate through the lines on the page in raw Textract order * * For reading order, see getLineClustersInReadingOrder instead. * * @example * for (const line of page.iterLines()) { * console.log(line.text); * } */ iterLines(): Iterable<Line> { return getIterable(() => this._lines); } /** * Iterate through the tables on the page * @example * for (const table of page.iterTables()) { * console.log(table.str()); * } * @example * const tables = [...page.iterTables()]; */ iterTables(): Iterable<Table> { return getIterable(() => this._tables); } lineAtIndex(ix: number): Line { if (ix < 0 || ix >= this._lines.length) { throw new Error(`Line index ${ix} must be >=0 and <${this._lines.length}`); } return this._lines[ix]; } listBlocks(): ApiBlock[] { return this._blocks.slice(); } listLines(): Line[] { return this._lines.slice(); } listTables(): Table[] { return this._tables.slice(); } tableAtIndex(ix: number): Table { if (ix < 0 || ix >= this._tables.length) { throw new Error(`Table index ${ix} must be >=0 and <${this._tables.length}`); } return this._tables[ix]; } get form(): Form { return this._form; } get geometry(): Geometry<ApiPageBlock, Page> { return this._geometry; } get nLines(): number { return this._lines.length; } get nTables(): number { return this._tables.length; } get parentDocument(): TextractDocument { return this._parentDocument; } get text(): string { return this._lines.map((l) => l.text).join("\n"); } str(): string { return `Page\n==========\n${this._content.join("\n")}\n`; } } export class TextractDocument extends ApiObjectWrapper<ApiResponsePage & ApiResponseWithContent> { _blockMap: { [blockId: string]: ApiBlock }; _pages: Page[]; /** * @param textractResults A (parsed) Textract response JSON, or an array of multiple from the same job */ constructor(textractResults: ApiResponsePage | ApiResponsePages) { let dict; if (Array.isArray(textractResults)) { dict = TextractDocument._consolidateMultipleResponses(textractResults); } else { if (!("Blocks" in textractResults && textractResults.Blocks?.length)) { throw new Error(`Provided Textract JSON has no content! (.Blocks array)`); } dict = textractResults; } super(dict); if ("NextToken" in this._dict) { console.warn(`Provided Textract JSON contains a NextToken: Content may be truncated!`); } this._blockMap = {}; this._pages = []; this._parse(); } _parse(): void { this._blockMap = this._dict.Blocks.reduce((acc, next) => { acc[next.Id] = next; return acc; }, {} as { [blockId: string]: ApiBlock }); let currentPageBlock: ApiPageBlock | null = null; let currentPageContent: ApiBlock[] = []; this._pages = []; this._dict.Blocks.forEach((block) => { if (block.BlockType == ApiBlockType.Page) { if (currentPageBlock) { this._pages.push(new Page(currentPageBlock, currentPageContent, this)); } currentPageBlock = block; currentPageContent = [block]; } else { currentPageContent.push(block); } }); if (currentPageBlock) { this._pages.push(new Page(currentPageBlock, currentPageContent, this)); } } static _consolidateMultipleResponses( textractResultArray: ApiResponsePages ): ApiResponsePage & ApiResponseWithContent { if (!textractResultArray?.length) throw new Error(`Input Textract Results list empty!`); let nPages = 0; const docMetadata: ApiDocumentMetadata = { Pages: 0 }; let blocks: ApiBlock[] = []; let modelVersion = ""; let analysisType: null | "AnalyzeDocument" | "DetectText" = null; let jobStatus: null | "IN_PROGRESS" | "SUCCEEDED" | "PARTIAL_SUCCESS" = null; let jobStatusMessage: null | string = null; let warnings: null | ApiResultWarning[] = null; for (const textractResult of textractResultArray) { if ("Blocks" in textractResult && textractResult.Blocks) { blocks = blocks.concat(textractResult.Blocks); } else { console.warn("Found Textract response with no content"); } if ("DocumentMetadata" in textractResult) { Object.assign(docMetadata, textractResult["DocumentMetadata"]); nPages = Math.max(nPages, textractResult.DocumentMetadata.Pages); } if ("AnalyzeDocumentModelVersion" in textractResult) { if (analysisType && analysisType !== "AnalyzeDocument") { throw new Error("Inconsistent textractResults contain both AnalyzeDocument and DetectText results"); } analysisType = "AnalyzeDocument"; if (modelVersion && modelVersion !== textractResult.AnalyzeDocumentModelVersion) { console.warn( `Inconsistent Textract model versions ${modelVersion} and ${textractResult.AnalyzeDocumentModelVersion}: Ignoring latter` ); } else { modelVersion = textractResult.AnalyzeDocumentModelVersion; } } if ("DetectDocumentTextModelVersion" in textractResult) { if (analysisType && analysisType !== "DetectText") { throw new Error("Inconsistent textractResults contain both AnalyzeDocument and DetectText results"); } analysisType = "DetectText"; if (modelVersion && modelVersion !== textractResult.DetectDocumentTextModelVersion) { console.warn( `Inconsistent Textract model versions ${modelVersion} and ${textractResult.DetectDocumentTextModelVersion}: Ignoring latter` ); } else { modelVersion = textractResult.DetectDocumentTextModelVersion; } } if ("JobStatus" in textractResult) { if ( textractResult.JobStatus == "FAILED" || (textractResult.JobStatus || "").toLocaleUpperCase().indexOf("FAIL") >= 0 ) { throw new Error(`Textract results contain failed job of status ${textractResult.JobStatus}`); } else if (jobStatus && jobStatus !== textractResult.JobStatus) { throw new Error( `Textract results inconsistent JobStatus values ${jobStatus}, ${textractResult.JobStatus}` ); } jobStatus = textractResult.JobStatus; } if ("StatusMessage" in textractResult && textractResult.StatusMessage) { if (jobStatusMessage && textractResult.StatusMessage !== jobStatusMessage) { console.warn(`Multiple StatusMessages in Textract results - keeping longest`); if (textractResult.StatusMessage.length > jobStatusMessage.length) { jobStatusMessage = textractResult.StatusMessage; } } else { jobStatusMessage = textractResult.StatusMessage; } } if ("Warnings" in textractResult && textractResult.Warnings) { warnings = warnings ? warnings.concat(textractResult.Warnings) : textractResult.Warnings; } } const content: ApiResponseWithContent = { DocumentMetadata: docMetadata, Blocks: blocks, }; const modelVersionFields = analysisType == "AnalyzeDocument" ? { AnalyzeDocumentModelVersion: modelVersion } : analysisType == "DetectText" ? { DetectDocumentTextModelVersion: modelVersion } : { AnalyzeDocumentModelVersion: modelVersion || "Unknown" }; const jobStatusFields = jobStatus ? { JobStatus: jobStatus } : {}; const statusMessageFields = jobStatusMessage ? { StatusMessage: jobStatusMessage } : {}; const warningFields = warnings ? { ArfBarf: warnings } : {}; return { ...content, ...modelVersionFields, ...jobStatusFields, ...statusMessageFields, ...warningFields, }; } get nPages(): number { return this._pages.length; } getBlockById(blockId: string): ApiBlock | undefined { return this._blockMap && this._blockMap[blockId]; } /** * Iterate through the pages of the document * @example * for (const page of doc.iterPages()) { * console.log(page.str()); * } * @example * const pages = [...doc.iterPages()]; */ iterPages(): Iterable<Page> { return getIterable(() => this._pages); } listBlocks(): ApiBlock[] { return this._dict.Blocks.slice(); } listPages(): Page[] { return this._pages.slice(); } pageNumber(pageNum: number): Page { if (!(pageNum >= 1 && pageNum <= this._pages.length)) { throw new Error(`pageNum ${pageNum} must be between 1 and ${this._pages.length}`); } return this._pages[pageNum - 1]; } str(): string { return `\nDocument\n==========\n${this._pages.map((p) => p.str()).join("\n\n")}\n\n`; } }
the_stack
import { floorMod } from './utils'; import Vector from './Vector'; export interface IField { xmin: number; // 一般格点数据是按照矩形范围来切割,所以定义其经纬度范围 ymin: number; xmax: number; ymax: number; deltaX: number; // x(经度)增量 deltaY: number; // y(维度)增量 cols: number; // 列(可由 `(xmax - xmin) / deltaX` 得到) rows: number; // 行 us: number[]; // U分量 vs: number[]; // V分量 wrappedX?: boolean; // 当数据范围时按照 [0, 360] 时需要对x方向进行切割转换为 [-180, 180] } export interface IPosition { age?: number; x?: number; y?: number; xt?: number; yt?: number; m?: number; } export default class Field { private readonly xmin: number; private readonly xmax: number; private readonly ymin: number; private readonly ymax: number; private readonly cols: number; private readonly rows: number; private readonly us: number[]; private readonly vs: number[]; private readonly isContinuous: boolean; private readonly deltaY: number; private readonly deltaX: number; private readonly wrappedX: undefined | boolean; private readonly isFields: boolean; public grid: (Vector | null)[][]; public range: (number | undefined)[] | undefined; constructor(params: IField) { this.grid = []; this.xmin = params.xmin; this.xmax = params.xmax; this.ymin = params.ymin; this.ymax = params.ymax; this.cols = params.cols; // 列数 this.rows = params.rows; // 行数 this.us = params.us; // this.vs = params.vs; this.deltaX = params.deltaX; // x 方向增量 this.deltaY = params.deltaY; // y方向增量 if (this.deltaY < 0 && this.ymin < this.ymax) { console.warn('[wind-core]: The data is flipY'); } else { this.ymin = Math.min(params.ymax, params.ymin); this.ymax = Math.max(params.ymax, params.ymin); } this.isFields = true; const cols = Math.ceil((this.xmax - this.xmin) / params.deltaX); // 列 const rows = Math.ceil((this.ymax - this.ymin) / params.deltaY); // 行 if (cols !== this.cols || rows !== this.rows) { console.warn('[wind-core]: The data grid not equal'); } // Math.floor(ni * Δλ) >= 360; // lon lat 经度 纬度 this.isContinuous = Math.floor(this.cols * params.deltaX) >= 360; this.wrappedX = 'wrappedX' in params ? params.wrappedX : this.xmax > 180; // [0, 360] --> [-180, 180]; this.grid = this.buildGrid(); this.range = this.calculateRange(); } // from https://github.com/sakitam-fdd/wind-layer/blob/95368f9433/src/windy/windy.js#L110 public buildGrid(): (Vector | null)[][] { let grid = []; let p = 0; const { rows, cols, us, vs } = this; for (let j = 0; j < rows; j++) { const row = []; for (let i = 0; i < cols; i++, p++) { let u = us[p]; let v = vs[p]; let valid = this.isValid(u) && this.isValid(v); row[i] = valid ? new Vector(u, v) : null; } if (this.isContinuous) { row.push(row[0]); } grid[j] = row; } return grid; } public release() { this.grid = []; } /** * grib data extent * 格点数据范围 */ public extent() { return [ this.xmin, this.ymin, this.xmax, this.ymax, ] } /** * Bilinear interpolation for Vector * 针对向量进行双线性插值 * https://en.wikipedia.org/wiki/Bilinear_interpolation * @param {Number} x * @param {Number} y * @param {Number[]} g00 * @param {Number[]} g10 * @param {Number[]} g01 * @param {Number[]} g11 * @returns {Vector} */ private bilinearInterpolateVector( x: number, y: number, g00: { u: number; v: number; }, g10: { u: number; v: number; }, g01: { u: number; v: number; }, g11: { u: number; v: number; } ) { const rx = 1 - x; const ry = 1 - y; const a = rx * ry; const b = x * ry; const c = rx * y; const d = x * y; const u = g00.u * a + g10.u * b + g01.u * c + g11.u * d; const v = g00.v * a + g10.v * b + g01.v * c + g11.v * d; return new Vector(u, v); } /** * calculate vector value range */ calculateRange() { if (!this.grid || !this.grid[0]) return; const rows = this.grid.length as number; const cols = this.grid[0].length as number; // const vectors = []; let min; let max; // @from: https://stackoverflow.com/questions/13544476/how-to-find-max-and-min-in-array-using-minimum-comparisons for (let j = 0; j < rows; j++) { for (let i = 0; i < cols; i++) { const vec = this.grid[j][i]; if (vec !== null) { const val = vec.m || vec.magnitude(); // vectors.push(); if (min === undefined) { min = val; } else if (max === undefined) { max = val; // update min max // 1. Pick 2 elements(a, b), compare them. (say a > b) min = Math.min(min, max); max = Math.max(min, max); } else { // 2. Update min by comparing (min, b) // 3. Update max by comparing (max, a) min = Math.min(val, min); max = Math.max(val, max); } } } } return [min, max]; } /** * 检查 uv是否合法 * @param x * @private */ public isValid(x: any) { return x !== null && x !== undefined; } private getWrappedLongitudes() { let xmin = this.xmin; let xmax = this.xmax; if (this.wrappedX) { if (this.isContinuous) { xmin = -180; xmax = 180; } else { // not sure about this (just one particular case, but others...?) xmax = this.xmax - 360; xmin = this.xmin - 360; /* eslint-disable no-console */ // console.warn(`are these xmin: ${xmin} & xmax: ${xmax} OK?`); // TODO: Better throw an exception on no-controlled situations. /* eslint-enable no-console */ } } return [xmin, xmax]; } public contains(lon: number, lat: number) { const [xmin, xmax] = this.getWrappedLongitudes(); let longitudeIn = lon >= xmin && lon <= xmax; let latitudeIn; if (this.deltaY >= 0) { latitudeIn = lat >= this.ymin && lat <= this.ymax; } else { latitudeIn = lat >= this.ymax && lat <= this.ymin; } return longitudeIn && latitudeIn; } /** * 获取经纬度所在的位置索引 * @param lon * @param lat */ public getDecimalIndexes(lon: number, lat: number) { const i = floorMod(lon - this.xmin, 360) / this.deltaX; // calculate longitude index in wrapped range [0, 360) const j = (this.ymax - lat) / this.deltaY; // calculate latitude index in direction +90 to -90 return [i, j]; } /** * Nearest value at lon-lat coordinates * 线性插值 * @param lon * @param lat */ public valueAt(lon: number, lat: number) { if (!this.contains(lon, lat)) return null; const indexes = this.getDecimalIndexes(lon, lat); let ii = Math.floor(indexes[0]); let jj = Math.floor(indexes[1]); const ci = this.clampColumnIndex(ii); const cj = this.clampRowIndex(jj); return this.valueAtIndexes(ci, cj); } /** * Get interpolated grid value lon-lat coordinates * 双线性插值 * @param lon * @param lat */ public interpolatedValueAt(lon: number, lat: number) { if (!this.contains(lon, lat)) return null; let [i, j] = this.getDecimalIndexes(lon, lat); return this.interpolatePoint(i, j); } public hasValueAt(lon: number, lat: number) { let value = this.valueAt(lon, lat); return value !== null; } /** * 基于向量的双线性插值 * @param i * @param j */ private interpolatePoint(i: number, j: number) { // 1 2 After converting λ and φ to fractional grid indexes i and j, we find the // fi i ci four points 'G' that enclose point (i, j). These points are at the four // | =1.4 | corners specified by the floor and ceiling of i and j. For example, given // ---G--|---G--- fj 8 i = 1.4 and j = 8.3, the four surrounding grid points are (1, 8), (2, 8), // j ___|_ . | (1, 9) and (2, 9). // =8.3 | | // ---G------G--- cj 9 Note that for wrapped grids, the first column is duplicated as the last // | | column, so the index ci can be used without taking a modulo. const indexes = this.getFourSurroundingIndexes(i, j); const [fi, ci, fj, cj] = indexes; let values = this.getFourSurroundingValues(fi, ci, fj, cj); if (values) { const [g00, g10, g01, g11] = values; // @ts-ignore return this.bilinearInterpolateVector(i - fi, j - fj, g00, g10, g01, g11); } return null; } /** * Check the column index is inside the field, * adjusting to min or max when needed * @private * @param {Number} ii - index * @returns {Number} i - inside the allowed indexes */ private clampColumnIndex(ii: number) { let i = ii; if (ii < 0) { i = 0; } let maxCol = this.cols - 1; if (ii > maxCol) { i = maxCol; } return i; } /** * Check the row index is inside the field, * adjusting to min or max when needed * @private * @param {Number} jj index * @returns {Number} j - inside the allowed indexes */ private clampRowIndex(jj: number) { let j = jj; if (jj < 0) { j = 0; } let maxRow = this.rows - 1; if (jj > maxRow) { j = maxRow; } return j; } /** * from: https://github.com/IHCantabria/Leaflet.CanvasLayer.Field/blob/master/src/Field.js#L252 * 计算索引位置周围的数据 * @private * @param {Number} i - decimal index * @param {Number} j - decimal index * @returns {Array} [fi, ci, fj, cj] */ private getFourSurroundingIndexes(i: number, j: number) { let fi = Math.floor(i); // 左 let ci = fi + 1; // 右 // duplicate colum to simplify interpolation logic (wrapped value) if (this.isContinuous && ci >= this.cols) { ci = 0; } ci = this.clampColumnIndex(ci); let fj = this.clampRowIndex(Math.floor(j)); // 上 纬度方向索引(取整) let cj = this.clampRowIndex(fj + 1); // 下 return [fi, ci, fj, cj]; } /** * from https://github.com/IHCantabria/Leaflet.CanvasLayer.Field/blob/master/src/Field.js#L277 * Get four surrounding values or null if not available, * from 4 integer indexes * @private * @param {Number} fi * @param {Number} ci * @param {Number} fj * @param {Number} cj * @returns {Array} */ private getFourSurroundingValues(fi: number, ci: number, fj: number, cj: number) { let row; if ((row = this.grid[fj])) { const g00 = row[fi]; // << left const g10 = row[ci]; // right >> if ( this.isValid(g00) && this.isValid(g10) && (row = this.grid[cj]) ) { // lower row vv const g01 = row[fi]; // << left const g11 = row[ci]; // right >> if (this.isValid(g01) && this.isValid(g11)) { return [g00, g10, g01, g11]; // 4 values found! } } } return null; } /** * Value for grid indexes * @param {Number} i - column index (integer) * @param {Number} j - row index (integer) * @returns {Vector|Number} */ public valueAtIndexes(i: number, j: number) { return this.grid[j][i]; // <-- j,i !! } /** * Lon-Lat for grid indexes * @param {Number} i - column index (integer) * @param {Number} j - row index (integer) * @returns {Number[]} [lon, lat] */ public lonLatAtIndexes(i: number, j: number) { let lon = this.longitudeAtX(i); let lat = this.latitudeAtY(j); return [lon, lat]; } /** * Longitude for grid-index * @param {Number} i - column index (integer) * @returns {Number} longitude at the center of the cell */ private longitudeAtX(i: number) { let halfXPixel = this.deltaX / 2.0; let lon = this.xmin + halfXPixel + i * this.deltaX; if (this.wrappedX) { lon = lon > 180 ? lon - 360 : lon; } return lon; } /** * Latitude for grid-index * @param {Number} j - row index (integer) * @returns {Number} latitude at the center of the cell */ private latitudeAtY(j: number) { let halfYPixel = this.deltaY / 2.0; return this.ymax - halfYPixel - j * this.deltaY; } /** * 生成粒子位置 * @param o * @param width * @param height * @param unproject */ public randomize(o: IPosition = {}, width: number, height: number, unproject: (...args: any[]) => ([number, number] | null)) { let i = (Math.random() * (width || this.cols)) | 0; let j = (Math.random() * (height || this.rows)) | 0; const coords = unproject([i, j]); if (coords !== null) { o.x = coords[0]; o.y = coords[1]; } else { o.x = this.longitudeAtX(i); o.y = this.latitudeAtY(j); } return o; } /** * check is custom field */ public checkFields() { return this.isFields; } public startBatchInterpolate(width: number, height: number, unproject: (...args: any[]) => ([number, number] | null)) {} }
the_stack
import { hex2string, hex2rgb, EventEmitter, deprecation } from '@pixi/utils'; import { Matrix, Rectangle } from '@pixi/math'; import { MSAA_QUALITY, RENDERER_TYPE } from '@pixi/constants'; import { settings } from '@pixi/settings'; import { RenderTexture } from './renderTexture/RenderTexture'; import type { SCALE_MODES } from '@pixi/constants'; import type { IRenderingContext } from './IRenderingContext'; import type { IRenderableContainer, IRenderableObject } from './IRenderableObject'; const tempMatrix = new Matrix(); export interface IRendererOptions extends GlobalMixins.IRendererOptions { width?: number; height?: number; view?: HTMLCanvasElement; useContextAlpha?: boolean | 'notMultiplied'; /** * Use `backgroundAlpha` instead. * @deprecated */ transparent?: boolean; autoDensity?: boolean; antialias?: boolean; resolution?: number; preserveDrawingBuffer?: boolean; clearBeforeRender?: boolean; backgroundColor?: number; backgroundAlpha?: number; powerPreference?: WebGLPowerPreference; context?: IRenderingContext; } export interface IRendererPlugins { [key: string]: any; } export interface IRendererRenderOptions { renderTexture?: RenderTexture; clear?: boolean; transform?: Matrix; skipUpdateTransform?: boolean; } export interface IGenerateTextureOptions { scaleMode?: SCALE_MODES; resolution?: number; region?: Rectangle; multisample?: MSAA_QUALITY; } /** * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. * * @abstract * @class * @extends PIXI.utils.EventEmitter * @memberof PIXI */ export abstract class AbstractRenderer extends EventEmitter { public resolution: number; public clearBeforeRender?: boolean; public readonly options: IRendererOptions; public readonly type: RENDERER_TYPE; public readonly screen: Rectangle; public readonly view: HTMLCanvasElement; public readonly plugins: IRendererPlugins; public readonly useContextAlpha: boolean | 'notMultiplied'; public readonly autoDensity: boolean; public readonly preserveDrawingBuffer: boolean; protected _backgroundColor: number; protected _backgroundColorString: string; _backgroundColorRgba: number[]; _lastObjectRendered: IRenderableObject; /** * @param system - The name of the system this renderer is for. * @param [options] - The optional renderer parameters. * @param {number} [options.width=800] - The width of the screen. * @param {number} [options.height=600] - The height of the screen. * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the * canvas needs to be opaque, possibly for performance reasons on some older devices. * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for * resolutions other than 1. * @param {boolean} [options.antialias=false] - Sets antialias * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, * enable this if you need to call toDataUrl on the WebGL context. * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or * not before the new render pass. * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area * (shown if not transparent). * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). */ constructor(type: RENDERER_TYPE = RENDERER_TYPE.UNKNOWN, options?: IRendererOptions) { super(); // Add the default render options options = Object.assign({}, settings.RENDER_OPTIONS, options); /** * The supplied constructor options. * * @member {Object} * @readOnly */ this.options = options; /** * The type of the renderer. * * @member {number} * @default PIXI.RENDERER_TYPE.UNKNOWN * @see PIXI.RENDERER_TYPE */ this.type = type; /** * Measurements of the screen. (0, 0, screenWidth, screenHeight). * * Its safe to use as filterArea or hitArea for the whole stage. * * @member {PIXI.Rectangle} */ this.screen = new Rectangle(0, 0, options.width, options.height); /** * The canvas element that everything is drawn to. * * @member {HTMLCanvasElement} */ this.view = options.view || document.createElement('canvas'); /** * The resolution / device pixel ratio of the renderer. * * @member {number} * @default PIXI.settings.RESOLUTION */ this.resolution = options.resolution || settings.RESOLUTION; /** * Pass-thru setting for the the canvas' context `alpha` property. This is typically * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`. * * @member {boolean} */ this.useContextAlpha = options.useContextAlpha; /** * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. * * @member {boolean} */ this.autoDensity = !!options.autoDensity; /** * The value of the preserveDrawingBuffer flag affects whether or not the contents of * the stencil buffer is retained after rendering. * * @member {boolean} */ this.preserveDrawingBuffer = options.preserveDrawingBuffer; /** * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect * to clear the canvas every frame. Disable this by setting this to false. For example, if * your game has a canvas filling background image you often don't need this set. * * @member {boolean} * @default */ this.clearBeforeRender = options.clearBeforeRender; /** * The background color as a number. * * @member {number} * @protected */ this._backgroundColor = 0x000000; /** * The background color as an [R, G, B, A] array. * * @member {number[]} * @protected */ this._backgroundColorRgba = [0, 0, 0, 1]; /** * The background color as a string. * * @member {string} * @protected */ this._backgroundColorString = '#000000'; this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter this.backgroundAlpha = options.backgroundAlpha; // @deprecated if (options.transparent !== undefined) { // #if _DEBUG deprecation('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.'); // #endif this.useContextAlpha = options.transparent; this.backgroundAlpha = options.transparent ? 0 : 1; } /** * The last root object that the renderer tried to render. * * @member {PIXI.DisplayObject} * @protected */ this._lastObjectRendered = null; /** * Collection of plugins. * @readonly * @member {object} */ this.plugins = {}; } /** * Initialize the plugins. * * @protected * @param {object} staticMap - The dictionary of statically saved plugins. */ initPlugins(staticMap: IRendererPlugins): void { for (const o in staticMap) { this.plugins[o] = new (staticMap[o])(this); } } /** * Same as view.width, actual number of pixels in the canvas by horizontal. * * @member {number} * @readonly * @default 800 */ get width(): number { return this.view.width; } /** * Same as view.height, actual number of pixels in the canvas by vertical. * * @member {number} * @readonly * @default 600 */ get height(): number { return this.view.height; } /** * Resizes the screen and canvas as close as possible to the specified width and height. * Canvas dimensions are multiplied by resolution and rounded to the nearest integers. * The new canvas dimensions divided by the resolution become the new screen dimensions. * * @param desiredScreenWidth - The desired width of the screen. * @param desiredScreenHeight - The desired height of the screen. */ resize(desiredScreenWidth: number, desiredScreenHeight: number): void { this.view.width = Math.round(desiredScreenWidth * this.resolution); this.view.height = Math.round(desiredScreenHeight * this.resolution); const screenWidth = this.view.width / this.resolution; const screenHeight = this.view.height / this.resolution; this.screen.width = screenWidth; this.screen.height = screenHeight; if (this.autoDensity) { this.view.style.width = `${screenWidth}px`; this.view.style.height = `${screenHeight}px`; } /** * Fired after view has been resized. * * @event PIXI.Renderer#resize * @param {number} screenWidth - The new width of the screen. * @param {number} screenHeight - The new height of the screen. */ this.emit('resize', screenWidth, screenHeight); } /** * Useful function that returns a texture of the display object that can then be used to create sprites * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. * @method PIXI.AbstractRenderer#generateTexture * @param displayObject - The displayObject the object will be generated from. * @param {object} options - Generate texture options. * @param {PIXI.SCALE_MODES} options.scaleMode - The scale mode of the texture. * @param {number} options.resolution - The resolution / device pixel ratio of the texture being generated. * @param {PIXI.Rectangle} options.region - The region of the displayObject, that shall be rendered, * if no region is specified, defaults to the local bounds of the displayObject. * @param {PIXI.MSAA_QUALITY} options.multisample - The number of samples of the frame buffer. * @return A texture of the graphics object. */ generateTexture(displayObject: IRenderableObject, options?: IGenerateTextureOptions): RenderTexture; /** * Please use the options argument instead. * * @method PIXI.AbstractRenderer#generateTexture * @deprecated Since 6.1.0 * @param displayObject - The displayObject the object will be generated from. * @param scaleMode - The scale mode of the texture. * @param resolution - The resolution / device pixel ratio of the texture being generated. * @param region - The region of the displayObject, that shall be rendered, * if no region is specified, defaults to the local bounds of the displayObject. * @return A texture of the graphics object. */ generateTexture( displayObject: IRenderableObject, scaleMode?: SCALE_MODES, resolution?: number, region?: Rectangle): RenderTexture; /** * @ignore */ generateTexture(displayObject: IRenderableObject, options: IGenerateTextureOptions | SCALE_MODES = {}, resolution?: number, region?: Rectangle): RenderTexture { // @deprecated parameters spread, use options instead if (typeof options === 'number') { // #if _DEBUG deprecation('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.'); // #endif options = { scaleMode: options, resolution, region }; } const { region: manualRegion, ...textureOptions } = options; region = manualRegion || (displayObject as IRenderableContainer).getLocalBounds(null, true); // minimum texture size is 1x1, 0x0 will throw an error if (region.width === 0) region.width = 1; if (region.height === 0) region.height = 1; const renderTexture = RenderTexture.create( { width: region.width, height: region.height, ...textureOptions, }); tempMatrix.tx = -region.x; tempMatrix.ty = -region.y; this.render(displayObject, { renderTexture, clear: false, transform: tempMatrix, skipUpdateTransform: !!displayObject.parent }); return renderTexture; } abstract render(displayObject: IRenderableObject, options?: IRendererRenderOptions): void; /** * Removes everything from the renderer and optionally removes the Canvas DOM element. * * @param [removeView=false] - Removes the Canvas element from the DOM. */ destroy(removeView?: boolean): void { for (const o in this.plugins) { this.plugins[o].destroy(); this.plugins[o] = null; } if (removeView && this.view.parentNode) { this.view.parentNode.removeChild(this.view); } const thisAny = this as any; // null-ing all objects, that's a tradition! thisAny.plugins = null; thisAny.type = RENDERER_TYPE.UNKNOWN; thisAny.view = null; thisAny.screen = null; thisAny._tempDisplayObjectParent = null; thisAny.options = null; this._backgroundColorRgba = null; this._backgroundColorString = null; this._lastObjectRendered = null; } /** * The background color to fill if not transparent * * @member {number} */ get backgroundColor(): number { return this._backgroundColor; } set backgroundColor(value: number) { this._backgroundColor = value; this._backgroundColorString = hex2string(value); hex2rgb(value, this._backgroundColorRgba); } /** * The background color alpha. Setting this to 0 will make the canvas transparent. * * @member {number} */ get backgroundAlpha(): number { return this._backgroundColorRgba[3]; } set backgroundAlpha(value: number) { this._backgroundColorRgba[3] = value; } }
the_stack
import { Actions, Schema, StrictSchema, ValidatorValidateResult } from './types'; import { aggregator, get, isValidAction, isActionString, isActionSelector, isActionAggregator, isActionFunction, isFunction, isString, isObject, SCHEMA_OPTIONS_SYMBOL, isEmptyObject, } from './helpers'; import { ValidationError, ERRORS, targetHasErrors, ValidationErrors, reporter, Reporter } from './validation/reporter'; import { ValidatorError } from './validation/validators/ValidatorError'; import { isArray } from 'util'; export enum NodeKind { Root = 'Root', Property = 'Property', ActionFunction = 'ActionFunction', ActionAggregator = 'ActionAggregator', ActionString = 'ActionString', ActionSelector = 'ActionSelector', } type PreparedAction = (params: { object: any; items: any; objectToCompute: any }) => any; interface SchemaNodeData<Target, Source> { propertyName: string; action: Actions<Target, Source> | null; preparedAction?: PreparedAction | null; kind: NodeKind; targetPropertyPath: string; } export interface SchemaNode<Target, Source> { data: SchemaNodeData<Target, Source>; parent: SchemaNode<Target, Source> | null; children: SchemaNode<Target, Source>[]; } type Overwrite<T1, T2> = { [P in Exclude<keyof T1, keyof T2>]: T1[P] } & T2; type AddNode<Target, Source> = Overwrite< SchemaNodeData<Target, Source>, { kind?: NodeKind; targetPropertyPath?: string; preparedAction?: (...args: any) => any; } >; /** * Options attached to a `Schema` or `StrictSchema` */ export interface SchemaOptions<Target = any> { /** * Specify how to handle ES6 Class * @memberof SchemaOptions */ class?: { /** * Specify wether ES6 Class fields should be automapped if names on source and target match * @default true * @type {boolean} */ automapping: boolean; }; /** * Specify how to handle undefined values mapped during the transformations * @memberof SchemaOptions */ undefinedValues?: { /** * Undefined values should be removed from the target * @default false * @type {boolean} */ strip: boolean; /** * Optional callback to be executed for every undefined property on the Target * @function default */ default?: (target: Target, propertyPath: string) => any; }; /** * Schema validation options * @memberof SchemaOptions */ validation?: { /** * Should throw when property validation fails * @default false * @type {boolean} */ throw: boolean; /** * Custom reporter to use when throw option is set to true * @default false * @type {boolean} */ reporter?: Reporter; }; } /** * A utility function that allows defining a `StrictSchema` with extra-options e.g: how to handle `undefinedValues` * * @param {StrictSchema} schema * @param {SchemaOptions<Target>} [options] */ export function createSchema<Target = any, Source = any>(schema: StrictSchema<Target, Source>, options?: SchemaOptions<Target>) { if (options && !isEmptyObject(options)) (schema as any)[SCHEMA_OPTIONS_SYMBOL] = options; return schema; } export class MorphismSchemaTree<Target, Source> { schemaOptions: SchemaOptions<Target>; root: SchemaNode<Target, Source>; schema: Schema | StrictSchema | null; constructor(schema: Schema<Target, Source> | StrictSchema<Target, Source> | null) { this.schema = schema; this.schemaOptions = MorphismSchemaTree.getSchemaOptions(this.schema); this.root = { data: { targetPropertyPath: '', propertyName: 'MorphismTreeRoot', action: null, kind: NodeKind.Root, }, parent: null, children: [], }; if (schema) { this.parseSchema(schema); } } static getSchemaOptions<Target>(schema: Schema | StrictSchema | null): SchemaOptions<Target> { const defaultSchemaOptions: SchemaOptions<Target> = { class: { automapping: true }, undefinedValues: { strip: false }, }; const options = schema ? (schema as any)[SCHEMA_OPTIONS_SYMBOL] : undefined; return { ...defaultSchemaOptions, ...options }; } private parseSchema(partialSchema: Partial<Schema | StrictSchema> | string | number, actionKey?: string, parentKeyPath?: string): void { if (isValidAction(partialSchema) && actionKey) { this.add( { propertyName: actionKey, action: partialSchema as Actions<Target, Source>, }, parentKeyPath ); parentKeyPath = parentKeyPath ? `${parentKeyPath}.${actionKey}` : actionKey; } else { if (actionKey) { if (isObject(partialSchema) && isEmptyObject(partialSchema as any)) throw new Error( `A value of a schema property can't be an empty object. Value ${JSON.stringify(partialSchema)} found for property ${actionKey}` ); // check if actionKey exists to verify if not root node this.add( { propertyName: actionKey, action: partialSchema as Actions<Target, Source>, }, parentKeyPath ); parentKeyPath = parentKeyPath ? `${parentKeyPath}.${actionKey}` : actionKey; } if (Array.isArray(partialSchema)) { partialSchema.forEach((subSchema, index) => { this.parseSchema(subSchema, index.toString(), parentKeyPath); }); } else if (isObject(partialSchema)) { Object.keys(partialSchema).forEach(key => { this.parseSchema((partialSchema as any)[key], key, parentKeyPath); }); } } } *traverseBFS() { const queue: SchemaNode<Target, Source>[] = []; queue.push(this.root); while (queue.length > 0) { let node = queue.shift(); if (node) { for (let i = 0, length = node.children.length; i < length; i++) { queue.push(node.children[i]); } if (node.data.kind !== NodeKind.Root) { yield node; } } } } add(data: AddNode<Target, Source>, targetPropertyPath?: string) { const kind = this.getActionKind(data); const nodeToAdd: SchemaNode<Target, Source> = { data: { ...data, kind, targetPropertyPath: '' }, parent: null, children: [], }; nodeToAdd.data.preparedAction = this.getPreparedAction(nodeToAdd.data); if (!targetPropertyPath) { nodeToAdd.parent = this.root; nodeToAdd.data.targetPropertyPath = nodeToAdd.data.propertyName; this.root.children.push(nodeToAdd); } else { for (const node of this.traverseBFS()) { if (node.data.targetPropertyPath === targetPropertyPath) { nodeToAdd.parent = node; nodeToAdd.data.targetPropertyPath = `${node.data.targetPropertyPath}.${nodeToAdd.data.propertyName}`; node.children.push(nodeToAdd); } } } } getActionKind(data: AddNode<Target, Source>) { if (isActionString(data.action)) return NodeKind.ActionString; if (isFunction(data.action)) return NodeKind.ActionFunction; if (isActionSelector(data.action)) return NodeKind.ActionSelector; if (isActionAggregator(data.action)) return NodeKind.ActionAggregator; if (isObject(data.action)) return NodeKind.Property; throw new Error(`The action specified for ${data.propertyName} is not supported.`); } getPreparedAction(nodeData: SchemaNodeData<Target, Source>): PreparedAction | null | undefined { const { propertyName: targetProperty, action, kind } = nodeData; // iterate on every action of the schema if (isActionString(action)) { // Action<String>: string path => [ target: 'source' ] return ({ object }) => get(object, action); } else if (isActionFunction(action)) { // Action<Function>: Free Computin - a callback called with the current object and collection [ destination: (object) => {...} ] return ({ object, items, objectToCompute }) => action.call(undefined, object, items, objectToCompute); } else if (isActionAggregator(action)) { // Action<Array>: Aggregator - string paths => : [ destination: ['source1', 'source2', 'source3'] ] return ({ object }) => aggregator(action, object); } else if (isActionSelector(action)) { // Action<Object>: a path and a function: [ destination : { path: 'source', fn:(fieldValue, items) }] return ({ object, items, objectToCompute }) => { let targetValue: any; if (action.path) { if (Array.isArray(action.path)) { targetValue = aggregator(action.path, object); } else if (isString(action.path)) { targetValue = get(object, action.path); } } else { targetValue = object; } if (action.fn) { try { targetValue = action.fn.call(undefined, targetValue, object, items, objectToCompute); } catch (e) { e.message = `Unable to set target property [${targetProperty}]. \n An error occured when applying [${action.fn.name}] on property [${action.path}] \n Internal error: ${e.message}`; throw e; } } if (action.validation) { const validationResult = action.validation({ value: targetValue }); this.processValidationResult(validationResult, targetProperty, objectToCompute); targetValue = validationResult.value; } return targetValue; }; } else if (kind === NodeKind.Property) { return null; } } private processValidationResult(validationResult: ValidatorValidateResult, targetProperty: string, objectToCompute: any) { if (validationResult.error) { const error = validationResult.error; if (error instanceof ValidatorError) { this.addErrorToTarget(targetProperty, error, objectToCompute); } else { throw error; } } } private addErrorToTarget(targetProperty: string, error: ValidatorError, objectToCompute: any) { const validationError = new ValidationError({ targetProperty, innerError: error, }); if (targetHasErrors(objectToCompute)) { objectToCompute[ERRORS].addError(validationError); } else { if (this.schemaOptions.validation && this.schemaOptions.validation.reporter) { objectToCompute[ERRORS] = new ValidationErrors(this.schemaOptions.validation.reporter, objectToCompute); } else { objectToCompute[ERRORS] = new ValidationErrors(reporter, objectToCompute); } objectToCompute[ERRORS].addError(validationError); } } }
the_stack
import { isTwoDimArray, ModelTypes, JointDataset, IExplanationModelMetadata, ModelExplanationUtils, FabricStyles } from "@responsible-ai/core-ui"; import { localization } from "@responsible-ai/localization"; import { IPlotlyProperty, RangeTypes, AccessibleChart, PlotlyMode } from "@responsible-ai/mlchartlib"; import _, { toNumber, map } from "lodash"; import { IComboBox, IComboBoxOption, ComboBox, SpinButton, Text, getTheme } from "office-ui-fabric-react"; import { Data } from "plotly.js"; import React from "react"; import { NoDataMessage } from "../../SharedComponents/NoDataMessage"; import { IRangeView } from "../ICEPlot"; import { multiIcePlotStyles } from "./MultiICEPlot.styles"; export interface IMultiICEPlotProps { invokeModel?: (data: any[], abortSignal: AbortSignal) => Promise<any[]>; datapoints: Array<Array<string | number>>; rowNames: string[]; colors: string[]; jointDataset: JointDataset; metadata: IExplanationModelMetadata; feature: string; selectedClass: number; } export interface IMultiICEPlotState { yAxes: number[][] | number[][][] | undefined; xAxisArray: string[] | number[]; abortControllers: Array<AbortController | undefined>; rangeView: IRangeView | undefined; errorMessage?: string; } export class MultiICEPlot extends React.PureComponent< IMultiICEPlotProps, IMultiICEPlotState > { private debounceFetchData: () => void; public constructor(props: IMultiICEPlotProps) { super(props); const rangeView = this.buildRangeView(this.props.feature); const xAxisArray = this.buildRange(rangeView); this.state = { abortControllers: [], rangeView, xAxisArray, yAxes: [] }; this.debounceFetchData = _.debounce(this.fetchData.bind(this), 500); } private static buildYAxis( metadata: IExplanationModelMetadata, selectedClass: number ): string { if (metadata.modelType === ModelTypes.Regression) { return localization.Interpret.IcePlot.prediction; } return `${ localization.Interpret.IcePlot.predictedProbability }<br>${localization.formatString( localization.Interpret.WhatIfTab.classLabel, metadata.classNames[selectedClass] )}`; } private static buildPlotlyProps( metadata: IExplanationModelMetadata, featureName: string, selectedClass: number, colors: string[], rowNames: string[], rangeType?: RangeTypes, xData?: Array<number | string>, yData?: number[][] | number[][][] ): IPlotlyProperty | undefined { if ( yData === undefined || xData === undefined || yData.length === 0 || yData.some((row: number[] | number[][]) => row === undefined) ) { return undefined; } const data: Data[] = map<number[] | number[][]>( yData, (singleRow: number[] | number[][], rowIndex: number) => { const transposedY: number[][] = isTwoDimArray(singleRow) ? ModelExplanationUtils.transpose2DArray(singleRow) : [singleRow]; const predictionLabel = metadata.modelType === ModelTypes.Regression ? localization.Interpret.IcePlot.prediction : `${localization.Interpret.IcePlot.predictedProbability}: ${metadata.classNames[selectedClass]}`; const hovertemplate = `%{customdata.Name}<br>${featureName}: %{x}<br>${predictionLabel}: %{customdata.Yformatted}<br><extra></extra>`; return { customdata: transposedY[selectedClass].map((predY) => { return { Name: rowNames[rowIndex], Yformatted: predY.toLocaleString(undefined, { maximumFractionDigits: 3 }) }; }), hoverinfo: "all", hovertemplate, marker: { color: colors[rowIndex] }, mode: rangeType === RangeTypes.Categorical ? PlotlyMode.Markers : PlotlyMode.LinesMarkers, name: rowNames[rowIndex], type: "scatter", x: xData, y: transposedY[selectedClass] }; } ) as any; return { config: { displaylogo: false, displayModeBar: false, responsive: true }, data, layout: { autosize: true, dragmode: false, font: { size: 10 }, hovermode: "closest", margin: { b: 30, r: 10, t: 10 }, showlegend: false, xaxis: { automargin: true, title: featureName }, yaxis: { automargin: true, title: MultiICEPlot.buildYAxis(metadata, selectedClass) } } }; } public componentDidMount(): void { this.fetchData(); } public componentDidUpdate(prevProps: IMultiICEPlotProps): void { if (this.props.datapoints !== prevProps.datapoints) { this.fetchData(); } if (this.props.feature !== prevProps.feature) { this.onFeatureSelected(); } } public componentWillUnmount(): void { this.state.abortControllers.forEach((abortController) => { if (abortController !== undefined) { abortController.abort(); } }); } public render(): React.ReactNode { if (this.props.invokeModel === undefined) { return <NoDataMessage />; } const classNames = multiIcePlotStyles(); const hasOutgoingRequest = this.state.abortControllers.some( (x) => x !== undefined ); const plotlyProps = this.state.rangeView ? MultiICEPlot.buildPlotlyProps( this.props.metadata, this.props.jointDataset.metaDict[this.props.feature].label, this.props.selectedClass, this.props.colors, this.props.rowNames, this.state.rangeView.type, this.state.xAxisArray, this.state.yAxes ) : undefined; const hasError = this.state.rangeView !== undefined && (this.state.rangeView.maxErrorMessage !== undefined || this.state.rangeView.minErrorMessage !== undefined || this.state.rangeView.stepsErrorMessage !== undefined); return ( <div className={classNames.iceWrapper}> {this.state.rangeView !== undefined && ( <div className={classNames.controlArea}> {this.state.rangeView.type === RangeTypes.Categorical && ( <ComboBox multiSelect selectedKey={ this.state.rangeView.selectedOptionKeys as string[] } allowFreeform autoComplete="on" options={this.state.rangeView.categoricalOptions} onChange={this.onCategoricalRangeChanged} styles={FabricStyles.defaultDropdownStyle} calloutProps={FabricStyles.calloutProps} /> )} {this.state.rangeView.type !== RangeTypes.Categorical && ( <div className={classNames.parameterList}> <SpinButton styles={{ labelWrapper: { alignSelf: "center" }, root: { display: "inline-flex", float: "right", selectors: { "> div": { maxWidth: "78px" } } }, spinButtonWrapper: { maxWidth: "68px" } }} label={localization.Interpret.WhatIfTab.minLabel} value={this.state.rangeView.min?.toString()} onIncrement={this.onMinRangeChanged.bind(this, 1)} onDecrement={this.onMinRangeChanged.bind(this, -1)} onValidate={this.onMinRangeChanged.bind(this, 0)} /> <SpinButton styles={{ labelWrapper: { alignSelf: "center" }, root: { display: "inline-flex", float: "right", selectors: { "> div": { maxWidth: "78px" } } }, spinButtonWrapper: { maxWidth: "68px" } }} label={localization.Interpret.WhatIfTab.maxLabel} value={this.state.rangeView.max?.toString()} onIncrement={this.onMaxRangeChanged.bind(this, 1)} onDecrement={this.onMaxRangeChanged.bind(this, -1)} onValidate={this.onMaxRangeChanged.bind(this, 0)} /> <SpinButton styles={{ labelWrapper: { alignSelf: "center" }, root: { display: "inline-flex", float: "right", selectors: { "> div": { maxWidth: "78px" } } }, spinButtonWrapper: { maxWidth: "68px" } }} label={localization.Interpret.WhatIfTab.stepsLabel} value={this.state.rangeView.steps?.toString()} onIncrement={this.onStepsRangeChanged.bind(this, 1)} onDecrement={this.onStepsRangeChanged.bind(this, -1)} onValidate={this.onStepsRangeChanged.bind(this, 0)} /> </div> )} </div> )} {hasOutgoingRequest && ( <div className={classNames.placeholder}> <Text>{localization.Interpret.IcePlot.loadingMessage}</Text> </div> )} {this.state.errorMessage && ( <div className={classNames.placeholder}> <Text>{this.state.errorMessage}</Text> </div> )} {plotlyProps === undefined && !hasOutgoingRequest && ( <div className={classNames.placeholder}> <Text>{localization.Interpret.IcePlot.submitPrompt}</Text> </div> )} {hasError && ( <div className={classNames.placeholder}> <Text>{localization.Interpret.IcePlot.topLevelErrorMessage}</Text> </div> )} {plotlyProps !== undefined && !hasOutgoingRequest && !hasError && ( <div className={classNames.chartWrapper}> <AccessibleChart plotlyProps={plotlyProps} theme={getTheme()} /> </div> )} </div> ); } private onFeatureSelected(): void { const rangeView = this.buildRangeView(this.props.feature); const xAxisArray = this.buildRange(rangeView); this.setState({ rangeView, xAxisArray }, () => { this.debounceFetchData(); }); } private onMinRangeChanged(delta: number, stringVal: string): string | void { const rangeView = _.cloneDeep(this.state.rangeView); if (!rangeView) { return; } if (delta === 0 || rangeView.min === undefined) { const numberVal = +stringVal; if (Number.isNaN(numberVal)) { return rangeView.min?.toString(); } rangeView.min = numberVal; } else { rangeView.min += delta; } if ( rangeView.max !== undefined && rangeView.min !== undefined && rangeView.max <= rangeView.min ) { return rangeView.min?.toString(); } const xAxisArray = this.buildRange(rangeView); this.setState( { abortControllers: [new AbortController()], rangeView, xAxisArray, yAxes: undefined }, () => { this.debounceFetchData(); } ); } private onMaxRangeChanged(delta: number, stringVal: string): string | void { const rangeView = _.cloneDeep(this.state.rangeView); if (!rangeView) { return; } if (delta === 0 || rangeView.max === undefined) { const numberVal = +stringVal; if (Number.isNaN(numberVal)) { return rangeView.max?.toString(); } rangeView.max = numberVal; } else { rangeView.max += delta; } if ( rangeView.max !== undefined && rangeView.min !== undefined && rangeView.max <= rangeView.min ) { return rangeView.max.toString(); } const xAxisArray = this.buildRange(rangeView); this.setState( { abortControllers: [new AbortController()], rangeView, xAxisArray, yAxes: undefined }, () => { this.debounceFetchData(); } ); } private onStepsRangeChanged(delta: number, stringVal: string): string | void { const rangeView = _.cloneDeep(this.state.rangeView); if (!rangeView) { return; } if (delta === 0 || rangeView.steps === undefined) { const numberVal = +stringVal; if (!Number.isInteger(numberVal)) { return rangeView.steps?.toString(); } rangeView.steps = numberVal; } else { rangeView.steps += delta; } if (rangeView.steps <= 0) { return rangeView.steps.toString(); } const xAxisArray = this.buildRange(rangeView); this.setState( { abortControllers: [new AbortController()], rangeView, xAxisArray, yAxes: undefined }, () => { this.debounceFetchData(); } ); } private onCategoricalRangeChanged = ( _event: React.FormEvent<IComboBox>, option?: IComboBoxOption, _index?: number, value?: string ): void => { const rangeView = _.cloneDeep(this.state.rangeView); if (!rangeView) { return; } const currentSelectedKeys = rangeView.selectedOptionKeys || []; if (option) { // User selected/de-selected an existing option rangeView.selectedOptionKeys = this.updateSelectedOptionKeys( currentSelectedKeys, option ); } else if (value !== undefined) { // User typed a freeform option const newOption: IComboBoxOption = { key: value, text: value }; rangeView.selectedOptionKeys = [ ...currentSelectedKeys, newOption.key as string ]; rangeView.categoricalOptions?.push(newOption); } const xAxisArray = this.buildRange(rangeView); this.setState({ rangeView, xAxisArray }, () => { this.debounceFetchData(); }); }; private updateSelectedOptionKeys = ( selectedKeys: Array<string | number>, option: IComboBoxOption ): Array<string | number> => { selectedKeys = [...selectedKeys]; // modify a copy const index = selectedKeys.indexOf(option.key as string); if (option.selected && index < 0) { selectedKeys.push(option.key as string); } else { selectedKeys.splice(index, 1); } return selectedKeys; }; private fetchData(): void { if (!this.props.invokeModel) { return; } const invokeModel = this.props.invokeModel; this.state.abortControllers.forEach((abortController) => { if (abortController !== undefined) { abortController.abort(); } }); const promises = this.props.datapoints.map((row, index) => { const newController = [...this.state.abortControllers]; const abortController = new AbortController(); newController[index] = abortController; this.setState({ abortControllers: newController }); const permutations = this.buildDataSpans(row, this.state.xAxisArray); return invokeModel(permutations, abortController.signal); }); const yAxes = undefined; this.setState({ errorMessage: undefined, yAxes }, async () => { try { const fetchedData = await Promise.all(promises); if ( Array.isArray(fetchedData) && fetchedData.every((prediction) => Array.isArray(prediction)) ) { this.setState({ abortControllers: this.props.datapoints.map(() => undefined), yAxes: fetchedData }); } } catch (error) { if (error.name === "AbortError") { return; } if (error.name === "PythonError") { this.setState({ errorMessage: localization.formatString( localization.Interpret.IcePlot.errorPrefix, error.message ) }); } } }); } private buildDataSpans( row: Array<string | number>, range: Array<string | number> ): Array<Array<number | string>> { if (!this.state.rangeView) { return []; } const rangeView = this.state.rangeView; return range.map((val: number | string) => { const copy = _.cloneDeep(row); copy[rangeView.featureIndex] = val; return copy; }); } private buildRangeView(featureKey: string): IRangeView | undefined { const summary = this.props.jointDataset.metaDict[featureKey]; if (!summary || summary.index === undefined) { return undefined; } if (summary.treatAsCategorical) { // Columns that are passed in as categorical strings should be strings when passed to predict if (summary.isCategorical) { return { categoricalOptions: summary.sortedCategoricalValues?.map((text) => { return { key: text, text }; }), featureIndex: summary.index, key: featureKey, selectedOptionKeys: summary.sortedCategoricalValues, type: RangeTypes.Categorical }; } // Columns that were integers that are flagged in the UX as categorical should still be integers when // calling predict on the model. return { categoricalOptions: summary.sortedCategoricalValues?.map((text) => { return { key: +text, text: text.toString() }; }), featureIndex: summary.index, key: featureKey, selectedOptionKeys: summary.sortedCategoricalValues?.map((x) => +x), type: RangeTypes.Categorical }; } if (!summary.featureRange) { return undefined; } return { featureIndex: summary.index, key: featureKey, max: summary.featureRange?.max, min: summary.featureRange?.min, steps: 20, type: summary.featureRange.rangeType }; } private buildRange(rangeView: IRangeView | undefined): number[] | string[] { if ( rangeView === undefined || rangeView.minErrorMessage !== undefined || rangeView.maxErrorMessage !== undefined || rangeView.stepsErrorMessage !== undefined ) { return []; } const min = toNumber(rangeView.min); const max = toNumber(rangeView.max); const steps = toNumber(rangeView.steps); if ( rangeView.type === RangeTypes.Categorical && Array.isArray(rangeView.selectedOptionKeys) ) { return rangeView.selectedOptionKeys as string[]; } else if ( !Number.isNaN(min) && !Number.isNaN(max) && Number.isInteger(steps) ) { const delta = steps > 0 ? (max - min) / steps : max - min; return _.uniq( Array.from({ length: steps }, (_, i) => rangeView.type === RangeTypes.Integer ? Math.round(min + i * delta) : min + i * delta ) ); } return []; } }
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; export interface AcceptInvitationRequest { /** * <p>The ARN of the behavior graph that the member account is accepting the invitation * for.</p> * <p>The member account status in the behavior graph must be <code>INVITED</code>.</p> */ GraphArn: string | undefined; } export namespace AcceptInvitationRequest { /** * @internal */ export const filterSensitiveLog = (obj: AcceptInvitationRequest): any => ({ ...obj, }); } /** * <p>The request attempted an invalid action.</p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; Message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } /** * <p>The request was valid but failed because of a problem with the service.</p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; Message?: string; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>The request refers to a nonexistent resource.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; Message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p>The request parameters are invalid.</p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; Message?: string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } /** * <p>An AWS account that is the administrator account of or a member of a behavior * graph.</p> */ export interface Account { /** * <p>The account identifier of the AWS account.</p> */ AccountId: string | undefined; /** * <p>The AWS account root user email address for the AWS account.</p> */ EmailAddress: string | undefined; } export namespace Account { /** * @internal */ export const filterSensitiveLog = (obj: Account): any => ({ ...obj, }); } export interface CreateGraphRequest { /** * <p>The tags to assign to the new behavior graph. You can add up to 50 tags. For each tag, * you provide the tag key and the tag value. Each tag key can contain up to 128 characters. * Each tag value can contain up to 256 characters.</p> */ Tags?: { [key: string]: string }; } export namespace CreateGraphRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateGraphRequest): any => ({ ...obj, }); } export interface CreateGraphResponse { /** * <p>The ARN of the new behavior graph.</p> */ GraphArn?: string; } export namespace CreateGraphResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateGraphResponse): any => ({ ...obj, }); } /** * <p>This request cannot be completed for one of the following reasons.</p> * <ul> * <li> * <p>The request would cause the number of member accounts in the behavior graph to * exceed the maximum allowed. A behavior graph cannot have more than 1000 member * accounts.</p> * </li> * <li> * <p>The request would cause the data rate for the behavior graph to exceed the maximum * allowed.</p> * </li> * <li> * <p>Detective is unable to verify the data rate for the member account. This is usually * because the member account is not enrolled in Amazon GuardDuty. </p> * </li> * </ul> */ export interface ServiceQuotaExceededException extends __SmithyException, $MetadataBearer { name: "ServiceQuotaExceededException"; $fault: "client"; Message?: string; } export namespace ServiceQuotaExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceQuotaExceededException): any => ({ ...obj, }); } export interface CreateMembersRequest { /** * <p>The ARN of the behavior graph to invite the member accounts to contribute their data * to.</p> */ GraphArn: string | undefined; /** * <p>Customized message text to include in the invitation email message to the invited member * accounts.</p> */ Message?: string; /** * <p>if set to <code>true</code>, then the member accounts do not receive email * notifications. By default, this is set to <code>false</code>, and the member accounts * receive email notifications.</p> */ DisableEmailNotification?: boolean; /** * <p>The list of AWS accounts to invite to become member accounts in the behavior graph. * You can invite up to 50 accounts at a time. For each invited account, the account list * contains the account identifier and the AWS account root user email address.</p> */ Accounts: Account[] | undefined; } export namespace CreateMembersRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateMembersRequest): any => ({ ...obj, }); } export enum MemberDisabledReason { VOLUME_TOO_HIGH = "VOLUME_TOO_HIGH", VOLUME_UNKNOWN = "VOLUME_UNKNOWN", } export enum MemberStatus { ACCEPTED_BUT_DISABLED = "ACCEPTED_BUT_DISABLED", ENABLED = "ENABLED", INVITED = "INVITED", VERIFICATION_FAILED = "VERIFICATION_FAILED", VERIFICATION_IN_PROGRESS = "VERIFICATION_IN_PROGRESS", } /** * <p>Details about a member account that was invited to contribute to a behavior * graph.</p> */ export interface MemberDetail { /** * <p>The AWS account identifier for the member account.</p> */ AccountId?: string; /** * <p>The AWS account root user email address for the member account.</p> */ EmailAddress?: string; /** * <p>The ARN of the behavior graph that the member account was invited to.</p> */ GraphArn?: string; /** * @deprecated * * <p>The AWS account identifier of the administrator account for the behavior graph.</p> */ MasterId?: string; /** * <p>The AWS account identifier of the administrator account for the behavior graph.</p> */ AdministratorId?: string; /** * <p>The current membership status of the member account. The status can have one of the * following values:</p> * <ul> * <li> * <p> * <code>INVITED</code> - Indicates that the member was sent an invitation but has * not yet responded.</p> * </li> * <li> * <p> * <code>VERIFICATION_IN_PROGRESS</code> - Indicates that Detective is verifying that the * account identifier and email address provided for the member account match. If they * do match, then Detective sends the invitation. If the email address and account * identifier don't match, then the member cannot be added to the behavior graph.</p> * </li> * <li> * <p> * <code>VERIFICATION_FAILED</code> - Indicates that the account and email address * provided for the member account do not match, and Detective did not send an invitation to * the account.</p> * </li> * <li> * <p> * <code>ENABLED</code> - Indicates that the member account accepted the invitation * to contribute to the behavior graph.</p> * </li> * <li> * <p> * <code>ACCEPTED_BUT_DISABLED</code> - Indicates that the member account accepted * the invitation but is prevented from contributing data to the behavior graph. * <code>DisabledReason</code> provides the reason why the member account is not * enabled.</p> * </li> * </ul> * <p>Member accounts that declined an invitation or that were removed from the behavior graph * are not included.</p> */ Status?: MemberStatus | string; /** * <p>For member accounts with a status of <code>ACCEPTED_BUT_DISABLED</code>, the reason that * the member account is not enabled.</p> * <p>The reason can have one of the following values:</p> * <ul> * <li> * <p> * <code>VOLUME_TOO_HIGH</code> - Indicates that adding the member account would * cause the data volume for the behavior graph to be too high.</p> * </li> * <li> * <p> * <code>VOLUME_UNKNOWN</code> - Indicates that Detective is unable to verify the data * volume for the member account. This is usually because the member account is not * enrolled in Amazon GuardDuty. </p> * </li> * </ul> */ DisabledReason?: MemberDisabledReason | string; /** * <p>The date and time that Detective sent the invitation to the member account. The value is in * milliseconds since the epoch.</p> */ InvitedTime?: Date; /** * <p>The date and time that the member account was last updated. The value is in milliseconds * since the epoch.</p> */ UpdatedTime?: Date; /** * <p>The data volume in bytes per day for the member account.</p> */ VolumeUsageInBytes?: number; /** * <p>The data and time when the member account data volume was last updated.</p> */ VolumeUsageUpdatedTime?: Date; /** * @deprecated * * <p>The member account data volume as a percentage of the maximum allowed data volume. 0 * indicates 0 percent, and 100 indicates 100 percent.</p> * <p>Note that this is not the percentage of the behavior graph data volume.</p> * <p>For example, the data volume for the behavior graph is 80 GB per day. The maximum data * volume is 160 GB per day. If the data volume for the member account is 40 GB per day, then * <code>PercentOfGraphUtilization</code> is 25. It represents 25% of the maximum allowed * data volume. </p> */ PercentOfGraphUtilization?: number; /** * @deprecated * * <p>The date and time when the graph utilization percentage was last updated.</p> */ PercentOfGraphUtilizationUpdatedTime?: Date; } export namespace MemberDetail { /** * @internal */ export const filterSensitiveLog = (obj: MemberDetail): any => ({ ...obj, }); } /** * <p>A member account that was included in a request but for which the request could not be * processed.</p> */ export interface UnprocessedAccount { /** * <p>The AWS account identifier of the member account that was not processed.</p> */ AccountId?: string; /** * <p>The reason that the member account request could not be processed.</p> */ Reason?: string; } export namespace UnprocessedAccount { /** * @internal */ export const filterSensitiveLog = (obj: UnprocessedAccount): any => ({ ...obj, }); } export interface CreateMembersResponse { /** * <p>The set of member account invitation requests that Detective was able to process. This * includes accounts that are being verified, that failed verification, and that passed * verification and are being sent an invitation.</p> */ Members?: MemberDetail[]; /** * <p>The list of accounts for which Detective was unable to process the invitation request. For * each account, the list provides the reason why the request could not be processed. The list * includes accounts that are already member accounts in the behavior graph.</p> */ UnprocessedAccounts?: UnprocessedAccount[]; } export namespace CreateMembersResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateMembersResponse): any => ({ ...obj, }); } export interface DeleteGraphRequest { /** * <p>The ARN of the behavior graph to disable.</p> */ GraphArn: string | undefined; } export namespace DeleteGraphRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteGraphRequest): any => ({ ...obj, }); } export interface DeleteMembersRequest { /** * <p>The ARN of the behavior graph to delete members from.</p> */ GraphArn: string | undefined; /** * <p>The list of AWS account identifiers for the member accounts to delete from the * behavior graph. You can delete up to 50 member accounts at a time.</p> */ AccountIds: string[] | undefined; } export namespace DeleteMembersRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteMembersRequest): any => ({ ...obj, }); } export interface DeleteMembersResponse { /** * <p>The list of AWS account identifiers for the member accounts that Detective successfully * deleted from the behavior graph.</p> */ AccountIds?: string[]; /** * <p>The list of member accounts that Detective was not able to delete from the behavior graph. * For each member account, provides the reason that the deletion could not be * processed.</p> */ UnprocessedAccounts?: UnprocessedAccount[]; } export namespace DeleteMembersResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteMembersResponse): any => ({ ...obj, }); } export interface DisassociateMembershipRequest { /** * <p>The ARN of the behavior graph to remove the member account from.</p> * <p>The member account's member status in the behavior graph must be * <code>ENABLED</code>.</p> */ GraphArn: string | undefined; } export namespace DisassociateMembershipRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateMembershipRequest): any => ({ ...obj, }); } export interface GetMembersRequest { /** * <p>The ARN of the behavior graph for which to request the member details.</p> */ GraphArn: string | undefined; /** * <p>The list of AWS account identifiers for the member account for which to return member * details. You can request details for up to 50 member accounts at a time.</p> * <p>You cannot use <code>GetMembers</code> to retrieve information about member accounts * that were removed from the behavior graph.</p> */ AccountIds: string[] | undefined; } export namespace GetMembersRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetMembersRequest): any => ({ ...obj, }); } export interface GetMembersResponse { /** * <p>The member account details that Detective is returning in response to the request.</p> */ MemberDetails?: MemberDetail[]; /** * <p>The requested member accounts for which Detective was unable to return member * details.</p> * <p>For each account, provides the reason why the request could not be processed.</p> */ UnprocessedAccounts?: UnprocessedAccount[]; } export namespace GetMembersResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetMembersResponse): any => ({ ...obj, }); } export interface ListGraphsRequest { /** * <p>For requests to get the next page of results, the pagination token that was returned * with the previous set of results. The initial request does not include a pagination * token.</p> */ NextToken?: string; /** * <p>The maximum number of graphs to return at a time. The total must be less than the * overall limit on the number of results to return, which is currently 200.</p> */ MaxResults?: number; } export namespace ListGraphsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListGraphsRequest): any => ({ ...obj, }); } /** * <p>A behavior graph in Detective.</p> */ export interface Graph { /** * <p>The ARN of the behavior graph.</p> */ Arn?: string; /** * <p>The date and time that the behavior graph was created. The value is in milliseconds * since the epoch.</p> */ CreatedTime?: Date; } export namespace Graph { /** * @internal */ export const filterSensitiveLog = (obj: Graph): any => ({ ...obj, }); } export interface ListGraphsResponse { /** * <p>A list of behavior graphs that the account is an administrator account for.</p> */ GraphList?: Graph[]; /** * <p>If there are more behavior graphs remaining in the results, then this is the pagination * token to use to request the next page of behavior graphs.</p> */ NextToken?: string; } export namespace ListGraphsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListGraphsResponse): any => ({ ...obj, }); } export interface ListInvitationsRequest { /** * <p>For requests to retrieve the next page of results, the pagination token that was * returned with the previous page of results. The initial request does not include a * pagination token.</p> */ NextToken?: string; /** * <p>The maximum number of behavior graph invitations to return in the response. The total * must be less than the overall limit on the number of results to return, which is currently * 200.</p> */ MaxResults?: number; } export namespace ListInvitationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListInvitationsRequest): any => ({ ...obj, }); } export interface ListInvitationsResponse { /** * <p>The list of behavior graphs for which the member account has open or accepted * invitations.</p> */ Invitations?: MemberDetail[]; /** * <p>If there are more behavior graphs remaining in the results, then this is the pagination * token to use to request the next page of behavior graphs.</p> */ NextToken?: string; } export namespace ListInvitationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListInvitationsResponse): any => ({ ...obj, }); } export interface ListMembersRequest { /** * <p>The ARN of the behavior graph for which to retrieve the list of member accounts.</p> */ GraphArn: string | undefined; /** * <p>For requests to retrieve the next page of member account results, the pagination token * that was returned with the previous page of results. The initial request does not include a * pagination token.</p> */ NextToken?: string; /** * <p>The maximum number of member accounts to include in the response. The total must be less * than the overall limit on the number of results to return, which is currently 200.</p> */ MaxResults?: number; } export namespace ListMembersRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListMembersRequest): any => ({ ...obj, }); } export interface ListMembersResponse { /** * <p>The list of member accounts in the behavior graph.</p> * <p>The results include member accounts that did not pass verification and member accounts * that have not yet accepted the invitation to the behavior graph. The results do not include * member accounts that were removed from the behavior graph.</p> */ MemberDetails?: MemberDetail[]; /** * <p>If there are more member accounts remaining in the results, then this is the pagination * token to use to request the next page of member accounts.</p> */ NextToken?: string; } export namespace ListMembersResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListMembersResponse): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The ARN of the behavior graph for which to retrieve the tag values.</p> */ ResourceArn: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p>The tag values that are assigned to the behavior graph. The request returns up to 50 tag * values.</p> */ Tags?: { [key: string]: string }; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface RejectInvitationRequest { /** * <p>The ARN of the behavior graph to reject the invitation to.</p> * <p>The member account's current member status in the behavior graph must be * <code>INVITED</code>.</p> */ GraphArn: string | undefined; } export namespace RejectInvitationRequest { /** * @internal */ export const filterSensitiveLog = (obj: RejectInvitationRequest): any => ({ ...obj, }); } export interface StartMonitoringMemberRequest { /** * <p>The ARN of the behavior graph.</p> */ GraphArn: string | undefined; /** * <p>The account ID of the member account to try to enable.</p> * <p>The account must be an invited member account with a status of * <code>ACCEPTED_BUT_DISABLED</code>. </p> */ AccountId: string | undefined; } export namespace StartMonitoringMemberRequest { /** * @internal */ export const filterSensitiveLog = (obj: StartMonitoringMemberRequest): any => ({ ...obj, }); } export interface TagResourceRequest { /** * <p>The ARN of the behavior graph to assign the tags to.</p> */ ResourceArn: string | undefined; /** * <p>The tags to assign to the behavior graph. You can add up to 50 tags. For each tag, you * provide the tag key and the tag value. Each tag key can contain up to 128 characters. Each * tag value can contain up to 256 characters.</p> */ Tags: { [key: string]: string } | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p>The ARN of the behavior graph to remove the tags from.</p> */ ResourceArn: string | undefined; /** * <p>The tag keys of the tags to remove from the behavior graph. You can remove up to 50 tags * at a time.</p> */ TagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResponse {} export namespace UntagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({ ...obj, }); }
the_stack
import * as coreHttp from "@azure/core-http"; import { LROSYM, LROResponseInfo } from "../lro/models"; /** Represents a phone number search request to find phone numbers. Found phone numbers are temporarily held for a following purchase. */ export interface PhoneNumberSearchRequest { /** The type of phone numbers to search for, e.g. geographic, or tollFree. */ phoneNumberType: PhoneNumberType; /** The assignment type of the phone numbers to search for. A phone number can be assigned to a person, or to an application. */ assignmentType: PhoneNumberAssignmentType; /** Capabilities of a phone number. */ capabilities: PhoneNumberCapabilities; /** The area code of the desired phone number, e.g. 425. */ areaCode?: string; /** The quantity of desired phone numbers. The default value is 1. */ quantity?: number; } /** Capabilities of a phone number. */ export interface PhoneNumberCapabilities { /** Capability value for calling. */ calling: PhoneNumberCapabilityType; /** Capability value for SMS. */ sms: PhoneNumberCapabilityType; } /** The result of a phone number search operation. */ export interface PhoneNumberSearchResult { /** The search id. */ searchId: string; /** The phone numbers that are available. Can be fewer than the desired search quantity. */ phoneNumbers: string[]; /** The phone number's type, e.g. geographic, or tollFree. */ phoneNumberType: PhoneNumberType; /** Phone number's assignment type. */ assignmentType: PhoneNumberAssignmentType; /** Capabilities of a phone number. */ capabilities: PhoneNumberCapabilities; /** The incurred cost for a single phone number. */ cost: PhoneNumberCost; /** The date that this search result expires and phone numbers are no longer on hold. A search result expires in less than 15min, e.g. 2020-11-19T16:31:49.048Z. */ searchExpiresBy: Date; } /** The incurred cost for a single phone number. */ export interface PhoneNumberCost { /** The cost amount. */ amount: number; /** The ISO 4217 currency code for the cost amount, e.g. USD. */ currencyCode: string; /** The frequency with which the cost gets billed. */ billingFrequency: "monthly"; } /** The Communication Services error. */ export interface CommunicationErrorResponse { /** The Communication Services error. */ error: CommunicationError; } /** The Communication Services error. */ export interface CommunicationError { /** The error code. */ code: string; /** The error message. */ message: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * Further details about specific errors that led to this error. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: CommunicationError[]; /** * The inner error if any. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly innerError?: CommunicationError; } /** The phone number search purchase request. */ export interface PhoneNumberPurchaseRequest { /** The search id. */ searchId?: string; } /** Long running operation. */ export interface PhoneNumberOperation { /** Status of operation. */ status: PhoneNumberOperationStatus; /** URL for retrieving the result of the operation, if any. */ resourceLocation?: string; /** The date that the operation was created. */ createdDateTime: Date; /** The Communication Services error. */ error?: CommunicationError; /** Id of operation. */ id: string; /** The type of operation, e.g. Search */ operationType: PhoneNumberOperationType; /** * The most recent date that the operation was changed. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly lastActionDateTime?: Date; } /** Capabilities of a phone number. */ export interface PhoneNumberCapabilitiesRequest { /** Capability value for calling. */ calling?: PhoneNumberCapabilityType; /** Capability value for SMS. */ sms?: PhoneNumberCapabilityType; } /** Represents a purchased phone number. */ export interface PurchasedPhoneNumber { /** The id of the phone number, e.g. 11234567890. */ id: string; /** String of the E.164 format of the phone number, e.g. +11234567890. */ phoneNumber: string; /** The ISO 3166-2 code of the phone number's country, e.g. US. */ countryCode: string; /** The phone number's type, e.g. Geographic, TollFree. */ phoneNumberType: PhoneNumberType; /** Capabilities of a phone number. */ capabilities: PhoneNumberCapabilities; /** The assignment type of the phone number. A phone number can be assigned to a person, or to an application. */ assignmentType: PhoneNumberAssignmentType; /** The date and time that the phone number was purchased. */ purchaseDate: Date; /** The incurred cost for a single phone number. */ cost: PhoneNumberCost; } /** The list of purchased phone numbers. */ export interface PurchasedPhoneNumbers { /** Represents a list of phone numbers. */ phoneNumbers: PurchasedPhoneNumber[]; /** Represents the URL link to the next page of phone number results. */ nextLink?: string; } /** Defines headers for PhoneNumbers_searchAvailablePhoneNumbers operation. */ export interface PhoneNumbersSearchAvailablePhoneNumbersHeaders { /** URL to retrieve the final result after operation completes. */ location?: string; /** URL to query for status of the operation. */ operationLocation?: string; /** The operation id. */ operationId?: string; /** The search operation id. */ searchId?: string; } /** Defines headers for PhoneNumbers_purchasePhoneNumbers operation. */ export interface PhoneNumbersPurchasePhoneNumbersHeaders { /** URL to query for status of the operation. */ operationLocation?: string; /** The operation id. */ operationId?: string; /** The purchase operation id. */ purchaseId?: string; } /** Defines headers for PhoneNumbers_getOperation operation. */ export interface PhoneNumbersGetOperationHeaders { /** Url to retrieve the final result after operation completes. */ location?: string; } /** Defines headers for PhoneNumbers_updateCapabilities operation. */ export interface PhoneNumbersUpdateCapabilitiesHeaders { /** URL to retrieve the final result after operation completes. */ location?: string; /** URL to query for status of the operation. */ operationLocation?: string; /** The operation id. */ operationId?: string; /** The capabilities operation id. */ capabilitiesId?: string; } /** Defines headers for PhoneNumbers_releasePhoneNumber operation. */ export interface PhoneNumbersReleasePhoneNumberHeaders { /** URL to query for status of the operation. */ operationLocation?: string; /** The operation id. */ operationId?: string; /** The release operation id. */ releaseId?: string; } /** Defines values for PhoneNumberType. */ export type PhoneNumberType = "geographic" | "tollFree"; /** Defines values for PhoneNumberAssignmentType. */ export type PhoneNumberAssignmentType = "person" | "application"; /** Defines values for PhoneNumberCapabilityType. */ export type PhoneNumberCapabilityType = | "none" | "inbound" | "outbound" | "inbound+outbound"; /** Defines values for PhoneNumberOperationStatus. */ export type PhoneNumberOperationStatus = | "notStarted" | "running" | "succeeded" | "failed"; /** Defines values for PhoneNumberOperationType. */ export type PhoneNumberOperationType = | "purchase" | "releasePhoneNumber" | "search" | "updatePhoneNumberCapabilities"; /** Optional parameters. */ export interface PhoneNumbersSearchAvailablePhoneNumbersOptionalParams extends coreHttp.OperationOptions { /** The area code of the desired phone number, e.g. 425. */ areaCode?: string; /** The quantity of desired phone numbers. The default value is 1. */ quantity?: number; } /** Contains response data for the searchAvailablePhoneNumbers operation. */ export type PhoneNumbersSearchAvailablePhoneNumbersResponse = PhoneNumbersSearchAvailablePhoneNumbersHeaders & PhoneNumberSearchResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PhoneNumberSearchResult; /** The parsed HTTP response headers. */ parsedHeaders: PhoneNumbersSearchAvailablePhoneNumbersHeaders; /** The parsed HTTP response headers. */ [LROSYM]: LROResponseInfo; }; }; /** Contains response data for the getSearchResult operation. */ export type PhoneNumbersGetSearchResultResponse = PhoneNumberSearchResult & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PhoneNumberSearchResult; }; }; /** Optional parameters. */ export interface PhoneNumbersPurchasePhoneNumbersOptionalParams extends coreHttp.OperationOptions { /** The search id. */ searchId?: string; } /** Contains response data for the purchasePhoneNumbers operation. */ export type PhoneNumbersPurchasePhoneNumbersResponse = PhoneNumbersPurchasePhoneNumbersHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: PhoneNumbersPurchasePhoneNumbersHeaders; /** The parsed HTTP response headers. */ [LROSYM]: LROResponseInfo; }; }; /** Contains response data for the getOperation operation. */ export type PhoneNumbersGetOperationResponse = PhoneNumbersGetOperationHeaders & PhoneNumberOperation & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PhoneNumberOperation; /** The parsed HTTP response headers. */ parsedHeaders: PhoneNumbersGetOperationHeaders; }; }; /** Optional parameters. */ export interface PhoneNumbersUpdateCapabilitiesOptionalParams extends coreHttp.OperationOptions { /** Capability value for calling. */ calling?: PhoneNumberCapabilityType; /** Capability value for SMS. */ sms?: PhoneNumberCapabilityType; } /** Contains response data for the updateCapabilities operation. */ export type PhoneNumbersUpdateCapabilitiesResponse = PhoneNumbersUpdateCapabilitiesHeaders & PurchasedPhoneNumber & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PurchasedPhoneNumber; /** The parsed HTTP response headers. */ parsedHeaders: PhoneNumbersUpdateCapabilitiesHeaders; /** The parsed HTTP response headers. */ [LROSYM]: LROResponseInfo; }; }; /** Contains response data for the getByNumber operation. */ export type PhoneNumbersGetByNumberResponse = PurchasedPhoneNumber & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PurchasedPhoneNumber; }; }; /** Contains response data for the releasePhoneNumber operation. */ export type PhoneNumbersReleasePhoneNumberResponse = PhoneNumbersReleasePhoneNumberHeaders & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The parsed HTTP response headers. */ parsedHeaders: PhoneNumbersReleasePhoneNumberHeaders; /** The parsed HTTP response headers. */ [LROSYM]: LROResponseInfo; }; }; /** Optional parameters. */ export interface PhoneNumbersListPhoneNumbersOptionalParams extends coreHttp.OperationOptions { /** An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. */ skip?: number; /** An optional parameter for how many entries to return, for pagination purposes. The default value is 100. */ top?: number; } /** Contains response data for the listPhoneNumbers operation. */ export type PhoneNumbersListPhoneNumbersResponse = PurchasedPhoneNumbers & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PurchasedPhoneNumbers; }; }; /** Optional parameters. */ export interface PhoneNumbersListPhoneNumbersNextOptionalParams extends coreHttp.OperationOptions { /** An optional parameter for how many entries to skip, for pagination purposes. The default value is 0. */ skip?: number; /** An optional parameter for how many entries to return, for pagination purposes. The default value is 100. */ top?: number; } /** Contains response data for the listPhoneNumbersNext operation. */ export type PhoneNumbersListPhoneNumbersNextResponse = PurchasedPhoneNumbers & { /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { /** The response body as text (string format) */ bodyAsText: string; /** The response body as parsed JSON or XML */ parsedBody: PurchasedPhoneNumbers; }; }; /** Optional parameters. */ export interface PhoneNumbersClientOptionalParams extends coreHttp.ServiceClientOptions { /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AcceptGrantCommand, AcceptGrantCommandInput, AcceptGrantCommandOutput } from "./commands/AcceptGrantCommand"; import { CheckInLicenseCommand, CheckInLicenseCommandInput, CheckInLicenseCommandOutput, } from "./commands/CheckInLicenseCommand"; import { CheckoutBorrowLicenseCommand, CheckoutBorrowLicenseCommandInput, CheckoutBorrowLicenseCommandOutput, } from "./commands/CheckoutBorrowLicenseCommand"; import { CheckoutLicenseCommand, CheckoutLicenseCommandInput, CheckoutLicenseCommandOutput, } from "./commands/CheckoutLicenseCommand"; import { CreateGrantCommand, CreateGrantCommandInput, CreateGrantCommandOutput } from "./commands/CreateGrantCommand"; import { CreateGrantVersionCommand, CreateGrantVersionCommandInput, CreateGrantVersionCommandOutput, } from "./commands/CreateGrantVersionCommand"; import { CreateLicenseCommand, CreateLicenseCommandInput, CreateLicenseCommandOutput, } from "./commands/CreateLicenseCommand"; import { CreateLicenseConfigurationCommand, CreateLicenseConfigurationCommandInput, CreateLicenseConfigurationCommandOutput, } from "./commands/CreateLicenseConfigurationCommand"; import { CreateLicenseConversionTaskForResourceCommand, CreateLicenseConversionTaskForResourceCommandInput, CreateLicenseConversionTaskForResourceCommandOutput, } from "./commands/CreateLicenseConversionTaskForResourceCommand"; import { CreateLicenseManagerReportGeneratorCommand, CreateLicenseManagerReportGeneratorCommandInput, CreateLicenseManagerReportGeneratorCommandOutput, } from "./commands/CreateLicenseManagerReportGeneratorCommand"; import { CreateLicenseVersionCommand, CreateLicenseVersionCommandInput, CreateLicenseVersionCommandOutput, } from "./commands/CreateLicenseVersionCommand"; import { CreateTokenCommand, CreateTokenCommandInput, CreateTokenCommandOutput } from "./commands/CreateTokenCommand"; import { DeleteGrantCommand, DeleteGrantCommandInput, DeleteGrantCommandOutput } from "./commands/DeleteGrantCommand"; import { DeleteLicenseCommand, DeleteLicenseCommandInput, DeleteLicenseCommandOutput, } from "./commands/DeleteLicenseCommand"; import { DeleteLicenseConfigurationCommand, DeleteLicenseConfigurationCommandInput, DeleteLicenseConfigurationCommandOutput, } from "./commands/DeleteLicenseConfigurationCommand"; import { DeleteLicenseManagerReportGeneratorCommand, DeleteLicenseManagerReportGeneratorCommandInput, DeleteLicenseManagerReportGeneratorCommandOutput, } from "./commands/DeleteLicenseManagerReportGeneratorCommand"; import { DeleteTokenCommand, DeleteTokenCommandInput, DeleteTokenCommandOutput } from "./commands/DeleteTokenCommand"; import { ExtendLicenseConsumptionCommand, ExtendLicenseConsumptionCommandInput, ExtendLicenseConsumptionCommandOutput, } from "./commands/ExtendLicenseConsumptionCommand"; import { GetAccessTokenCommand, GetAccessTokenCommandInput, GetAccessTokenCommandOutput, } from "./commands/GetAccessTokenCommand"; import { GetGrantCommand, GetGrantCommandInput, GetGrantCommandOutput } from "./commands/GetGrantCommand"; import { GetLicenseCommand, GetLicenseCommandInput, GetLicenseCommandOutput } from "./commands/GetLicenseCommand"; import { GetLicenseConfigurationCommand, GetLicenseConfigurationCommandInput, GetLicenseConfigurationCommandOutput, } from "./commands/GetLicenseConfigurationCommand"; import { GetLicenseConversionTaskCommand, GetLicenseConversionTaskCommandInput, GetLicenseConversionTaskCommandOutput, } from "./commands/GetLicenseConversionTaskCommand"; import { GetLicenseManagerReportGeneratorCommand, GetLicenseManagerReportGeneratorCommandInput, GetLicenseManagerReportGeneratorCommandOutput, } from "./commands/GetLicenseManagerReportGeneratorCommand"; import { GetLicenseUsageCommand, GetLicenseUsageCommandInput, GetLicenseUsageCommandOutput, } from "./commands/GetLicenseUsageCommand"; import { GetServiceSettingsCommand, GetServiceSettingsCommandInput, GetServiceSettingsCommandOutput, } from "./commands/GetServiceSettingsCommand"; import { ListAssociationsForLicenseConfigurationCommand, ListAssociationsForLicenseConfigurationCommandInput, ListAssociationsForLicenseConfigurationCommandOutput, } from "./commands/ListAssociationsForLicenseConfigurationCommand"; import { ListDistributedGrantsCommand, ListDistributedGrantsCommandInput, ListDistributedGrantsCommandOutput, } from "./commands/ListDistributedGrantsCommand"; import { ListFailuresForLicenseConfigurationOperationsCommand, ListFailuresForLicenseConfigurationOperationsCommandInput, ListFailuresForLicenseConfigurationOperationsCommandOutput, } from "./commands/ListFailuresForLicenseConfigurationOperationsCommand"; import { ListLicenseConfigurationsCommand, ListLicenseConfigurationsCommandInput, ListLicenseConfigurationsCommandOutput, } from "./commands/ListLicenseConfigurationsCommand"; import { ListLicenseConversionTasksCommand, ListLicenseConversionTasksCommandInput, ListLicenseConversionTasksCommandOutput, } from "./commands/ListLicenseConversionTasksCommand"; import { ListLicenseManagerReportGeneratorsCommand, ListLicenseManagerReportGeneratorsCommandInput, ListLicenseManagerReportGeneratorsCommandOutput, } from "./commands/ListLicenseManagerReportGeneratorsCommand"; import { ListLicensesCommand, ListLicensesCommandInput, ListLicensesCommandOutput, } from "./commands/ListLicensesCommand"; import { ListLicenseSpecificationsForResourceCommand, ListLicenseSpecificationsForResourceCommandInput, ListLicenseSpecificationsForResourceCommandOutput, } from "./commands/ListLicenseSpecificationsForResourceCommand"; import { ListLicenseVersionsCommand, ListLicenseVersionsCommandInput, ListLicenseVersionsCommandOutput, } from "./commands/ListLicenseVersionsCommand"; import { ListReceivedGrantsCommand, ListReceivedGrantsCommandInput, ListReceivedGrantsCommandOutput, } from "./commands/ListReceivedGrantsCommand"; import { ListReceivedLicensesCommand, ListReceivedLicensesCommandInput, ListReceivedLicensesCommandOutput, } from "./commands/ListReceivedLicensesCommand"; import { ListResourceInventoryCommand, ListResourceInventoryCommandInput, ListResourceInventoryCommandOutput, } from "./commands/ListResourceInventoryCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { ListTokensCommand, ListTokensCommandInput, ListTokensCommandOutput } from "./commands/ListTokensCommand"; import { ListUsageForLicenseConfigurationCommand, ListUsageForLicenseConfigurationCommandInput, ListUsageForLicenseConfigurationCommandOutput, } from "./commands/ListUsageForLicenseConfigurationCommand"; import { RejectGrantCommand, RejectGrantCommandInput, RejectGrantCommandOutput } from "./commands/RejectGrantCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdateLicenseConfigurationCommand, UpdateLicenseConfigurationCommandInput, UpdateLicenseConfigurationCommandOutput, } from "./commands/UpdateLicenseConfigurationCommand"; import { UpdateLicenseManagerReportGeneratorCommand, UpdateLicenseManagerReportGeneratorCommandInput, UpdateLicenseManagerReportGeneratorCommandOutput, } from "./commands/UpdateLicenseManagerReportGeneratorCommand"; import { UpdateLicenseSpecificationsForResourceCommand, UpdateLicenseSpecificationsForResourceCommandInput, UpdateLicenseSpecificationsForResourceCommandOutput, } from "./commands/UpdateLicenseSpecificationsForResourceCommand"; import { UpdateServiceSettingsCommand, UpdateServiceSettingsCommandInput, UpdateServiceSettingsCommandOutput, } from "./commands/UpdateServiceSettingsCommand"; import { LicenseManagerClient } from "./LicenseManagerClient"; /** * <p>License Manager makes it easier to manage licenses from software vendors across multiple * Amazon Web Services accounts and on-premises servers.</p> */ export class LicenseManager extends LicenseManagerClient { /** * <p>Accepts the specified grant.</p> */ public acceptGrant(args: AcceptGrantCommandInput, options?: __HttpHandlerOptions): Promise<AcceptGrantCommandOutput>; public acceptGrant(args: AcceptGrantCommandInput, cb: (err: any, data?: AcceptGrantCommandOutput) => void): void; public acceptGrant( args: AcceptGrantCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AcceptGrantCommandOutput) => void ): void; public acceptGrant( args: AcceptGrantCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AcceptGrantCommandOutput) => void), cb?: (err: any, data?: AcceptGrantCommandOutput) => void ): Promise<AcceptGrantCommandOutput> | void { const command = new AcceptGrantCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Checks in the specified license. Check in a license when it is no longer in use.</p> */ public checkInLicense( args: CheckInLicenseCommandInput, options?: __HttpHandlerOptions ): Promise<CheckInLicenseCommandOutput>; public checkInLicense( args: CheckInLicenseCommandInput, cb: (err: any, data?: CheckInLicenseCommandOutput) => void ): void; public checkInLicense( args: CheckInLicenseCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CheckInLicenseCommandOutput) => void ): void; public checkInLicense( args: CheckInLicenseCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CheckInLicenseCommandOutput) => void), cb?: (err: any, data?: CheckInLicenseCommandOutput) => void ): Promise<CheckInLicenseCommandOutput> | void { const command = new CheckInLicenseCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Checks out the specified license for offline use.</p> */ public checkoutBorrowLicense( args: CheckoutBorrowLicenseCommandInput, options?: __HttpHandlerOptions ): Promise<CheckoutBorrowLicenseCommandOutput>; public checkoutBorrowLicense( args: CheckoutBorrowLicenseCommandInput, cb: (err: any, data?: CheckoutBorrowLicenseCommandOutput) => void ): void; public checkoutBorrowLicense( args: CheckoutBorrowLicenseCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CheckoutBorrowLicenseCommandOutput) => void ): void; public checkoutBorrowLicense( args: CheckoutBorrowLicenseCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CheckoutBorrowLicenseCommandOutput) => void), cb?: (err: any, data?: CheckoutBorrowLicenseCommandOutput) => void ): Promise<CheckoutBorrowLicenseCommandOutput> | void { const command = new CheckoutBorrowLicenseCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Checks out the specified license.</p> */ public checkoutLicense( args: CheckoutLicenseCommandInput, options?: __HttpHandlerOptions ): Promise<CheckoutLicenseCommandOutput>; public checkoutLicense( args: CheckoutLicenseCommandInput, cb: (err: any, data?: CheckoutLicenseCommandOutput) => void ): void; public checkoutLicense( args: CheckoutLicenseCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CheckoutLicenseCommandOutput) => void ): void; public checkoutLicense( args: CheckoutLicenseCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CheckoutLicenseCommandOutput) => void), cb?: (err: any, data?: CheckoutLicenseCommandOutput) => void ): Promise<CheckoutLicenseCommandOutput> | void { const command = new CheckoutLicenseCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a grant for the specified license. A grant shares the use of license entitlements with specific Amazon Web Services accounts.</p> */ public createGrant(args: CreateGrantCommandInput, options?: __HttpHandlerOptions): Promise<CreateGrantCommandOutput>; public createGrant(args: CreateGrantCommandInput, cb: (err: any, data?: CreateGrantCommandOutput) => void): void; public createGrant( args: CreateGrantCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateGrantCommandOutput) => void ): void; public createGrant( args: CreateGrantCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateGrantCommandOutput) => void), cb?: (err: any, data?: CreateGrantCommandOutput) => void ): Promise<CreateGrantCommandOutput> | void { const command = new CreateGrantCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new version of the specified grant.</p> */ public createGrantVersion( args: CreateGrantVersionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateGrantVersionCommandOutput>; public createGrantVersion( args: CreateGrantVersionCommandInput, cb: (err: any, data?: CreateGrantVersionCommandOutput) => void ): void; public createGrantVersion( args: CreateGrantVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateGrantVersionCommandOutput) => void ): void; public createGrantVersion( args: CreateGrantVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateGrantVersionCommandOutput) => void), cb?: (err: any, data?: CreateGrantVersionCommandOutput) => void ): Promise<CreateGrantVersionCommandOutput> | void { const command = new CreateGrantVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a license.</p> */ public createLicense( args: CreateLicenseCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLicenseCommandOutput>; public createLicense( args: CreateLicenseCommandInput, cb: (err: any, data?: CreateLicenseCommandOutput) => void ): void; public createLicense( args: CreateLicenseCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLicenseCommandOutput) => void ): void; public createLicense( args: CreateLicenseCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLicenseCommandOutput) => void), cb?: (err: any, data?: CreateLicenseCommandOutput) => void ): Promise<CreateLicenseCommandOutput> | void { const command = new CreateLicenseCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a license configuration.</p> * <p>A license configuration is an abstraction of a customer license agreement that can be * consumed and enforced by License Manager. Components include specifications for the license * type (licensing by instance, socket, CPU, or vCPU), allowed tenancy (shared tenancy, * Dedicated Instance, Dedicated Host, or all of these), license affinity to host (how long a * license must be associated with a host), and the number of licenses purchased and used.</p> */ public createLicenseConfiguration( args: CreateLicenseConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLicenseConfigurationCommandOutput>; public createLicenseConfiguration( args: CreateLicenseConfigurationCommandInput, cb: (err: any, data?: CreateLicenseConfigurationCommandOutput) => void ): void; public createLicenseConfiguration( args: CreateLicenseConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLicenseConfigurationCommandOutput) => void ): void; public createLicenseConfiguration( args: CreateLicenseConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLicenseConfigurationCommandOutput) => void), cb?: (err: any, data?: CreateLicenseConfigurationCommandOutput) => void ): Promise<CreateLicenseConfigurationCommandOutput> | void { const command = new CreateLicenseConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new license conversion task.</p> */ public createLicenseConversionTaskForResource( args: CreateLicenseConversionTaskForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLicenseConversionTaskForResourceCommandOutput>; public createLicenseConversionTaskForResource( args: CreateLicenseConversionTaskForResourceCommandInput, cb: (err: any, data?: CreateLicenseConversionTaskForResourceCommandOutput) => void ): void; public createLicenseConversionTaskForResource( args: CreateLicenseConversionTaskForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLicenseConversionTaskForResourceCommandOutput) => void ): void; public createLicenseConversionTaskForResource( args: CreateLicenseConversionTaskForResourceCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: CreateLicenseConversionTaskForResourceCommandOutput) => void), cb?: (err: any, data?: CreateLicenseConversionTaskForResourceCommandOutput) => void ): Promise<CreateLicenseConversionTaskForResourceCommandOutput> | void { const command = new CreateLicenseConversionTaskForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a report generator.</p> */ public createLicenseManagerReportGenerator( args: CreateLicenseManagerReportGeneratorCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLicenseManagerReportGeneratorCommandOutput>; public createLicenseManagerReportGenerator( args: CreateLicenseManagerReportGeneratorCommandInput, cb: (err: any, data?: CreateLicenseManagerReportGeneratorCommandOutput) => void ): void; public createLicenseManagerReportGenerator( args: CreateLicenseManagerReportGeneratorCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLicenseManagerReportGeneratorCommandOutput) => void ): void; public createLicenseManagerReportGenerator( args: CreateLicenseManagerReportGeneratorCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLicenseManagerReportGeneratorCommandOutput) => void), cb?: (err: any, data?: CreateLicenseManagerReportGeneratorCommandOutput) => void ): Promise<CreateLicenseManagerReportGeneratorCommandOutput> | void { const command = new CreateLicenseManagerReportGeneratorCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new version of the specified license.</p> */ public createLicenseVersion( args: CreateLicenseVersionCommandInput, options?: __HttpHandlerOptions ): Promise<CreateLicenseVersionCommandOutput>; public createLicenseVersion( args: CreateLicenseVersionCommandInput, cb: (err: any, data?: CreateLicenseVersionCommandOutput) => void ): void; public createLicenseVersion( args: CreateLicenseVersionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateLicenseVersionCommandOutput) => void ): void; public createLicenseVersion( args: CreateLicenseVersionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateLicenseVersionCommandOutput) => void), cb?: (err: any, data?: CreateLicenseVersionCommandOutput) => void ): Promise<CreateLicenseVersionCommandOutput> | void { const command = new CreateLicenseVersionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a long-lived token.</p> * <p>A refresh token is a JWT token used to get an access token. With an access token, * you can call AssumeRoleWithWebIdentity to get role credentials that you can use to * call License Manager to manage the specified license.</p> */ public createToken(args: CreateTokenCommandInput, options?: __HttpHandlerOptions): Promise<CreateTokenCommandOutput>; public createToken(args: CreateTokenCommandInput, cb: (err: any, data?: CreateTokenCommandOutput) => void): void; public createToken( args: CreateTokenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateTokenCommandOutput) => void ): void; public createToken( args: CreateTokenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateTokenCommandOutput) => void), cb?: (err: any, data?: CreateTokenCommandOutput) => void ): Promise<CreateTokenCommandOutput> | void { const command = new CreateTokenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified grant.</p> */ public deleteGrant(args: DeleteGrantCommandInput, options?: __HttpHandlerOptions): Promise<DeleteGrantCommandOutput>; public deleteGrant(args: DeleteGrantCommandInput, cb: (err: any, data?: DeleteGrantCommandOutput) => void): void; public deleteGrant( args: DeleteGrantCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteGrantCommandOutput) => void ): void; public deleteGrant( args: DeleteGrantCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteGrantCommandOutput) => void), cb?: (err: any, data?: DeleteGrantCommandOutput) => void ): Promise<DeleteGrantCommandOutput> | void { const command = new DeleteGrantCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified license.</p> */ public deleteLicense( args: DeleteLicenseCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteLicenseCommandOutput>; public deleteLicense( args: DeleteLicenseCommandInput, cb: (err: any, data?: DeleteLicenseCommandOutput) => void ): void; public deleteLicense( args: DeleteLicenseCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteLicenseCommandOutput) => void ): void; public deleteLicense( args: DeleteLicenseCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteLicenseCommandOutput) => void), cb?: (err: any, data?: DeleteLicenseCommandOutput) => void ): Promise<DeleteLicenseCommandOutput> | void { const command = new DeleteLicenseCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified license configuration.</p> * <p>You cannot delete a license configuration that is in use.</p> */ public deleteLicenseConfiguration( args: DeleteLicenseConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteLicenseConfigurationCommandOutput>; public deleteLicenseConfiguration( args: DeleteLicenseConfigurationCommandInput, cb: (err: any, data?: DeleteLicenseConfigurationCommandOutput) => void ): void; public deleteLicenseConfiguration( args: DeleteLicenseConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteLicenseConfigurationCommandOutput) => void ): void; public deleteLicenseConfiguration( args: DeleteLicenseConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteLicenseConfigurationCommandOutput) => void), cb?: (err: any, data?: DeleteLicenseConfigurationCommandOutput) => void ): Promise<DeleteLicenseConfigurationCommandOutput> | void { const command = new DeleteLicenseConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified report generator.</p> * <p>This action deletes the report generator, which stops it from generating future reports. * The action cannot be reversed. It has no effect on the previous reports from this generator.</p> */ public deleteLicenseManagerReportGenerator( args: DeleteLicenseManagerReportGeneratorCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteLicenseManagerReportGeneratorCommandOutput>; public deleteLicenseManagerReportGenerator( args: DeleteLicenseManagerReportGeneratorCommandInput, cb: (err: any, data?: DeleteLicenseManagerReportGeneratorCommandOutput) => void ): void; public deleteLicenseManagerReportGenerator( args: DeleteLicenseManagerReportGeneratorCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteLicenseManagerReportGeneratorCommandOutput) => void ): void; public deleteLicenseManagerReportGenerator( args: DeleteLicenseManagerReportGeneratorCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteLicenseManagerReportGeneratorCommandOutput) => void), cb?: (err: any, data?: DeleteLicenseManagerReportGeneratorCommandOutput) => void ): Promise<DeleteLicenseManagerReportGeneratorCommandOutput> | void { const command = new DeleteLicenseManagerReportGeneratorCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the specified token. Must be called in the license home Region.</p> */ public deleteToken(args: DeleteTokenCommandInput, options?: __HttpHandlerOptions): Promise<DeleteTokenCommandOutput>; public deleteToken(args: DeleteTokenCommandInput, cb: (err: any, data?: DeleteTokenCommandOutput) => void): void; public deleteToken( args: DeleteTokenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteTokenCommandOutput) => void ): void; public deleteToken( args: DeleteTokenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTokenCommandOutput) => void), cb?: (err: any, data?: DeleteTokenCommandOutput) => void ): Promise<DeleteTokenCommandOutput> | void { const command = new DeleteTokenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Extends the expiration date for license consumption.</p> */ public extendLicenseConsumption( args: ExtendLicenseConsumptionCommandInput, options?: __HttpHandlerOptions ): Promise<ExtendLicenseConsumptionCommandOutput>; public extendLicenseConsumption( args: ExtendLicenseConsumptionCommandInput, cb: (err: any, data?: ExtendLicenseConsumptionCommandOutput) => void ): void; public extendLicenseConsumption( args: ExtendLicenseConsumptionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ExtendLicenseConsumptionCommandOutput) => void ): void; public extendLicenseConsumption( args: ExtendLicenseConsumptionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ExtendLicenseConsumptionCommandOutput) => void), cb?: (err: any, data?: ExtendLicenseConsumptionCommandOutput) => void ): Promise<ExtendLicenseConsumptionCommandOutput> | void { const command = new ExtendLicenseConsumptionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets a temporary access token to use with AssumeRoleWithWebIdentity. Access tokens * are valid for one hour.</p> */ public getAccessToken( args: GetAccessTokenCommandInput, options?: __HttpHandlerOptions ): Promise<GetAccessTokenCommandOutput>; public getAccessToken( args: GetAccessTokenCommandInput, cb: (err: any, data?: GetAccessTokenCommandOutput) => void ): void; public getAccessToken( args: GetAccessTokenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAccessTokenCommandOutput) => void ): void; public getAccessToken( args: GetAccessTokenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAccessTokenCommandOutput) => void), cb?: (err: any, data?: GetAccessTokenCommandOutput) => void ): Promise<GetAccessTokenCommandOutput> | void { const command = new GetAccessTokenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets detailed information about the specified grant.</p> */ public getGrant(args: GetGrantCommandInput, options?: __HttpHandlerOptions): Promise<GetGrantCommandOutput>; public getGrant(args: GetGrantCommandInput, cb: (err: any, data?: GetGrantCommandOutput) => void): void; public getGrant( args: GetGrantCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetGrantCommandOutput) => void ): void; public getGrant( args: GetGrantCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetGrantCommandOutput) => void), cb?: (err: any, data?: GetGrantCommandOutput) => void ): Promise<GetGrantCommandOutput> | void { const command = new GetGrantCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets detailed information about the specified license.</p> */ public getLicense(args: GetLicenseCommandInput, options?: __HttpHandlerOptions): Promise<GetLicenseCommandOutput>; public getLicense(args: GetLicenseCommandInput, cb: (err: any, data?: GetLicenseCommandOutput) => void): void; public getLicense( args: GetLicenseCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLicenseCommandOutput) => void ): void; public getLicense( args: GetLicenseCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLicenseCommandOutput) => void), cb?: (err: any, data?: GetLicenseCommandOutput) => void ): Promise<GetLicenseCommandOutput> | void { const command = new GetLicenseCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets detailed information about the specified license configuration.</p> */ public getLicenseConfiguration( args: GetLicenseConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<GetLicenseConfigurationCommandOutput>; public getLicenseConfiguration( args: GetLicenseConfigurationCommandInput, cb: (err: any, data?: GetLicenseConfigurationCommandOutput) => void ): void; public getLicenseConfiguration( args: GetLicenseConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLicenseConfigurationCommandOutput) => void ): void; public getLicenseConfiguration( args: GetLicenseConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLicenseConfigurationCommandOutput) => void), cb?: (err: any, data?: GetLicenseConfigurationCommandOutput) => void ): Promise<GetLicenseConfigurationCommandOutput> | void { const command = new GetLicenseConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about the specified license type conversion task.</p> */ public getLicenseConversionTask( args: GetLicenseConversionTaskCommandInput, options?: __HttpHandlerOptions ): Promise<GetLicenseConversionTaskCommandOutput>; public getLicenseConversionTask( args: GetLicenseConversionTaskCommandInput, cb: (err: any, data?: GetLicenseConversionTaskCommandOutput) => void ): void; public getLicenseConversionTask( args: GetLicenseConversionTaskCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLicenseConversionTaskCommandOutput) => void ): void; public getLicenseConversionTask( args: GetLicenseConversionTaskCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLicenseConversionTaskCommandOutput) => void), cb?: (err: any, data?: GetLicenseConversionTaskCommandOutput) => void ): Promise<GetLicenseConversionTaskCommandOutput> | void { const command = new GetLicenseConversionTaskCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets information about the specified report generator.</p> */ public getLicenseManagerReportGenerator( args: GetLicenseManagerReportGeneratorCommandInput, options?: __HttpHandlerOptions ): Promise<GetLicenseManagerReportGeneratorCommandOutput>; public getLicenseManagerReportGenerator( args: GetLicenseManagerReportGeneratorCommandInput, cb: (err: any, data?: GetLicenseManagerReportGeneratorCommandOutput) => void ): void; public getLicenseManagerReportGenerator( args: GetLicenseManagerReportGeneratorCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLicenseManagerReportGeneratorCommandOutput) => void ): void; public getLicenseManagerReportGenerator( args: GetLicenseManagerReportGeneratorCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLicenseManagerReportGeneratorCommandOutput) => void), cb?: (err: any, data?: GetLicenseManagerReportGeneratorCommandOutput) => void ): Promise<GetLicenseManagerReportGeneratorCommandOutput> | void { const command = new GetLicenseManagerReportGeneratorCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets detailed information about the usage of the specified license.</p> */ public getLicenseUsage( args: GetLicenseUsageCommandInput, options?: __HttpHandlerOptions ): Promise<GetLicenseUsageCommandOutput>; public getLicenseUsage( args: GetLicenseUsageCommandInput, cb: (err: any, data?: GetLicenseUsageCommandOutput) => void ): void; public getLicenseUsage( args: GetLicenseUsageCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetLicenseUsageCommandOutput) => void ): void; public getLicenseUsage( args: GetLicenseUsageCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetLicenseUsageCommandOutput) => void), cb?: (err: any, data?: GetLicenseUsageCommandOutput) => void ): Promise<GetLicenseUsageCommandOutput> | void { const command = new GetLicenseUsageCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets the License Manager settings for the current Region.</p> */ public getServiceSettings( args: GetServiceSettingsCommandInput, options?: __HttpHandlerOptions ): Promise<GetServiceSettingsCommandOutput>; public getServiceSettings( args: GetServiceSettingsCommandInput, cb: (err: any, data?: GetServiceSettingsCommandOutput) => void ): void; public getServiceSettings( args: GetServiceSettingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetServiceSettingsCommandOutput) => void ): void; public getServiceSettings( args: GetServiceSettingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetServiceSettingsCommandOutput) => void), cb?: (err: any, data?: GetServiceSettingsCommandOutput) => void ): Promise<GetServiceSettingsCommandOutput> | void { const command = new GetServiceSettingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the resource associations for the specified license configuration.</p> * <p>Resource associations need not consume licenses from a license configuration. * For example, an AMI or a stopped instance might not consume a license (depending on * the license rules).</p> */ public listAssociationsForLicenseConfiguration( args: ListAssociationsForLicenseConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<ListAssociationsForLicenseConfigurationCommandOutput>; public listAssociationsForLicenseConfiguration( args: ListAssociationsForLicenseConfigurationCommandInput, cb: (err: any, data?: ListAssociationsForLicenseConfigurationCommandOutput) => void ): void; public listAssociationsForLicenseConfiguration( args: ListAssociationsForLicenseConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAssociationsForLicenseConfigurationCommandOutput) => void ): void; public listAssociationsForLicenseConfiguration( args: ListAssociationsForLicenseConfigurationCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: ListAssociationsForLicenseConfigurationCommandOutput) => void), cb?: (err: any, data?: ListAssociationsForLicenseConfigurationCommandOutput) => void ): Promise<ListAssociationsForLicenseConfigurationCommandOutput> | void { const command = new ListAssociationsForLicenseConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the grants distributed for the specified license.</p> */ public listDistributedGrants( args: ListDistributedGrantsCommandInput, options?: __HttpHandlerOptions ): Promise<ListDistributedGrantsCommandOutput>; public listDistributedGrants( args: ListDistributedGrantsCommandInput, cb: (err: any, data?: ListDistributedGrantsCommandOutput) => void ): void; public listDistributedGrants( args: ListDistributedGrantsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListDistributedGrantsCommandOutput) => void ): void; public listDistributedGrants( args: ListDistributedGrantsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDistributedGrantsCommandOutput) => void), cb?: (err: any, data?: ListDistributedGrantsCommandOutput) => void ): Promise<ListDistributedGrantsCommandOutput> | void { const command = new ListDistributedGrantsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the license configuration operations that failed.</p> */ public listFailuresForLicenseConfigurationOperations( args: ListFailuresForLicenseConfigurationOperationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListFailuresForLicenseConfigurationOperationsCommandOutput>; public listFailuresForLicenseConfigurationOperations( args: ListFailuresForLicenseConfigurationOperationsCommandInput, cb: (err: any, data?: ListFailuresForLicenseConfigurationOperationsCommandOutput) => void ): void; public listFailuresForLicenseConfigurationOperations( args: ListFailuresForLicenseConfigurationOperationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListFailuresForLicenseConfigurationOperationsCommandOutput) => void ): void; public listFailuresForLicenseConfigurationOperations( args: ListFailuresForLicenseConfigurationOperationsCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: ListFailuresForLicenseConfigurationOperationsCommandOutput) => void), cb?: (err: any, data?: ListFailuresForLicenseConfigurationOperationsCommandOutput) => void ): Promise<ListFailuresForLicenseConfigurationOperationsCommandOutput> | void { const command = new ListFailuresForLicenseConfigurationOperationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the license configurations for your account.</p> */ public listLicenseConfigurations( args: ListLicenseConfigurationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListLicenseConfigurationsCommandOutput>; public listLicenseConfigurations( args: ListLicenseConfigurationsCommandInput, cb: (err: any, data?: ListLicenseConfigurationsCommandOutput) => void ): void; public listLicenseConfigurations( args: ListLicenseConfigurationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLicenseConfigurationsCommandOutput) => void ): void; public listLicenseConfigurations( args: ListLicenseConfigurationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLicenseConfigurationsCommandOutput) => void), cb?: (err: any, data?: ListLicenseConfigurationsCommandOutput) => void ): Promise<ListLicenseConfigurationsCommandOutput> | void { const command = new ListLicenseConfigurationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the license type conversion tasks for your account.</p> */ public listLicenseConversionTasks( args: ListLicenseConversionTasksCommandInput, options?: __HttpHandlerOptions ): Promise<ListLicenseConversionTasksCommandOutput>; public listLicenseConversionTasks( args: ListLicenseConversionTasksCommandInput, cb: (err: any, data?: ListLicenseConversionTasksCommandOutput) => void ): void; public listLicenseConversionTasks( args: ListLicenseConversionTasksCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLicenseConversionTasksCommandOutput) => void ): void; public listLicenseConversionTasks( args: ListLicenseConversionTasksCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLicenseConversionTasksCommandOutput) => void), cb?: (err: any, data?: ListLicenseConversionTasksCommandOutput) => void ): Promise<ListLicenseConversionTasksCommandOutput> | void { const command = new ListLicenseConversionTasksCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the report generators for your account.</p> */ public listLicenseManagerReportGenerators( args: ListLicenseManagerReportGeneratorsCommandInput, options?: __HttpHandlerOptions ): Promise<ListLicenseManagerReportGeneratorsCommandOutput>; public listLicenseManagerReportGenerators( args: ListLicenseManagerReportGeneratorsCommandInput, cb: (err: any, data?: ListLicenseManagerReportGeneratorsCommandOutput) => void ): void; public listLicenseManagerReportGenerators( args: ListLicenseManagerReportGeneratorsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLicenseManagerReportGeneratorsCommandOutput) => void ): void; public listLicenseManagerReportGenerators( args: ListLicenseManagerReportGeneratorsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLicenseManagerReportGeneratorsCommandOutput) => void), cb?: (err: any, data?: ListLicenseManagerReportGeneratorsCommandOutput) => void ): Promise<ListLicenseManagerReportGeneratorsCommandOutput> | void { const command = new ListLicenseManagerReportGeneratorsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the licenses for your account.</p> */ public listLicenses( args: ListLicensesCommandInput, options?: __HttpHandlerOptions ): Promise<ListLicensesCommandOutput>; public listLicenses(args: ListLicensesCommandInput, cb: (err: any, data?: ListLicensesCommandOutput) => void): void; public listLicenses( args: ListLicensesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLicensesCommandOutput) => void ): void; public listLicenses( args: ListLicensesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLicensesCommandOutput) => void), cb?: (err: any, data?: ListLicensesCommandOutput) => void ): Promise<ListLicensesCommandOutput> | void { const command = new ListLicensesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the license configurations for the specified resource.</p> */ public listLicenseSpecificationsForResource( args: ListLicenseSpecificationsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListLicenseSpecificationsForResourceCommandOutput>; public listLicenseSpecificationsForResource( args: ListLicenseSpecificationsForResourceCommandInput, cb: (err: any, data?: ListLicenseSpecificationsForResourceCommandOutput) => void ): void; public listLicenseSpecificationsForResource( args: ListLicenseSpecificationsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLicenseSpecificationsForResourceCommandOutput) => void ): void; public listLicenseSpecificationsForResource( args: ListLicenseSpecificationsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLicenseSpecificationsForResourceCommandOutput) => void), cb?: (err: any, data?: ListLicenseSpecificationsForResourceCommandOutput) => void ): Promise<ListLicenseSpecificationsForResourceCommandOutput> | void { const command = new ListLicenseSpecificationsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all versions of the specified license.</p> */ public listLicenseVersions( args: ListLicenseVersionsCommandInput, options?: __HttpHandlerOptions ): Promise<ListLicenseVersionsCommandOutput>; public listLicenseVersions( args: ListLicenseVersionsCommandInput, cb: (err: any, data?: ListLicenseVersionsCommandOutput) => void ): void; public listLicenseVersions( args: ListLicenseVersionsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListLicenseVersionsCommandOutput) => void ): void; public listLicenseVersions( args: ListLicenseVersionsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListLicenseVersionsCommandOutput) => void), cb?: (err: any, data?: ListLicenseVersionsCommandOutput) => void ): Promise<ListLicenseVersionsCommandOutput> | void { const command = new ListLicenseVersionsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists grants that are received but not accepted.</p> */ public listReceivedGrants( args: ListReceivedGrantsCommandInput, options?: __HttpHandlerOptions ): Promise<ListReceivedGrantsCommandOutput>; public listReceivedGrants( args: ListReceivedGrantsCommandInput, cb: (err: any, data?: ListReceivedGrantsCommandOutput) => void ): void; public listReceivedGrants( args: ListReceivedGrantsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListReceivedGrantsCommandOutput) => void ): void; public listReceivedGrants( args: ListReceivedGrantsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListReceivedGrantsCommandOutput) => void), cb?: (err: any, data?: ListReceivedGrantsCommandOutput) => void ): Promise<ListReceivedGrantsCommandOutput> | void { const command = new ListReceivedGrantsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists received licenses.</p> */ public listReceivedLicenses( args: ListReceivedLicensesCommandInput, options?: __HttpHandlerOptions ): Promise<ListReceivedLicensesCommandOutput>; public listReceivedLicenses( args: ListReceivedLicensesCommandInput, cb: (err: any, data?: ListReceivedLicensesCommandOutput) => void ): void; public listReceivedLicenses( args: ListReceivedLicensesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListReceivedLicensesCommandOutput) => void ): void; public listReceivedLicenses( args: ListReceivedLicensesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListReceivedLicensesCommandOutput) => void), cb?: (err: any, data?: ListReceivedLicensesCommandOutput) => void ): Promise<ListReceivedLicensesCommandOutput> | void { const command = new ListReceivedLicensesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists resources managed using Systems Manager inventory.</p> */ public listResourceInventory( args: ListResourceInventoryCommandInput, options?: __HttpHandlerOptions ): Promise<ListResourceInventoryCommandOutput>; public listResourceInventory( args: ListResourceInventoryCommandInput, cb: (err: any, data?: ListResourceInventoryCommandOutput) => void ): void; public listResourceInventory( args: ListResourceInventoryCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListResourceInventoryCommandOutput) => void ): void; public listResourceInventory( args: ListResourceInventoryCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListResourceInventoryCommandOutput) => void), cb?: (err: any, data?: ListResourceInventoryCommandOutput) => void ): Promise<ListResourceInventoryCommandOutput> | void { const command = new ListResourceInventoryCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the tags for the specified license configuration.</p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists your tokens.</p> */ public listTokens(args: ListTokensCommandInput, options?: __HttpHandlerOptions): Promise<ListTokensCommandOutput>; public listTokens(args: ListTokensCommandInput, cb: (err: any, data?: ListTokensCommandOutput) => void): void; public listTokens( args: ListTokensCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTokensCommandOutput) => void ): void; public listTokens( args: ListTokensCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTokensCommandOutput) => void), cb?: (err: any, data?: ListTokensCommandOutput) => void ): Promise<ListTokensCommandOutput> | void { const command = new ListTokensCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists all license usage records for a license configuration, displaying license * consumption details by resource at a selected point in time. Use this action to audit the * current license consumption for any license inventory and configuration.</p> */ public listUsageForLicenseConfiguration( args: ListUsageForLicenseConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<ListUsageForLicenseConfigurationCommandOutput>; public listUsageForLicenseConfiguration( args: ListUsageForLicenseConfigurationCommandInput, cb: (err: any, data?: ListUsageForLicenseConfigurationCommandOutput) => void ): void; public listUsageForLicenseConfiguration( args: ListUsageForLicenseConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListUsageForLicenseConfigurationCommandOutput) => void ): void; public listUsageForLicenseConfiguration( args: ListUsageForLicenseConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListUsageForLicenseConfigurationCommandOutput) => void), cb?: (err: any, data?: ListUsageForLicenseConfigurationCommandOutput) => void ): Promise<ListUsageForLicenseConfigurationCommandOutput> | void { const command = new ListUsageForLicenseConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Rejects the specified grant.</p> */ public rejectGrant(args: RejectGrantCommandInput, options?: __HttpHandlerOptions): Promise<RejectGrantCommandOutput>; public rejectGrant(args: RejectGrantCommandInput, cb: (err: any, data?: RejectGrantCommandOutput) => void): void; public rejectGrant( args: RejectGrantCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RejectGrantCommandOutput) => void ): void; public rejectGrant( args: RejectGrantCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RejectGrantCommandOutput) => void), cb?: (err: any, data?: RejectGrantCommandOutput) => void ): Promise<RejectGrantCommandOutput> | void { const command = new RejectGrantCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds the specified tags to the specified license configuration.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified tags from the specified license configuration.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Modifies the attributes of an existing license configuration.</p> */ public updateLicenseConfiguration( args: UpdateLicenseConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateLicenseConfigurationCommandOutput>; public updateLicenseConfiguration( args: UpdateLicenseConfigurationCommandInput, cb: (err: any, data?: UpdateLicenseConfigurationCommandOutput) => void ): void; public updateLicenseConfiguration( args: UpdateLicenseConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateLicenseConfigurationCommandOutput) => void ): void; public updateLicenseConfiguration( args: UpdateLicenseConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateLicenseConfigurationCommandOutput) => void), cb?: (err: any, data?: UpdateLicenseConfigurationCommandOutput) => void ): Promise<UpdateLicenseConfigurationCommandOutput> | void { const command = new UpdateLicenseConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a report generator.</p> * <p>After you make changes to a report generator, it starts generating new reports within 60 minutes of being updated.</p> */ public updateLicenseManagerReportGenerator( args: UpdateLicenseManagerReportGeneratorCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateLicenseManagerReportGeneratorCommandOutput>; public updateLicenseManagerReportGenerator( args: UpdateLicenseManagerReportGeneratorCommandInput, cb: (err: any, data?: UpdateLicenseManagerReportGeneratorCommandOutput) => void ): void; public updateLicenseManagerReportGenerator( args: UpdateLicenseManagerReportGeneratorCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateLicenseManagerReportGeneratorCommandOutput) => void ): void; public updateLicenseManagerReportGenerator( args: UpdateLicenseManagerReportGeneratorCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateLicenseManagerReportGeneratorCommandOutput) => void), cb?: (err: any, data?: UpdateLicenseManagerReportGeneratorCommandOutput) => void ): Promise<UpdateLicenseManagerReportGeneratorCommandOutput> | void { const command = new UpdateLicenseManagerReportGeneratorCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds or removes the specified license configurations for the specified Amazon Web Services resource.</p> * <p>You can update the license specifications of AMIs, instances, and hosts. * You cannot update the license specifications for launch templates and CloudFormation templates, * as they send license configurations to the operation that creates the resource.</p> */ public updateLicenseSpecificationsForResource( args: UpdateLicenseSpecificationsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateLicenseSpecificationsForResourceCommandOutput>; public updateLicenseSpecificationsForResource( args: UpdateLicenseSpecificationsForResourceCommandInput, cb: (err: any, data?: UpdateLicenseSpecificationsForResourceCommandOutput) => void ): void; public updateLicenseSpecificationsForResource( args: UpdateLicenseSpecificationsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateLicenseSpecificationsForResourceCommandOutput) => void ): void; public updateLicenseSpecificationsForResource( args: UpdateLicenseSpecificationsForResourceCommandInput, optionsOrCb?: | __HttpHandlerOptions | ((err: any, data?: UpdateLicenseSpecificationsForResourceCommandOutput) => void), cb?: (err: any, data?: UpdateLicenseSpecificationsForResourceCommandOutput) => void ): Promise<UpdateLicenseSpecificationsForResourceCommandOutput> | void { const command = new UpdateLicenseSpecificationsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates License Manager settings for the current Region.</p> */ public updateServiceSettings( args: UpdateServiceSettingsCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateServiceSettingsCommandOutput>; public updateServiceSettings( args: UpdateServiceSettingsCommandInput, cb: (err: any, data?: UpdateServiceSettingsCommandOutput) => void ): void; public updateServiceSettings( args: UpdateServiceSettingsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateServiceSettingsCommandOutput) => void ): void; public updateServiceSettings( args: UpdateServiceSettingsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateServiceSettingsCommandOutput) => void), cb?: (err: any, data?: UpdateServiceSettingsCommandOutput) => void ): Promise<UpdateServiceSettingsCommandOutput> | void { const command = new UpdateServiceSettingsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { AST_NODE_TYPES, TSESTree, } from '@typescript-eslint/experimental-utils'; import debug from 'debug'; import { isCallExpression, isJsxExpression, isIdentifier, isNewExpression, isParameterDeclaration, isPropertyDeclaration, isTypeReference, isUnionOrIntersectionType, isVariableDeclaration, unionTypeParts, isPropertyAssignment, isBinaryExpression, } from 'tsutils'; import * as ts from 'typescript'; const log = debug('typescript-eslint:eslint-plugin:utils:types'); /** * Checks if the given type is either an array type, * or a union made up solely of array types. */ export function isTypeArrayTypeOrUnionOfArrayTypes( type: ts.Type, checker: ts.TypeChecker, ): boolean { for (const t of unionTypeParts(type)) { if (!checker.isArrayType(t)) { return false; } } return true; } /** * @param type Type being checked by name. * @param allowedNames Symbol names checking on the type. * @returns Whether the type is, extends, or contains all of the allowed names. */ export function containsAllTypesByName( type: ts.Type, allowAny: boolean, allowedNames: Set<string>, ): boolean { if (isTypeFlagSet(type, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { return !allowAny; } if (isTypeReference(type)) { type = type.target; } const symbol = type.getSymbol(); if (symbol && allowedNames.has(symbol.name)) { return true; } if (isUnionOrIntersectionType(type)) { return type.types.every(t => containsAllTypesByName(t, allowAny, allowedNames), ); } const bases = type.getBaseTypes(); return ( typeof bases !== 'undefined' && bases.length > 0 && bases.every(t => containsAllTypesByName(t, allowAny, allowedNames)) ); } /** * Get the type name of a given type. * @param typeChecker The context sensitive TypeScript TypeChecker. * @param type The type to get the name of. */ export function getTypeName( typeChecker: ts.TypeChecker, type: ts.Type, ): string { // It handles `string` and string literal types as string. if ((type.flags & ts.TypeFlags.StringLike) !== 0) { return 'string'; } // If the type is a type parameter which extends primitive string types, // but it was not recognized as a string like. So check the constraint // type of the type parameter. if ((type.flags & ts.TypeFlags.TypeParameter) !== 0) { // `type.getConstraint()` method doesn't return the constraint type of // the type parameter for some reason. So this gets the constraint type // via AST. const symbol = type.getSymbol(); const decls = symbol?.getDeclarations(); const typeParamDecl = decls?.[0] as ts.TypeParameterDeclaration; if ( ts.isTypeParameterDeclaration(typeParamDecl) && typeParamDecl.constraint != null ) { return getTypeName( typeChecker, typeChecker.getTypeFromTypeNode(typeParamDecl.constraint), ); } } // If the type is a union and all types in the union are string like, // return `string`. For example: // - `"a" | "b"` is string. // - `string | string[]` is not string. if ( type.isUnion() && type.types .map(value => getTypeName(typeChecker, value)) .every(t => t === 'string') ) { return 'string'; } // If the type is an intersection and a type in the intersection is string // like, return `string`. For example: `string & {__htmlEscaped: void}` if ( type.isIntersection() && type.types .map(value => getTypeName(typeChecker, value)) .some(t => t === 'string') ) { return 'string'; } return typeChecker.typeToString(type); } /** * Resolves the given node's type. Will resolve to the type's generic constraint, if it has one. */ export function getConstrainedTypeAtLocation( checker: ts.TypeChecker, node: ts.Node, ): ts.Type { const nodeType = checker.getTypeAtLocation(node); const constrained = checker.getBaseConstraintOfType(nodeType); return constrained ?? nodeType; } /** * Checks if the given type is (or accepts) nullable * @param isReceiver true if the type is a receiving type (i.e. the type of a called function's parameter) */ export function isNullableType( type: ts.Type, { isReceiver = false, allowUndefined = true, }: { isReceiver?: boolean; allowUndefined?: boolean } = {}, ): boolean { const flags = getTypeFlags(type); if (isReceiver && flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { return true; } if (allowUndefined) { return (flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0; } else { return (flags & ts.TypeFlags.Null) !== 0; } } /** * Gets the declaration for the given variable */ export function getDeclaration( checker: ts.TypeChecker, node: ts.Expression, ): ts.Declaration | null { const symbol = checker.getSymbolAtLocation(node); if (!symbol) { return null; } const declarations = symbol.getDeclarations(); return declarations?.[0] ?? null; } /** * Gets all of the type flags in a type, iterating through unions automatically */ export function getTypeFlags(type: ts.Type): ts.TypeFlags { let flags: ts.TypeFlags = 0; for (const t of unionTypeParts(type)) { flags |= t.flags; } return flags; } /** * Checks if the given type is (or accepts) the given flags * @param isReceiver true if the type is a receiving type (i.e. the type of a called function's parameter) */ export function isTypeFlagSet( type: ts.Type, flagsToCheck: ts.TypeFlags, isReceiver?: boolean, ): boolean { const flags = getTypeFlags(type); if (isReceiver && flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { return true; } return (flags & flagsToCheck) !== 0; } /** * @returns Whether a type is an instance of the parent type, including for the parent's base types. */ export function typeIsOrHasBaseType( type: ts.Type, parentType: ts.Type, ): boolean { const parentSymbol = parentType.getSymbol(); if (!type.getSymbol() || !parentSymbol) { return false; } const typeAndBaseTypes = [type]; const ancestorTypes = type.getBaseTypes(); if (ancestorTypes) { typeAndBaseTypes.push(...ancestorTypes); } for (const baseType of typeAndBaseTypes) { const baseSymbol = baseType.getSymbol(); if (baseSymbol && baseSymbol.name === parentSymbol.name) { return true; } } return false; } /** * Gets the source file for a given node */ export function getSourceFileOfNode(node: ts.Node): ts.SourceFile { while (node && node.kind !== ts.SyntaxKind.SourceFile) { node = node.parent; } return node as ts.SourceFile; } export function getTokenAtPosition( sourceFile: ts.SourceFile, position: number, ): ts.Node { const queue: ts.Node[] = [sourceFile]; let current: ts.Node; while (queue.length > 0) { current = queue.shift()!; // find the child that contains 'position' for (const child of current.getChildren(sourceFile)) { const start = child.getFullStart(); if (start > position) { // If this child begins after position, then all subsequent children will as well. return current; } const end = child.getEnd(); if ( position < end || (position === end && child.kind === ts.SyntaxKind.EndOfFileToken) ) { queue.push(child); break; } } } return current!; } export interface EqualsKind { isPositive: boolean; isStrict: boolean; } export function getEqualsKind(operator: string): EqualsKind | undefined { switch (operator) { case '==': return { isPositive: true, isStrict: false, }; case '===': return { isPositive: true, isStrict: true, }; case '!=': return { isPositive: false, isStrict: false, }; case '!==': return { isPositive: false, isStrict: true, }; default: return undefined; } } export function getTypeArguments( type: ts.TypeReference, checker: ts.TypeChecker, ): readonly ts.Type[] { // getTypeArguments was only added in TS3.7 if (checker.getTypeArguments) { return checker.getTypeArguments(type); } return type.typeArguments ?? []; } /** * @returns true if the type is `unknown` */ export function isTypeUnknownType(type: ts.Type): boolean { return isTypeFlagSet(type, ts.TypeFlags.Unknown); } /** * @returns true if the type is `any` */ export function isTypeAnyType(type: ts.Type): boolean { if (isTypeFlagSet(type, ts.TypeFlags.Any)) { if (type.intrinsicName === 'error') { log('Found an "error" any type'); } return true; } return false; } /** * @returns true if the type is `any[]` */ export function isTypeAnyArrayType( type: ts.Type, checker: ts.TypeChecker, ): boolean { return ( checker.isArrayType(type) && isTypeAnyType( // getTypeArguments was only added in TS3.7 getTypeArguments(type, checker)[0], ) ); } /** * @returns true if the type is `unknown[]` */ export function isTypeUnknownArrayType( type: ts.Type, checker: ts.TypeChecker, ): boolean { return ( checker.isArrayType(type) && isTypeUnknownType( // getTypeArguments was only added in TS3.7 getTypeArguments(type, checker)[0], ) ); } export const enum AnyType { Any, AnyArray, Safe, } /** * @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, * otherwise it returns `AnyType.Safe`. */ export function isAnyOrAnyArrayTypeDiscriminated( node: ts.Node, checker: ts.TypeChecker, ): AnyType { const type = checker.getTypeAtLocation(node); if (isTypeAnyType(type)) { return AnyType.Any; } if (isTypeAnyArrayType(type, checker)) { return AnyType.AnyArray; } return AnyType.Safe; } /** * Does a simple check to see if there is an any being assigned to a non-any type. * * This also checks generic positions to ensure there's no unsafe sub-assignments. * Note: in the case of generic positions, it makes the assumption that the two types are the same. * * @example See tests for examples * * @returns false if it's safe, or an object with the two types if it's unsafe */ export function isUnsafeAssignment( type: ts.Type, receiver: ts.Type, checker: ts.TypeChecker, senderNode: TSESTree.Node | null, ): false | { sender: ts.Type; receiver: ts.Type } { if (isTypeAnyType(type)) { // Allow assignment of any ==> unknown. if (isTypeUnknownType(receiver)) { return false; } if (!isTypeAnyType(receiver)) { return { sender: type, receiver }; } } if (isTypeReference(type) && isTypeReference(receiver)) { // TODO - figure out how to handle cases like this, // where the types are assignable, but not the same type /* function foo(): ReadonlySet<number> { return new Set<any>(); } // and type Test<T> = { prop: T } type Test2 = { prop: string } declare const a: Test<any>; const b: Test2 = a; */ if (type.target !== receiver.target) { // if the type references are different, assume safe, as we won't know how to compare the two types // the generic positions might not be equivalent for both types return false; } if ( senderNode?.type === AST_NODE_TYPES.NewExpression && senderNode.callee.type === AST_NODE_TYPES.Identifier && senderNode.callee.name === 'Map' && senderNode.arguments.length === 0 && senderNode.typeParameters == null ) { // special case to handle `new Map()` // unfortunately Map's default empty constructor is typed to return `Map<any, any>` :( // https://github.com/typescript-eslint/typescript-eslint/issues/2109#issuecomment-634144396 return false; } const typeArguments = type.typeArguments ?? []; const receiverTypeArguments = receiver.typeArguments ?? []; for (let i = 0; i < typeArguments.length; i += 1) { const arg = typeArguments[i]; const receiverArg = receiverTypeArguments[i]; const unsafe = isUnsafeAssignment(arg, receiverArg, checker, senderNode); if (unsafe) { return { sender: type, receiver }; } } return false; } return false; } /** * Returns the contextual type of a given node. * Contextual type is the type of the target the node is going into. * i.e. the type of a called function's parameter, or the defined type of a variable declaration */ export function getContextualType( checker: ts.TypeChecker, node: ts.Expression, ): ts.Type | undefined { const parent = node.parent; if (!parent) { return; } if (isCallExpression(parent) || isNewExpression(parent)) { if (node === parent.expression) { // is the callee, so has no contextual type return; } } else if ( isVariableDeclaration(parent) || isPropertyDeclaration(parent) || isParameterDeclaration(parent) ) { return parent.type ? checker.getTypeFromTypeNode(parent.type) : undefined; } else if (isJsxExpression(parent)) { return checker.getContextualType(parent); } else if (isPropertyAssignment(parent) && isIdentifier(node)) { return checker.getContextualType(node); } else if ( isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && parent.right === node ) { // is RHS of assignment return checker.getTypeAtLocation(parent.left); } else if ( ![ts.SyntaxKind.TemplateSpan, ts.SyntaxKind.JsxExpression].includes( parent.kind, ) ) { // parent is not something we know we can get the contextual type of return; } // TODO - support return statement checking return checker.getContextualType(node); }
the_stack
import { Lazy, HashCode, Equivalent, Compare, Murmur3, Numbers, Constructors, Interpolate, Interpolator, } from "@swim/util"; import type {Display, Output} from "@swim/codec"; import {Item, Value, Form} from "@swim/structure"; import {AnyTimeZone, TimeZone} from "./TimeZone"; import {DateTimeInterpolator} from "./"; // forward import import {DateTimeForm} from "./"; // forward import import {DateTimeFormat} from "./"; // forward import /** @public */ export type AnyDateTime = DateTime | DateTimeInit | Date | string | number; /** @public */ export interface DateTimeInit { year?: number; month?: number; day?: number; hour?: number; minute?: number; second?: number; millisecond?: number; zone?: AnyTimeZone; } /** @public */ export class DateTime implements Interpolate<DateTime>, HashCode, Equivalent, Compare, Display { constructor(time: number, zone: TimeZone = TimeZone.utc) { this.time = time; this.zone = zone; } isDefined(): boolean { return isFinite(new Date(this.time).getTime()); } readonly time: number; readonly zone: TimeZone; get year(): number { return this.toUTCLocalDate().getUTCFullYear(); } withYear(year: number, month?: number, day?: number, hour?: number, minute?: number, second?: number, millisecond?: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCFullYear(year); if (month !== void 0) { date.setUTCMonth(month); } if (day !== void 0) { date.setUTCDate(day); } if (hour !== void 0) { date.setUTCHours(hour); } if (minute !== void 0) { date.setUTCMinutes(minute); } if (second !== void 0) { date.setUTCSeconds(second); } if (millisecond !== void 0) { date.setUTCMilliseconds(millisecond); } return DateTime.fromUTCLocalDate(date, this.zone); } get month(): number { return this.toUTCLocalDate().getUTCMonth(); } withMonth(month: number, day?: number, hour?: number, minute?: number, second?: number, millisecond?: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCMonth(month); if (day !== void 0) { date.setUTCDate(day); } if (hour !== void 0) { date.setUTCHours(hour); } if (minute !== void 0) { date.setUTCMinutes(minute); } if (second !== void 0) { date.setUTCSeconds(second); } if (millisecond !== void 0) { date.setUTCMilliseconds(millisecond); } return DateTime.fromUTCLocalDate(date, this.zone); } get day(): number { return this.toUTCLocalDate().getUTCDate(); } withDay(day: number, hour?: number, minute?: number, second?: number, millisecond?: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCDate(day); if (hour !== void 0) { date.setUTCHours(hour); } if (minute !== void 0) { date.setUTCMinutes(minute); } if (second !== void 0) { date.setUTCSeconds(second); } if (millisecond !== void 0) { date.setUTCMilliseconds(millisecond); } return DateTime.fromUTCLocalDate(date, this.zone); } get hour(): number { return this.toUTCLocalDate().getUTCHours(); } withHour(hour: number, minute?: number, second?: number, millisecond?: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCHours(hour); if (minute !== void 0) { date.setUTCMinutes(minute); } if (second !== void 0) { date.setUTCSeconds(second); } if (millisecond !== void 0) { date.setUTCMilliseconds(millisecond); } return DateTime.fromUTCLocalDate(date, this.zone); } get minute(): number { return this.toUTCLocalDate().getUTCMinutes(); } withMinute(minute: number, second?: number, millisecond?: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCMinutes(minute); if (second !== void 0) { date.setUTCSeconds(second); } if (millisecond !== void 0) { date.setUTCMilliseconds(millisecond); } return DateTime.fromUTCLocalDate(date, this.zone); } get second(): number { return this.toUTCLocalDate().getUTCSeconds(); } withSecond(second: number, millisecond?: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCSeconds(second); if (millisecond !== void 0) { date.setUTCMilliseconds(millisecond); } return DateTime.fromUTCLocalDate(date, this.zone); } get millisecond(): number { return this.toUTCLocalDate().getUTCMilliseconds(); } withMillisecond(millisecond: number): DateTime { const date = this.toUTCLocalDate(); date.setUTCMilliseconds(millisecond); return DateTime.fromUTCLocalDate(date, this.zone); } get weekday(): number { return this.toUTCLocalDate().getUTCDay(); } /** * Returns this date time shifted by the time zone offset. * @internal */ toUTCLocalDate(): Date { return new Date(this.time + 60000 * this.zone.offset); } toDate(): Date { return new Date(this.time); } valueOf(): number { return this.time; } interpolateTo(that: DateTime): Interpolator<DateTime>; interpolateTo(that: unknown): Interpolator<DateTime> | null; interpolateTo(that: unknown): Interpolator<DateTime> | null { if (that instanceof DateTime) { return DateTimeInterpolator(this, that); } else { return null; } } compareTo(that: unknown): number { if (that instanceof DateTime) { const x = this.time; const y = that.time; return x < y ? -1 : x > y ? 1 : x === y ? 0 : NaN; } return NaN; } equivalentTo(that: AnyDateTime, epsilon?: number): boolean { if (this === that) { return true; } else if (that instanceof DateTime) { return Numbers.equivalent(this.time, that.time, epsilon); } return false; } equals(that: unknown): boolean { if (this === that) { return true; } else if (that instanceof DateTime) { return this.time === that.time && this.zone.equals(that.zone); } return false; } hashCode(): number { return Murmur3.mash(Murmur3.mix(Murmur3.mix(Constructors.hash(DateTime), Numbers.hash(this.time)), this.zone.hashCode())); } display<T>(output: Output<T>, format: DateTimeFormat = DateTimeFormat.iso8601): Output<T> { output = format.writeDate(output, this); return output; } toString(format: DateTimeFormat = DateTimeFormat.iso8601): string { return format.format(this); } static current(zone?: AnyTimeZone): DateTime { zone = zone !== void 0 ? TimeZone.fromAny(zone) : TimeZone.local; return new DateTime(Date.now(), zone); } /** * Returns this date time shifted back by the time zone offset. * @internal */ static fromUTCLocalDate(date: Date, zone: TimeZone): DateTime { return new DateTime(date.getTime() - 60000 * zone.offset, zone); } static fromInit(init: DateTimeInit, zone?: AnyTimeZone): DateTime { let time = Date.UTC(init.year !== void 0 ? init.year : 1970, init.month !== void 0 ? init.month : 0, init.day !== void 0 ? init.day : 1, init.hour !== void 0 ? init.hour : 0, init.minute !== void 0 ? init.minute : 0, init.second !== void 0 ? init.second : 0, init.millisecond !== void 0 ? init.millisecond : 0); if (init.zone !== void 0) { zone = TimeZone.fromAny(init.zone); } if (zone !== void 0) { zone = TimeZone.fromAny(zone); time += 60000 * zone.offset; } else { zone = TimeZone.utc; } return new DateTime(time, zone); } static fromAny(value: AnyDateTime, zone?: AnyTimeZone): DateTime { if (value === void 0 || value === null || value instanceof DateTime) { return value; } else if (value instanceof Date) { zone = zone !== void 0 ? TimeZone.fromAny(zone) : TimeZone.utc; return new DateTime(value.getTime(), zone); } else if (typeof value === "number") { zone = zone !== void 0 ? TimeZone.fromAny(zone) : TimeZone.utc; return new DateTime(value, zone); } else if (typeof value === "string") { return DateTime.parse(value, zone); } else if (DateTime.isInit(value)) { return DateTime.fromInit(value, zone); } throw new TypeError("" + value); } static fromValue(value: Value): DateTime | null { let positional: boolean; const header = value.header("date"); if (header.isDefined()) { value = header; positional = true; } else { positional = false; } const init: DateTimeInit = {}; value.forEach(function (item: Item, index: number) { const key = item.key.stringValue(void 0); if (key !== void 0) { if (key === "year") { init.year = item.toValue().numberValue(init.year); } else if (key === "month") { init.month = item.toValue().numberValue(init.month); } else if (key === "day") { init.day = item.toValue().numberValue(init.day); } else if (key === "hour") { init.hour = item.toValue().numberValue(init.hour); } else if (key === "minute") { init.minute = item.toValue().numberValue(init.minute); } else if (key === "second") { init.second = item.toValue().numberValue(init.second); } else if (key === "millisecond") { init.millisecond = item.toValue().numberValue(init.millisecond); } else if (key === "zone") { init.zone = item.toValue().cast(TimeZone.form(), init.zone); } } else if (item instanceof Value && positional) { if (index === 0) { init.year = item.numberValue(init.year); } else if (index === 1) { init.month = item.numberValue(init.month); } else if (index === 2) { init.day = item.numberValue(init.day); } else if (index === 3) { init.hour = item.numberValue(init.hour); } else if (index === 4) { init.minute = item.numberValue(init.minute); } else if (index === 5) { init.second = item.numberValue(init.second); } else if (index === 6) { init.millisecond = item.numberValue(init.millisecond); } else if (index === 7) { init.zone = item.cast(TimeZone.form(), init.zone); } } }); if (DateTime.isInit(init)) { return DateTime.fromInit(init); } return null; } static parse(date: string, zone?: AnyTimeZone): DateTime { return DateTimeFormat.iso8601.parse(date); } static time(date: AnyDateTime): number { if (date instanceof DateTime) { return date.time; } else if (date instanceof Date) { return date.getTime(); } else if (typeof date === "number") { return date; } else if (typeof date === "string") { return DateTime.parse(date).time; } else if (DateTime.isInit(date)) { return DateTime.fromInit(date).time; } throw new TypeError("" + date); } static zone(date: AnyDateTime): TimeZone { if (date instanceof DateTime) { return date.zone; } else { return TimeZone.utc; } } /** @internal */ static isInit(value: unknown): value is DateTimeInit { if (typeof value === "object" && value !== null) { const init = value as DateTimeInit; return (typeof init.year === "undefined" || typeof init.year === "number") && (typeof init.month === "undefined" || typeof init.month === "number") && (typeof init.day === "undefined" || typeof init.day === "number") && (typeof init.hour === "undefined" || typeof init.hour === "number") && (typeof init.minute === "undefined" || typeof init.minute === "number") && (typeof init.second === "undefined" || typeof init.second === "number") && (typeof init.millisecond === "undefined" || typeof init.millisecond === "number") && (typeof init.zone === "undefined" || TimeZone.isAny(init.zone)) && (typeof init.year === "number" || typeof init.month === "number" || typeof init.day === "number" || typeof init.hour === "number" || typeof init.minute === "number" || typeof init.second === "number" || typeof init.millisecond === "number"); } return false; } /** @internal */ static isAny(value: unknown): value is AnyDateTime { return value instanceof DateTime || value instanceof Date || typeof value === "number" || typeof value === "string" || DateTime.isInit(value); } @Lazy static form(): Form<DateTime, AnyDateTime> { return new DateTimeForm(new DateTime(0)); } }
the_stack
namespace eui { /** * The ProgressBar control provides a visual representation of the progress of a task over time. * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @includeExample extension/eui/components/ProgressBarExample.ts * @language en_US */ /** * ProgressBar 控件为随时间而变的任务进度提供了形象化的表示。 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @includeExample extension/eui/components/ProgressBarExample.ts * @language zh_CN */ export class ProgressBar extends Range { /** * Constructor. * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 构造函数。 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public constructor() { super(); this.animation = new sys.Animation(this.animationUpdateHandler, this); } /** * this hightlight component of the progressbar. * * @skinPart * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 进度高亮显示对象。 * * @skinPart * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public thumb:eui.UIComponent = null; /** * the label of the progressbar. * * @skinPart * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 进度条文本 * * @skinPart * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public labelDisplay:Label = null; /** * @private */ private _labelFunction:(value:number, maximum:number)=>string = null; /** * a text format callback function。example: * <code>labelFunction(value:Number,maximum:Number):String;</code> * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 进度条文本格式化回调函数。示例: * <code>labelFunction(value:Number,maximum:Number):String;</code> * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get labelFunction():(value:number, maximum:number)=>string { return this._labelFunction; } public set labelFunction(value:(value:number, maximum:number)=>string) { if (this._labelFunction == value) return; this._labelFunction = value; this.invalidateDisplayList(); } /** * Convert the current value to display text * * @param value the current value * @param maximum the maximum value * * @return a converted text * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * 将当前value转换成文本 * * @param value 当前值 * @param maximum 最大值 * * @return 转换后的文本 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ protected valueToLabel(value:number, maximum:number):string { if (this.labelFunction != null) { return this._labelFunction(value, maximum); } return value + " / " + maximum; } /** * @private */ private _slideDuration:number = 500; /** * Duration in milliseconds for a sliding animation * when the value changing. If the vlaue is 0, no animation will be done. * * @default 500 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * value改变时更新视图的缓动动画时间(毫秒为单位)。设置为0则不执行缓动。 * * @default 500 * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get slideDuration():number { return this._slideDuration; } public set slideDuration(value:number) { value = +value | 0; if (this._slideDuration === value) return; this._slideDuration = value; if (this.animation.isPlaying) { this.animation.stop(); this.setValue(this.slideToValue); } } /** * @private */ private _direction:string = Direction.LTR; /** * Direction in which the fill of the ProgressBar expands toward completion. * you should use the <code>Direction</code> class constants to set the property. * * @default Direction.LTR * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language en_US */ /** * ProgressBar 填充在逐步完成过程中扩展的方向。使用 <code>Direction</code> 类定义的常量。 * * @default Direction.LTR * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native * @language zh_CN */ public get direction():string { return this._direction; } public set direction(value:string) { if (this._direction == value) return; if(this.thumb) this.thumb.x = this.thumbInitX; if(this.thumb) this.thumb.y = this.thumbInitY; this._direction = value; this.invalidateDisplayList(); } /** * @private * 动画实例 */ private animation:sys.Animation; /** * @private * 动画播放结束时要到达的value。 */ private slideToValue:number = 0; /** * @private * * @param newValue */ $setValue(newValue:number):boolean { if (this.value === newValue) return false; let values = this.$Range; let result:boolean = super.$setValue(newValue); if (this._slideDuration > 0 && this.$stage) { this.validateProperties();//最大值最小值发生改变时要立即应用,防止当前起始值不正确。 let animation = this.animation; if (animation.isPlaying) { this.animationValue = this.slideToValue; this.invalidateDisplayList(); animation.stop(); } this.slideToValue = this.nearestValidValue(newValue, values[sys.RangeKeys.snapInterval]); if (this.slideToValue === this.animationValue) return result; let duration = this._slideDuration * (Math.abs(this.animationValue - this.slideToValue) / (values[sys.RangeKeys.maximum] - values[sys.RangeKeys.minimum])); animation.duration = duration === Infinity ? 0 : duration; animation.from = this.animationValue; animation.to = this.slideToValue; animation.play(); } else { this.animationValue = this.value; } return result; } /** * @private */ private animationValue:number = 0; /** * @private * 动画播放更新数值 */ private animationUpdateHandler(animation:sys.Animation):void { let values = this.$Range; let value = this.nearestValidValue(animation.currentValue, values[sys.RangeKeys.snapInterval]); this.animationValue = Math.min(values[sys.RangeKeys.maximum], Math.max(values[sys.RangeKeys.minimum], value)); this.invalidateDisplayList(); } /** * @private */ private thumbInitX = 0; /** * @private */ private thumbInitY = 0; /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ protected partAdded(partName:string, instance:any):void { super.partAdded(partName, instance); if (instance === this.thumb) { if(this.thumb.x) this.thumbInitX = this.thumb.x; if(this.thumb.y) this.thumbInitY = this.thumb.y; this.thumb.addEventListener(egret.Event.RESIZE, this.onThumbResize, this); } } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ protected partRemoved(partName:string, instance:any):void { super.partRemoved(partName, instance); if (instance === this.thumb) { this.thumb.removeEventListener(egret.Event.RESIZE, this.onThumbResize, this); } } /** * @private * thumb的位置或尺寸发生改变 */ private onThumbResize(event:egret.Event):void { this.updateSkinDisplayList(); } /** * @inheritDoc * * @version Egret 2.4 * @version eui 1.0 * @platform Web,Native */ protected updateSkinDisplayList():void { let currentValue = this.animation.isPlaying ? this.animationValue : this.value; let maxValue = this.maximum; let thumb = this.thumb; if (thumb) { let thumbWidth = thumb.width; let thumbHeight = thumb.height; let clipWidth = Math.round((currentValue / maxValue) * thumbWidth); if (clipWidth < 0 || clipWidth === Infinity) clipWidth = 0; let clipHeight = Math.round((currentValue / maxValue) * thumbHeight); if (clipHeight < 0 || clipHeight === Infinity) clipHeight = 0; let rect = thumb.$scrollRect; if (!rect) { rect = egret.$TempRectangle; } rect.setTo(0,0,thumbWidth,thumbHeight); let thumbPosX = thumb.x - rect.x; let thumbPosY = thumb.y - rect.y; switch (this._direction) { case eui.Direction.LTR: rect.width = clipWidth; thumb.x = thumbPosX; break; case eui.Direction.RTL: rect.width = clipWidth; rect.x = thumbWidth - clipWidth; thumb.x = rect.x; break; case eui.Direction.TTB: rect.height = clipHeight; thumb.y = thumbPosY; break; case eui.Direction.BTT: rect.height = clipHeight; rect.y = thumbHeight - clipHeight; thumb.y = rect.y; break; } thumb.scrollRect = rect; } if (this.labelDisplay) { this.labelDisplay.text = this.valueToLabel(currentValue, maxValue); } } } }
the_stack
namespace gdjs { import PIXI = GlobalPIXIModule.PIXI; /** * The renderer for a gdjs.RuntimeScene using Pixi.js. */ export class RuntimeScenePixiRenderer { _pixiRenderer: PIXI.Renderer | null; _runtimeScene: gdjs.RuntimeScene; _pixiContainer: PIXI.Container; _debugDraw: PIXI.Graphics | null = null; _debugDrawContainer: PIXI.Container | null = null; _profilerText: PIXI.Text | null = null; _debugDrawRenderedObjectsPoints: Record< number, { wasRendered: boolean; points: Record<string, PIXI.Text>; } >; constructor( runtimeScene: gdjs.RuntimeScene, runtimeGameRenderer: gdjs.RuntimeGamePixiRenderer | null ) { this._pixiRenderer = runtimeGameRenderer ? runtimeGameRenderer.getPIXIRenderer() : null; this._runtimeScene = runtimeScene; this._pixiContainer = new PIXI.Container(); this._debugDrawRenderedObjectsPoints = {}; // Contains the layers of the scene (and, optionally, debug PIXI objects). this._pixiContainer.sortableChildren = true; this._debugDraw = null; } onGameResolutionResized() { if (!this._pixiRenderer) { return; } const runtimeGame = this._runtimeScene.getGame(); this._pixiContainer.scale.x = this._pixiRenderer.width / runtimeGame.getGameResolutionWidth(); this._pixiContainer.scale.y = this._pixiRenderer.height / runtimeGame.getGameResolutionHeight(); } // Nothing to do. onSceneUnloaded() {} render() { if (!this._pixiRenderer) { return; } // this._renderProfileText(); //Uncomment to display profiling times // render the PIXI container of the scene this._pixiRenderer.backgroundColor = this._runtimeScene.getBackgroundColor(); this._pixiRenderer.render(this._pixiContainer); } _renderProfileText() { const profiler = this._runtimeScene.getProfiler(); if (!profiler) { return; } if (!this._profilerText) { this._profilerText = new PIXI.Text(' ', { align: 'left', stroke: '#FFF', strokeThickness: 1, }); // Add on top of all layers: this._pixiContainer.addChild(this._profilerText); } const average = profiler.getFramesAverageMeasures(); const outputs = []; gdjs.Profiler.getProfilerSectionTexts('All', average, outputs); this._profilerText.text = outputs.join('\n'); } /** * Render graphics for debugging purpose. Activate this in `gdjs.RuntimeScene`, * in the `renderAndStep` method. */ renderDebugDraw( instances: gdjs.RuntimeObject[], layersCameraCoordinates: Record<string, [float, float, float, float]>, showHiddenInstances: boolean, showPointsNames: boolean, showCustomPoints: boolean ) { if (!this._debugDraw || !this._debugDrawContainer) { this._debugDrawContainer = new PIXI.Container(); this._debugDraw = new PIXI.Graphics(); // Add on top of all layers: this._debugDrawContainer.addChild(this._debugDraw); this._pixiContainer.addChild(this._debugDrawContainer); } const debugDraw = this._debugDraw; // Reset the boolean "wasRendered" of all points of objects to false: for (let id in this._debugDrawRenderedObjectsPoints) { this._debugDrawRenderedObjectsPoints[id].wasRendered = false; } const renderObjectPoint = ( points: Record<string, PIXI.Text>, name: string, fillColor: integer, x: float, y: float ) => { debugDraw.line.color = fillColor; debugDraw.fill.color = fillColor; debugDraw.drawCircle(x, y, 3); if (showPointsNames) { if (!points[name]) { points[name] = new PIXI.Text(name, { fill: fillColor, fontSize: 12, }); this._debugDrawContainer!.addChild(points[name]); } points[name].position.set(x, y); } }; debugDraw.clear(); debugDraw.beginFill(); debugDraw.alpha = 0.8; debugDraw.lineStyle(2, 0x0000ff, 1); // Draw AABB for (let i = 0; i < instances.length; i++) { const object = instances[i]; const layer = this._runtimeScene.getLayer(object.getLayer()); if ( (!object.isVisible() || !layer.isVisible()) && !showHiddenInstances ) { continue; } const rendererObject = object.getRendererObject(); if (!rendererObject) { continue; } const aabb = object.getAABB(); debugDraw.fill.alpha = 0.2; debugDraw.line.color = 0x778ee8; debugDraw.fill.color = 0x778ee8; const polygon: float[] = []; polygon.push.apply( polygon, layer.convertInverseCoords(aabb.min[0], aabb.min[1]) ); polygon.push.apply( polygon, layer.convertInverseCoords(aabb.max[0], aabb.min[1]) ); polygon.push.apply( polygon, layer.convertInverseCoords(aabb.max[0], aabb.max[1]) ); polygon.push.apply( polygon, layer.convertInverseCoords(aabb.min[0], aabb.max[1]) ); debugDraw.drawPolygon(polygon); } // Draw hitboxes and points for (let i = 0; i < instances.length; i++) { const object = instances[i]; const layer = this._runtimeScene.getLayer(object.getLayer()); if ( (!object.isVisible() || !layer.isVisible()) && !showHiddenInstances ) { continue; } const rendererObject = object.getRendererObject(); if (!rendererObject) { continue; } // Create the structure to store the points in memory const id = object.id; if (!this._debugDrawRenderedObjectsPoints[id]) { this._debugDrawRenderedObjectsPoints[id] = { wasRendered: true, points: {}, }; } const renderedObjectPoints = this._debugDrawRenderedObjectsPoints[id]; renderedObjectPoints.wasRendered = true; // Draw hitboxes (sub-optimal performance) const hitboxes = object.getHitBoxes(); for (let j = 0; j < hitboxes.length; j++) { // Note that this conversion is sub-optimal, but we don't care // as this is for debug draw. const polygon: float[] = []; hitboxes[j].vertices.forEach((point) => { point = layer.convertInverseCoords(point[0], point[1]); polygon.push(point[0]); polygon.push(point[1]); }); debugDraw.fill.alpha = 0; debugDraw.line.alpha = 0.5; debugDraw.line.color = 0xff0000; debugDraw.drawPolygon(polygon); } // Draw points debugDraw.fill.alpha = 0.3; // Draw Center point const centerPointX = object.getDrawableX() + object.getCenterX(); const centerPointY = object.getDrawableY() + object.getCenterY(); const centerPoint = layer.convertInverseCoords( centerPointX, centerPointY ); renderObjectPoint( renderedObjectPoints.points, 'Center', 0xffff00, centerPoint[0], centerPoint[1] ); // Draw Origin point let originPoint = [object.getDrawableX(), object.getDrawableY()]; if (object instanceof gdjs.SpriteRuntimeObject) { // For Sprite objects get the position of the origin point. originPoint = object.getPointPosition('origin'); } originPoint = layer.convertInverseCoords( originPoint[0], originPoint[1] ); renderObjectPoint( renderedObjectPoints.points, 'Origin', 0xff0000, originPoint[0], originPoint[1] ); // Draw custom point if (showCustomPoints && object instanceof gdjs.SpriteRuntimeObject) { if (!object._animationFrame) continue; for (const customPointName in object._animationFrame.points.items) { let customPoint = object.getPointPosition(customPointName); customPoint = layer.convertInverseCoords( customPoint[0], customPoint[1] ); renderObjectPoint( renderedObjectPoints.points, customPointName, 0x0000ff, customPoint[0], customPoint[1] ); } } } // Clean any point text from an object that is not rendered. for (const objectID in this._debugDrawRenderedObjectsPoints) { const renderedObjectPoints = this._debugDrawRenderedObjectsPoints[ objectID ]; if (renderedObjectPoints.wasRendered) continue; const points = renderedObjectPoints.points; for (const name in points) { this._debugDrawContainer.removeChild(points[name]); } } debugDraw.endFill(); } clearDebugDraw(): void { if (this._debugDraw) { this._debugDraw.clear(); } if (this._debugDrawContainer) { this._debugDrawContainer.destroy({ children: true, }); this._pixiContainer.removeChild(this._debugDrawContainer); } this._debugDraw = null; this._debugDrawContainer = null; this._debugDrawRenderedObjectsPoints = {}; } hideCursor(): void { if (!this._pixiRenderer) { return; } this._pixiRenderer.view.style.cursor = 'none'; } showCursor(): void { if (!this._pixiRenderer) { return; } this._pixiRenderer.view.style.cursor = ''; } getPIXIContainer() { return this._pixiContainer; } getPIXIRenderer() { return this._pixiRenderer; } setLayerIndex(layer: gdjs.Layer, index: float): void { const layerPixiRenderer: gdjs.LayerPixiRenderer = layer.getRenderer(); let layerPixiObject: | PIXI.Container | PIXI.Sprite | null = layerPixiRenderer.getRendererObject(); if (layer.isLightingLayer()) { layerPixiObject = layerPixiRenderer.getLightingSprite(); } if (!layerPixiObject) { return; } if (this._pixiContainer.children.indexOf(layerPixiObject) === index) { return; } this._pixiContainer.removeChild(layerPixiObject); this._pixiContainer.addChildAt(layerPixiObject, index); } } //Register the class to let the engine use it. export type RuntimeSceneRenderer = gdjs.RuntimeScenePixiRenderer; export const RuntimeSceneRenderer = gdjs.RuntimeScenePixiRenderer; }
the_stack
import { player, format } from './Synergism'; import { Globals as G } from './Variables'; import { toggleCorruptionLevel } from './Toggles'; import { getElementById } from './Utility'; import { Alert, Prompt } from "./UpdateHTML"; import { DOMCacheGetOrSet } from './Cache/DOM'; export const corruptionDisplay = (index: number) => { if (DOMCacheGetOrSet("corruptionDetails").style.visibility !== "visible") { DOMCacheGetOrSet("corruptionDetails").style.visibility = "visible" } if (DOMCacheGetOrSet("corruptionSelectedPic").style.visibility !== "visible") { DOMCacheGetOrSet("corruptionSelectedPic").style.visibility = "visible" } G['corruptionTrigger'] = index const currentExponent = ((index === 1 || index === 2) && player.usedCorruptions[index] >= 10) ? 1 + 0.02 * player.platonicUpgrades[17] + 0.75 * Math.min(1, player.platonicUpgrades[17]) : 1; const protoExponent = ((index === 1 || index === 2) && player.prototypeCorruptions[index] >= 10) ? 1 + 0.02 * player.platonicUpgrades[17] + 0.75 * Math.min(1, player.platonicUpgrades[17]) : 1; const corruptionTexts: Record<'name' | 'description' | 'current' | 'planned' | 'multiplier' | 'spiritContribution' | 'image', string>[] = [ { name: "Corruption I: Divisiveness", description: "Your multipliers get disintegrated! Is extra devious without also using Maladaption Corruption", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[1]) + ". Effect: Free Mult Exponent ^" + format(G['divisivenessPower'][player.usedCorruptions[1]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[1]) + ". Effect: Free Multiplier Exponent ^" + format(G['divisivenessPower'][player.prototypeCorruptions[1]], 3), multiplier: "Current Score Multiplier: " + format(Math.pow(G['corruptionPointMultipliers'][player.usedCorruptions[1]], currentExponent), 1) + " / Next Ascension Score Multiplier: " + format(Math.pow(G['corruptionPointMultipliers'][player.prototypeCorruptions[1]], protoExponent), 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[1],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[1],2),1) + "%", image: "Pictures/Divisiveness Level 7.png" }, { name: "Corruption II: Maladaption", description: "Insert Cool Text Here. Is extra devious without also using Divisiveness Corruption. Yin/Yang!", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[2]) + ". Effect: Free Accel. Exponent ^" + format(G['maladaptivePower'][player.usedCorruptions[2]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[2]) + ". Effect: Free Accelerator Exponent ^" + format(G['maladaptivePower'][player.prototypeCorruptions[2]], 3), multiplier: "Current Score Multiplier: " + format(Math.pow(G['corruptionPointMultipliers'][player.usedCorruptions[2]], currentExponent), 1) + " / Next Ascension Score Multiplier: " + format(Math.pow(G['corruptionPointMultipliers'][player.prototypeCorruptions[2]], protoExponent), 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[2],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[2],2),1) + "%", image: "Pictures/Maladaption Lvl 7.png" }, { name: "Corruption III: Spacial Dilation", description: "Way to go, Albert.", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[3]) + ". Effect: Time Speed is divided by " + format(1 / G['lazinessMultiplier'][player.usedCorruptions[3]], 5), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[3]) + ". Effect: Time is divided by " + format(1 / G['lazinessMultiplier'][player.prototypeCorruptions[3]], 5), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[3]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[3]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[3],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[3],2),1) + "%", image: "Pictures/Laziness Lvl 7.png" }, { name: "Corruption IV: Hyperchallenged", description: "What's in a challenge?", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[4]) + ". Effect: Challenge Exponent Reqs. x" + format(G['hyperchallengedMultiplier'][player.usedCorruptions[4]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[4]) + ". Effect: Challenge Exponent Reqs. x" + format(G['hyperchallengedMultiplier'][player.prototypeCorruptions[4]], 3), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[4]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[4]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[4],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[4],2),1) + "%", image: "Pictures/Hyperchallenged Lvl 7.png" }, { name: "Corruption V: Scientific Illiteracy", description: "Maybe Albert wouldn't have theorized Dilation after all.", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[5]) + ". Effect: Obtainium gain ^" + format(G['illiteracyPower'][player.usedCorruptions[5]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[5]) + ". Effect: Obtainium gain ^" + format(G['illiteracyPower'][player.prototypeCorruptions[5]], 3), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[5]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[5]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[5],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[5],2),1) + "%", image: "Pictures/Scientific Illiteracy Lvl 7.png" }, { name: "Corruption VI: Market Deflation", description: "Diamond Mine destroyed... no more monopolies!", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[6]) + ". Effect: Diamond gain ^1/" + format(1 / G['deflationMultiplier'][player.usedCorruptions[6]], 2), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[6]) + ". Effect: Diamond gain ^1/" + format(1 / G['deflationMultiplier'][player.prototypeCorruptions[6]], 2), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[6]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[6]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[6],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[6],2),1) + "%", image: "Pictures/Deflation Lvl 7.png" }, { name: "Corruption VII: Extinction", description: "It killed the dinosaurs too, ya dingus.", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[7]) + ". Effect: Ant Production ^" + format(G['extinctionMultiplier'][player.usedCorruptions[7]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[7]) + ". Effect: Ant Production ^" + format(G['extinctionMultiplier'][player.prototypeCorruptions[7]], 3), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[7]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[7]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[7],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[7],2),1) + "%", image: "Pictures/Extinction Lvl 7.png" }, { name: "Corruption VIII: Drought", description: "More like California, am I right?", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[8]) + ". Effect: Offering EXP divided by " + format(G['droughtMultiplier'][player.usedCorruptions[8]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[8]) + ". Effect: Offering EXP divided by " + format(G['droughtMultiplier'][player.prototypeCorruptions[8]], 3), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[8]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[8]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[8],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[8],2),1) + "%", image: "Pictures/Drought Lvl 7.png" }, { name: "Corruption IX: Financial Recession", description: "2008.exe has stopped working.", current: "On this Ascension, this corruption is level " + format(player.usedCorruptions[9]) + ". Effect: Coin Gain ^" + format(G['financialcollapsePower'][player.usedCorruptions[9]], 3), planned: "On next Ascension, this corruption will be level " + format(player.prototypeCorruptions[9]) + ". Effect: Coin Gain ^" + format(G['financialcollapsePower'][player.prototypeCorruptions[9]], 3), multiplier: "Current Score Multiplier: " + format(G['corruptionPointMultipliers'][player.usedCorruptions[9]], 1) + " / Next Ascension Score Multiplier: " + format(G['corruptionPointMultipliers'][player.prototypeCorruptions[9]], 1), spiritContribution: "This Ascension gives Rune Spirit Effect +" + format(4 * Math.pow(player.usedCorruptions[9],2),1) + "% / Next Ascension Rune Spirit Effect +" + format(4 * Math.pow(player.prototypeCorruptions[9],2),1) + "%", image: "Pictures/Financial Collapse Lvl 7.png" }, { name: "CLEANSE THE CORRUPTION", description: "Free this world of sin.", current: "Reset all Corruptions to level 0 for your current ascension. Does not reset your current ascension.", planned: "Push that big 'Reset Corruptions' button to confirm your decision.", multiplier: "Note: if you need to do this, you may have bitten off more than you can chew.", spiritContribution: "", image: "Pictures/ExitCorruption.png" } ]; const text = corruptionTexts[index-1]; DOMCacheGetOrSet("corruptionName").textContent = text.name DOMCacheGetOrSet("corruptionDescription").textContent = text.description DOMCacheGetOrSet("corruptionLevelCurrent").textContent = text.current DOMCacheGetOrSet("corruptionLevelPlanned").textContent = text.planned DOMCacheGetOrSet("corruptionMultiplierContribution").textContent = text.multiplier DOMCacheGetOrSet("corruptionSpiritContribution").textContent = text.spiritContribution DOMCacheGetOrSet("corruptionSelectedPic").setAttribute("src", text.image) if (index < 10) { DOMCacheGetOrSet(`corrCurrent${index}`).textContent = format(player.usedCorruptions[index]) DOMCacheGetOrSet(`corrNext${index}`).textContent = format(player.prototypeCorruptions[index]) } } export const corruptionStatsUpdate = () => { for (let i = 1; i <= 9; i++) { // https://discord.com/channels/677271830838640680/706329553639047241/841749032841379901 const a = DOMCacheGetOrSet(`corrCurrent${i}`); const b = DOMCacheGetOrSet(`corrNext${i}`) if (a) a.textContent = format(player.usedCorruptions[i]) else console.log(`Send to Platonic: corrCurrent${i} is null`); if (b) b.textContent = format(player.prototypeCorruptions[i]) else console.log(`Send to Platonic: corrNext${i} is null`); } } export const corruptionButtonsAdd = () => { const rows = document.getElementsByClassName("corruptionStatRow"); for (let i = 0; i < rows.length; i++) { const row = rows[i]; const p = document.createElement("p"); p.className = "corrDesc" let text = document.createTextNode("Current: ") p.appendChild(text) let span = document.createElement("span"); span.id = `corrCurrent${i + 1}`; span.textContent = player.usedCorruptions[i + 1] + ''; p.appendChild(span); text = document.createTextNode(" / Next: "); p.appendChild(text); span = document.createElement("span"); span.id = `corrNext${i + 1}`; span.textContent = player.prototypeCorruptions[i + 1] + ''; p.appendChild(span); row.appendChild(p); let btn; btn = document.createElement("button"); btn.className = "corrBtn corruptionMax"; btn.textContent = "+13"; btn.onclick = () => toggleCorruptionLevel(i + 1, 13); row.appendChild(btn); btn = document.createElement("button"); btn.className = "corrBtn corruptionUp"; btn.textContent = "+1"; btn.onclick = () => toggleCorruptionLevel(i + 1, 1); row.appendChild(btn); btn = document.createElement("button"); btn.className = "corrBtn corruptionDown"; btn.textContent = "-1"; btn.onclick = () => toggleCorruptionLevel(i + 1, -1); row.appendChild(btn); btn = document.createElement("button"); btn.className = "corrBtn corruptionReset"; btn.textContent = "-13"; btn.addEventListener('click', () => toggleCorruptionLevel(i + 1, -13)); row.appendChild(btn); row.addEventListener('click', () => corruptionDisplay(i + 1)); } } export const corruptionLoadoutTableCreate = () => { const corrCount = 9 const table = getElementById<HTMLTableElement>("corruptionLoadoutTable") for (let i = 0; i < Object.keys(player.corruptionLoadouts).length + 1; i++) { const row = table.insertRow() for (let j = 0; j <= corrCount; j++) { const cell = row.insertCell(); if (j === 0) { if (i === 0) cell.textContent = 'Next:' // Other loadout names are updated after player load in Synergism.ts > loadSynergy } else if (j <= corrCount) { cell.textContent = ((i === 0) ? player.prototypeCorruptions[j] : player.corruptionLoadouts[i][j]).toString(); cell.style.textAlign = "center" } } if (i === 0) { let cell = row.insertCell(); //empty cell = row.insertCell(); const btn = document.createElement("button"); btn.className = "corrLoad" btn.textContent = "Zero" btn.onclick = () => corruptionLoadoutSaveLoad(false, i); cell.appendChild(btn); cell.title = "Reset corruptions to zero on your next ascension" } else { let cell = row.insertCell(); let btn = document.createElement("button"); btn.className = "corrSave" btn.textContent = "Save" btn.onclick = () => corruptionLoadoutSaveLoad(true, i); cell.appendChild(btn); cell = row.insertCell(); btn = document.createElement("button"); btn.className = "corrLoad" btn.textContent = "Load" btn.onclick = () => corruptionLoadoutSaveLoad(false, i); cell.appendChild(btn); } } } export const corruptionLoadoutTableUpdate = (updateRow = 0) => { const row = getElementById<HTMLTableElement>("corruptionLoadoutTable").rows[updateRow + 1].cells; for (let i = 1; i < row.length; i++) { if (i > 9) break; row[i].textContent = ((updateRow === 0) ? player.prototypeCorruptions[i] : player.corruptionLoadouts[updateRow][i]).toString(); } } const corruptionLoadoutSaveLoad = (save = true, loadout = 1) => { if (save) { player.corruptionLoadouts[loadout] = Array.from(player.prototypeCorruptions) corruptionLoadoutTableUpdate(loadout) } else { if (loadout === 0) { player.prototypeCorruptions = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } else { player.prototypeCorruptions = Array.from(player.corruptionLoadouts[loadout]) } corruptionLoadoutTableUpdate() corruptionStatsUpdate(); } } async function corruptionLoadoutGetNewName(loadout = 0) { const maxChars = 9 // eslint-disable-next-line const regex = /^[\x00-\xFF]*$/ const renamePrompt = await Prompt( `What would you like to name Loadout ${loadout + 1}? ` + `Names cannot be longer than ${maxChars} characters. Nothing crazy!` ); if (!renamePrompt) { return Alert('Okay, maybe next time.'); } else if (renamePrompt.length > maxChars) { return Alert('The name you provided is too long! Try again.') } else if (!regex.test(renamePrompt)) { return Alert("The Loadout Renamer didn't like a character in your name! Try something else.") } else { player.corruptionLoadoutNames[loadout] = renamePrompt updateCorruptionLoadoutNames(); } } export const updateCorruptionLoadoutNames = () => { const rows = getElementById<HTMLTableElement>("corruptionLoadoutTable").rows for (let i = 0; i < Object.keys(player.corruptionLoadouts).length; i++) { const cells = rows[i + 2].cells //start changes on 2nd row if (cells[0].textContent.length === 0) { //first time setup cells[0].addEventListener('click', () => corruptionLoadoutGetNewName(i)); //get name function handles -1 for array cells[0].classList.add('corrLoadoutName'); } cells[0].textContent = `${player.corruptionLoadoutNames[i]}:`; } } export const corruptionCleanseConfirm = () => { const corrupt = DOMCacheGetOrSet('corruptionCleanseConfirm'); corrupt.style.visibility = 'visible'; setTimeout(() => corrupt.style.visibility = 'hidden', 10000); }
the_stack
import { parseMol2 } from '../mol2/parser'; const Mol2String = `@<TRIPOS>MOLECULE 5816 26 26 0 0 0 SMALL GASTEIGER @<TRIPOS>ATOM 1 O 1.7394 -2.1169 -1.0894 O.3 1 LIG1 -0.3859 2 O -2.2941 1.0781 -1.7979 O.3 1 LIG1 -0.5033 3 O -3.6584 0.5842 0.5722 O.3 1 LIG1 -0.5033 4 N 2.6359 1.0243 0.7030 N.3 1 LIG1 -0.3162 5 C 1.6787 -1.1447 -0.0373 C.3 1 LIG1 0.0927 6 C 0.2684 -0.6866 0.1208 C.ar 1 LIG1 -0.0143 7 C 2.6376 0.0193 -0.3576 C.3 1 LIG1 0.0258 8 C -0.3658 -0.0099 -0.9212 C.ar 1 LIG1 -0.0109 9 C -0.4164 -0.9343 1.3105 C.ar 1 LIG1 -0.0524 10 C -1.6849 0.4191 -0.7732 C.ar 1 LIG1 0.1586 11 C -1.7353 -0.5053 1.4585 C.ar 1 LIG1 -0.0162 12 C -2.3696 0.1713 0.4166 C.ar 1 LIG1 0.1582 13 C 3.5645 2.1013 0.3950 C.3 1 LIG1 -0.0157 14 H 2.0210 -1.6511 0.8741 H 1 LIG1 0.0656 15 H 2.3808 0.4742 -1.3225 H 1 LIG1 0.0453 16 H 3.6478 -0.3931 -0.4831 H 1 LIG1 0.0453 17 H 0.1501 0.1801 -1.8589 H 1 LIG1 0.0659 18 H 0.0640 -1.4598 2.1315 H 1 LIG1 0.0622 19 H 2.9013 0.5888 1.5858 H 1 LIG1 0.1217 20 H -2.2571 -0.7050 2.3907 H 1 LIG1 0.0655 21 H 2.6646 -2.4067 -1.1652 H 1 LIG1 0.2103 22 H 3.2862 2.6124 -0.5325 H 1 LIG1 0.0388 23 H 4.5925 1.7346 0.3078 H 1 LIG1 0.0388 24 H 3.5401 2.8441 1.1985 H 1 LIG1 0.0388 25 H -3.2008 1.2997 -1.5231 H 1 LIG1 0.2923 26 H -3.9690 0.3259 1.4570 H 1 LIG1 0.2923 @<TRIPOS>BOND 1 1 5 1 2 1 21 1 3 2 10 1 4 2 25 1 5 3 12 1 6 3 26 1 7 4 7 1 8 4 13 1 9 4 19 1 10 5 6 1 11 5 7 1 12 5 14 1 13 6 8 ar 14 6 9 ar 15 7 15 1 16 7 16 1 17 8 10 ar 18 8 17 1 19 9 11 ar 20 9 18 1 21 10 12 ar 22 11 12 ar 23 11 20 1 24 13 22 1 25 13 23 1 26 13 24 1`; const Mol2StringMultiBlocks = `@<TRIPOS>MOLECULE 5816 26 26 0 0 0 SMALL GASTEIGER @<TRIPOS>ATOM 1 O 1.7394 -2.1169 -1.0894 O.3 1 LIG1 -0.3859 2 O -2.2941 1.0781 -1.7979 O.3 1 LIG1 -0.5033 3 O -3.6584 0.5842 0.5722 O.3 1 LIG1 -0.5033 4 N 2.6359 1.0243 0.7030 N.3 1 LIG1 -0.3162 5 C 1.6787 -1.1447 -0.0373 C.3 1 LIG1 0.0927 6 C 0.2684 -0.6866 0.1208 C.ar 1 LIG1 -0.0143 7 C 2.6376 0.0193 -0.3576 C.3 1 LIG1 0.0258 8 C -0.3658 -0.0099 -0.9212 C.ar 1 LIG1 -0.0109 9 C -0.4164 -0.9343 1.3105 C.ar 1 LIG1 -0.0524 10 C -1.6849 0.4191 -0.7732 C.ar 1 LIG1 0.1586 11 C -1.7353 -0.5053 1.4585 C.ar 1 LIG1 -0.0162 12 C -2.3696 0.1713 0.4166 C.ar 1 LIG1 0.1582 13 C 3.5645 2.1013 0.3950 C.3 1 LIG1 -0.0157 14 H 2.0210 -1.6511 0.8741 H 1 LIG1 0.0656 15 H 2.3808 0.4742 -1.3225 H 1 LIG1 0.0453 16 H 3.6478 -0.3931 -0.4831 H 1 LIG1 0.0453 17 H 0.1501 0.1801 -1.8589 H 1 LIG1 0.0659 18 H 0.0640 -1.4598 2.1315 H 1 LIG1 0.0622 19 H 2.9013 0.5888 1.5858 H 1 LIG1 0.1217 20 H -2.2571 -0.7050 2.3907 H 1 LIG1 0.0655 21 H 2.6646 -2.4067 -1.1652 H 1 LIG1 0.2103 22 H 3.2862 2.6124 -0.5325 H 1 LIG1 0.0388 23 H 4.5925 1.7346 0.3078 H 1 LIG1 0.0388 24 H 3.5401 2.8441 1.1985 H 1 LIG1 0.0388 25 H -3.2008 1.2997 -1.5231 H 1 LIG1 0.2923 26 H -3.9690 0.3259 1.4570 H 1 LIG1 0.2923 @<TRIPOS>BOND 1 1 5 1 2 1 21 1 3 2 10 1 4 2 25 1 5 3 12 1 6 3 26 1 7 4 7 1 8 4 13 1 9 4 19 1 10 5 6 1 11 5 7 1 12 5 14 1 13 6 8 ar 14 6 9 ar 15 7 15 1 16 7 16 1 17 8 10 ar 18 8 17 1 19 9 11 ar 20 9 18 1 21 10 12 ar 22 11 12 ar 23 11 20 1 24 13 22 1 25 13 23 1 26 13 24 1 @<TRIPOS>MOLECULE 5816 26 26 0 0 0 SMALL GASTEIGER @<TRIPOS>ATOM 1 O 1.7394 -2.1169 -1.0894 O.3 1 LIG1 -0.3859 2 O -2.2941 1.0781 -1.7979 O.3 1 LIG1 -0.5033 3 O -3.6584 0.5842 0.5722 O.3 1 LIG1 -0.5033 4 N 2.6359 1.0243 0.7030 N.3 1 LIG1 -0.3162 5 C 1.6787 -1.1447 -0.0373 C.3 1 LIG1 0.0927 6 C 0.2684 -0.6866 0.1208 C.ar 1 LIG1 -0.0143 7 C 2.6376 0.0193 -0.3576 C.3 1 LIG1 0.0258 8 C -0.3658 -0.0099 -0.9212 C.ar 1 LIG1 -0.0109 9 C -0.4164 -0.9343 1.3105 C.ar 1 LIG1 -0.0524 10 C -1.6849 0.4191 -0.7732 C.ar 1 LIG1 0.1586 11 C -1.7353 -0.5053 1.4585 C.ar 1 LIG1 -0.0162 12 C -2.3696 0.1713 0.4166 C.ar 1 LIG1 0.1582 13 C 3.5645 2.1013 0.3950 C.3 1 LIG1 -0.0157 14 H 2.0210 -1.6511 0.8741 H 1 LIG1 0.0656 15 H 2.3808 0.4742 -1.3225 H 1 LIG1 0.0453 16 H 3.6478 -0.3931 -0.4831 H 1 LIG1 0.0453 17 H 0.1501 0.1801 -1.8589 H 1 LIG1 0.0659 18 H 0.0640 -1.4598 2.1315 H 1 LIG1 0.0622 19 H 2.9013 0.5888 1.5858 H 1 LIG1 0.1217 20 H -2.2571 -0.7050 2.3907 H 1 LIG1 0.0655 21 H 2.6646 -2.4067 -1.1652 H 1 LIG1 0.2103 22 H 3.2862 2.6124 -0.5325 H 1 LIG1 0.0388 23 H 4.5925 1.7346 0.3078 H 1 LIG1 0.0388 24 H 3.5401 2.8441 1.1985 H 1 LIG1 0.0388 25 H -3.2008 1.2997 -1.5231 H 1 LIG1 0.2923 26 H -3.9690 0.3259 1.4570 H 1 LIG1 0.2923 @<TRIPOS>BOND 1 1 5 1 2 1 21 1 3 2 10 1 4 2 25 1 5 3 12 1 6 3 26 1 7 4 7 1 8 4 13 1 9 4 19 1 10 5 6 1 11 5 7 1 12 5 14 1 13 6 8 ar 14 6 9 ar 15 7 15 1 16 7 16 1 17 8 10 ar 18 8 17 1 19 9 11 ar 20 9 18 1 21 10 12 ar 22 11 12 ar 23 11 20 1 24 13 22 1 25 13 23 1 26 13 24 1`; const Mol2StringMinimal = `@<TRIPOS>MOLECULE 5816 26 26 0 0 0 SMALL GASTEIGER @<TRIPOS>ATOM 1 O 1.7394 -2.1169 -1.0894 O.3 2 O -2.2941 1.0781 -1.7979 O.3 3 O -3.6584 0.5842 0.5722 O.3 4 N 2.6359 1.0243 0.7030 N.3 5 C 1.6787 -1.1447 -0.0373 C.3 6 C 0.2684 -0.6866 0.1208 C.ar 7 C 2.6376 0.0193 -0.3576 C.3 8 C -0.3658 -0.0099 -0.9212 C.ar 9 C -0.4164 -0.9343 1.3105 C.ar 10 C -1.6849 0.4191 -0.7732 C.ar 11 C -1.7353 -0.5053 1.4585 C.ar 12 C -2.3696 0.1713 0.4166 C.ar 13 C 3.5645 2.1013 0.3950 C.3 14 H 2.0210 -1.6511 0.8741 H 15 H 2.3808 0.4742 -1.3225 H 16 H 3.6478 -0.3931 -0.4831 H 17 H 0.1501 0.1801 -1.8589 H 18 H 0.0640 -1.4598 2.1315 H 19 H 2.9013 0.5888 1.5858 H 20 H -2.2571 -0.7050 2.3907 H 21 H 2.6646 -2.4067 -1.1652 H 22 H 3.2862 2.6124 -0.5325 H 23 H 4.5925 1.7346 0.3078 H 24 H 3.5401 2.8441 1.1985 H 25 H -3.2008 1.2997 -1.5231 H 26 H -3.9690 0.3259 1.4570 H @<TRIPOS>BOND 1 1 5 1 2 1 21 1 3 2 10 1 4 2 25 1 5 3 12 1 6 3 26 1 7 4 7 1 8 4 13 1 9 4 19 1 10 5 6 1 11 5 7 1 12 5 14 1 13 6 8 ar 14 6 9 ar 15 7 15 1 16 7 16 1 17 8 10 ar 18 8 17 1 19 9 11 ar 20 9 18 1 21 10 12 ar 22 11 12 ar 23 11 20 1 24 13 22 1 25 13 23 1 26 13 24 1`; describe('mol2 reader', () => { it('basic', async () => { const parsed = await parseMol2(Mol2String, '').run(); if (parsed.isError) { throw new Error(parsed.message); } const mol2File = parsed.result; // number of structures expect(mol2File.structures.length).toBe(1); const data = mol2File.structures[0]; const { molecule, atoms, bonds } = data; // molecule fields expect(molecule.mol_name).toBe('5816'); expect(molecule.num_atoms).toBe(26); expect(molecule.num_bonds).toBe(26); expect(molecule.num_subst).toBe(0); expect(molecule.num_feat).toBe(0); expect(molecule.num_sets).toBe(0); expect(molecule.mol_type).toBe('SMALL'); expect(molecule.charge_type).toBe('GASTEIGER'); expect(molecule.status_bits).toBe(''); expect(molecule.mol_comment).toBe(''); // required atom fields expect(atoms.count).toBe(26); expect(atoms.atom_id.value(0)).toBe(1); expect(atoms.atom_name.value(0)).toBe('O'); expect(atoms.x.value(0)).toBeCloseTo(1.7394, 0.001); expect(atoms.y.value(0)).toBeCloseTo(-2.1169, 0.0001); expect(atoms.z.value(0)).toBeCloseTo(-1.0893, 0.0001); expect(atoms.atom_type.value(0)).toBe('O.3'); // optional atom fields expect(atoms.subst_id.value(0)).toBe(1); expect(atoms.subst_name.value(0)).toBe('LIG1'); expect(atoms.charge.value(0)).toBeCloseTo(-0.3859); expect(atoms.status_bit.value(0)).toBe(''); // required bond fields expect(bonds.count).toBe(26); expect(bonds.bond_id.value(0)).toBe(1); expect(bonds.origin_atom_id.value(0)).toBe(1); expect(bonds.target_atom_id.value(0)).toBe(5); expect(bonds.bond_type.value(0)).toBe('1'); // optional bond fields expect(bonds.status_bits.value(0)).toBe(''); }); it('multiblocks', async () => { const parsed = await parseMol2(Mol2StringMultiBlocks, '').run(); if (parsed.isError) { throw new Error(parsed.message); } const mol2File = parsed.result; // number of structures expect(mol2File.structures.length).toBe(2); const data = mol2File.structures[1]; const { molecule, atoms, bonds } = data; // molecule fields expect(molecule.mol_name).toBe('5816'); expect(molecule.num_atoms).toBe(26); expect(molecule.num_bonds).toBe(26); expect(molecule.num_subst).toBe(0); expect(molecule.num_feat).toBe(0); expect(molecule.num_sets).toBe(0); expect(molecule.mol_type).toBe('SMALL'); expect(molecule.charge_type).toBe('GASTEIGER'); expect(molecule.status_bits).toBe(''); expect(molecule.mol_comment).toBe(''); // required atom fields expect(atoms.count).toBe(26); expect(atoms.atom_id.value(0)).toBe(1); expect(atoms.atom_name.value(0)).toBe('O'); expect(atoms.x.value(0)).toBeCloseTo(1.7394, 0.001); expect(atoms.y.value(0)).toBeCloseTo(-2.1169, 0.0001); expect(atoms.z.value(0)).toBeCloseTo(-1.0893, 0.0001); expect(atoms.atom_type.value(0)).toBe('O.3'); // optional atom fields expect(atoms.subst_id.value(0)).toBe(1); expect(atoms.subst_name.value(0)).toBe('LIG1'); expect(atoms.charge.value(0)).toBeCloseTo(-0.3859); expect(atoms.status_bit.value(0)).toBe(''); // required bond fields expect(bonds.count).toBe(26); expect(bonds.bond_id.value(0)).toBe(1); expect(bonds.origin_atom_id.value(0)).toBe(1); expect(bonds.target_atom_id.value(0)).toBe(5); expect(bonds.bond_type.value(0)).toBe('1'); // optional bond fields expect(bonds.status_bits.value(0)).toBe(''); }); it('minimal', async () => { const parsed = await parseMol2(Mol2StringMinimal, '').run(); if (parsed.isError) { throw new Error(parsed.message); } const mol2File = parsed.result; // number of structures expect(mol2File.structures.length).toBe(1); const data = mol2File.structures[0]; const { molecule, atoms, bonds } = data; // molecule fields expect(molecule.mol_name).toBe('5816'); expect(molecule.num_atoms).toBe(26); expect(molecule.num_bonds).toBe(26); expect(molecule.num_subst).toBe(0); expect(molecule.num_feat).toBe(0); expect(molecule.num_sets).toBe(0); expect(molecule.mol_type).toBe('SMALL'); expect(molecule.charge_type).toBe('GASTEIGER'); expect(molecule.status_bits).toBe(''); expect(molecule.mol_comment).toBe(''); // required atom fields expect(atoms.count).toBe(26); expect(atoms.atom_id.value(0)).toBe(1); expect(atoms.atom_name.value(0)).toBe('O'); expect(atoms.x.value(0)).toBeCloseTo(1.7394, 0.001); expect(atoms.y.value(0)).toBeCloseTo(-2.1169, 0.0001); expect(atoms.z.value(0)).toBeCloseTo(-1.0893, 0.0001); expect(atoms.atom_type.value(0)).toBe('O.3'); // optional atom fields expect(atoms.subst_id.value(0)).toBe(0); expect(atoms.subst_name.value(0)).toBe(''); expect(atoms.charge.value(0)).toBeCloseTo(0); expect(atoms.status_bit.value(0)).toBe(''); // required bond fields expect(bonds.count).toBe(26); expect(bonds.bond_id.value(0)).toBe(1); expect(bonds.origin_atom_id.value(0)).toBe(1); expect(bonds.target_atom_id.value(0)).toBe(5); expect(bonds.bond_type.value(0)).toBe('1'); // optional bond fields expect(bonds.status_bits.value(0)).toBe(''); }); });
the_stack
'use strict'; import * as jwt from 'jsonwebtoken'; import * as _ from 'lodash'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as utils from '../utils'; import * as mocks from '../../resources/mocks'; import { FirebaseApp } from '../../../src/app/firebase-app'; import { AuthRequestHandler, TenantAwareAuthRequestHandler, AbstractAuthRequestHandler, } from '../../../src/auth/auth-api-request'; import { AuthClientErrorCode, FirebaseAuthError } from '../../../src/utils/error'; import * as validator from '../../../src/utils/validator'; import { FirebaseTokenVerifier } from '../../../src/auth/token-verifier'; import { OIDCConfig, SAMLConfig, OIDCConfigServerResponse, SAMLConfigServerResponse, } from '../../../src/auth/auth-config'; import { deepCopy } from '../../../src/utils/deep-copy'; import { ServiceAccountCredential } from '../../../src/app/credential-internal'; import { HttpClient } from '../../../src/utils/api-request'; import { Auth, TenantAwareAuth, BaseAuth, UserRecord, DecodedIdToken, UpdateRequest, AuthProviderConfigFilter, TenantManager, } from '../../../src/auth/index'; chai.should(); chai.use(sinonChai); chai.use(chaiAsPromised); const expect = chai.expect; interface AuthTest { name: string; supportsTenantManagement: boolean; Auth: new (...args: any[]) => BaseAuth; RequestHandler: new (...args: any[]) => AbstractAuthRequestHandler; init(app: FirebaseApp): BaseAuth; } interface EmailActionTest { api: string; requestType: string; requiresSettings: boolean; } /** * @param {string=} tenantId The optional tenant Id. * @return {object} A sample valid server response as returned from getAccountInfo * endpoint. */ function getValidGetAccountInfoResponse(tenantId?: string): {kind: string; users: any[]} { const userResponse: any = { localId: 'abcdefghijklmnopqrstuvwxyz', email: 'user@gmail.com', emailVerified: true, displayName: 'John Doe', phoneNumber: '+11234567890', providerUserInfo: [ { providerId: 'google.com', displayName: 'John Doe', photoUrl: 'https://lh3.googleusercontent.com/1234567890/photo.jpg', federatedId: '1234567890', email: 'user@gmail.com', rawId: '1234567890', }, { providerId: 'facebook.com', displayName: 'John Smith', photoUrl: 'https://facebook.com/0987654321/photo.jpg', federatedId: '0987654321', email: 'user@facebook.com', rawId: '0987654321', }, { providerId: 'phone', phoneNumber: '+11234567890', rawId: '+11234567890', }, ], mfaInfo: [ { mfaEnrollmentId: 'enrolledSecondFactor1', phoneInfo: '+16505557348', displayName: 'Spouse\'s phone number', enrolledAt: new Date().toISOString(), }, { mfaEnrollmentId: 'enrolledSecondFactor2', phoneInfo: '+16505551000', }, ], photoUrl: 'https://lh3.googleusercontent.com/1234567890/photo.jpg', validSince: '1476136676', lastLoginAt: '1476235905000', createdAt: '1476136676000', }; if (typeof tenantId !== 'undefined') { userResponse.tenantId = tenantId; } return { kind: 'identitytoolkit#GetAccountInfoResponse', users: [userResponse], }; } /** * Returns a user record corresponding to the getAccountInfo response. * * @param {any} serverResponse Raw getAccountInfo response. * @return {Object} The corresponding user record. */ function getValidUserRecord(serverResponse: any): UserRecord { return new UserRecord(serverResponse.users[0]); } /** * Generates a mock decoded ID token with the provided parameters. * * @param {string} uid The uid corresponding to the ID token. * @param {Date} authTime The authentication time of the ID token. * @param {string=} tenantId The optional tenant ID. * @return {DecodedIdToken} The generated decoded ID token. */ function getDecodedIdToken(uid: string, authTime: Date, tenantId?: string): DecodedIdToken { return { iss: 'https://securetoken.google.com/project123456789', aud: 'project123456789', auth_time: Math.floor(authTime.getTime() / 1000), // eslint-disable-line @typescript-eslint/camelcase sub: uid, iat: Math.floor(authTime.getTime() / 1000), exp: Math.floor(authTime.getTime() / 1000 + 3600), firebase: { identities: {}, sign_in_provider: 'custom', // eslint-disable-line @typescript-eslint/camelcase tenant: tenantId, }, uid, }; } /** * Generates a mock decoded session cookie with the provided parameters. * * @param {string} uid The uid corresponding to the session cookie. * @param {Date} authTime The authentication time of the session cookie. * @param {string=} tenantId The optional tenant ID. * @return {DecodedIdToken} The generated decoded session cookie. */ function getDecodedSessionCookie(uid: string, authTime: Date, tenantId?: string): DecodedIdToken { return { iss: 'https://session.firebase.google.com/project123456789', aud: 'project123456789', auth_time: Math.floor(authTime.getTime() / 1000), // eslint-disable-line @typescript-eslint/camelcase sub: uid, iat: Math.floor(authTime.getTime() / 1000), exp: Math.floor(authTime.getTime() / 1000 + 3600), firebase: { identities: {}, sign_in_provider: 'custom', // eslint-disable-line @typescript-eslint/camelcase tenant: tenantId, }, uid, }; } /** * Generates a mock OIDC config server response for the corresponding provider ID. * * @param {string} providerId The provider ID whose sample OIDCConfigServerResponse is to be returned. * @return {OIDCConfigServerResponse} The corresponding sample OIDCConfigServerResponse. */ function getOIDCConfigServerResponse(providerId: string): OIDCConfigServerResponse { return { name: `projects/project_id/oauthIdpConfigs/${providerId}`, displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; } /** * Generates a mock SAML config server response for the corresponding provider ID. * * @param {string} providerId The provider ID whose sample SAMLConfigServerResponse is to be returned. * @return {SAMLConfigServerResponse} The corresponding sample SAMLConfigServerResponse. */ function getSAMLConfigServerResponse(providerId: string): SAMLConfigServerResponse { return { name: `projects/project_id/inboundSamlConfigs/${providerId}`, idpConfig: { idpEntityId: 'IDP_ENTITY_ID', ssoUrl: 'https://example.com/login', signRequest: true, idpCertificates: [ { x509Certificate: 'CERT1' }, { x509Certificate: 'CERT2' }, ], }, spConfig: { spEntityId: 'RP_ENTITY_ID', callbackUri: 'https://projectId.firebaseapp.com/__/auth/handler', }, displayName: 'SAML_DISPLAY_NAME', enabled: true, }; } const INVALID_PROVIDER_IDS = [ undefined, null, NaN, 0, 1, true, false, '', [], [1, 'a'], {}, { a: 1 }, _.noop]; const TENANT_ID = 'tenantId'; const AUTH_CONFIGS: AuthTest[] = [ { name: 'Auth', Auth, supportsTenantManagement: true, RequestHandler: AuthRequestHandler, init: (app: FirebaseApp) => { return new Auth(app); }, }, { name: 'TenantAwareAuth', Auth: TenantAwareAuth, supportsTenantManagement: false, RequestHandler: TenantAwareAuthRequestHandler, init: (app: FirebaseApp) => { return new TenantAwareAuth(app, TENANT_ID); }, }, ]; AUTH_CONFIGS.forEach((testConfig) => { describe(testConfig.name, () => { let auth: BaseAuth; let mockApp: FirebaseApp; let getTokenStub: sinon.SinonStub; let oldProcessEnv: NodeJS.ProcessEnv; let nullAccessTokenAuth: BaseAuth; let malformedAccessTokenAuth: BaseAuth; let rejectedPromiseAccessTokenAuth: BaseAuth; beforeEach(() => { mockApp = mocks.app(); getTokenStub = utils.stubGetAccessToken(undefined, mockApp); auth = testConfig.init(mockApp); nullAccessTokenAuth = testConfig.init(mocks.appReturningNullAccessToken()); malformedAccessTokenAuth = testConfig.init(mocks.appReturningMalformedAccessToken()); rejectedPromiseAccessTokenAuth = testConfig.init(mocks.appRejectedWhileFetchingAccessToken()); oldProcessEnv = process.env; // Project ID not set in the environment. delete process.env.GOOGLE_CLOUD_PROJECT; delete process.env.GCLOUD_PROJECT; }); afterEach(() => { getTokenStub.restore(); process.env = oldProcessEnv; return mockApp.delete(); }); if (testConfig.Auth === Auth) { // Run tests for Auth. describe('Constructor', () => { const invalidApps = [null, NaN, 0, 1, true, false, '', 'a', [], [1, 'a'], {}, { a: 1 }, _.noop]; invalidApps.forEach((invalidApp) => { it('should throw given invalid app: ' + JSON.stringify(invalidApp), () => { expect(() => { const authAny: any = Auth; return new authAny(invalidApp); }).to.throw('First argument passed to admin.auth() must be a valid Firebase app instance.'); }); }); it('should throw given no app', () => { expect(() => { const authAny: any = Auth; return new authAny(); }).to.throw('First argument passed to admin.auth() must be a valid Firebase app instance.'); }); it('should reject given no project ID', () => { const authWithoutProjectId = new Auth(mocks.mockCredentialApp()); authWithoutProjectId.getUser('uid') .should.eventually.be.rejectedWith( 'Failed to determine project ID for Auth. Initialize the SDK with service ' + 'account credentials or set project ID as an app option. Alternatively set the ' + 'GOOGLE_CLOUD_PROJECT environment variable.'); }); it('should not throw given a valid app', () => { expect(() => { return new Auth(mockApp); }).not.to.throw(); }); }); describe('app', () => { it('returns the app from the constructor', () => { // We expect referential equality here expect((auth as Auth).app).to.equal(mockApp); }); it('is read-only', () => { expect(() => { (auth as any).app = mockApp; }).to.throw('Cannot set property app of #<Auth> which has only a getter'); }); }); describe('tenantManager()', () => { it('should return a TenantManager with the expected attributes', () => { const tenantManager1 = (auth as Auth).tenantManager(); const tenantManager2 = new TenantManager(mockApp); expect(tenantManager1).to.deep.equal(tenantManager2); }); it('should return the same cached instance', () => { const tenantManager1 = (auth as Auth).tenantManager(); const tenantManager2 = (auth as Auth).tenantManager(); expect(tenantManager1).to.equal(tenantManager2); }); }); } describe('createCustomToken()', () => { it('should return a jwt', async () => { const token = await auth.createCustomToken('uid1'); const decodedToken = jwt.decode(token, { complete: true }); expect(decodedToken).to.have.property('header').that.has.property('typ', 'JWT'); }); if (testConfig.Auth === TenantAwareAuth) { it('should contain tenant_id', async () => { const token = await auth.createCustomToken('uid1'); expect(jwt.decode(token)).to.have.property('tenant_id', TENANT_ID); }); } else { it('should not contain tenant_id', async () => { const token = await auth.createCustomToken('uid1'); expect(jwt.decode(token)).to.not.have.property('tenant_id'); }); } it('should be eventually rejected if a cert credential is not specified', () => { const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); // Force the service account ID discovery to fail. getTokenStub = sinon.stub(HttpClient.prototype, 'send').rejects(utils.errorFrom({})); return mockCredentialAuth.createCustomToken(mocks.uid, mocks.developerClaims) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-credential'); }); it('should be fulfilled given an app which returns null access tokens', () => { getTokenStub = sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken') .resolves(null as any); // createCustomToken() does not rely on an access token and therefore works in this scenario. return auth.createCustomToken(mocks.uid, mocks.developerClaims) .should.eventually.be.fulfilled; }); it('should be fulfilled given an app which returns invalid access tokens', () => { getTokenStub = sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken') .resolves('malformed' as any); // createCustomToken() does not rely on an access token and therefore works in this scenario. return auth.createCustomToken(mocks.uid, mocks.developerClaims) .should.eventually.be.fulfilled; }); it('should be fulfilled given an app which fails to generate access tokens', () => { getTokenStub = sinon.stub(ServiceAccountCredential.prototype, 'getAccessToken').rejects('error'); // createCustomToken() does not rely on an access token and therefore works in this scenario. return auth.createCustomToken(mocks.uid, mocks.developerClaims) .should.eventually.be.fulfilled; }); }); it('verifyIdToken() should reject when project ID is not specified', () => { const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); const expected = 'Must initialize app with a cert credential or set your Firebase project ID ' + 'as the GOOGLE_CLOUD_PROJECT environment variable to call verifyIdToken().'; return mockCredentialAuth.verifyIdToken(mocks.generateIdToken()) .should.eventually.be.rejectedWith(expected); }); it('verifySessionCookie() should reject when project ID is not specified', () => { const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); const expected = 'Must initialize app with a cert credential or set your Firebase project ID ' + 'as the GOOGLE_CLOUD_PROJECT environment variable to call verifySessionCookie().'; return mockCredentialAuth.verifySessionCookie(mocks.generateSessionCookie()) .should.eventually.be.rejectedWith(expected); }); describe('verifyIdToken()', () => { let stub: sinon.SinonStub; let mockIdToken: string; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedUserRecord = getValidUserRecord(getValidGetAccountInfoResponse(tenantId)); // Set auth_time of token to expected user's tokensValidAfterTime. expect( expectedUserRecord.tokensValidAfterTime, "getValidUserRecord didn't properly set tokensValueAfterTime", ).to.exist; const validSince = new Date(expectedUserRecord.tokensValidAfterTime!); // Set expected uid to expected user's. const uid = expectedUserRecord.uid; // Set expected decoded ID token with expected UID and auth time. const decodedIdToken = getDecodedIdToken(uid, validSince, tenantId); let clock: sinon.SinonFakeTimers; // Stubs used to simulate underlying api calls. const stubs: sinon.SinonStub[] = []; beforeEach(() => { stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(decodedIdToken); stubs.push(stub); mockIdToken = mocks.generateIdToken(); clock = sinon.useFakeTimers(validSince.getTime()); }); afterEach(() => { _.forEach(stubs, (s) => s.restore()); clock.restore(); }); it('should forward on the call to the token generator\'s verifyIdToken() method', () => { // Stub getUser call. const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser'); stubs.push(getUserStub); return auth.verifyIdToken(mockIdToken).then((result) => { // Confirm getUser never called. expect(getUserStub).not.to.have.been.called; expect(result).to.deep.equal(decodedIdToken); expect(stub).to.have.been.calledOnce.and.calledWith(mockIdToken); }); }); it('should reject when underlying idTokenVerifier.verifyJWT() rejects with expected error', () => { const expectedError = new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'Decoding Firebase ID token failed'); // Restore verifyIdToken stub. stub.restore(); // Simulate ID token is invalid. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .rejects(expectedError); stubs.push(stub); return auth.verifyIdToken(mockIdToken) .should.eventually.be.rejectedWith('Decoding Firebase ID token failed'); }); it('should be rejected with checkRevoked set to true and corresponding user disabled', () => { const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId); expectedAccountInfoResponse.users[0].disabled = true; const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponse); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecordDisabled); expect(expectedUserRecordDisabled.disabled).to.be.equal(true); stubs.push(getUserStub); return auth.verifyIdToken(mockIdToken, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.have.property('code', 'auth/user-disabled'); }); }); it('verifyIdToken() should reject user disabled before ID tokens revoked', () => { const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId); const expectedAccountInfoResponseUserDisabled = Object.assign({}, expectedAccountInfoResponse); expectedAccountInfoResponseUserDisabled.users[0].disabled = true; const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponseUserDisabled); const validSince = new Date(expectedUserRecordDisabled.tokensValidAfterTime!); // Restore verifyIdToken stub. stub.restore(); // One second before validSince. const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000); stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(getDecodedIdToken(expectedUserRecordDisabled.uid, oneSecBeforeValidSince)); stubs.push(stub); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecordDisabled); expect(expectedUserRecordDisabled.disabled).to.be.equal(true); stubs.push(getUserStub); return auth.verifyIdToken(mockIdToken, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.have.property('code', 'auth/user-disabled'); // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(expectedUserRecordDisabled.uid); }); }); it('should work with a non-cert credential when the GOOGLE_CLOUD_PROJECT environment variable is present', () => { process.env.GOOGLE_CLOUD_PROJECT = mocks.projectId; const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); return mockCredentialAuth.verifyIdToken(mockIdToken).then(() => { expect(stub).to.have.been.calledOnce.and.calledWith(mockIdToken); }); }); it('should work with a non-cert credential when the GCLOUD_PROJECT environment variable is present', () => { process.env.GCLOUD_PROJECT = mocks.projectId; const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); return mockCredentialAuth.verifyIdToken(mockIdToken).then(() => { expect(stub).to.have.been.calledOnce.and.calledWith(mockIdToken); }); }); it('should be fulfilled given an app which returns null access tokens', () => { // verifyIdToken() does not rely on an access token and therefore works in this scenario. return nullAccessTokenAuth.verifyIdToken(mockIdToken) .should.eventually.be.fulfilled; }); it('should be fulfilled given an app which returns invalid access tokens', () => { // verifyIdToken() does not rely on an access token and therefore works in this scenario. return malformedAccessTokenAuth.verifyIdToken(mockIdToken) .should.eventually.be.fulfilled; }); it('should be fulfilled given an app which fails to generate access tokens', () => { // verifyIdToken() does not rely on an access token and therefore works in this scenario. return rejectedPromiseAccessTokenAuth.verifyIdToken(mockIdToken) .should.eventually.be.fulfilled; }); it('should be fulfilled with checkRevoked set to true using an unrevoked ID token', () => { const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecord); stubs.push(getUserStub); // Verify ID token while checking if revoked. return auth.verifyIdToken(mockIdToken, true) .then((result) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); expect(result).to.deep.equal(decodedIdToken); }); }); it('should be rejected with checkRevoked set to true using a revoked ID token', () => { // One second before validSince. const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000); // Restore verifyIdToken stub. stub.restore(); // Simulate revoked ID token returned with auth_time one second before validSince. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(getDecodedIdToken(uid, oneSecBeforeValidSince)); stubs.push(stub); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecord); stubs.push(getUserStub); // Verify ID token while checking if revoked. return auth.verifyIdToken(mockIdToken, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.have.property('code', 'auth/id-token-revoked'); }); }); it('should be fulfilled with checkRevoked set to false using a revoked ID token', () => { // One second before validSince. const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000); const oneSecBeforeValidSinceDecodedIdToken = getDecodedIdToken(uid, oneSecBeforeValidSince, tenantId); // Restore verifyIdToken stub. stub.restore(); // Simulate revoked ID token returned with auth_time one second before validSince. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(oneSecBeforeValidSinceDecodedIdToken); stubs.push(stub); // Verify ID token without checking if revoked. // This call should succeed. return auth.verifyIdToken(mockIdToken, false) .then((result) => { expect(result).to.deep.equal(oneSecBeforeValidSinceDecodedIdToken); }); }); it('should be rejected with checkRevoked set to true if underlying RPC fails', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .rejects(expectedError); stubs.push(getUserStub); // Verify ID token while checking if revoked. // This should fail with the underlying RPC error. return auth.verifyIdToken(mockIdToken, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); it('should be fulfilled with checkRevoked set to true when no validSince available', () => { // Simulate no validSince set on the user. const noValidSinceGetAccountInfoResponse = getValidGetAccountInfoResponse(tenantId); delete (noValidSinceGetAccountInfoResponse.users[0] as any).validSince; const noValidSinceExpectedUserRecord = getValidUserRecord(noValidSinceGetAccountInfoResponse); // Confirm null tokensValidAfterTime on user. expect(noValidSinceExpectedUserRecord.tokensValidAfterTime).to.be.undefined; // Simulate getUser returns the expected user with no validSince. const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(noValidSinceExpectedUserRecord); stubs.push(getUserStub); // Verify ID token while checking if revoked. return auth.verifyIdToken(mockIdToken, true) .then((result) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); expect(result).to.deep.equal(decodedIdToken); }); }); it('should be rejected with checkRevoked set to true using an invalid ID token', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CREDENTIAL); // Restore verifyIdToken stub. stub.restore(); // Simulate ID token is invalid. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .rejects(expectedError); stubs.push(stub); // Verify ID token while checking if revoked. // This should fail with the underlying token generator verifyIdToken error. return auth.verifyIdToken(mockIdToken, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); if (testConfig.Auth === TenantAwareAuth) { it('should be rejected with ID token missing tenant ID', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.MISMATCHING_TENANT_ID); // Restore verifyIdToken stub. stub.restore(); // Simulate JWT does not contain tenant ID. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .returns(Promise.resolve(getDecodedIdToken(uid, validSince))); // Verify ID token. return auth.verifyIdToken(mockIdToken) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.deep.include(expectedError); }); }); it('should be rejected with ID token containing mismatching tenant ID', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.MISMATCHING_TENANT_ID); // Restore verifyIdToken stub. stub.restore(); // Simulate JWT does not contain matching tenant ID. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .returns(Promise.resolve(getDecodedIdToken(uid, validSince, 'otherTenantId'))); // Verify ID token. return auth.verifyIdToken(mockIdToken) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.deep.include(expectedError); }); }); } }); describe('verifySessionCookie()', () => { let stub: sinon.SinonStub; let mockSessionCookie: string; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedUserRecord = getValidUserRecord(getValidGetAccountInfoResponse(tenantId)); // Set auth_time of token to expected user's tokensValidAfterTime. if (!expectedUserRecord.tokensValidAfterTime) { throw new Error("getValidUserRecord didn't properly set tokensValidAfterTime."); } const validSince = new Date(expectedUserRecord.tokensValidAfterTime); // Set expected uid to expected user's. const uid = expectedUserRecord.uid; // Set expected decoded session cookie with expected UID and auth time. const decodedSessionCookie = getDecodedSessionCookie(uid, validSince, tenantId); let clock: sinon.SinonFakeTimers; // Stubs used to simulate underlying api calls. const stubs: sinon.SinonStub[] = []; beforeEach(() => { stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(decodedSessionCookie); stubs.push(stub); mockSessionCookie = mocks.generateSessionCookie(); clock = sinon.useFakeTimers(validSince.getTime()); }); afterEach(() => { _.forEach(stubs, (s) => s.restore()); clock.restore(); }); it('should forward on the call to the token verifier\'s verifySessionCookie() method', () => { // Stub getUser call. const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser'); stubs.push(getUserStub); return auth.verifySessionCookie(mockSessionCookie).then((result) => { // Confirm getUser never called. expect(getUserStub).not.to.have.been.called; expect(result).to.deep.equal(decodedSessionCookie); expect(stub).to.have.been.calledOnce.and.calledWith(mockSessionCookie); }); }); it('should reject when underlying sessionCookieVerifier.verifyJWT() rejects with expected error', () => { const expectedError = new FirebaseAuthError( AuthClientErrorCode.INVALID_ARGUMENT, 'Decoding Firebase session cookie failed'); // Restore verifySessionCookie stub. stub.restore(); // Simulate session cookie is invalid. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .rejects(expectedError); stubs.push(stub); return auth.verifySessionCookie(mockSessionCookie) .should.eventually.be.rejectedWith('Decoding Firebase session cookie failed'); }); it('should work with a non-cert credential when the GOOGLE_CLOUD_PROJECT environment variable is present', () => { process.env.GOOGLE_CLOUD_PROJECT = mocks.projectId; const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); return mockCredentialAuth.verifySessionCookie(mockSessionCookie).then(() => { expect(stub).to.have.been.calledOnce.and.calledWith(mockSessionCookie); }); }); it('should work with a non-cert credential when the GCLOUD_PROJECT environment variable is present', () => { process.env.GCLOUD_PROJECT = mocks.projectId; const mockCredentialAuth = testConfig.init(mocks.mockCredentialApp()); return mockCredentialAuth.verifySessionCookie(mockSessionCookie).then(() => { expect(stub).to.have.been.calledOnce.and.calledWith(mockSessionCookie); }); }); it('should be fulfilled given an app which returns null access tokens', () => { // verifySessionCookie() does not rely on an access token and therefore works in this scenario. return nullAccessTokenAuth.verifySessionCookie(mockSessionCookie) .should.eventually.be.fulfilled; }); it('should be fulfilled given an app which returns invalid access tokens', () => { // verifySessionCookie() does not rely on an access token and therefore works in this scenario. return malformedAccessTokenAuth.verifySessionCookie(mockSessionCookie) .should.eventually.be.fulfilled; }); it('should be fulfilled given an app which fails to generate access tokens', () => { // verifySessionCookie() does not rely on an access token and therefore works in this scenario. return rejectedPromiseAccessTokenAuth.verifySessionCookie(mockSessionCookie) .should.eventually.be.fulfilled; }); it('should be fulfilled with checkRevoked set to true using an unrevoked session cookie', () => { const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecord); stubs.push(getUserStub); // Verify ID token while checking if revoked. return auth.verifySessionCookie(mockSessionCookie, true) .then((result) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); expect(result).to.deep.equal(decodedSessionCookie); }); }); it('should be rejected with checkRevoked set to true using a revoked session cookie', () => { // One second before validSince. const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000); // Restore verifySessionCookie stub. stub.restore(); // Simulate revoked session cookie returned with auth_time one second before validSince. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(getDecodedSessionCookie(uid, oneSecBeforeValidSince)); stubs.push(stub); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecord); stubs.push(getUserStub); // Verify session cookie while checking if revoked. return auth.verifySessionCookie(mockSessionCookie, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.have.property('code', 'auth/session-cookie-revoked'); }); }); it('should be fulfilled with checkRevoked set to false using a revoked session cookie', () => { // One second before validSince. const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000); const oneSecBeforeValidSinceDecodedSessionCookie = getDecodedSessionCookie(uid, oneSecBeforeValidSince, tenantId); // Restore verifySessionCookie stub. stub.restore(); // Simulate revoked session cookie returned with auth_time one second before validSince. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(oneSecBeforeValidSinceDecodedSessionCookie); stubs.push(stub); // Verify session cookie without checking if revoked. // This call should succeed. return auth.verifySessionCookie(mockSessionCookie, false) .then((result) => { expect(result).to.deep.equal(oneSecBeforeValidSinceDecodedSessionCookie); }); }); it('should be rejected with checkRevoked set to true if underlying RPC fails', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .rejects(expectedError); stubs.push(getUserStub); // Verify session cookie while checking if revoked. // This should fail with the underlying RPC error. return auth.verifySessionCookie(mockSessionCookie, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); it('should be rejected with checkRevoked set to true and corresponding user disabled', () => { const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId); expectedAccountInfoResponse.users[0].disabled = true; const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponse); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecordDisabled); expect(expectedUserRecordDisabled.disabled).to.be.equal(true); stubs.push(getUserStub); return auth.verifySessionCookie(mockSessionCookie, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.have.property('code', 'auth/user-disabled'); }); }); it('verifySessionCookie() should reject user disabled before ID tokens revoked', () => { const expectedAccountInfoResponse = getValidGetAccountInfoResponse(tenantId); const expectedAccountInfoResponseUserDisabled = Object.assign({}, expectedAccountInfoResponse); expectedAccountInfoResponseUserDisabled.users[0].disabled = true; const expectedUserRecordDisabled = getValidUserRecord(expectedAccountInfoResponseUserDisabled); const validSince = new Date(expectedUserRecordDisabled.tokensValidAfterTime!); // Restore verifySessionCookie stub. stub.restore(); // One second before validSince. const oneSecBeforeValidSince = new Date(validSince.getTime() - 1000); stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .resolves(getDecodedIdToken(expectedUserRecordDisabled.uid, oneSecBeforeValidSince)); stubs.push(stub); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(expectedUserRecordDisabled); expect(expectedUserRecordDisabled.disabled).to.be.equal(true); stubs.push(getUserStub); return auth.verifySessionCookie(mockSessionCookie, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(expectedUserRecordDisabled.uid); // Confirm expected error returned. expect(error).to.have.property('code', 'auth/user-disabled'); }); }); it('should be fulfilled with checkRevoked set to true when no validSince available', () => { // Simulate no validSince set on the user. const noValidSinceGetAccountInfoResponse = getValidGetAccountInfoResponse(tenantId); delete (noValidSinceGetAccountInfoResponse.users[0] as any).validSince; const noValidSinceExpectedUserRecord = getValidUserRecord(noValidSinceGetAccountInfoResponse); // Confirm null tokensValidAfterTime on user. expect(noValidSinceExpectedUserRecord.tokensValidAfterTime).to.be.undefined; // Simulate getUser returns the expected user with no validSince. const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(noValidSinceExpectedUserRecord); stubs.push(getUserStub); // Verify session cookie while checking if revoked. return auth.verifySessionCookie(mockSessionCookie, true) .then((result) => { // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); expect(result).to.deep.equal(decodedSessionCookie); }); }); it('should be rejected with checkRevoked set to true using an invalid session cookie', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CREDENTIAL); // Restore verifySessionCookie stub. stub.restore(); // Simulate session cookie is invalid. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .rejects(expectedError); stubs.push(stub); // Verify session cookie while checking if revoked. // This should fail with the underlying token generator verifySessionCookie error. return auth.verifySessionCookie(mockSessionCookie, true) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); if (testConfig.Auth === TenantAwareAuth) { it('should be rejected with session cookie missing tenant ID', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.MISMATCHING_TENANT_ID); // Restore verifyIdToken stub. stub.restore(); // Simulate JWT does not contain tenant ID.. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .returns(Promise.resolve(getDecodedSessionCookie(uid, validSince))); // Verify session cookie token. return auth.verifySessionCookie(mockSessionCookie) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.deep.include(expectedError); }); }); it('should be rejected with ID token containing mismatching tenant ID', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.MISMATCHING_TENANT_ID); // Restore verifyIdToken stub. stub.restore(); // Simulate JWT does not contain matching tenant ID.. stub = sinon.stub(FirebaseTokenVerifier.prototype, 'verifyJWT') .returns(Promise.resolve(getDecodedSessionCookie(uid, validSince, 'otherTenantId'))); // Verify session cookie token. return auth.verifySessionCookie(mockSessionCookie) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.deep.include(expectedError); }); }); } }); describe('getUser()', () => { const uid = 'abcdefghijklmnopqrstuvwxyz'; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedGetAccountInfoResult = getValidGetAccountInfoResponse(tenantId); const expectedUserRecord = getValidUserRecord(expectedGetAccountInfoResult); const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => sinon.spy(validator, 'isUid')); afterEach(() => { (validator.isUid as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no uid', () => { return (auth as any).getUser() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-uid'); }); it('should be rejected given an invalid uid', () => { const invalidUid = ('a' as any).repeat(129); return auth.getUser(invalidUid) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-uid'); expect(validator.isUid).to.have.been.calledOnce.and.calledWith(invalidUid); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.getUser(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.getUser(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.getUser(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with a UserRecord on success', () => { // Stub getAccountInfoByUid to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves(expectedGetAccountInfoResult); stubs.push(stub); return auth.getUser(uid) .then((userRecord) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected user record response returned. expect(userRecord).to.deep.equal(expectedUserRecord); }); }); it('should throw an error when the backend returns an error', () => { // Stub getAccountInfoByUid to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .rejects(expectedError); stubs.push(stub); return auth.getUser(uid) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('getUserByEmail()', () => { const email = 'user@gmail.com'; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedGetAccountInfoResult = getValidGetAccountInfoResponse(tenantId); const expectedUserRecord = getValidUserRecord(expectedGetAccountInfoResult); const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => sinon.spy(validator, 'isEmail')); afterEach(() => { (validator.isEmail as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no email', () => { return (auth as any).getUserByEmail() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-email'); }); it('should be rejected given an invalid email', () => { const invalidEmail = 'name-example-com'; return auth.getUserByEmail(invalidEmail) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-email'); expect(validator.isEmail).to.have.been.calledOnce.and.calledWith(invalidEmail); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.getUserByEmail(email) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.getUserByEmail(email) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.getUserByEmail(email) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with a UserRecord on success', () => { // Stub getAccountInfoByEmail to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByEmail') .resolves(expectedGetAccountInfoResult); stubs.push(stub); return auth.getUserByEmail(email) .then((userRecord) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(email); // Confirm expected user record response returned. expect(userRecord).to.deep.equal(expectedUserRecord); }); }); it('should throw an error when the backend returns an error', () => { // Stub getAccountInfoByEmail to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByEmail') .rejects(expectedError); stubs.push(stub); return auth.getUserByEmail(email) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(email); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('getUserByPhoneNumber()', () => { const phoneNumber = '+11234567890'; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedGetAccountInfoResult = getValidGetAccountInfoResponse(tenantId); const expectedUserRecord = getValidUserRecord(expectedGetAccountInfoResult); const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => sinon.spy(validator, 'isPhoneNumber')); afterEach(() => { (validator.isPhoneNumber as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no phone number', () => { return (auth as any).getUserByPhoneNumber() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-phone-number'); }); it('should be rejected given an invalid phone number', () => { const invalidPhoneNumber = 'invalid'; return auth.getUserByPhoneNumber(invalidPhoneNumber) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-phone-number'); expect(validator.isPhoneNumber) .to.have.been.calledOnce.and.calledWith(invalidPhoneNumber); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.getUserByPhoneNumber(phoneNumber) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.getUserByPhoneNumber(phoneNumber) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.getUserByPhoneNumber(phoneNumber) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with a UserRecord on success', () => { // Stub getAccountInfoByPhoneNumber to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByPhoneNumber') .resolves(expectedGetAccountInfoResult); stubs.push(stub); return auth.getUserByPhoneNumber(phoneNumber) .then((userRecord) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(phoneNumber); // Confirm expected user record response returned. expect(userRecord).to.deep.equal(expectedUserRecord); }); }); it('should throw an error when the backend returns an error', () => { // Stub getAccountInfoByPhoneNumber to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByPhoneNumber') .rejects(expectedError); stubs.push(stub); return auth.getUserByPhoneNumber(phoneNumber) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(phoneNumber); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('getUserByProviderUid()', () => { const providerId = 'google.com'; const providerUid = 'google_uid'; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedGetAccountInfoResult = getValidGetAccountInfoResponse(tenantId); const expectedUserRecord = getValidUserRecord(expectedGetAccountInfoResult); const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => sinon.spy(validator, 'isEmail')); afterEach(() => { (validator.isEmail as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no provider id', () => { expect(() => (auth as any).getUserByProviderUid()) .to.throw(FirebaseAuthError) .with.property('code', 'auth/invalid-provider-id'); }); it('should be rejected given an invalid provider id', () => { expect(() => auth.getUserByProviderUid('', 'uid')) .to.throw(FirebaseAuthError) .with.property('code', 'auth/invalid-provider-id'); }); it('should be rejected given an invalid provider uid', () => { expect(() => auth.getUserByProviderUid('id', '')) .to.throw(FirebaseAuthError) .with.property('code', 'auth/invalid-provider-id'); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.getUserByProviderUid(providerId, providerUid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.getUserByProviderUid(providerId, providerUid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.getUserByProviderUid(providerId, providerUid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with a UserRecord on success', () => { // Stub getAccountInfoByEmail to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByFederatedUid') .resolves(expectedGetAccountInfoResult); stubs.push(stub); return auth.getUserByProviderUid(providerId, providerUid) .then((userRecord) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId, providerUid); // Confirm expected user record response returned. expect(userRecord).to.deep.equal(expectedUserRecord); }); }); describe('non-federated providers', () => { let invokeRequestHandlerStub: sinon.SinonStub; beforeEach(() => { invokeRequestHandlerStub = sinon.stub(testConfig.RequestHandler.prototype, 'invokeRequestHandler') .resolves({ // nothing here is checked; we just need enough to not crash. users: [{ localId: 1, }], }); }); afterEach(() => { invokeRequestHandlerStub.restore(); }); it('phone lookups should use phoneNumber field', async () => { await auth.getUserByProviderUid('phone', '+15555550001'); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { phoneNumber: ['+15555550001'], }); }); it('email lookups should use email field', async () => { await auth.getUserByProviderUid('email', 'user@example.com'); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { email: ['user@example.com'], }); }); }); it('should throw an error when the backend returns an error', () => { // Stub getAccountInfoByFederatedUid to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByFederatedUid') .rejects(expectedError); stubs.push(stub); return auth.getUserByProviderUid(providerId, providerUid) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId, providerUid); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('getUsers()', () => { let stubs: sinon.SinonStub[] = []; afterEach(() => { stubs.forEach((stub) => stub.restore()); stubs = []; }); it('should throw when given a non array parameter', () => { const nonArrayValues = [ null, undefined, 42, 3.14, "i'm not an array", {} ]; nonArrayValues.forEach((v) => { expect(() => auth.getUsers(v as any)) .to.throw(FirebaseAuthError) .with.property('code', 'auth/argument-error'); }); }); it('should return no results when given no identifiers', () => { return auth.getUsers([]) .then((getUsersResult) => { expect(getUsersResult.users).to.deep.equal([]); expect(getUsersResult.notFound).to.deep.equal([]); }); }); it('should return no users when given identifiers that do not exist', () => { const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByIdentifiers') .resolves({}); stubs.push(stub); const notFoundIds = [{ uid: 'id that doesnt exist' }]; return auth.getUsers(notFoundIds) .then((getUsersResult) => { expect(getUsersResult.users).to.deep.equal([]); expect(getUsersResult.notFound).to.deep.equal(notFoundIds); }); }); it('returns users by various identifier types in a single call', async () => { const mockUsers = [{ localId: 'uid1', email: 'user1@example.com', phoneNumber: '+15555550001', }, { localId: 'uid2', email: 'user2@example.com', phoneNumber: '+15555550002', }, { localId: 'uid3', email: 'user3@example.com', phoneNumber: '+15555550003', }, { localId: 'uid4', email: 'user4@example.com', phoneNumber: '+15555550004', providerUserInfo: [{ providerId: 'google.com', rawId: 'google_uid4', }], }]; const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByIdentifiers') .resolves({ users: mockUsers }); stubs.push(stub); const users = await auth.getUsers([ { uid: 'uid1' }, { email: 'user2@example.com' }, { phoneNumber: '+15555550003' }, { providerId: 'google.com', providerUid: 'google_uid4' }, { uid: 'this-user-doesnt-exist' }, ]); expect(users.users).to.have.deep.members(mockUsers.map((u) => new UserRecord(u))); expect(users.notFound).to.have.deep.members([{ uid: 'this-user-doesnt-exist' }]); }); }); describe('deleteUser()', () => { const uid = 'abcdefghijklmnopqrstuvwxyz'; const expectedDeleteAccountResult = { kind: 'identitytoolkit#DeleteAccountResponse' }; const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => sinon.spy(validator, 'isUid')); afterEach(() => { (validator.isUid as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no uid', () => { return (auth as any).deleteUser() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-uid'); }); it('should be rejected given an invalid uid', () => { const invalidUid = ('a' as any).repeat(129); return auth.deleteUser(invalidUid) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-uid'); expect(validator.isUid).to.have.been.calledOnce.and.calledWith(invalidUid); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.deleteUser(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.deleteUser(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.deleteUser(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with void on success', () => { // Stub deleteAccount to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteAccount') .resolves(expectedDeleteAccountResult); stubs.push(stub); return auth.deleteUser(uid) .then((result) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected result is undefined. expect(result).to.be.undefined; }); }); it('should throw an error when the backend returns an error', () => { // Stub deleteAccount to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteAccount') .rejects(expectedError); stubs.push(stub); return auth.deleteUser(uid) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('deleteUsers()', () => { it('should succeed given an empty list', () => { return auth.deleteUsers([]) .then((deleteUsersResult) => { expect(deleteUsersResult.successCount).to.equal(0); expect(deleteUsersResult.failureCount).to.equal(0); expect(deleteUsersResult.errors).to.have.length(0); }); }); it('should index errors correctly in result', async () => { const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteAccounts') .resolves({ errors: [{ index: 0, localId: 'uid1', message: 'NOT_DISABLED : Disable the account before batch deletion.', }, { index: 2, localId: 'uid3', message: 'something awful', }], }); try { const deleteUsersResult = await auth.deleteUsers(['uid1', 'uid2', 'uid3', 'uid4']); expect(deleteUsersResult.successCount).to.equal(2); expect(deleteUsersResult.failureCount).to.equal(2); expect(deleteUsersResult.errors).to.have.length(2); expect(deleteUsersResult.errors[0].index).to.equal(0); expect(deleteUsersResult.errors[0].error).to.have.property('code', 'auth/user-not-disabled'); expect(deleteUsersResult.errors[1].index).to.equal(2); expect(deleteUsersResult.errors[1].error).to.have.property('code', 'auth/internal-error'); } finally { stub.restore(); } }); it('should resolve with void on success', async () => { const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteAccounts') .resolves({}); try { await auth.deleteUsers(['uid1', 'uid2', 'uid3']) .then((result) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(['uid1', 'uid2', 'uid3']); expect(result.failureCount).to.equal(0); expect(result.successCount).to.equal(3); expect(result.errors).to.be.empty; }); } finally { stub.restore(); } }); }); describe('createUser()', () => { const uid = 'abcdefghijklmnopqrstuvwxyz'; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedGetAccountInfoResult = getValidGetAccountInfoResponse(tenantId); const expectedUserRecord = getValidUserRecord(expectedGetAccountInfoResult); const expectedError = new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.'); const unableToCreateUserError = new FirebaseAuthError( AuthClientErrorCode.INTERNAL_ERROR, 'Unable to create the user record provided.'); const propertiesToCreate = { displayName: expectedUserRecord.displayName, photoURL: expectedUserRecord.photoURL, email: expectedUserRecord.email, emailVerified: expectedUserRecord.emailVerified, password: 'password', phoneNumber: expectedUserRecord.phoneNumber, }; // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => sinon.spy(validator, 'isNonNullObject')); afterEach(() => { (validator.isNonNullObject as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no properties', () => { return (auth as any).createUser() .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); it('should be rejected given invalid properties', () => { return auth.createUser(null as any) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/argument-error'); expect(validator.isNonNullObject).to.have.been.calledOnce.and.calledWith(null); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.createUser(propertiesToCreate) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.createUser(propertiesToCreate) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.createUser(propertiesToCreate) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with a UserRecord on createNewAccount request success', () => { // Stub createNewAccount to return expected uid. const createUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'createNewAccount') .resolves(uid); // Stub getAccountInfoByUid to return expected result. const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves(expectedGetAccountInfoResult); stubs.push(createUserStub); stubs.push(getUserStub); return auth.createUser(propertiesToCreate) .then((userRecord) => { // Confirm underlying API called with expected parameters. expect(createUserStub).to.have.been.calledOnce.and.calledWith(propertiesToCreate); expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected user record response returned. expect(userRecord).to.deep.equal(expectedUserRecord); }); }); it('should throw an error when createNewAccount returns an error', () => { // Stub createNewAccount to throw a backend error. const createUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'createNewAccount') .rejects(expectedError); stubs.push(createUserStub); return auth.createUser(propertiesToCreate) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(createUserStub).to.have.been.calledOnce.and.calledWith(propertiesToCreate); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); it('should throw an error when getUser returns a User not found error', () => { // Stub createNewAccount to return expected uid. const createUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'createNewAccount') .resolves(uid); // Stub getAccountInfoByUid to throw user not found error. const userNotFoundError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .rejects(userNotFoundError); stubs.push(createUserStub); stubs.push(getUserStub); return auth.createUser(propertiesToCreate) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(createUserStub).to.have.been.calledOnce.and.calledWith(propertiesToCreate); expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error.toString()).to.equal(unableToCreateUserError.toString()); }); }); it('should echo getUser error if an error occurs while retrieving the user record', () => { // Stub createNewAccount to return expected uid. const createUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'createNewAccount') .resolves(uid); // Stub getAccountInfoByUid to throw expected error. const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .rejects(expectedError); stubs.push(createUserStub); stubs.push(getUserStub); return auth.createUser(propertiesToCreate) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(createUserStub).to.have.been.calledOnce.and.calledWith(propertiesToCreate); expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned (same error thrown by getUser). expect(error).to.equal(expectedError); }); }); }); describe('updateUser()', () => { const uid = 'abcdefghijklmnopqrstuvwxyz'; const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const expectedGetAccountInfoResult = getValidGetAccountInfoResponse(tenantId); const expectedUserRecord = getValidUserRecord(expectedGetAccountInfoResult); const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); const propertiesToEdit = { displayName: expectedUserRecord.displayName, photoURL: expectedUserRecord.photoURL, email: expectedUserRecord.email, emailVerified: expectedUserRecord.emailVerified, password: 'password', phoneNumber: expectedUserRecord.phoneNumber, providerToLink: { providerId: 'google.com', uid: 'google_uid', }, }; // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => { sinon.spy(validator, 'isUid'); sinon.spy(validator, 'isNonNullObject'); }); afterEach(() => { (validator.isUid as any).restore(); (validator.isNonNullObject as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no uid', () => { return (auth as any).updateUser(undefined, propertiesToEdit) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-uid'); }); it('should be rejected given an invalid uid', () => { const invalidUid = ('a' as any).repeat(129); return auth.updateUser(invalidUid, propertiesToEdit) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-uid'); expect(validator.isUid).to.have.been.calledOnce.and.calledWith(invalidUid); }); }); it('should be rejected given no properties', () => { return (auth as any).updateUser(uid) .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); it('should be rejected given invalid properties', () => { return auth.updateUser(uid, null as unknown as UpdateRequest) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/argument-error'); expect(validator.isNonNullObject).to.have.been.calledWith(null); }); }); const invalidUpdateRequests: UpdateRequest[] = [ { providerToLink: { uid: 'google_uid' } }, { providerToLink: { providerId: 'google.com' } }, { providerToLink: { providerId: 'google.com', uid: '' } }, { providerToLink: { providerId: '', uid: 'google_uid' } }, ]; invalidUpdateRequests.forEach((invalidUpdateRequest) => { it('should be rejected given an UpdateRequest with an invalid providerToLink parameter', () => { expect(() => { auth.updateUser(uid, invalidUpdateRequest); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); }); it('should rename providerToLink property to linkProviderUserInfo', async () => { const invokeRequestHandlerStub = sinon.stub(testConfig.RequestHandler.prototype, 'invokeRequestHandler') .resolves({ localId: uid, }); // Stub getAccountInfoByUid to return a valid result (unchecked; we // just need it to be valid so as to not crash.) const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves(expectedGetAccountInfoResult); stubs.push(invokeRequestHandlerStub); stubs.push(getUserStub); await auth.updateUser(uid, { providerToLink: { providerId: 'google.com', uid: 'google_uid', }, }); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { localId: uid, linkProviderUserInfo: { providerId: 'google.com', rawId: 'google_uid', }, }); }); INVALID_PROVIDER_IDS.forEach((invalidProviderId) => { it('should be rejected given a deleteProvider list with an invalid provider ID ' + JSON.stringify(invalidProviderId), () => { expect(() => { auth.updateUser(uid, { providersToUnlink: [ invalidProviderId as any ], }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); }); it('should merge deletion of phone provider with the providersToUnlink list', async () => { const invokeRequestHandlerStub = sinon.stub(testConfig.RequestHandler.prototype, 'invokeRequestHandler') .resolves({ localId: uid, }); // Stub getAccountInfoByUid to return a valid result (unchecked; we // just need it to be valid so as to not crash.) const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves(expectedGetAccountInfoResult); stubs.push(invokeRequestHandlerStub); stubs.push(getUserStub); await auth.updateUser(uid, { phoneNumber: null, providersToUnlink: [ 'google.com' ], }); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { localId: uid, deleteProvider: [ 'phone', 'google.com' ], }); }); describe('non-federated providers', () => { let invokeRequestHandlerStub: sinon.SinonStub; let getAccountInfoByUidStub: sinon.SinonStub; beforeEach(() => { invokeRequestHandlerStub = sinon.stub(testConfig.RequestHandler.prototype, 'invokeRequestHandler') .resolves({ // nothing here is checked; we just need enough to not crash. users: [{ localId: 1, }], }); getAccountInfoByUidStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves({ // nothing here is checked; we just need enough to not crash. users: [{ localId: 1, }], }); }); afterEach(() => { invokeRequestHandlerStub.restore(); getAccountInfoByUidStub.restore(); }); it('specifying both email and providerId=email should be rejected', () => { expect(() => { auth.updateUser(uid, { email: 'user@example.com', providerToLink: { providerId: 'email', uid: 'user@example.com', }, }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); it('specifying both phoneNumber and providerId=phone should be rejected', () => { expect(() => { auth.updateUser(uid, { phoneNumber: '+15555550001', providerToLink: { providerId: 'phone', uid: '+15555550001', }, }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); it('email linking should use email field', async () => { await auth.updateUser(uid, { providerToLink: { providerId: 'email', uid: 'user@example.com', }, }); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { localId: uid, email: 'user@example.com', }); }); it('phone linking should use phoneNumber field', async () => { await auth.updateUser(uid, { providerToLink: { providerId: 'phone', uid: '+15555550001', }, }); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { localId: uid, phoneNumber: '+15555550001', }); }); it('specifying both phoneNumber=null and providersToUnlink=phone should be rejected', () => { expect(() => { auth.updateUser(uid, { phoneNumber: null, providersToUnlink: ['phone'], }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); it('doesnt mutate the properties parameter', async () => { const properties: UpdateRequest = { providerToLink: { providerId: 'email', uid: 'user@example.com', }, }; await auth.updateUser(uid, properties); expect(properties).to.deep.equal({ providerToLink: { providerId: 'email', uid: 'user@example.com', }, }); }); }); describe('non-federated providers', () => { let invokeRequestHandlerStub: sinon.SinonStub; let getAccountInfoByUidStub: sinon.SinonStub; beforeEach(() => { invokeRequestHandlerStub = sinon.stub(testConfig.RequestHandler.prototype, 'invokeRequestHandler') .resolves({ // nothing here is checked; we just need enough to not crash. users: [{ localId: 1, }], }); getAccountInfoByUidStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves({ // nothing here is checked; we just need enough to not crash. users: [{ localId: 1, }], }); }); afterEach(() => { invokeRequestHandlerStub.restore(); getAccountInfoByUidStub.restore(); }); it('specifying both email and providerId=email should be rejected', () => { expect(() => { auth.updateUser(uid, { email: 'user@example.com', providerToLink: { providerId: 'email', uid: 'user@example.com', }, }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); it('specifying both phoneNumber and providerId=phone should be rejected', () => { expect(() => { auth.updateUser(uid, { phoneNumber: '+15555550001', providerToLink: { providerId: 'phone', uid: '+15555550001', }, }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); it('email linking should use email field', async () => { await auth.updateUser(uid, { providerToLink: { providerId: 'email', uid: 'user@example.com', }, }); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { localId: uid, email: 'user@example.com', }); }); it('phone linking should use phoneNumber field', async () => { await auth.updateUser(uid, { providerToLink: { providerId: 'phone', uid: '+15555550001', }, }); expect(invokeRequestHandlerStub).to.have.been.calledOnce.and.calledWith( sinon.match.any, sinon.match.any, { localId: uid, phoneNumber: '+15555550001', }); }); it('specifying both phoneNumber=null and providersToUnlink=phone should be rejected', () => { expect(() => { auth.updateUser(uid, { phoneNumber: null, providersToUnlink: ['phone'], }); }).to.throw(FirebaseAuthError).with.property('code', 'auth/argument-error'); }); it('doesnt mutate the properties parameter', async () => { const properties: UpdateRequest = { providerToLink: { providerId: 'email', uid: 'user@example.com', }, }; await auth.updateUser(uid, properties); expect(properties).to.deep.equal({ providerToLink: { providerId: 'email', uid: 'user@example.com', }, }); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.updateUser(uid, propertiesToEdit) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.updateUser(uid, propertiesToEdit) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.updateUser(uid, propertiesToEdit) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve with a UserRecord on updateExistingAccount request success', () => { // Stub updateExistingAccount to return expected uid. const updateUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateExistingAccount') .resolves(uid); // Stub getAccountInfoByUid to return expected result. const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .resolves(expectedGetAccountInfoResult); stubs.push(updateUserStub); stubs.push(getUserStub); return auth.updateUser(uid, propertiesToEdit) .then((userRecord) => { // Confirm underlying API called with expected parameters. expect(updateUserStub).to.have.been.calledOnce.and.calledWith(uid, propertiesToEdit); expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected user record response returned. expect(userRecord).to.deep.equal(expectedUserRecord); }); }); it('should throw an error when updateExistingAccount returns an error', () => { // Stub updateExistingAccount to throw a backend error. const updateUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateExistingAccount') .rejects(expectedError); stubs.push(updateUserStub); return auth.updateUser(uid, propertiesToEdit) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(updateUserStub).to.have.been.calledOnce.and.calledWith(uid, propertiesToEdit); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); it('should echo getUser error if an error occurs while retrieving the user record', () => { // Stub updateExistingAccount to return expected uid. const updateUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateExistingAccount') .resolves(uid); // Stub getAccountInfoByUid to throw an expected error. const getUserStub = sinon.stub(testConfig.RequestHandler.prototype, 'getAccountInfoByUid') .rejects(expectedError); stubs.push(updateUserStub); stubs.push(getUserStub); return auth.updateUser(uid, propertiesToEdit) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(updateUserStub).to.have.been.calledOnce.and.calledWith(uid, propertiesToEdit); expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned (same error thrown by getUser). expect(error).to.equal(expectedError); }); }); }); describe('setCustomUserClaims()', () => { const uid = 'abcdefghijklmnopqrstuvwxyz'; const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); const customClaims = { admin: true, groupId: '123456', }; // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => { sinon.spy(validator, 'isUid'); sinon.spy(validator, 'isObject'); }); afterEach(() => { (validator.isUid as any).restore(); (validator.isObject as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no uid', () => { return (auth as any).setCustomUserClaims(undefined, customClaims) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-uid'); }); it('should be rejected given an invalid uid', () => { const invalidUid = ('a' as any).repeat(129); return auth.setCustomUserClaims(invalidUid, customClaims) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-uid'); expect(validator.isUid).to.have.been.calledOnce.and.calledWith(invalidUid); }); }); it('should be rejected given no custom user claims', () => { return (auth as any).setCustomUserClaims(uid) .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); it('should be rejected given invalid custom user claims', () => { return auth.setCustomUserClaims(uid, 'invalid' as any) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/argument-error'); expect(validator.isObject).to.have.been.calledOnce.and.calledWith('invalid'); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.setCustomUserClaims(uid, customClaims) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.setCustomUserClaims(uid, customClaims) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.setCustomUserClaims(uid, customClaims) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve on setCustomUserClaims request success', () => { // Stub setCustomUserClaims to return expected uid. const setCustomUserClaimsStub = sinon .stub(testConfig.RequestHandler.prototype, 'setCustomUserClaims') .resolves(uid); stubs.push(setCustomUserClaimsStub); return auth.setCustomUserClaims(uid, customClaims) .then((response) => { expect(response).to.be.undefined; // Confirm underlying API called with expected parameters. expect(setCustomUserClaimsStub) .to.have.been.calledOnce.and.calledWith(uid, customClaims); }); }); it('should throw an error when setCustomUserClaims returns an error', () => { // Stub setCustomUserClaims to throw a backend error. const setCustomUserClaimsStub = sinon .stub(testConfig.RequestHandler.prototype, 'setCustomUserClaims') .rejects(expectedError); stubs.push(setCustomUserClaimsStub); return auth.setCustomUserClaims(uid, customClaims) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(setCustomUserClaimsStub) .to.have.been.calledOnce.and.calledWith(uid, customClaims); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('listUsers()', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.INTERNAL_ERROR); const pageToken = 'PAGE_TOKEN'; const maxResult = 500; const downloadAccountResponse: any = { users: [ { localId: 'UID1' }, { localId: 'UID2' }, { localId: 'UID3' }, ], nextPageToken: 'NEXT_PAGE_TOKEN', }; const expectedResult: any = { users: [ new UserRecord({ localId: 'UID1' }), new UserRecord({ localId: 'UID2' }), new UserRecord({ localId: 'UID3' }), ], pageToken: 'NEXT_PAGE_TOKEN', }; const emptyDownloadAccountResponse: any = { users: [], }; const emptyExpectedResult: any = { users: [], }; // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => { sinon.spy(validator, 'isNonEmptyString'); sinon.spy(validator, 'isNumber'); }); afterEach(() => { (validator.isNonEmptyString as any).restore(); (validator.isNumber as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given an invalid page token', () => { const invalidToken = {}; return auth.listUsers(undefined, invalidToken as any) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-page-token'); }); }); it('should be rejected given an invalid max result', () => { const invalidResults = 5000; return auth.listUsers(invalidResults) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/argument-error'); expect(validator.isNumber) .to.have.been.calledOnce.and.calledWith(invalidResults); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.listUsers(maxResult) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.listUsers(maxResult) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.listUsers(maxResult) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve on downloadAccount request success with users in response', () => { // Stub downloadAccount to return expected response. const downloadAccountStub = sinon .stub(testConfig.RequestHandler.prototype, 'downloadAccount') .resolves(downloadAccountResponse); stubs.push(downloadAccountStub); return auth.listUsers(maxResult, pageToken) .then((response) => { expect(response).to.deep.equal(expectedResult); // Confirm underlying API called with expected parameters. expect(downloadAccountStub) .to.have.been.calledOnce.and.calledWith(maxResult, pageToken); }); }); it('should resolve on downloadAccount request success with default options', () => { // Stub downloadAccount to return expected response. const downloadAccountStub = sinon .stub(testConfig.RequestHandler.prototype, 'downloadAccount') .resolves(downloadAccountResponse); stubs.push(downloadAccountStub); return auth.listUsers() .then((response) => { expect(response).to.deep.equal(expectedResult); // Confirm underlying API called with expected parameters. expect(downloadAccountStub) .to.have.been.calledOnce.and.calledWith(undefined, undefined); }); }); it('should resolve on downloadAccount request success with no users in response', () => { // Stub downloadAccount to return expected response. const downloadAccountStub = sinon .stub(testConfig.RequestHandler.prototype, 'downloadAccount') .resolves(emptyDownloadAccountResponse); stubs.push(downloadAccountStub); return auth.listUsers(maxResult, pageToken) .then((response) => { expect(response).to.deep.equal(emptyExpectedResult); // Confirm underlying API called with expected parameters. expect(downloadAccountStub) .to.have.been.calledOnce.and.calledWith(maxResult, pageToken); }); }); it('should throw an error when downloadAccount returns an error', () => { // Stub downloadAccount to throw a backend error. const downloadAccountStub = sinon .stub(testConfig.RequestHandler.prototype, 'downloadAccount') .rejects(expectedError); stubs.push(downloadAccountStub); return auth.listUsers(maxResult, pageToken) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(downloadAccountStub) .to.have.been.calledOnce.and.calledWith(maxResult, pageToken); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('revokeRefreshTokens()', () => { const uid = 'abcdefghijklmnopqrstuvwxyz'; const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => { sinon.spy(validator, 'isUid'); }); afterEach(() => { (validator.isUid as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no uid', () => { return (auth as any).revokeRefreshTokens(undefined) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-uid'); }); it('should be rejected given an invalid uid', () => { const invalidUid = ('a' as any).repeat(129); return auth.revokeRefreshTokens(invalidUid) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-uid'); expect(validator.isUid).to.have.been.calledOnce.and.calledWith(invalidUid); }); }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.revokeRefreshTokens(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.revokeRefreshTokens(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.revokeRefreshTokens(uid) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve on underlying revokeRefreshTokens request success', () => { // Stub revokeRefreshTokens to return expected uid. const revokeRefreshTokensStub = sinon.stub(testConfig.RequestHandler.prototype, 'revokeRefreshTokens') .resolves(uid); stubs.push(revokeRefreshTokensStub); return auth.revokeRefreshTokens(uid) .then((result) => { // Confirm underlying API called with expected parameters. expect(revokeRefreshTokensStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected response returned. expect(result).to.be.undefined; }); }); it('should throw when underlying revokeRefreshTokens request returns an error', () => { // Stub revokeRefreshTokens to throw a backend error. const revokeRefreshTokensStub = sinon.stub(testConfig.RequestHandler.prototype, 'revokeRefreshTokens') .rejects(expectedError); stubs.push(revokeRefreshTokensStub); return auth.revokeRefreshTokens(uid) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(revokeRefreshTokensStub).to.have.been.calledOnce.and.calledWith(uid); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('importUsers()', () => { const users = [ { uid: '1234', email: 'user@example.com', passwordHash: Buffer.from('password') }, { uid: '5678', phoneNumber: 'invalid' }, ]; const options = { hash: { algorithm: 'BCRYPT' as any, }, }; const expectedUserImportResultError = new FirebaseAuthError(AuthClientErrorCode.INVALID_PHONE_NUMBER); const expectedOptionsError = new FirebaseAuthError(AuthClientErrorCode.INVALID_HASH_ALGORITHM); const expectedServerError = new FirebaseAuthError(AuthClientErrorCode.INTERNAL_ERROR); const expectedUserImportResult = { successCount: 1, failureCount: 1, errors: [ { index: 1, error: expectedUserImportResultError, }, ], }; // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given an app which returns null access tokens', () => { return nullAccessTokenAuth.importUsers(users, options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return malformedAccessTokenAuth.importUsers(users, options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return rejectedPromiseAccessTokenAuth.importUsers(users, options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve on underlying uploadAccount request resolution', () => { // Stub uploadAccount to return expected result. const uploadAccountStub = sinon.stub(testConfig.RequestHandler.prototype, 'uploadAccount') .resolves(expectedUserImportResult); stubs.push(uploadAccountStub); return auth.importUsers(users, options) .then((result) => { // Confirm underlying API called with expected parameters. expect(uploadAccountStub).to.have.been.calledOnce.and.calledWith(users, options); // Confirm expected response returned. expect(result).to.be.equal(expectedUserImportResult); }); }); it('should reject when underlying uploadAccount request rejects with an error', () => { // Stub uploadAccount to reject with expected error. const uploadAccountStub = sinon.stub(testConfig.RequestHandler.prototype, 'uploadAccount') .rejects(expectedServerError); stubs.push(uploadAccountStub); return auth.importUsers(users, options) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(uploadAccountStub).to.have.been.calledOnce.and.calledWith(users, options); // Confirm expected error returned. expect(error).to.equal(expectedServerError); }); }); it('should throw and fail quickly when underlying uploadAccount throws', () => { // Stub uploadAccount to throw with expected error. const uploadAccountStub = sinon.stub(testConfig.RequestHandler.prototype, 'uploadAccount') .throws(expectedOptionsError); stubs.push(uploadAccountStub); expect(() => { return auth.importUsers(users, { hash: { algorithm: 'invalid' as any } }); }).to.throw(expectedOptionsError); }); if (testConfig.Auth === TenantAwareAuth) { it('should throw and fail quickly when users provided have mismatching tenant IDs', () => { const usersCopy = deepCopy(users); // Simulate one user with mismatching tenant ID. (usersCopy[0] as any).tenantId = 'otherTenantId'; expect(() => { return auth.importUsers(usersCopy, options); }).to.throw('UserRecord of index "0" has mismatching tenant ID "otherTenantId"'); }); it('should resolve when users provided have matching tenant IDs', () => { // Stub uploadAccount to return expected result. const uploadAccountStub = sinon.stub(testConfig.RequestHandler.prototype, 'uploadAccount') .returns(Promise.resolve(expectedUserImportResult)); const usersCopy = deepCopy(users); usersCopy.forEach((user) => { (user as any).tenantId = TENANT_ID; }); stubs.push(uploadAccountStub); return auth.importUsers(usersCopy, options) .then((result) => { // Confirm underlying API called with expected parameters. expect(uploadAccountStub).to.have.been.calledOnce.and.calledWith(usersCopy, options); // Confirm expected response returned. expect(result).to.be.equal(expectedUserImportResult); }); }); } }); describe('createSessionCookie()', () => { const tenantId = testConfig.supportsTenantManagement ? undefined : TENANT_ID; const idToken = 'ID_TOKEN'; const options = { expiresIn: 60 * 60 * 24 * 1000 }; const sessionCookie = 'SESSION_COOKIE'; const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_ID_TOKEN); const expectedUserRecord = getValidUserRecord(getValidGetAccountInfoResponse(tenantId)); // Set auth_time of token to expected user's tokensValidAfterTime. if (!expectedUserRecord.tokensValidAfterTime) { throw new Error("getValidUserRecord didn't properly set tokensValidAfterTime."); } const validSince = new Date(expectedUserRecord.tokensValidAfterTime); // Set expected uid to expected user's. const uid = expectedUserRecord.uid; // Set expected decoded ID token with expected UID and auth time. const decodedIdToken = getDecodedIdToken(uid, validSince, tenantId); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; beforeEach(() => { // If verifyIdToken stubbed, restore it. if (testConfig.Auth.prototype.verifyIdToken.restore) { testConfig.Auth.prototype.verifyIdToken.restore(); } sinon.spy(validator, 'isNonEmptyString'); }); afterEach(() => { (validator.isNonEmptyString as any).restore(); _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no ID token', () => { return (auth as any).createSessionCookie(undefined, options) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-id-token'); }); it('should be rejected given an invalid ID token', () => { const invalidIdToken = {} as any; return auth.createSessionCookie(invalidIdToken, options) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-id-token'); }); }); it('should be rejected given no session duration', () => { // Simulate auth.verifyIdToken() succeeds if called. stubs.push(sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.resolve(decodedIdToken))); return (auth as any).createSessionCookie(idToken, undefined) .should.eventually.be.rejected.and.have.property( 'code', 'auth/invalid-session-cookie-duration'); }); it('should be rejected given an invalid session duration', () => { // Invalid object. const invalidOptions = {} as any; return auth.createSessionCookie(idToken, invalidOptions) .should.eventually.be.rejected.and.have.property( 'code', 'auth/invalid-session-cookie-duration'); }); it('should be rejected given out of range session duration', () => { // Simulate auth.verifyIdToken() succeeds if called. stubs.push(sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.resolve(decodedIdToken))); // 1 minute duration. const invalidOptions = { expiresIn: 60 * 1000 }; return auth.createSessionCookie(idToken, invalidOptions) .should.eventually.be.rejected.and.have.property( 'code', 'auth/invalid-session-cookie-duration'); }); it('should be rejected given an app which returns null access tokens', () => { // Simulate auth.verifyIdToken() succeeds if called. stubs.push(sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.resolve(decodedIdToken))); return nullAccessTokenAuth.createSessionCookie(idToken, options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { stubs.push(sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.resolve(decodedIdToken))); return malformedAccessTokenAuth.createSessionCookie(idToken, options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { stubs.push(sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.resolve(decodedIdToken))); return rejectedPromiseAccessTokenAuth.createSessionCookie(idToken, options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve on underlying createSessionCookie request success', () => { // Simulate auth.verifyIdToken() succeeds if called. const verifyIdTokenStub = sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.resolve(decodedIdToken)); // Stub createSessionCookie to return expected sessionCookie. const createSessionCookieStub = sinon.stub(testConfig.RequestHandler.prototype, 'createSessionCookie') .resolves(sessionCookie); stubs.push(createSessionCookieStub); return auth.createSessionCookie(idToken, options) .then((result) => { // Confirm underlying API called with expected parameters. expect(createSessionCookieStub) .to.have.been.calledOnce.and.calledWith(idToken, options.expiresIn); // TenantAwareAuth should verify the ID token first. if (testConfig.Auth === TenantAwareAuth) { expect(verifyIdTokenStub) .to.have.been.calledOnce.and.calledWith(idToken); } else { expect(verifyIdTokenStub).to.have.not.been.called; } // Confirm expected response returned. expect(result).to.be.equal(sessionCookie); }); }); it('should throw when underlying createSessionCookie request returns an error', () => { // Simulate auth.verifyIdToken() succeeds if called. stubs.push(sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .resolves(decodedIdToken)); // Stub createSessionCookie to throw a backend error. const createSessionCookieStub = sinon.stub(testConfig.RequestHandler.prototype, 'createSessionCookie') .rejects(expectedError); stubs.push(createSessionCookieStub); return auth.createSessionCookie(idToken, options) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(createSessionCookieStub) .to.have.been.calledOnce.and.calledWith(idToken, options.expiresIn); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); if (testConfig.Auth === TenantAwareAuth) { it('should be rejected when ID token provided is invalid', () => { // Simulate auth.verifyIdToken() fails when called. const verifyIdTokenStub = sinon.stub(testConfig.Auth.prototype, 'verifyIdToken') .returns(Promise.reject(expectedError)); stubs.push(verifyIdTokenStub); return auth.createSessionCookie(idToken, options) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(verifyIdTokenStub) .to.have.been.calledOnce.and.calledWith(idToken); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); } }); const emailActionFlows: EmailActionTest[] = [ { api: 'generatePasswordResetLink', requestType: 'PASSWORD_RESET', requiresSettings: false }, { api: 'generateEmailVerificationLink', requestType: 'VERIFY_EMAIL', requiresSettings: false }, { api: 'generateSignInWithEmailLink', requestType: 'EMAIL_SIGNIN', requiresSettings: true }, ]; emailActionFlows.forEach((emailActionFlow) => { describe(`${emailActionFlow.api}()`, () => { const email = 'user@example.com'; const actionCodeSettings = { url: 'https://www.example.com/path/file?a=1&b=2', handleCodeInApp: true, iOS: { bundleId: 'com.example.ios', }, android: { packageName: 'com.example.android', installApp: true, minimumVersion: '6', }, dynamicLinkDomain: 'custom.page.link', }; const expectedLink = 'https://custom.page.link?link=' + encodeURIComponent('https://projectId.firebaseapp.com/__/auth/action?oobCode=CODE') + '&apn=com.example.android&ibi=com.example.ios'; const expectedError = new FirebaseAuthError(AuthClientErrorCode.USER_NOT_FOUND); // Stubs used to simulate underlying api calls. let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no email', () => { return (auth as any)[emailActionFlow.api](undefined, actionCodeSettings) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-email'); }); it('should be rejected given an invalid email', () => { return (auth as any)[emailActionFlow.api]('invalid', actionCodeSettings) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-email'); }); it('should be rejected given an invalid ActionCodeSettings object', () => { return (auth as any)[emailActionFlow.api](email, 'invalid') .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); it('should be rejected given an app which returns null access tokens', () => { return (nullAccessTokenAuth as any)[emailActionFlow.api](email, actionCodeSettings) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return (malformedAccessTokenAuth as any)[emailActionFlow.api](email, actionCodeSettings) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return (rejectedPromiseAccessTokenAuth as any)[emailActionFlow.api](email, actionCodeSettings) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should resolve when called with actionCodeSettings with a generated link on success', () => { // Stub getEmailActionLink to return expected link. const getEmailActionLinkStub = sinon.stub(testConfig.RequestHandler.prototype, 'getEmailActionLink') .resolves(expectedLink); stubs.push(getEmailActionLinkStub); return (auth as any)[emailActionFlow.api](email, actionCodeSettings) .then((actualLink: string) => { // Confirm underlying API called with expected parameters. expect(getEmailActionLinkStub).to.have.been.calledOnce.and.calledWith( emailActionFlow.requestType, email, actionCodeSettings); // Confirm expected user record response returned. expect(actualLink).to.equal(expectedLink); }); }); if (emailActionFlow.requiresSettings) { it('should reject when called without actionCodeSettings', () => { return (auth as any)[emailActionFlow.api](email, undefined) .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); } else { it('should resolve when called without actionCodeSettings with a generated link on success', () => { // Stub getEmailActionLink to return expected link. const getEmailActionLinkStub = sinon.stub(testConfig.RequestHandler.prototype, 'getEmailActionLink') .resolves(expectedLink); stubs.push(getEmailActionLinkStub); return (auth as any)[emailActionFlow.api](email) .then((actualLink: string) => { // Confirm underlying API called with expected parameters. expect(getEmailActionLinkStub).to.have.been.calledOnce.and.calledWith( emailActionFlow.requestType, email, undefined); // Confirm expected user record response returned. expect(actualLink).to.equal(expectedLink); }); }); } it('should throw an error when getEmailAction returns an error', () => { // Stub getEmailActionLink to throw a backend error. const getEmailActionLinkStub = sinon.stub(testConfig.RequestHandler.prototype, 'getEmailActionLink') .rejects(expectedError); stubs.push(getEmailActionLinkStub); return (auth as any)[emailActionFlow.api](email, actionCodeSettings) .then(() => { throw new Error('Unexpected success'); }, (error: any) => { // Confirm underlying API called with expected parameters. expect(getEmailActionLinkStub).to.have.been.calledOnce.and.calledWith( emailActionFlow.requestType, email, actionCodeSettings); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); }); describe('getProviderConfig()', () => { let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no provider ID', () => { return (auth as any).getProviderConfig() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-provider-id'); }); INVALID_PROVIDER_IDS.forEach((invalidProviderId) => { it(`should be rejected given an invalid provider ID "${JSON.stringify(invalidProviderId)}"`, () => { return (auth as Auth).getProviderConfig(invalidProviderId as any) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-provider-id'); }); }); }); it('should be rejected given an app which returns null access tokens', () => { const providerId = 'oidc.provider'; return (nullAccessTokenAuth as Auth).getProviderConfig(providerId) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { const providerId = 'oidc.provider'; return (malformedAccessTokenAuth as Auth).getProviderConfig(providerId) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { const providerId = 'oidc.provider'; return (rejectedPromiseAccessTokenAuth as Auth).getProviderConfig(providerId) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); describe('using OIDC configurations', () => { const providerId = 'oidc.provider'; const serverResponse = { name: `projects/project_id/oauthIdpConfigs/${providerId}`, displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; const expectedConfig = new OIDCConfig(serverResponse); const expectedError = new FirebaseAuthError(AuthClientErrorCode.CONFIGURATION_NOT_FOUND); it('should resolve with an OIDCConfig on success', () => { // Stub getOAuthIdpConfig to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getOAuthIdpConfig') .resolves(serverResponse); stubs.push(stub); return (auth as Auth).getProviderConfig(providerId) .then((result) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected config returned. expect(result).to.deep.equal(expectedConfig); }); }); it('should throw an error when the backend returns an error', () => { // Stub getOAuthIdpConfig to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getOAuthIdpConfig') .rejects(expectedError); stubs.push(stub); return (auth as Auth).getProviderConfig(providerId) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('using SAML configurations', () => { const providerId = 'saml.provider'; const serverResponse = { name: `projects/project_id/inboundSamlConfigs/${providerId}`, idpConfig: { idpEntityId: 'IDP_ENTITY_ID', ssoUrl: 'https://example.com/login', signRequest: true, idpCertificates: [ { x509Certificate: 'CERT1' }, { x509Certificate: 'CERT2' }, ], }, spConfig: { spEntityId: 'RP_ENTITY_ID', callbackUri: 'https://projectId.firebaseapp.com/__/auth/handler', }, displayName: 'SAML_DISPLAY_NAME', enabled: true, }; const expectedConfig = new SAMLConfig(serverResponse); const expectedError = new FirebaseAuthError(AuthClientErrorCode.CONFIGURATION_NOT_FOUND); it('should resolve with a SAMLConfig on success', () => { // Stub getInboundSamlConfig to return expected result. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getInboundSamlConfig') .resolves(serverResponse); stubs.push(stub); return (auth as Auth).getProviderConfig(providerId) .then((result) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected config returned. expect(result).to.deep.equal(expectedConfig); }); }); it('should throw an error when the backend returns an error', () => { // Stub getInboundSamlConfig to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'getInboundSamlConfig') .rejects(expectedError); stubs.push(stub); return (auth as Auth).getProviderConfig(providerId) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); }); describe('listProviderConfigs()', () => { const options: AuthProviderConfigFilter = { type: 'oidc', }; let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no options', () => { return (auth as any).listProviderConfigs() .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); it('should be rejected given an invalid AuthProviderConfigFilter type', () => { const invalidOptions = { type: 'unsupported', }; return (auth as Auth).listProviderConfigs(invalidOptions as any) .should.eventually.be.rejected.and.have.property('code', 'auth/argument-error'); }); it('should be rejected given an app which returns null access tokens', () => { return (nullAccessTokenAuth as Auth).listProviderConfigs(options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return (malformedAccessTokenAuth as Auth).listProviderConfigs(options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return (rejectedPromiseAccessTokenAuth as Auth).listProviderConfigs(options) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); describe('using OIDC type filter', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.INTERNAL_ERROR); const pageToken = 'PAGE_TOKEN'; const maxResults = 50; const filterOptions: AuthProviderConfigFilter = { type: 'oidc', pageToken, maxResults, }; const listConfigsResponse: any = { oauthIdpConfigs : [ getOIDCConfigServerResponse('oidc.provider1'), getOIDCConfigServerResponse('oidc.provider2'), ], nextPageToken: 'NEXT_PAGE_TOKEN', }; const expectedResult: any = { providerConfigs: [ new OIDCConfig(listConfigsResponse.oauthIdpConfigs[0]), new OIDCConfig(listConfigsResponse.oauthIdpConfigs[1]), ], pageToken: 'NEXT_PAGE_TOKEN', }; const emptyListConfigsResponse: any = { oauthIdpConfigs: [], }; const emptyExpectedResult: any = { providerConfigs: [], }; it('should resolve on success with configs in response', () => { // Stub listOAuthIdpConfigs to return expected response. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listOAuthIdpConfigs') .resolves(listConfigsResponse); stubs.push(listConfigsStub); return auth.listProviderConfigs(filterOptions) .then((response) => { expect(response).to.deep.equal(expectedResult); // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(maxResults, pageToken); }); }); it('should resolve on success with default options', () => { // Stub listOAuthIdpConfigs to return expected response. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listOAuthIdpConfigs') .resolves(listConfigsResponse); stubs.push(listConfigsStub); return (auth as Auth).listProviderConfigs({ type: 'oidc' }) .then((response) => { expect(response).to.deep.equal(expectedResult); // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(undefined, undefined); }); }); it('should resolve on success with no configs in response', () => { // Stub listOAuthIdpConfigs to return expected response. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listOAuthIdpConfigs') .resolves(emptyListConfigsResponse); stubs.push(listConfigsStub); return auth.listProviderConfigs(filterOptions) .then((response) => { expect(response).to.deep.equal(emptyExpectedResult); // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(maxResults, pageToken); }); }); it('should throw an error when listOAuthIdpConfigs returns an error', () => { // Stub listOAuthIdpConfigs to throw a backend error. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listOAuthIdpConfigs') .rejects(expectedError); stubs.push(listConfigsStub); return auth.listProviderConfigs(filterOptions) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(maxResults, pageToken); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('using SAML type filter', () => { const expectedError = new FirebaseAuthError(AuthClientErrorCode.INTERNAL_ERROR); const pageToken = 'PAGE_TOKEN'; const maxResults = 50; const filterOptions: AuthProviderConfigFilter = { type: 'saml', pageToken, maxResults, }; const listConfigsResponse: any = { inboundSamlConfigs : [ getSAMLConfigServerResponse('saml.provider1'), getSAMLConfigServerResponse('saml.provider2'), ], nextPageToken: 'NEXT_PAGE_TOKEN', }; const expectedResult: any = { providerConfigs: [ new SAMLConfig(listConfigsResponse.inboundSamlConfigs[0]), new SAMLConfig(listConfigsResponse.inboundSamlConfigs[1]), ], pageToken: 'NEXT_PAGE_TOKEN', }; const emptyListConfigsResponse: any = { inboundSamlConfigs: [], }; const emptyExpectedResult: any = { providerConfigs: [], }; it('should resolve on success with configs in response', () => { // Stub listInboundSamlConfigs to return expected response. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listInboundSamlConfigs') .resolves(listConfigsResponse); stubs.push(listConfigsStub); return auth.listProviderConfigs(filterOptions) .then((response) => { expect(response).to.deep.equal(expectedResult); // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(maxResults, pageToken); }); }); it('should resolve on success with default options', () => { // Stub listInboundSamlConfigs to return expected response. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listInboundSamlConfigs') .resolves(listConfigsResponse); stubs.push(listConfigsStub); return (auth as Auth).listProviderConfigs({ type: 'saml' }) .then((response) => { expect(response).to.deep.equal(expectedResult); // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(undefined, undefined); }); }); it('should resolve on success with no configs in response', () => { // Stub listInboundSamlConfigs to return expected response. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listInboundSamlConfigs') .resolves(emptyListConfigsResponse); stubs.push(listConfigsStub); return auth.listProviderConfigs(filterOptions) .then((response) => { expect(response).to.deep.equal(emptyExpectedResult); // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(maxResults, pageToken); }); }); it('should throw an error when listInboundSamlConfigs returns an error', () => { // Stub listInboundSamlConfigs to throw a backend error. const listConfigsStub = sinon .stub(testConfig.RequestHandler.prototype, 'listInboundSamlConfigs') .rejects(expectedError); stubs.push(listConfigsStub); return auth.listProviderConfigs(filterOptions) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(listConfigsStub) .to.have.been.calledOnce.and.calledWith(maxResults, pageToken); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); }); describe('deleteProviderConfig()', () => { let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no provider ID', () => { return (auth as any).deleteProviderConfig() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-provider-id'); }); INVALID_PROVIDER_IDS.forEach((invalidProviderId) => { it(`should be rejected given an invalid provider ID "${JSON.stringify(invalidProviderId)}"`, () => { return (auth as Auth).deleteProviderConfig(invalidProviderId as any) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-provider-id'); }); }); }); it('should be rejected given an app which returns null access tokens', () => { const providerId = 'oidc.provider'; return (nullAccessTokenAuth as Auth).deleteProviderConfig(providerId) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { const providerId = 'oidc.provider'; return (malformedAccessTokenAuth as Auth).deleteProviderConfig(providerId) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { const providerId = 'oidc.provider'; return (rejectedPromiseAccessTokenAuth as Auth).deleteProviderConfig(providerId) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); describe('using OIDC configurations', () => { const providerId = 'oidc.provider'; const expectedError = new FirebaseAuthError(AuthClientErrorCode.CONFIGURATION_NOT_FOUND); it('should resolve with void on success', () => { // Stub deleteOAuthIdpConfig to resolve. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteOAuthIdpConfig') .resolves(); stubs.push(stub); return (auth as Auth).deleteProviderConfig(providerId) .then((result) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected result returned. expect(result).to.be.undefined; }); }); it('should throw an error when the backend returns an error', () => { // Stub deleteOAuthIdpConfig to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteOAuthIdpConfig') .rejects(expectedError); stubs.push(stub); return (auth as Auth).deleteProviderConfig(providerId) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('using SAML configurations', () => { const providerId = 'saml.provider'; const expectedError = new FirebaseAuthError(AuthClientErrorCode.CONFIGURATION_NOT_FOUND); it('should resolve with void on success', () => { // Stub deleteInboundSamlConfig to resolve. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteInboundSamlConfig') .resolves(); stubs.push(stub); return (auth as Auth).deleteProviderConfig(providerId) .then((result) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected result returned. expect(result).to.be.undefined; }); }); it('should throw an error when the backend returns an error', () => { // Stub deleteInboundSamlConfig to throw a backend error. const stub = sinon.stub(testConfig.RequestHandler.prototype, 'deleteInboundSamlConfig') .rejects(expectedError); stubs.push(stub); return (auth as Auth).deleteProviderConfig(providerId) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(stub).to.have.been.calledOnce.and.calledWith(providerId); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); }); describe('updateProviderConfig()', () => { const oidcConfigOptions = { displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no provider ID', () => { return (auth as any).updateProviderConfig(undefined, oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-provider-id'); }); INVALID_PROVIDER_IDS.forEach((invalidProviderId) => { it(`should be rejected given an invalid provider ID "${JSON.stringify(invalidProviderId)}"`, () => { return (auth as Auth).updateProviderConfig(invalidProviderId as any, oidcConfigOptions) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-provider-id'); }); }); }); it('should be rejected given no options', () => { const providerId = 'oidc.provider'; return (auth as any).updateProviderConfig(providerId) .then(() => { throw new Error('Unexpected success'); }) .catch((error: FirebaseAuthError) => { expect(error).to.have.property('code', 'auth/invalid-config'); }); }); it('should be rejected given an app which returns null access tokens', () => { const providerId = 'oidc.provider'; return (nullAccessTokenAuth as Auth).updateProviderConfig(providerId, oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { const providerId = 'oidc.provider'; return (malformedAccessTokenAuth as Auth).updateProviderConfig(providerId, oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { const providerId = 'oidc.provider'; return (rejectedPromiseAccessTokenAuth as Auth).updateProviderConfig(providerId, oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); describe('using OIDC configurations', () => { const providerId = 'oidc.provider'; const configOptions = { displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; const serverResponse = { name: `projects/project_id/oauthIdpConfigs/${providerId}`, displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; const expectedConfig = new OIDCConfig(serverResponse); const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CONFIG); it('should resolve with an OIDCConfig on updateOAuthIdpConfig request success', () => { // Stub updateOAuthIdpConfig to return expected server response. const updateConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateOAuthIdpConfig') .resolves(serverResponse); stubs.push(updateConfigStub); return auth.updateProviderConfig(providerId, configOptions) .then((actualConfig) => { // Confirm underlying API called with expected parameters. expect(updateConfigStub).to.have.been.calledOnce.and.calledWith(providerId, configOptions); // Confirm expected config response returned. expect(actualConfig).to.deep.equal(expectedConfig); }); }); it('should throw an error when updateOAuthIdpConfig returns an error', () => { // Stub updateOAuthIdpConfig to throw a backend error. const updateConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateOAuthIdpConfig') .rejects(expectedError); stubs.push(updateConfigStub); return auth.updateProviderConfig(providerId, configOptions) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(updateConfigStub).to.have.been.calledOnce.and.calledWith(providerId, configOptions); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('using SAML configurations', () => { const providerId = 'saml.provider'; const configOptions = { displayName: 'SAML_DISPLAY_NAME', enabled: true, idpEntityId: 'IDP_ENTITY_ID', ssoURL: 'https://example.com/login', x509Certificates: ['CERT1', 'CERT2'], rpEntityId: 'RP_ENTITY_ID', callbackURL: 'https://projectId.firebaseapp.com/__/auth/handler', enableRequestSigning: true, }; const serverResponse = { name: `projects/project_id/inboundSamlConfigs/${providerId}`, idpConfig: { idpEntityId: 'IDP_ENTITY_ID', ssoUrl: 'https://example.com/login', signRequest: true, idpCertificates: [ { x509Certificate: 'CERT1' }, { x509Certificate: 'CERT2' }, ], }, spConfig: { spEntityId: 'RP_ENTITY_ID', callbackUri: 'https://projectId.firebaseapp.com/__/auth/handler', }, displayName: 'SAML_DISPLAY_NAME', enabled: true, }; const expectedConfig = new SAMLConfig(serverResponse); const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CONFIG); it('should resolve with a SAMLConfig on updateInboundSamlConfig request success', () => { // Stub updateInboundSamlConfig to return expected server response. const updateConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateInboundSamlConfig') .resolves(serverResponse); stubs.push(updateConfigStub); return auth.updateProviderConfig(providerId, configOptions) .then((actualConfig) => { // Confirm underlying API called with expected parameters. expect(updateConfigStub).to.have.been.calledOnce.and.calledWith(providerId, configOptions); // Confirm expected config response returned. expect(actualConfig).to.deep.equal(expectedConfig); }); }); it('should throw an error when updateInboundSamlConfig returns an error', () => { // Stub updateInboundSamlConfig to throw a backend error. const updateConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'updateInboundSamlConfig') .rejects(expectedError); stubs.push(updateConfigStub); return auth.updateProviderConfig(providerId, configOptions) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(updateConfigStub).to.have.been.calledOnce.and.calledWith(providerId, configOptions); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); }); describe('createProviderConfig()', () => { const oidcConfigOptions = { providerId: 'oidc.provider', displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; let stubs: sinon.SinonStub[] = []; afterEach(() => { _.forEach(stubs, (stub) => stub.restore()); stubs = []; }); it('should be rejected given no configuration options', () => { return (auth as any).createProviderConfig() .should.eventually.be.rejected.and.have.property('code', 'auth/invalid-config'); }); it('should be rejected given an invalid provider ID', () => { const invalidConfigOptions = deepCopy(oidcConfigOptions); invalidConfigOptions.providerId = 'unsupported'; return (auth as Auth).createProviderConfig(invalidConfigOptions) .then(() => { throw new Error('Unexpected success'); }) .catch((error) => { expect(error).to.have.property('code', 'auth/invalid-provider-id'); }); }); it('should be rejected given an app which returns null access tokens', () => { return (nullAccessTokenAuth as Auth).createProviderConfig(oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which returns invalid access tokens', () => { return (malformedAccessTokenAuth as Auth).createProviderConfig(oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); it('should be rejected given an app which fails to generate access tokens', () => { return (rejectedPromiseAccessTokenAuth as Auth).createProviderConfig(oidcConfigOptions) .should.eventually.be.rejected.and.have.property('code', 'app/invalid-credential'); }); describe('using OIDC configurations', () => { const providerId = 'oidc.provider'; const configOptions = { providerId, displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; const serverResponse = { name: `projects/project_id/oauthIdpConfigs/${providerId}`, displayName: 'OIDC_DISPLAY_NAME', enabled: true, clientId: 'CLIENT_ID', issuer: 'https://oidc.com/issuer', }; const expectedConfig = new OIDCConfig(serverResponse); const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CONFIG); it('should resolve with an OIDCConfig on createOAuthIdpConfig request success', () => { // Stub createOAuthIdpConfig to return expected server response. const createConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'createOAuthIdpConfig') .resolves(serverResponse); stubs.push(createConfigStub); return (auth as Auth).createProviderConfig(configOptions) .then((actualConfig) => { // Confirm underlying API called with expected parameters. expect(createConfigStub).to.have.been.calledOnce.and.calledWith(configOptions); // Confirm expected config response returned. expect(actualConfig).to.deep.equal(expectedConfig); }); }); it('should throw an error when createOAuthIdpConfig returns an error', () => { // Stub createOAuthIdpConfig to throw a backend error. const createConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'createOAuthIdpConfig') .rejects(expectedError); stubs.push(createConfigStub); return (auth as Auth).createProviderConfig(configOptions) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(createConfigStub).to.have.been.calledOnce.and.calledWith(configOptions); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); describe('using SAML configurations', () => { const providerId = 'saml.provider'; const configOptions = { providerId, displayName: 'SAML_DISPLAY_NAME', enabled: true, idpEntityId: 'IDP_ENTITY_ID', ssoURL: 'https://example.com/login', x509Certificates: ['CERT1', 'CERT2'], rpEntityId: 'RP_ENTITY_ID', callbackURL: 'https://projectId.firebaseapp.com/__/auth/handler', enableRequestSigning: true, }; const serverResponse = { name: `projects/project_id/inboundSamlConfigs/${providerId}`, idpConfig: { idpEntityId: 'IDP_ENTITY_ID', ssoUrl: 'https://example.com/login', signRequest: true, idpCertificates: [ { x509Certificate: 'CERT1' }, { x509Certificate: 'CERT2' }, ], }, spConfig: { spEntityId: 'RP_ENTITY_ID', callbackUri: 'https://projectId.firebaseapp.com/__/auth/handler', }, displayName: 'SAML_DISPLAY_NAME', enabled: true, }; const expectedConfig = new SAMLConfig(serverResponse); const expectedError = new FirebaseAuthError(AuthClientErrorCode.INVALID_CONFIG); it('should resolve with a SAMLConfig on createInboundSamlConfig request success', () => { // Stub createInboundSamlConfig to return expected server response. const createConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'createInboundSamlConfig') .resolves(serverResponse); stubs.push(createConfigStub); return (auth as Auth).createProviderConfig(configOptions) .then((actualConfig) => { // Confirm underlying API called with expected parameters. expect(createConfigStub).to.have.been.calledOnce.and.calledWith(configOptions); // Confirm expected config response returned. expect(actualConfig).to.deep.equal(expectedConfig); }); }); it('should throw an error when createInboundSamlConfig returns an error', () => { // Stub createInboundSamlConfig to throw a backend error. const createConfigStub = sinon.stub(testConfig.RequestHandler.prototype, 'createInboundSamlConfig') .rejects(expectedError); stubs.push(createConfigStub); return (auth as Auth).createProviderConfig(configOptions) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm underlying API called with expected parameters. expect(createConfigStub).to.have.been.calledOnce.and.calledWith(configOptions); // Confirm expected error returned. expect(error).to.equal(expectedError); }); }); }); }); describe('auth emulator support', () => { let mockAuth = testConfig.init(mocks.app()); const userRecord = getValidUserRecord(getValidGetAccountInfoResponse()); const validSince = new Date(userRecord.tokensValidAfterTime!); const stubs: sinon.SinonStub[] = []; let clock: sinon.SinonFakeTimers; beforeEach(() => { process.env.FIREBASE_AUTH_EMULATOR_HOST = '127.0.0.1:9099'; mockAuth = testConfig.init(mocks.app()); clock = sinon.useFakeTimers(validSince.getTime()); }); afterEach(() => { _.forEach(stubs, (s) => s.restore()); delete process.env.FIREBASE_AUTH_EMULATOR_HOST; clock.restore(); }); it('createCustomToken() generates an unsigned token', async () => { const token = await mockAuth.createCustomToken('uid1'); // Check the decoded token has the right algorithm const decoded = jwt.decode(token, { complete: true }); expect(decoded).to.have.property('header').that.has.property('alg', 'none'); expect(decoded).to.have.property('payload').that.has.property('uid', 'uid1'); // Make sure this doesn't throw jwt.verify(token, '', { algorithms: ['none'] }); }); it('verifyIdToken() should reject revoked ID tokens', () => { const uid = userRecord.uid; // One second before validSince. const oneSecBeforeValidSince = Math.floor(validSince.getTime() / 1000 - 1); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(userRecord); stubs.push(getUserStub); const unsignedToken = mocks.generateIdToken({ algorithm: 'none', subject: uid, }, { iat: oneSecBeforeValidSince, auth_time: oneSecBeforeValidSince, // eslint-disable-line @typescript-eslint/camelcase }); // verifyIdToken should force checking revocation in emulator mode, // even if checkRevoked=false. return mockAuth.verifyIdToken(unsignedToken, false) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.have.property('code', 'auth/id-token-revoked'); // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); }); }); it('verifySessionCookie() should reject revoked session cookies', () => { const uid = userRecord.uid; // One second before validSince. const oneSecBeforeValidSince = Math.floor(validSince.getTime() / 1000 - 1); const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser') .resolves(userRecord); stubs.push(getUserStub); const unsignedToken = mocks.generateIdToken({ algorithm: 'none', subject: uid, issuer: 'https://session.firebase.google.com/' + mocks.projectId, }, { iat: oneSecBeforeValidSince, auth_time: oneSecBeforeValidSince, // eslint-disable-line @typescript-eslint/camelcase }); // verifySessionCookie should force checking revocation in emulator // mode, even if checkRevoked=false. return mockAuth.verifySessionCookie(unsignedToken, false) .then(() => { throw new Error('Unexpected success'); }, (error) => { // Confirm expected error returned. expect(error).to.have.property('code', 'auth/session-cookie-revoked'); // Confirm underlying API called with expected parameters. expect(getUserStub).to.have.been.calledOnce.and.calledWith(uid); }); }); it('verifyIdToken() rejects an unsigned token if auth emulator is unreachable', async () => { const unsignedToken = mocks.generateIdToken({ algorithm: 'none' }); const errorMessage = 'Error while making request: connect ECONNREFUSED 127.0.0.1. Error code: ECONNREFUSED'; const getUserStub = sinon.stub(testConfig.Auth.prototype, 'getUser').rejects(new Error(errorMessage)); stubs.push(getUserStub); // Since revocation check is forced on in emulator mode, this will call // the getUser method and get rejected (instead of succeed locally). await expect(mockAuth.verifyIdToken(unsignedToken)) .to.be.rejectedWith(errorMessage); }); }); }); });
the_stack
import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { GrammarSpecContext } from "./ANTLRv4Parser"; import { GrammarTypeContext } from "./ANTLRv4Parser"; import { PrequelConstructContext } from "./ANTLRv4Parser"; import { OptionsSpecContext } from "./ANTLRv4Parser"; import { OptionContext } from "./ANTLRv4Parser"; import { OptionValueContext } from "./ANTLRv4Parser"; import { DelegateGrammarsContext } from "./ANTLRv4Parser"; import { DelegateGrammarContext } from "./ANTLRv4Parser"; import { TokensSpecContext } from "./ANTLRv4Parser"; import { ChannelsSpecContext } from "./ANTLRv4Parser"; import { IdListContext } from "./ANTLRv4Parser"; import { NamedActionContext } from "./ANTLRv4Parser"; import { ActionScopeNameContext } from "./ANTLRv4Parser"; import { ActionBlockContext } from "./ANTLRv4Parser"; import { ArgActionBlockContext } from "./ANTLRv4Parser"; import { ModeSpecContext } from "./ANTLRv4Parser"; import { RulesContext } from "./ANTLRv4Parser"; import { RuleSpecContext } from "./ANTLRv4Parser"; import { ParserRuleSpecContext } from "./ANTLRv4Parser"; import { ExceptionGroupContext } from "./ANTLRv4Parser"; import { ExceptionHandlerContext } from "./ANTLRv4Parser"; import { FinallyClauseContext } from "./ANTLRv4Parser"; import { RulePrequelContext } from "./ANTLRv4Parser"; import { RuleReturnsContext } from "./ANTLRv4Parser"; import { ThrowsSpecContext } from "./ANTLRv4Parser"; import { LocalsSpecContext } from "./ANTLRv4Parser"; import { RuleActionContext } from "./ANTLRv4Parser"; import { RuleModifiersContext } from "./ANTLRv4Parser"; import { RuleModifierContext } from "./ANTLRv4Parser"; import { RuleBlockContext } from "./ANTLRv4Parser"; import { RuleAltListContext } from "./ANTLRv4Parser"; import { LabeledAltContext } from "./ANTLRv4Parser"; import { LexerRuleSpecContext } from "./ANTLRv4Parser"; import { LexerRuleBlockContext } from "./ANTLRv4Parser"; import { LexerAltListContext } from "./ANTLRv4Parser"; import { LexerAltContext } from "./ANTLRv4Parser"; import { LexerElementsContext } from "./ANTLRv4Parser"; import { LexerElementContext } from "./ANTLRv4Parser"; import { LabeledLexerElementContext } from "./ANTLRv4Parser"; import { LexerBlockContext } from "./ANTLRv4Parser"; import { LexerCommandsContext } from "./ANTLRv4Parser"; import { LexerCommandContext } from "./ANTLRv4Parser"; import { LexerCommandNameContext } from "./ANTLRv4Parser"; import { LexerCommandExprContext } from "./ANTLRv4Parser"; import { AltListContext } from "./ANTLRv4Parser"; import { AlternativeContext } from "./ANTLRv4Parser"; import { ElementContext } from "./ANTLRv4Parser"; import { LabeledElementContext } from "./ANTLRv4Parser"; import { EbnfContext } from "./ANTLRv4Parser"; import { BlockSuffixContext } from "./ANTLRv4Parser"; import { EbnfSuffixContext } from "./ANTLRv4Parser"; import { LexerAtomContext } from "./ANTLRv4Parser"; import { AtomContext } from "./ANTLRv4Parser"; import { NotSetContext } from "./ANTLRv4Parser"; import { BlockSetContext } from "./ANTLRv4Parser"; import { SetElementContext } from "./ANTLRv4Parser"; import { BlockContext } from "./ANTLRv4Parser"; import { RulerefContext } from "./ANTLRv4Parser"; import { CharacterRangeContext } from "./ANTLRv4Parser"; import { TerminalRuleContext } from "./ANTLRv4Parser"; import { ElementOptionsContext } from "./ANTLRv4Parser"; import { ElementOptionContext } from "./ANTLRv4Parser"; import { IdentifierContext } from "./ANTLRv4Parser"; /** * This interface defines a complete listener for a parse tree produced by * `ANTLRv4Parser`. */ export interface ANTLRv4ParserListener extends ParseTreeListener { /** * Enter a parse tree produced by `ANTLRv4Parser.grammarSpec`. * @param ctx the parse tree */ enterGrammarSpec?: (ctx: GrammarSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.grammarSpec`. * @param ctx the parse tree */ exitGrammarSpec?: (ctx: GrammarSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.grammarType`. * @param ctx the parse tree */ enterGrammarType?: (ctx: GrammarTypeContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.grammarType`. * @param ctx the parse tree */ exitGrammarType?: (ctx: GrammarTypeContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.prequelConstruct`. * @param ctx the parse tree */ enterPrequelConstruct?: (ctx: PrequelConstructContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.prequelConstruct`. * @param ctx the parse tree */ exitPrequelConstruct?: (ctx: PrequelConstructContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.optionsSpec`. * @param ctx the parse tree */ enterOptionsSpec?: (ctx: OptionsSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.optionsSpec`. * @param ctx the parse tree */ exitOptionsSpec?: (ctx: OptionsSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.option`. * @param ctx the parse tree */ enterOption?: (ctx: OptionContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.option`. * @param ctx the parse tree */ exitOption?: (ctx: OptionContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.optionValue`. * @param ctx the parse tree */ enterOptionValue?: (ctx: OptionValueContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.optionValue`. * @param ctx the parse tree */ exitOptionValue?: (ctx: OptionValueContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.delegateGrammars`. * @param ctx the parse tree */ enterDelegateGrammars?: (ctx: DelegateGrammarsContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.delegateGrammars`. * @param ctx the parse tree */ exitDelegateGrammars?: (ctx: DelegateGrammarsContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.delegateGrammar`. * @param ctx the parse tree */ enterDelegateGrammar?: (ctx: DelegateGrammarContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.delegateGrammar`. * @param ctx the parse tree */ exitDelegateGrammar?: (ctx: DelegateGrammarContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.tokensSpec`. * @param ctx the parse tree */ enterTokensSpec?: (ctx: TokensSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.tokensSpec`. * @param ctx the parse tree */ exitTokensSpec?: (ctx: TokensSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.channelsSpec`. * @param ctx the parse tree */ enterChannelsSpec?: (ctx: ChannelsSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.channelsSpec`. * @param ctx the parse tree */ exitChannelsSpec?: (ctx: ChannelsSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.idList`. * @param ctx the parse tree */ enterIdList?: (ctx: IdListContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.idList`. * @param ctx the parse tree */ exitIdList?: (ctx: IdListContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.namedAction`. * @param ctx the parse tree */ enterNamedAction?: (ctx: NamedActionContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.namedAction`. * @param ctx the parse tree */ exitNamedAction?: (ctx: NamedActionContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.actionScopeName`. * @param ctx the parse tree */ enterActionScopeName?: (ctx: ActionScopeNameContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.actionScopeName`. * @param ctx the parse tree */ exitActionScopeName?: (ctx: ActionScopeNameContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.actionBlock`. * @param ctx the parse tree */ enterActionBlock?: (ctx: ActionBlockContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.actionBlock`. * @param ctx the parse tree */ exitActionBlock?: (ctx: ActionBlockContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.argActionBlock`. * @param ctx the parse tree */ enterArgActionBlock?: (ctx: ArgActionBlockContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.argActionBlock`. * @param ctx the parse tree */ exitArgActionBlock?: (ctx: ArgActionBlockContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.modeSpec`. * @param ctx the parse tree */ enterModeSpec?: (ctx: ModeSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.modeSpec`. * @param ctx the parse tree */ exitModeSpec?: (ctx: ModeSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.rules`. * @param ctx the parse tree */ enterRules?: (ctx: RulesContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.rules`. * @param ctx the parse tree */ exitRules?: (ctx: RulesContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleSpec`. * @param ctx the parse tree */ enterRuleSpec?: (ctx: RuleSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleSpec`. * @param ctx the parse tree */ exitRuleSpec?: (ctx: RuleSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.parserRuleSpec`. * @param ctx the parse tree */ enterParserRuleSpec?: (ctx: ParserRuleSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.parserRuleSpec`. * @param ctx the parse tree */ exitParserRuleSpec?: (ctx: ParserRuleSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.exceptionGroup`. * @param ctx the parse tree */ enterExceptionGroup?: (ctx: ExceptionGroupContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.exceptionGroup`. * @param ctx the parse tree */ exitExceptionGroup?: (ctx: ExceptionGroupContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.exceptionHandler`. * @param ctx the parse tree */ enterExceptionHandler?: (ctx: ExceptionHandlerContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.exceptionHandler`. * @param ctx the parse tree */ exitExceptionHandler?: (ctx: ExceptionHandlerContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.finallyClause`. * @param ctx the parse tree */ enterFinallyClause?: (ctx: FinallyClauseContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.finallyClause`. * @param ctx the parse tree */ exitFinallyClause?: (ctx: FinallyClauseContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.rulePrequel`. * @param ctx the parse tree */ enterRulePrequel?: (ctx: RulePrequelContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.rulePrequel`. * @param ctx the parse tree */ exitRulePrequel?: (ctx: RulePrequelContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleReturns`. * @param ctx the parse tree */ enterRuleReturns?: (ctx: RuleReturnsContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleReturns`. * @param ctx the parse tree */ exitRuleReturns?: (ctx: RuleReturnsContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.throwsSpec`. * @param ctx the parse tree */ enterThrowsSpec?: (ctx: ThrowsSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.throwsSpec`. * @param ctx the parse tree */ exitThrowsSpec?: (ctx: ThrowsSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.localsSpec`. * @param ctx the parse tree */ enterLocalsSpec?: (ctx: LocalsSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.localsSpec`. * @param ctx the parse tree */ exitLocalsSpec?: (ctx: LocalsSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleAction`. * @param ctx the parse tree */ enterRuleAction?: (ctx: RuleActionContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleAction`. * @param ctx the parse tree */ exitRuleAction?: (ctx: RuleActionContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleModifiers`. * @param ctx the parse tree */ enterRuleModifiers?: (ctx: RuleModifiersContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleModifiers`. * @param ctx the parse tree */ exitRuleModifiers?: (ctx: RuleModifiersContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleModifier`. * @param ctx the parse tree */ enterRuleModifier?: (ctx: RuleModifierContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleModifier`. * @param ctx the parse tree */ exitRuleModifier?: (ctx: RuleModifierContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleBlock`. * @param ctx the parse tree */ enterRuleBlock?: (ctx: RuleBlockContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleBlock`. * @param ctx the parse tree */ exitRuleBlock?: (ctx: RuleBlockContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleAltList`. * @param ctx the parse tree */ enterRuleAltList?: (ctx: RuleAltListContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleAltList`. * @param ctx the parse tree */ exitRuleAltList?: (ctx: RuleAltListContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.labeledAlt`. * @param ctx the parse tree */ enterLabeledAlt?: (ctx: LabeledAltContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.labeledAlt`. * @param ctx the parse tree */ exitLabeledAlt?: (ctx: LabeledAltContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerRuleSpec`. * @param ctx the parse tree */ enterLexerRuleSpec?: (ctx: LexerRuleSpecContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerRuleSpec`. * @param ctx the parse tree */ exitLexerRuleSpec?: (ctx: LexerRuleSpecContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerRuleBlock`. * @param ctx the parse tree */ enterLexerRuleBlock?: (ctx: LexerRuleBlockContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerRuleBlock`. * @param ctx the parse tree */ exitLexerRuleBlock?: (ctx: LexerRuleBlockContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerAltList`. * @param ctx the parse tree */ enterLexerAltList?: (ctx: LexerAltListContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerAltList`. * @param ctx the parse tree */ exitLexerAltList?: (ctx: LexerAltListContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerAlt`. * @param ctx the parse tree */ enterLexerAlt?: (ctx: LexerAltContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerAlt`. * @param ctx the parse tree */ exitLexerAlt?: (ctx: LexerAltContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerElements`. * @param ctx the parse tree */ enterLexerElements?: (ctx: LexerElementsContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerElements`. * @param ctx the parse tree */ exitLexerElements?: (ctx: LexerElementsContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerElement`. * @param ctx the parse tree */ enterLexerElement?: (ctx: LexerElementContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerElement`. * @param ctx the parse tree */ exitLexerElement?: (ctx: LexerElementContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.labeledLexerElement`. * @param ctx the parse tree */ enterLabeledLexerElement?: (ctx: LabeledLexerElementContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.labeledLexerElement`. * @param ctx the parse tree */ exitLabeledLexerElement?: (ctx: LabeledLexerElementContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerBlock`. * @param ctx the parse tree */ enterLexerBlock?: (ctx: LexerBlockContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerBlock`. * @param ctx the parse tree */ exitLexerBlock?: (ctx: LexerBlockContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerCommands`. * @param ctx the parse tree */ enterLexerCommands?: (ctx: LexerCommandsContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerCommands`. * @param ctx the parse tree */ exitLexerCommands?: (ctx: LexerCommandsContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerCommand`. * @param ctx the parse tree */ enterLexerCommand?: (ctx: LexerCommandContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerCommand`. * @param ctx the parse tree */ exitLexerCommand?: (ctx: LexerCommandContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerCommandName`. * @param ctx the parse tree */ enterLexerCommandName?: (ctx: LexerCommandNameContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerCommandName`. * @param ctx the parse tree */ exitLexerCommandName?: (ctx: LexerCommandNameContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerCommandExpr`. * @param ctx the parse tree */ enterLexerCommandExpr?: (ctx: LexerCommandExprContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerCommandExpr`. * @param ctx the parse tree */ exitLexerCommandExpr?: (ctx: LexerCommandExprContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.altList`. * @param ctx the parse tree */ enterAltList?: (ctx: AltListContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.altList`. * @param ctx the parse tree */ exitAltList?: (ctx: AltListContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.alternative`. * @param ctx the parse tree */ enterAlternative?: (ctx: AlternativeContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.alternative`. * @param ctx the parse tree */ exitAlternative?: (ctx: AlternativeContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.element`. * @param ctx the parse tree */ enterElement?: (ctx: ElementContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.element`. * @param ctx the parse tree */ exitElement?: (ctx: ElementContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.labeledElement`. * @param ctx the parse tree */ enterLabeledElement?: (ctx: LabeledElementContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.labeledElement`. * @param ctx the parse tree */ exitLabeledElement?: (ctx: LabeledElementContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ebnf`. * @param ctx the parse tree */ enterEbnf?: (ctx: EbnfContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ebnf`. * @param ctx the parse tree */ exitEbnf?: (ctx: EbnfContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.blockSuffix`. * @param ctx the parse tree */ enterBlockSuffix?: (ctx: BlockSuffixContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.blockSuffix`. * @param ctx the parse tree */ exitBlockSuffix?: (ctx: BlockSuffixContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ebnfSuffix`. * @param ctx the parse tree */ enterEbnfSuffix?: (ctx: EbnfSuffixContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ebnfSuffix`. * @param ctx the parse tree */ exitEbnfSuffix?: (ctx: EbnfSuffixContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.lexerAtom`. * @param ctx the parse tree */ enterLexerAtom?: (ctx: LexerAtomContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.lexerAtom`. * @param ctx the parse tree */ exitLexerAtom?: (ctx: LexerAtomContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.atom`. * @param ctx the parse tree */ enterAtom?: (ctx: AtomContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.atom`. * @param ctx the parse tree */ exitAtom?: (ctx: AtomContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.notSet`. * @param ctx the parse tree */ enterNotSet?: (ctx: NotSetContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.notSet`. * @param ctx the parse tree */ exitNotSet?: (ctx: NotSetContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.blockSet`. * @param ctx the parse tree */ enterBlockSet?: (ctx: BlockSetContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.blockSet`. * @param ctx the parse tree */ exitBlockSet?: (ctx: BlockSetContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.setElement`. * @param ctx the parse tree */ enterSetElement?: (ctx: SetElementContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.setElement`. * @param ctx the parse tree */ exitSetElement?: (ctx: SetElementContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.block`. * @param ctx the parse tree */ enterBlock?: (ctx: BlockContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.block`. * @param ctx the parse tree */ exitBlock?: (ctx: BlockContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.ruleref`. * @param ctx the parse tree */ enterRuleref?: (ctx: RulerefContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.ruleref`. * @param ctx the parse tree */ exitRuleref?: (ctx: RulerefContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.characterRange`. * @param ctx the parse tree */ enterCharacterRange?: (ctx: CharacterRangeContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.characterRange`. * @param ctx the parse tree */ exitCharacterRange?: (ctx: CharacterRangeContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.terminalRule`. * @param ctx the parse tree */ enterTerminalRule?: (ctx: TerminalRuleContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.terminalRule`. * @param ctx the parse tree */ exitTerminalRule?: (ctx: TerminalRuleContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.elementOptions`. * @param ctx the parse tree */ enterElementOptions?: (ctx: ElementOptionsContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.elementOptions`. * @param ctx the parse tree */ exitElementOptions?: (ctx: ElementOptionsContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.elementOption`. * @param ctx the parse tree */ enterElementOption?: (ctx: ElementOptionContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.elementOption`. * @param ctx the parse tree */ exitElementOption?: (ctx: ElementOptionContext) => void; /** * Enter a parse tree produced by `ANTLRv4Parser.identifier`. * @param ctx the parse tree */ enterIdentifier?: (ctx: IdentifierContext) => void; /** * Exit a parse tree produced by `ANTLRv4Parser.identifier`. * @param ctx the parse tree */ exitIdentifier?: (ctx: IdentifierContext) => void; }
the_stack
import { NgModule, Component, Pipe, OnInit, DoCheck, AfterContentInit, HostListener, Input, ElementRef, Output, EventEmitter, forwardRef, IterableDiffers } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Observable } from 'rxjs/Rx'; import { FormsModule, NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; declare var _:any; const MULTISELECT_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MultiselectDropdown), multi: true }; export interface IMultiSelectOption { id: any; name: string; badge?: string; } export interface IMultiSelectSettings { pullRight?: boolean; enableSearch?: boolean; checkedStyle?: 'checkboxes' | 'glyphicon'; buttonClasses?: string; selectionLimit?: number; closeOnSelect?: boolean; showCheckAll?: boolean; showUncheckAll?: boolean; dynamicTitleMaxItems?: number; maxHeight?: string; singleSelect?: boolean; } export interface IMultiSelectTexts { checkAll?: string; uncheckAll?: string; checked?: string; checkedPlural?: string; searchPlaceholder?: string; defaultTitle?: string; } @Pipe({ name: 'searchFilter' }) export class MultiSelectSearchFilter { transform(options: Array<IMultiSelectOption>, args: string): Array<IMultiSelectOption> { return options.filter((option: IMultiSelectOption) => option.name.toLowerCase().indexOf((args || '').toLowerCase()) > -1); } } @Component({ selector: 'ss-multiselect-dropdown', providers: [MULTISELECT_VALUE_ACCESSOR], styles: [` a { outline: none !important; } .badge-multi { background-color: #92c0e8; float: right; } `], template: ` <div class="btn-group"> <button type="button" class="dropdown-toggle" [ngClass]="settings.buttonClasses" (click)="toggleDropdown()">{{ title }}&nbsp;<span class="caret"></span></button> <ul *ngIf="isVisible" class="dropdown-menu" [class.pull-right]="settings.pullRight" [style.max-height]="settings.maxHeight" style="display: block; height: auto; overflow-y: auto; z-index:1001; min-width:300px"> <li style="margin: 0px 5px 5px 5px;" *ngIf="settings.enableSearch"> <div class="input-group input-group-sm"> <span class="input-group-addon" id="sizing-addon3" (click)="clearSearch()" role="button"><i class="glyphicon glyphicon-trash"></i></span> <input type="text" class="form-control" placeholder="{{ texts.searchPlaceholder }}" aria-describedby="sizing-addon3" [(ngModel)]="searchFilterText"> <span class="input-group-btn"> <button class="btn btn-default" role="text"><label style="font-size: 100%" class="label label-info">{{(options|searchFilter:searchFilterText).length}} results</label></button> </span> </div> </li> <li class="divider" *ngIf="settings.enableSearch"></li> <li *ngIf="settings.showCheckAll && settings.singleSelect === false"> <a href="javascript:;" role="menuitem" tabindex="-1" (click)="checkAll()"> <span style="width: 16px;" class="glyphicon glyphicon-ok text-success"></span> {{ texts.checkAll }} </a> </li> <li *ngIf="settings.showUncheckAll && settings.singleSelect === false"> <a href="javascript:;" role="menuitem" tabindex="-1" (click)="uncheckAll()"> <span style="width: 16px;" class="glyphicon glyphicon-remove text-danger"></span> {{ texts.uncheckAll }} </a> </li> <li *ngIf="(settings.showCheckAll || settings.showUncheckAll) && settings.singleSelect === false" class="divider"></li> <li *ngFor="let option of options | searchFilter:searchFilterText"> <a href="javascript:;" role="menuitem" tabindex="-1" (click)="setSelected($event, option)"> <input *ngIf="settings.checkedStyle == 'checkboxes'" type="checkbox" [checked]="isSelected(option)" /> <span *ngIf="settings.checkedStyle == 'glyphicon'" style="width: 16px;" [ngClass]="isSelected(option) ? ['glyphicon glyphicon-ok' , 'text-success'] : 'glyphicon'"></span> <span *ngIf="option.badge" style="padding-left: 10px"> | </span> {{ option.name }} <span *ngIf="option.badge" class="badge badge-multi"> {{option.badge}} </span> </a> </li> </ul> </div> ` }) export class MultiselectDropdown implements OnInit, DoCheck, ControlValueAccessor { @Input() options: Array<IMultiSelectOption>; @Input() settings: IMultiSelectSettings; @Input() texts: IMultiSelectTexts; @Output() selectionLimitReached = new EventEmitter(); @HostListener('document: click', ['$event.target']) onClick(target) { let parentFound = false; while (target !== null && !parentFound) { if (target === this.element.nativeElement) { parentFound = true; } target = target.parentElement; } if (!parentFound) { this.isVisible = false; } } protected onModelChange: Function = (_: any) => {}; protected onModelTouched: Function = () => {}; protected model: any[]; public title: string; protected differ: any; protected numSelected: number = 0; public isVisible: boolean = false; protected searchFilterText: string = ''; protected defaultSettings: IMultiSelectSettings = { pullRight: false, enableSearch: true, checkedStyle: 'glyphicon', buttonClasses: 'btn btn-default', selectionLimit: 0, closeOnSelect: false, showCheckAll: true, showUncheckAll: true, dynamicTitleMaxItems: 3, maxHeight: '300px', singleSelect: false, }; protected defaultTexts: IMultiSelectTexts = { checkAll: 'Check all filtered', uncheckAll: 'Uncheck all', checked: 'checked', checkedPlural: 'checked', searchPlaceholder: 'Search...', defaultTitle: 'Select', }; constructor( protected element: ElementRef, protected differs: IterableDiffers ) { this.differ = differs.find([]).create(null); } ngOnInit() { this.settings = Object.assign(this.defaultSettings, this.settings); this.texts = Object.assign(this.defaultTexts, this.texts); this.title = this.texts.defaultTitle; } writeValue(value: any) : void { if (value !== undefined) { this.model = value; } } registerOnChange(fn: Function): void { this.onModelChange = fn; } registerOnTouched(fn: Function): void { this.onModelTouched = fn; } ngAfterContentInit() { this.ngDoCheck(); } ngDoCheck() { if(this.model){ if (this.settings.singleSelect) { this.updateNumSelected(); this.updateTitle(); } else { this.updateNumSelected(); this.updateTitle(); } } else { this.title = this.texts.defaultTitle; } } clearSearch() { this.searchFilterText = ''; } toggleDropdown() { this.isVisible = !this.isVisible; } isSelected(option: IMultiSelectOption): boolean { if (this.settings.singleSelect === true) return (this.model === option.id); return this.model && this.model.indexOf(option.id) > -1; } setSelected(event: Event, option: IMultiSelectOption) { if (this.settings.singleSelect === true) { this.model = option.id; } else { if (!this.model) this.model = []; var index = this.model.indexOf(option.id); if (index > -1) { this.model.splice(index, 1); } else { if (this.settings.selectionLimit === 0 || this.model.length < this.settings.selectionLimit) { this.model.push(option.id); } else { this.selectionLimitReached.emit(this.model.length); return; } } } if (this.settings.closeOnSelect) { this.toggleDropdown(); } this.onModelChange(this.model); } updateNumSelected() { if (this.settings.singleSelect) this.numSelected = 1; else this.numSelected = this.model && this.model.length || 0; } updateTitle() { if (this.numSelected === 0) { this.title = this.texts.defaultTitle; } else if (this.settings.dynamicTitleMaxItems >= this.numSelected) { if (this.settings.singleSelect === true) { this.title = this.options .filter((option) => this.model === option.id) .map((fil) => fil.name).toString(); } else { this.title = this.options .filter((option: IMultiSelectOption) => this.model && this.model.indexOf(option.id) > -1) .map((option: IMultiSelectOption) => option.name) .join(', '); } } else { this.title = this.numSelected + ' ' + (this.numSelected === 1 ? this.texts.checked : this.texts.checkedPlural); } } checkAll() { if(!this.model) this.model = []; let newEntries = _.differenceWith(new MultiSelectSearchFilter().transform(this.options,this.searchFilterText).map(option => option.id),this.model,_.isEqual); this.model = newEntries.concat(this.model); this.onModelChange(this.model); } checkAllFiltered() { this.onModelChange(this.model); } uncheckAll() { this.model = []; this.onModelChange(this.model); } } @NgModule({ imports: [CommonModule, FormsModule], exports: [MultiselectDropdown], declarations: [MultiselectDropdown, MultiSelectSearchFilter], }) export class MultiselectDropdownModule { }
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Image, Dimensions, TouchableNativeFeedback, InteractionManager, ActivityIndicator, Animated, Easing, FlatList, Linking, Alert } from 'react-native' import { updown, fav, close } from '../../dao/sync' import Ionicons from 'react-native-vector-icons/Ionicons' import colorConfig, { standardColor, idColor, accentColor, getLevelColorFromProgress } from '../../constant/colorConfig' import { getTopicAPI, getTopicContentAPI, getTopicCommentSnapshotAPI, getBattleAPI } from '../../dao' import SimpleComment from '../../component/SimpleComment' import { getGameUrl } from '../../dao' let screen = Dimensions.get('window') const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = screen declare var global /* tslint:disable */ let toolbarActions = [ { title: '回复', iconName: 'md-create', iconSize: 22, show: 'always', onPress: function () { const { params } = this.props.navigation.state if (this.isReplyShowing === true) return const cb = () => { this.props.navigation.navigate('Reply', { type: params.type, id: params.rowData ? params.rowData.id : this.state.data && this.state.data.titleInfo && this.state.data.titleInfo.psnid, callback: this._refreshComment, shouldSeeBackground: true }) } if (this.state.openVal._value === 1) { this._animateToolbar(0, cb) } else if (this.state.openVal._value === 0) { cb() } } }, { title: '刷新', iconName: 'md-refresh', show: 'never', onPress: function () { this._refreshComment() } }, { title: '在浏览器中打开', iconName: 'md-refresh', show: 'never', onPress: function () { const { params = {} } = this.props.navigation.state Linking.openURL(params.URL).catch(err => global.toast(err.toString())) } }, { title: '收藏', iconName: 'md-star-half', show: 'never', onPress: function () { const { params } = this.props.navigation.state // console.log(params.type) fav({ type: params.type === 'community' ? 'topic' : params.type, param: params.rowData && params.rowData.id }).then(res => res.text()).then(text => { if (text) return global.toast(text) global.toast('操作成功') }).catch(err => { const msg = `操作失败: ${err.toString()}` global.toast(msg) }) } }, { title: '顶', iconName: 'md-star-half', show: 'never', onPress: function () { const { params } = this.props.navigation.state updown({ type: params.type === 'community' ? 'topic' : params.type, param: params.rowData && params.rowData.id, updown: 'up' }).then(res => res.text()).then(text => { if (text) return global.toast(text) global.toast('操作成功') }).catch(err => { const msg = `操作失败: ${err.toString()}` global.toast(msg) }) } }, { title: '分享', iconName: 'md-share-alt', show: 'never', onPress: function () { try { const { params } = this.props.navigation.state let title = this.state.data.titleInfo.title || '' if (title.length > 50) { title = title.slice(0, 50) + '... ' } global.Share.open({ url: params.URL, message: '[PSNINE] ' + title.replace(/<.*?>/igm, ''), title: 'PSNINE' }).catch((err) => { err && console.log(err) }) } catch (err) { } } }, { title: '出处', iconName: 'md-share-alt', show: 'never', onPress: function () { try { const url = this.state.data.titleInfo.shareInfo.source url && Linking.openURL(url).catch(err => global.toast(err.toString())) || global.toast('暂无出处') } catch (err) { } } } ] /* tslint:enable */ let toolbarHeight = 56 let config = { tension: 30, friction: 7, ease: Easing.in(Easing.ease(1, 0, 1, 1)), duration: 200 } const ApiMapper = { 'community': getTopicAPI, 'gene': getTopicAPI, 'battle': getBattleAPI } class CommunityTopic extends Component<any, any> { static navigationOptions({ navigation }) { return { title: navigation.state.params.title || '讨论' } } constructor(props) { super(props) // console.log(this.props.navigation.state.params) this.state = { data: false, isLoading: true, mainContent: false, rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), openVal: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), topicMarginTop: new Animated.Value(0) } } _refreshComment = () => { const { params } = this.props.navigation.state if (['community', 'gene'].includes(params.type) === false) { return } if (this.isReplyShowing === true) { this.isReplyShowing = false } if (this.state.isLoading === true) { return } this.setState({ isLoading: true }) getTopicCommentSnapshotAPI(params.URL).then(data => { this.hasComment = data.commentList.length !== 0 this.setState({ isLoading: false, commentList: data.commentList }) }) } componentWillMount() { const { params } = this.props.navigation.state InteractionManager.runAfterInteractions(() => { const API = ApiMapper[params.type] || getTopicAPI API(params.URL).then(data => { const content = data.contentInfo.html const html = params.type !== 'gene' ? content : content.replace('<div>', '<div align="center">') const emptyHTML = params.type !== 'gene' ? '<div></div>' : '<div align="center"></div>' this.hasContent = html !== emptyHTML this.hasGameTable = data.contentInfo.gameTable.length !== 0 this.hasComment = data.commentList.length !== 0 this.hasReadMore = this.hasComment ? data.commentList[0].isGettingMoreComment === true ? true : false : false this.hasPage = data.contentInfo.page.length !== 0 this.hasShare = data.contentInfo.external.length !== 0 this.setState({ data, mainContent: html, commentList: data.commentList, isLoading: false, page: data.contentInfo.page }) }) }) } handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) hasShare = false renderShare = (page) => { const { modeInfo } = this.props.screenProps const list: any[] = [] for (const item of page) { const thisJSX = ( <TouchableNativeFeedback key={item.url} onPress={() => { this.props.navigation.navigate('CommunityTopic', { title: item.text, URL: item.url }) }}> <View style={{ flex: -1, padding: 2 }}> <Text style={{ color: idColor }}>{item.text}</Text> </View> </TouchableNativeFeedback> ) list.push(thisJSX) } return ( <View style={{ elevation: 2, margin: 5, marginVertical: 0, backgroundColor: modeInfo.backgroundColor }}> <View style={{ elevation: 2, margin: 5, backgroundColor: modeInfo.backgroundColor, padding: 5 }}> {list} </View> </View> ) } renderHeader = (titleInfo) => { const { modeInfo } = this.props.screenProps const { params } = this.props.navigation.state const textStyle: any = { flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' } const isNotGene = params.type !== 'gene' let shouldRenderAvatar = isNotGene && !!(params.rowData && params.rowData.avatar) let avatar = '' if (shouldRenderAvatar) { avatar = params.rowData.avatar.replace('@50w.png', '@75w.png') } else { if (isNotGene && titleInfo.avatar) avatar = titleInfo.avatar } return ['battle'].includes(params.type) ? undefined : ( <View key={'header'} style={{ flex: 1, backgroundColor: modeInfo.backgroundColor, elevation: 1, margin: 5, marginBottom: 0, marginTop: 0 }}> <TouchableNativeFeedback useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View style={{ flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', padding: 5 }}> {avatar && <Image source={{ uri: avatar }} style={{ width: 75, height: 75 }} /> || undefined } <View style={{ flex: 1, flexDirection: 'column', padding: 5 }}> <global.HTMLView value={titleInfo.title} modeInfo={modeInfo} stylesheet={styles} shouldForceInline={true} onImageLongPress={this.handleImageOnclick} imagePaddingOffset={shouldRenderAvatar ? 30 + 75 + 10 : 30} /> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ flex: -1, color: modeInfo.standardColor, textAlign: 'center', textAlignVertical: 'center' }} onPress={ () => { this.props.navigation.navigate('Home', { title: titleInfo.psnid, id: titleInfo.psnid, URL: `https://psnine.com/psnid/${titleInfo.psnid}` }) } }>{titleInfo.psnid}</Text> <Text selectable={false} style={textStyle}>{titleInfo.date}</Text> <Text selectable={false} style={textStyle}>{titleInfo.reply}</Text> {isNotGene === false && <Text selectable={false} style={{ flex: -1, color: modeInfo.standardColor, textAlign: 'center', textAlignVertical: 'center' }} onPress={ () => { this.props.navigation.navigate('Circle', { URL: `https://psnine.com/gene?ele=${(titleInfo.node || []).join('')}`, title: (titleInfo.node || []).join('') }) } }>{(titleInfo.node || []).join('')}</Text>} </View> </View> </View> </TouchableNativeFeedback> </View> ) } hasContent = false renderContent = (html) => { const { modeInfo } = this.props.screenProps return ( <View key={'content'} style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor, padding: 10 }}> <global.HTMLView value={html} modeInfo={modeInfo} shouldShowLoadingIndicator={true} stylesheet={styles} imagePaddingOffset={30} key={modeInfo.themeName} onImageLongPress={this.handleImageOnclick} /> </View> ) } hasGameTable = false renderGameTable = (gameTable) => { const { modeInfo } = this.props.screenProps const list: any[] = [] for (const rowData of gameTable) { list.push( <View key={rowData.id} style={{ backgroundColor: modeInfo.backgroundColor }}> <TouchableNativeFeedback onPress={() => { const { navigation } = this.props const URL = getGameUrl(rowData.id) navigation.navigate('GamePage', { // URL: 'https://psnine.com/psngame/5424?psnid=Smallpath', URL, title: rowData.title, rowData, type: 'game' }) }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', alignItems: 'flex-start', padding: 12 }}> <Image source={{ uri: rowData.avatar }} style={[styles.avatar, { width: 91 }]} /> <View style={{ marginLeft: 10, flex: 1, flexDirection: 'column' }}> <Text ellipsizeMode={'tail'} numberOfLines={3} style={{ flex: 2.5, color: modeInfo.titleTextColor }}> {rowData.title} <Text selectable={false} style={{ fontSize: 12, flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.region}</Text> </Text> <View style={{ flex: 1.1, flexDirection: 'row', justifyContent: 'space-between' }}> <Text selectable={false} style={{ fontSize: 12, flex: -1, color: modeInfo.standardColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.platform}</Text> {rowData.alert && <Text selectable={false} style={{ fontSize: 12, flex: -1, color: getLevelColorFromProgress(rowData.allPercent), textAlign: 'center', textAlignVertical: 'center' }}>{ rowData.alert + ' ' }<Text style={{ fontSize: 12, flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' }}>{rowData.allPercent}</Text></Text> || undefined} <Text selectable={false} style={{ fontSize: 12, flex: -1, color: modeInfo.standardTextColor, textAlign: 'center', textAlignVertical: 'center' }}>{ [rowData.platium, rowData.gold, rowData.selver, rowData.bronze].map((item, index) => { return ( <Text key={index} style={{ color: colorConfig['trophyColor' + (index + 1)] }}> {item} </Text> ) }) }</Text> </View> {rowData.blockquote && <View style={{ flex: -1 }}> <global.HTMLView value={rowData.blockquote} modeInfo={modeInfo} shouldShowLoadingIndicator={true} stylesheet={styles} imagePaddingOffset={144} key={modeInfo.themeName} onImageLongPress={this.handleImageOnclick} /> </View> || undefined} </View> </View> </TouchableNativeFeedback> </View> ) } return ( <View style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor }}> {list} </View> ) } hasComment = false hasReadMore = false renderComment = (commentList) => { const { modeInfo } = this.props.screenProps const { navigation } = this.props const list: JSX.Element[] = [] let readMore: any = null for (const rowData of commentList) { if (rowData.isGettingMoreComment === false) { list.push( <SimpleComment key={rowData.id || list.length} {...{ navigation, rowData, modeInfo, onLongPress: () => { this.onCommentLongPress(rowData) }, callback: this._refreshComment, index: list.length }} /> ) } else { readMore = ( <View key={'readmore'} style={{ backgroundColor: modeInfo.backgroundColor, elevation: 1 }}> <TouchableNativeFeedback onPress={() => { this._readMore(`${this.props.navigation.state.params.URL}/comment?page=1`) }} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} > <View pointerEvents='box-only' style={{ flex: 1, flexDirection: 'row', padding: 12 }}> <View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center' }}> <Text style={{ flex: 2.5, color: accentColor }}>{'阅读更多评论'}</Text> </View> </View> </TouchableNativeFeedback> </View> ) } } const shouldMarginTop = !this.hasContent && !this.hasGameTable && !this.hasPage return ( <View style={{ marginTop: shouldMarginTop ? 5 : 0 }}> {readMore && <View style={{ elevation: 1, margin: 5, marginTop: 0, marginBottom: 5, backgroundColor: modeInfo.backgroundColor }}>{readMore}</View>} <View style={{ elevation: 1, margin: 5, marginTop: 0, backgroundColor: modeInfo.backgroundColor }}> {list} </View> {readMore && <View style={{ elevation: 1, margin: 5, marginTop: 0, marginBottom: 5, backgroundColor: modeInfo.backgroundColor }}>{readMore}</View>} </View> ) } isReplyShowing = false onCommentLongPress = (rowData) => { if (this.isReplyShowing === true) return const { params } = this.props.navigation.state const cb = () => { this.props.navigation.navigate('Reply', { type: params.type, id: params.rowData.id, at: rowData.psnid, callback: this._refreshComment, shouldSeeBackground: true }) } if (this.state.openVal._value === 1) { this._animateToolbar(0, cb) } else if (this.state.openVal._value === 0) { cb() } } _readMore = (URL) => { this.props.navigation.navigate('CommentList', { URL }) } hasPage = false renderPage = (page) => { const { modeInfo } = this.props.screenProps const list: any[] = [] for (const item of page) { const thisJSX: JSX.Element = ( <View style={{margin: 2}} key={item.url + item.isCurrent}> <TouchableNativeFeedback key={item.url} useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPress={() => { if (this.state.isLoading === true) { return } this.setState({ isLoading: true }) getTopicContentAPI(item.url).then(data => { this.setState({ mainContent: data.contentInfo.html, isLoading: false, page: this.state.page.map(inner => { if (inner.url === item.url) { return { ...inner, isCurrent: true } } return { ...inner, isCurrent: false } }) }) }) }}> <View style={{ flex: -1, padding: 4, paddingHorizontal: 6, backgroundColor: item.isCurrent ? modeInfo.accentColor : modeInfo.standardColor, borderRadius: 2 }}> <Text style={{ color: modeInfo.backgroundColor }}>{item.text}</Text> </View> </TouchableNativeFeedback> </View> ) list.push(thisJSX) } return ( <View style={{ elevation: 0, margin: 5, marginVertical: 0, backgroundColor: modeInfo.backgroundColor }}> <View style={{ elevation: 0, margin: 5, backgroundColor: modeInfo.backgroundColor, padding: 5, flexDirection: 'row', flexWrap: 'wrap' }}> {list} </View> </View> ) } viewTopIndex = 0 viewBottomIndex = 0 render() { const { params } = this.props.navigation.state // console.log('CommunityTopic.js rendered'); const { modeInfo } = this.props.screenProps const { data: source } = this.state const data: any = [] const renderFuncArr: any = [] const shouldPushData = !this.state.isLoading if (shouldPushData) { data.push(source.titleInfo) renderFuncArr.push(this.renderHeader) } if (shouldPushData && this.hasShare) { data.push(source.contentInfo.external) renderFuncArr.push(this.renderShare) } if (shouldPushData && this.hasPage) { data.push(this.state.page) renderFuncArr.push(this.renderPage) } if (shouldPushData && this.hasContent) { data.push(this.state.mainContent) renderFuncArr.push(this.renderContent) } if (shouldPushData && this.hasGameTable) { data.push(source.contentInfo.gameTable) renderFuncArr.push(this.renderGameTable) } if (shouldPushData && this.hasComment) { data.push(this.state.commentList) renderFuncArr.push(this.renderComment) } this.viewBottomIndex = Math.max(data.length - 1, 0) const targetActions = toolbarActions.slice() if (shouldPushData && this.state.data && this.state.data.titleInfo && this.state.data.titleInfo.shareInfo) { const shareInfo = this.state.data.titleInfo && this.state.data.titleInfo.shareInfo const link = shareInfo.linkGameUrl if (link) { const name = shareInfo.linkGame targetActions.unshift({ title: name, iconName: 'md-game-controller-b', iconSize: 22, show: 'always', onPress: function () { const { params } = this.props.navigation.state this.props.navigation.navigate('NewGame', { URL: link + '?page=1', title: shareInfo.linkGame }) } }) } try { if (!shareInfo.source) { targetActions.pop() } } catch (err) { } if (shareInfo.edit) { targetActions.push({ title: '编辑', iconName: 'md-create', iconSize: 22, show: 'never', onPress: function () { const { navigation } = this.props const target = params.type === 'gene' ? 'NewGene' : 'NewTopic' navigation.navigate(target, { URL: params.type !== 'gene' ? shareInfo.edit : params.URL }) } }) params.type === 'gene' && targetActions.push({ title: '关闭', iconName: 'md-create', iconSize: 22, show: 'never', onPress: function () { const onPress = () => close({ type: 'gene', id: params.URL.split('/').pop() }).then(res => res.text()).then(html => html ? global.toast('关闭失败: ' + html) : global.toast('关闭成功')) Alert.alert('提示', '关闭后,只有管理员和发布者可以看到本帖', [ { text: '取消' }, { text: '继续关闭', onPress: () => onPress() } ]) } }) } } return ( <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} onStartShouldSetResponder={() => false} onMoveShouldSetResponder={() => false} > <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={params.title ? params.title : `No.${params.rowData.id}`} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} style={[styles.toolbar, { backgroundColor: modeInfo.standardColor }]} actions={targetActions} onIconClicked={() => { this.props.navigation.goBack() }} onActionSelected={(index) => { targetActions[index].onPress.bind(this)() }} /> {this.state.isLoading && ( <ActivityIndicator animating={this.state.isLoading} style={{ flex: 999, justifyContent: 'center', alignItems: 'center' }} color={modeInfo.accentColor} size={50} /> )} {/*{params.type === 'community' && !this.state.isLoading && this.renderToolbar()}*/} {!this.state.isLoading && <FlatList style={{ flex: -1, backgroundColor: modeInfo.standardColor }} ref={flatlist => this.flatlist = flatlist} data={data} keyExtractor={(item, index) => item.id || index} renderItem={({ item, index }) => { return renderFuncArr[index](item) }} extraData={this.state} windowSize={999} disableVirtualization={true} viewabilityConfig={{ minimumViewTime: 3000, viewAreaCoveragePercentThreshold: 100, waitForInteraction: true }} > </FlatList> } </View> ) } renderToolbarItem = (props, index, maxLength) => { const { modeInfo } = this.props.screenProps return ( <Animated.View ref={float => this[`float${index}`] = float} collapsable={false} key={index} style={{ width: 40, height: 40, borderRadius: 20, backgroundColor: modeInfo.accentColor, position: 'absolute', bottom: props.openVal.interpolate({ inputRange: [0, 1], outputRange: [24, 56 + 10 + 16 * 2 + index * 50] }), right: 24, elevation: 1, zIndex: 1, opacity: 1 }}> <TouchableNativeFeedback onPress={() => this.pressToolbar(maxLength - index - 1)} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPressIn={() => { this.float1.setNativeProps({ style: { elevation: 12 } }) }} onPressOut={() => { this.float1.setNativeProps({ style: { elevation: 6 } }) }} style={{ width: 40, height: 40, borderRadius: 20, flex: 1, zIndex: 1, backgroundColor: accentColor }}> <View style={{ borderRadius: 20, width: 40, height: 40, justifyContent: 'center', alignItems: 'center' }}> <Ionicons name={props.iconName} size={20} color='#fff' /> </View> </TouchableNativeFeedback> </Animated.View> ) } renderToolbar = () => { const { modeInfo } = this.props.screenProps const { openVal } = this.state const tipHeight = toolbarHeight * 0.8 const list: any[] = [] const iconNameArr = ['md-arrow-down', 'md-arrow-up'] for (let i = 0; i < iconNameArr.length; i++) { list.push( this.renderToolbarItem({ iconName: iconNameArr[i], openVal: openVal }, i, iconNameArr.length) ) } return ( <View style={{ position: 'absolute', left: 0, top: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - toolbarHeight / 2 }}> {list} <Animated.View ref={float => this.float = float} collapsable={false} style={{ width: 56, height: 56, borderRadius: 30, backgroundColor: accentColor, position: 'absolute', bottom: 16, right: 16, elevation: 6, zIndex: 1, opacity: this.state.opacity, transform: [{ rotateZ: this.state.rotation.interpolate({ inputRange: [0, 1], outputRange: ['0deg', '360deg'] }) }] }}> <TouchableNativeFeedback onPress={this.pressNew} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPressIn={() => { this.float.setNativeProps({ style: { elevation: 12 } }) }} onPressOut={() => { this.float.setNativeProps({ style: { elevation: 6 } }) }} style={{ width: 56, height: 56, borderRadius: 30, flex: 1, zIndex: 1, backgroundColor: accentColor }}> <View style={{ borderRadius: 30, width: 56, height: 56, flex: -1, justifyContent: 'center', alignItems: 'center' }}> <Ionicons name='ios-add' size={40} color='#fff' /> </View> </TouchableNativeFeedback> </Animated.View> </View> ) } index = 0 pressToolbar = index => { const target = index === 0 ? this.viewTopIndex : this.viewBottomIndex this.flatlist && this.flatlist.scrollToIndex({ animated: true, viewPosition: 0, index: target }) } _animateToolbar = (value, cb) => { const ratationPreValue = this.state.rotation._value const rotationValue = value === 0 ? 0 : ratationPreValue + 3 / 8 const scaleAnimation = Animated.timing(this.state.rotation, { toValue: rotationValue, ...config }) const moveAnimation = Animated.timing(this.state.openVal, { toValue: value, ...config }) const target = [ moveAnimation ] if (value !== 0 || value !== 1) target.unshift(scaleAnimation) const type = value === 1 ? 'sequence' : 'parallel' Animated[type](target).start() setTimeout(() => { typeof cb === 'function' && cb() }, 200) } pressNew = (cb) => { if (this.state.openVal._value === 0) { this._animateToolbar(1, cb) } else { this._animateToolbar(0, cb) } } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, selectedTitle: { // backgroundColor: '#00ffff' // fontSize: 20 }, avatar: { width: 50, height: 50 }, a: { fontWeight: '300', color: idColor // make links coloured pink } }) export default CommunityTopic
the_stack
import { originDestinationMatrix } from "../src/originDestinationMatrix"; import * as fetchMock from "fetch-mock"; import { barriers, barriersFeatureSet, polylineBarriers, polygonBarriers, } from "./mocks/inputs"; import { OriginDestinationMatrix, OriginDestinationMatrix_esriNAODOutputStraightLines, OriginDestinationMatrix_esriNAODOutputNoLines, OriginDestinationMatrix_AllBarrierTypes, OriginDestinationMatrix_AllBarrierTypes_WebMercator, } from "./mocks/responses"; import { IPoint, ILocation, IFeatureSet } from "@esri/arcgis-rest-types"; // variations on `origins` and `destinations` required input params const origins: Array<[number, number]> = [[-118.257363, 34.076763]]; const destinations: Array<[number, number]> = [ [-118.3417932, 34.00451385], [-118.08788, 34.01752], [-118.20327, 34.19382], ]; const originsLatLong: ILocation[] = [ { lat: 34.076763, long: -118.257363, }, ]; const destinationsLatLong: ILocation[] = [ { lat: 34.00451385, long: -118.3417932, }, { lat: 34.01752, long: -118.08788, }, { lat: 34.19382, long: -118.20327, }, ]; const originsLatitudeLongitude: ILocation[] = [ { latitude: 34.076763, longitude: -118.257363, }, ]; const destinationsLatitudeLongitude: ILocation[] = [ { latitude: 34.00451385, longitude: -118.3417932, }, { latitude: 34.01752, longitude: -118.08788, }, { latitude: 34.19382, longitude: -118.20327, }, ]; const originsPoint: IPoint[] = [ { x: -118.257363, y: 34.076763, }, ]; const destinationsPoint: IPoint[] = [ { x: -118.3417932, y: 34.00451385, }, { x: -118.08788, y: 34.01752, }, { x: -118.20327, y: 34.19382, }, ]; const originsFeatureSet: IFeatureSet = { spatialReference: { wkid: 102100, }, features: [ { geometry: { x: -13635398.9398, y: 4544699.034400001, } as IPoint, attributes: { Name: "123 Main St", TargetDestinationCount: 1, }, }, { geometry: { x: -13632733.3441, y: 4547651.028300002, } as IPoint, attributes: { Name: "845 Mulberry St", TargetDestinationCount: 2, }, }, ], }; const destinationsFeatureSet: IFeatureSet = { spatialReference: { wkid: 102100, }, features: [ { geometry: { x: -13635398.9398, y: 4544699.034400001, } as IPoint, attributes: { Name: "Store 45", }, }, { geometry: { x: -13632733.3441, y: 4547651.028300002, } as IPoint, attributes: { Name: "Store 67", }, }, ], }; describe("originDestinationMatrix", () => { afterEach(fetchMock.restore); it("should throw an error when a originDestinationMatrix request is made without a token", (done) => { fetchMock.once("*", {}); originDestinationMatrix({ origins, destinations, }) // tslint:disable-next-line .catch((e) => { expect(e).toEqual( "Calculating the origin-destination cost matrix using the ArcGIS service requires authentication" ); done(); }); }); it("should make a simple originDestinationMatrix request (Point Arrays)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(url).toEqual( "https://route.arcgis.com/arcgis/rest/services/World/OriginDestinationCostMatrix/NAServer/OriginDestinationCostMatrix_World/solveODCostMatrix" ); expect(options.method).toBe("POST"); expect(options.body).toContain("f=json"); expect(options.body).toContain( `origins=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `destinations=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); expect(options.body).toContain("token=token"); expect(response.origins.spatialReference.latestWkid).toEqual(4326); expect(response.origins.features.length).toEqual(origins.length); expect(response.destinations.spatialReference.latestWkid).toEqual(4326); expect(response.destinations.features.length).toEqual( destinations.length ); expect(response.messages.length).toEqual(2); expect(response.messages[1].type).toEqual(50); done(); }) .catch((e) => { fail(e); }); }); it("should pass default values", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, params: { outSR: 102100, }, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain("outputType=esriNAODOutputSparseMatrix"); expect(options.body).toContain("returnOrigins=true"); expect(options.body).toContain("returnDestinations=true"); expect(options.body).toContain("returnBarriers=true"); expect(options.body).toContain("returnPolylineBarriers=true"); expect(options.body).toContain("returnPolygonBarriers=true"); done(); }) .catch((e) => { fail(e); }); }); it("should allow default values to be overridden", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, outputType: "esriNAODOutputStraightLines", returnOrigins: false, returnDestinations: false, returnBarriers: false, returnPolylineBarriers: false, returnPolygonBarriers: false, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( "outputType=esriNAODOutputStraightLines" ); expect(options.body).toContain("returnOrigins=false"); expect(options.body).toContain("returnDestinations=false"); expect(options.body).toContain("returnBarriers=false"); expect(options.body).toContain("returnPolylineBarriers=false"); expect(options.body).toContain("returnPolygonBarriers=false"); done(); }) .catch((e) => { fail(e); }); }); it("should make a originDestinationMatrix request with a custom endpoint", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, params: { outSR: 102100, }, authentication: MOCK_AUTH, endpoint: "https://esri.com/test", }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(url).toEqual("https://esri.com/test/solveODCostMatrix"); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple originDestinationMatrix request (array of objects - lat/lon)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins: originsLatLong, destinations: destinationsLatLong, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `origins=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `destinations=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple originDestinationMatrix request (array of objects - latitude/longitude)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins: originsLatitudeLongitude, destinations: destinationsLatitudeLongitude, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `origins=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `destinations=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple originDestinationMatrix request (array of IPoint)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins: originsPoint, destinations: destinationsPoint, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `origins=${encodeURIComponent("-118.257363,34.076763")}` ); expect(options.body).toContain( `destinations=${encodeURIComponent( "-118.3417932,34.00451385;-118.08788,34.01752;-118.20327,34.19382" )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should make a simple originDestinationMatrix request (FeatureSet)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins: originsFeatureSet, destinations: destinationsFeatureSet, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `origins=${encodeURIComponent(JSON.stringify(originsFeatureSet))}` ); expect(options.body).toContain( `destinations=${encodeURIComponent( JSON.stringify(destinationsFeatureSet) )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should include proper outputType (esriNAODOutputSparseMatrix)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, outputType: "esriNAODOutputSparseMatrix", authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain(`outputType=esriNAODOutputSparseMatrix`); expect(Object.keys(response)).toContain("odCostMatrix"); done(); }) .catch((e) => { fail(e); }); }); it("should include proper outputType (esriNAODOutputStraightLines)", (done) => { fetchMock.once("*", OriginDestinationMatrix_esriNAODOutputStraightLines); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, outputType: "esriNAODOutputStraightLines", authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `outputType=esriNAODOutputStraightLines` ); expect(Object.keys(response)).toContain("odLines"); done(); }) .catch((e) => { fail(e); }); }); it("should include proper outputType (esriNAODOutputNoLines)", (done) => { fetchMock.once("*", OriginDestinationMatrix_esriNAODOutputNoLines); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, outputType: "esriNAODOutputNoLines", authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain(`outputType=esriNAODOutputNoLines`); expect(Object.keys(response)).toContain("odLines"); done(); }) .catch((e) => { fail(e); }); }); it("should pass point barriers (array of IPoint)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, barriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `barriers=${encodeURIComponent("-117.1957,34.0564;-117.184,34.0546")}` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass point barriers (FeatureSet)", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, barriers: barriersFeatureSet, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `barriers=${encodeURIComponent(JSON.stringify(barriersFeatureSet))}` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass polyline barriers", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, polylineBarriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `polylineBarriers=${encodeURIComponent( JSON.stringify(polylineBarriers) )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should pass polygon barriers", (done) => { fetchMock.once("*", OriginDestinationMatrix); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, polygonBarriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); expect(options.body).toContain( `polygonBarriers=${encodeURIComponent( JSON.stringify(polygonBarriers) )}` ); done(); }) .catch((e) => { fail(e); }); }); it("should include geoJson for any geometries in the return", (done) => { fetchMock.once("*", OriginDestinationMatrix_AllBarrierTypes); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, barriers, polylineBarriers, polygonBarriers, authentication: MOCK_AUTH, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); // origins expect(Object.keys(response.origins)).toContain("geoJson"); expect(Object.keys(response.origins.geoJson)).toContain("type"); expect(response.origins.geoJson.type).toEqual("FeatureCollection"); expect(Object.keys(response.origins.geoJson)).toContain("features"); expect(response.origins.geoJson.features.length).toEqual( origins.length ); // destinations expect(Object.keys(response.destinations)).toContain("geoJson"); expect(Object.keys(response.destinations.geoJson)).toContain("type"); expect(response.destinations.geoJson.type).toEqual("FeatureCollection"); expect(Object.keys(response.destinations.geoJson)).toContain( "features" ); expect(response.destinations.geoJson.features.length).toEqual( destinations.length ); // barriers expect(Object.keys(response.barriers)).toContain("geoJson"); expect(Object.keys(response.barriers.geoJson)).toContain("type"); expect(response.barriers.geoJson.type).toEqual("FeatureCollection"); expect(Object.keys(response.barriers.geoJson)).toContain("features"); expect(response.barriers.geoJson.features.length).toEqual( barriers.length ); // polylineBarriers expect(Object.keys(response.polylineBarriers)).toContain("geoJson"); expect(Object.keys(response.polylineBarriers.geoJson)).toContain( "type" ); expect(response.polylineBarriers.geoJson.type).toEqual( "FeatureCollection" ); expect(Object.keys(response.polylineBarriers.geoJson)).toContain( "features" ); expect(response.polylineBarriers.geoJson.features.length).toEqual( polylineBarriers.features.length ); // polygonBarriers expect(Object.keys(response.polygonBarriers)).toContain("geoJson"); expect(Object.keys(response.polygonBarriers.geoJson)).toContain("type"); expect(response.polygonBarriers.geoJson.type).toEqual( "FeatureCollection" ); expect(Object.keys(response.polygonBarriers.geoJson)).toContain( "features" ); expect(response.polygonBarriers.geoJson.features.length).toEqual( polygonBarriers.features.length ); done(); }) .catch((e) => { fail(e); }); }); it("should not include routes.geoJson in the return for non-4326", (done) => { fetchMock.once("*", OriginDestinationMatrix_AllBarrierTypes_WebMercator); const MOCK_AUTH = { getToken() { return Promise.resolve("token"); }, portal: "https://mapsdev.arcgis.com", }; originDestinationMatrix({ origins, destinations, barriers, polylineBarriers, polygonBarriers, authentication: MOCK_AUTH, params: { outSR: 102100, }, }) .then((response) => { expect(fetchMock.called()).toEqual(true); const [url, options]: [string, RequestInit] = fetchMock.lastCall("*"); // origins expect(Object.keys(response.origins)).not.toContain("geoJson"); // destinations expect(Object.keys(response.destinations)).not.toContain("geoJson"); // barriers expect(Object.keys(response.barriers)).not.toContain("geoJson"); // polylineBarriers expect(Object.keys(response.polylineBarriers)).not.toContain("geoJson"); // polygonBarriers expect(Object.keys(response.polygonBarriers)).not.toContain("geoJson"); done(); }) .catch((e) => { fail(e); }); }); });
the_stack
import { define, freeze, getGetter, getSetter, createSymbol, assign, getDptor, WINDOW } from '../share/util' import { SUPER, NOCTOR, AWAIT, CLSCTOR, NEWTARGET, SUPERCALL } from '../share/const' import { pattern, createFunc, createClass } from './helper' import { Variable, Prop } from '../scope/variable' import { Identifier } from './identifier' import { Literal } from './literal' import * as estree from 'estree' import Scope from '../scope' import evaluate from '.' export function* ThisExpression(node: estree.ThisExpression, scope: Scope) { const superCall = scope.find(SUPERCALL) if (superCall && !superCall.get()) { throw new ReferenceError('Must call super constructor in derived class ' + 'before accessing \'this\' or returning from derived constructor') } else { return scope.find('this').get() } } export function* ArrayExpression(node: estree.ArrayExpression, scope: Scope) { let results: any[] = [] for (let i = 0; i < node.elements.length; i++) { const item = node.elements[i] if (item.type === 'SpreadElement') { results = results.concat(yield* SpreadElement(item, scope)) } else { results.push(yield* evaluate(item, scope)) } } return results } export function* ObjectExpression(node: estree.ObjectExpression, scope: Scope) { const object: { [key: string]: any } = {} for (let i = 0; i < node.properties.length; i++) { const property = node.properties[i] if (property.type as any === 'SpreadElement') { assign(object, yield* SpreadElement(property as any, scope)) } else { let key: string const propKey = property.key if (property.computed) { key = yield* evaluate(propKey, scope) } else { if (propKey.type === 'Identifier') { key = propKey.name } else { key = '' + (yield* Literal(propKey as estree.Literal, scope)) } } const value = yield* evaluate(property.value, scope) const propKind = property.kind if (propKind === 'init') { object[key] = value } else if (propKind === 'get') { const oriDptor = getDptor(object, key) define(object, key, { get: value, set: oriDptor && oriDptor.set, enumerable: true, configurable: true }) } else { // propKind === 'set' const oriDptor = getDptor(object, key) define(object, key, { get: oriDptor && oriDptor.get, set: value, enumerable: true, configurable: true }) } } } return object } export function* FunctionExpression(node: estree.FunctionExpression, scope: Scope) { if (node.id && node.id.name) { // it's for accessing function expression by its name inside // e.g. const a = function b() { console.log(b) } const tmpScope = new Scope(scope) const func = createFunc(node, tmpScope) tmpScope.const(node.id.name, func) return func } else { return createFunc(node, scope) } } export function* UnaryExpression(node: estree.UnaryExpression, scope: Scope) { const arg = node.argument switch (node.operator) { case '+': return +(yield* evaluate(arg, scope)) case '-': return -(yield* evaluate(arg, scope)) case '!': return !(yield* evaluate(arg, scope)) case '~': return ~(yield* evaluate(arg, scope)) case 'void': return void (yield* evaluate(arg, scope)) case 'typeof': if (arg.type === 'Identifier') { return typeof (yield* Identifier(arg, scope, { throwErr: false })) } else { return typeof (yield* evaluate(arg, scope)) } case 'delete': if (arg.type === 'MemberExpression') { const variable: Prop = yield* MemberExpression(arg, scope, { getVar: true }) return variable.del() } else if (arg.type === 'Identifier') { throw new SyntaxError('Delete of an unqualified identifier in strict mode') } else { yield* evaluate(arg, scope) return true } /* istanbul ignore next */ default: throw new SyntaxError(`Unexpected token ${node.operator}`) } } export function* UpdateExpression(node: estree.UpdateExpression, scope: Scope) { const arg = node.argument let variable: Variable if (arg.type === 'Identifier') { variable = yield* Identifier(arg, scope, { getVar: true }) } else if (arg.type === 'MemberExpression') { variable = yield* MemberExpression(arg, scope, { getVar: true }) } else { /* istanbul ignore next */ throw new SyntaxError('Unexpected token') } const value = variable.get() if (node.operator === '++') { variable.set(value + 1) return node.prefix ? variable.get() : value } else if (node.operator === '--') { variable.set(value - 1) return node.prefix ? variable.get() : value } else { /* istanbul ignore next */ throw new SyntaxError(`Unexpected token ${node.operator}`) } } export function* BinaryExpression(node: estree.BinaryExpression, scope: Scope) { const left = yield* evaluate(node.left, scope) const right = yield* evaluate(node.right, scope) switch (node.operator) { case '==': return left == right case '!=': return left != right case '===': return left === right case '!==': return left !== right case '<': return left < right case '<=': return left <= right case '>': return left > right case '>=': return left >= right case '<<': return left << right case '>>': return left >> right case '>>>': return left >>> right case '+': return left + right case '-': return left - right case '*': return left * right case '**': return left ** right case '/': return left / right case '%': return left % right case '|': return left | right case '^': return left ^ right case '&': return left & right case 'in': return left in right case 'instanceof': return left instanceof right /* istanbul ignore next */ default: throw new SyntaxError(`Unexpected token ${node.operator}`) } } export function* AssignmentExpression(node: estree.AssignmentExpression, scope: Scope) { const value = yield* evaluate(node.right, scope) const left = node.left let variable: Variable if (left.type === 'Identifier') { variable = yield* Identifier(left, scope, { getVar: true, throwErr: false }) if (!variable) { const win = scope.global().find('window').get() variable = new Prop(win, left.name) } } else if (left.type === 'MemberExpression') { variable = yield* MemberExpression(left, scope, { getVar: true }) } else { return yield* pattern(left, scope, { feed: value }) } switch (node.operator) { case '=': variable.set(value); return variable.get() case '+=': variable.set(variable.get() + value); return variable.get() case '-=': variable.set(variable.get() - value); return variable.get() case '*=': variable.set(variable.get() * value); return variable.get() case '/=': variable.set(variable.get() / value); return variable.get() case '%=': variable.set(variable.get() % value); return variable.get() case '**=': variable.set(variable.get() ** value); return variable.get() case '<<=': variable.set(variable.get() << value); return variable.get() case '>>=': variable.set(variable.get() >> value); return variable.get() case '>>>=': variable.set(variable.get() >>> value); return variable.get() case '|=': variable.set(variable.get() | value); return variable.get() case '^=': variable.set(variable.get() ^ value); return variable.get() case '&=': variable.set(variable.get() & value); return variable.get() /* istanbul ignore next */ default: throw new SyntaxError(`Unexpected token ${node.operator}`) } } export function* LogicalExpression(node: estree.LogicalExpression, scope: Scope) { switch (node.operator) { case '||': return (yield* evaluate(node.left, scope)) || (yield* evaluate(node.right, scope)) case '&&': return (yield* evaluate(node.left, scope)) && (yield* evaluate(node.right, scope)) default: /* istanbul ignore next */ throw new SyntaxError(`Unexpected token ${node.operator}`) } } export interface MemberExpressionOptions { getObj?: boolean getVar?: boolean } export function* MemberExpression( node: estree.MemberExpression, scope: Scope, options: MemberExpressionOptions = {}, ) { const { getObj = false, getVar = false } = options let object: any if (node.object.type === 'Super') { object = yield* Super(node.object, scope, { getProto: true }) } else { object = yield* evaluate(node.object, scope) } if (getObj) return object let key: string if (node.computed) { key = yield* evaluate(node.property, scope) } else { key = (node.property as estree.Identifier).name } if (getVar) { // left value const setter = getSetter(object, key) if (node.object.type === 'Super' && setter) { // transfer the setter from super to this with a private key const thisObject = scope.find('this').get() const privateKey = createSymbol(key) define(thisObject, privateKey, { set: setter }) return new Prop(thisObject, privateKey) } else { return new Prop(object, key) } } else { // right value const getter = getGetter(object, key) if (node.object.type === 'Super' && getter) { const thisObject = scope.find('this').get() return getter.call(thisObject) } else { return object[key] } } } export function* ConditionalExpression(node: estree.ConditionalExpression, scope: Scope) { return (yield* evaluate(node.test, scope)) ? (yield* evaluate(node.consequent, scope)) : (yield* evaluate(node.alternate, scope)) } export function* CallExpression(node: estree.CallExpression, scope: Scope) { let func: any let object: any if (node.callee.type === 'MemberExpression') { object = yield* MemberExpression(node.callee, scope, { getObj: true }) // get key let key: string if (node.callee.computed) { key = yield* evaluate(node.callee.property, scope) } else { key = (node.callee.property as estree.Identifier).name } // right value if (node.callee.object.type === 'Super') { const thisObject = scope.find('this').get() func = object[key].bind(thisObject) } else { func = object[key] } if (typeof func !== 'function') { throw new TypeError(`${key} is not a function`) } else if (func[CLSCTOR]) { throw new TypeError(`Class constructor ${key} cannot be invoked without 'new'`) } } else { object = scope.find('this').get() func = yield* evaluate(node.callee, scope) if (typeof func !== 'function' || node.callee.type !== 'Super' && func[CLSCTOR]) { let name: string if (node.callee.type === 'Identifier') { name = node.callee.name } else { try { name = JSON.stringify(func) } catch (err) { name = '' + func } } if (typeof func !== 'function') { throw new TypeError(`${name} is not a function`) } else { throw new TypeError(`Class constructor ${name} cannot be invoked without 'new'`) } } } let args: any[] = [] for (let i = 0; i < node.arguments.length; i++) { const arg = node.arguments[i] if (arg.type === 'SpreadElement') { args = args.concat(yield* SpreadElement(arg, scope)) } else { args.push(yield* evaluate(arg, scope)) } } if (node.callee.type === 'Super') { const superCall = scope.find(SUPERCALL) if (superCall.get()) { throw new ReferenceError('Super constructor may only be called once') } else { scope.find(SUPERCALL).set(true) } } if (object && object[WINDOW] && func.toString().indexOf('[native code]') !== -1) { // you will get "TypeError: Illegal invocation" if not binding native function with window return func.apply(object[WINDOW], args) } return func.apply(object, args) } export function* NewExpression(node: estree.NewExpression, scope: Scope) { const constructor = yield* evaluate(node.callee, scope) if (typeof constructor !== 'function') { let name: string if (node.callee.type === 'Identifier') { name = node.callee.name } else { try { name = JSON.stringify(constructor) } catch (err) { name = '' + constructor } } throw new TypeError(`${name} is not a constructor`) } else if (constructor[NOCTOR]) { throw new TypeError(`${constructor.name || '(intermediate value)'} is not a constructor`) } let args: any[] = [] for (let i = 0; i < node.arguments.length; i++) { const arg = node.arguments[i] if (arg.type === 'SpreadElement') { args = args.concat(yield* SpreadElement(arg, scope)) } else { args.push(yield* evaluate(arg, scope)) } } return new constructor(...args) } export function* MetaProperty(node: estree.MetaProperty, scope: Scope) { return scope.find(NEWTARGET).get() } export function* SequenceExpression(node: estree.SequenceExpression, scope: Scope) { let result: any for (let i = 0; i < node.expressions.length; i++) { result = yield* evaluate(node.expressions[i], scope) } return result } export function* ArrowFunctionExpression(node: estree.ArrowFunctionExpression, scope: Scope) { return createFunc(node, scope) } export function* TemplateLiteral(node: estree.TemplateLiteral, scope: Scope) { const quasis = node.quasis.slice() const expressions = node.expressions.slice() let result = '' let temEl: estree.TemplateElement let expr: estree.Expression while (temEl = quasis.shift()) { result += yield* TemplateElement(temEl, scope) expr = expressions.shift() if (expr) { result += yield* evaluate(expr, scope) } } return result } export function* TaggedTemplateExpression(node: estree.TaggedTemplateExpression, scope: Scope) { const tagFunc = yield* evaluate(node.tag, scope) const quasis = node.quasi.quasis const str = quasis.map(v => v.value.cooked) const raw = quasis.map(v => v.value.raw) define(str, 'raw', { value: freeze(raw) }) const expressions = node.quasi.expressions const args = [] if (expressions) { for (let i = 0; i < expressions.length; i++) { args.push(yield* evaluate(expressions[i], scope)) } } return tagFunc(freeze(str), ...args) } export function* TemplateElement(node: estree.TemplateElement, scope: Scope) { return node.value.raw } export function* ClassExpression(node: estree.ClassExpression, scope: Scope) { if (node.id && node.id.name) { // it's for accessing class expression by its name inside // e.g. const a = class b { log() { console.log(b) } } const tmpScope = new Scope(scope) const klass = yield* createClass(node, tmpScope) tmpScope.const(node.id.name, klass) return klass } else { return yield* createClass(node, scope) } } export interface SuperOptions { getProto?: boolean } export function* Super( node: estree.Super, scope: Scope, options: SuperOptions = {}, ) { const { getProto = false } = options const superClass = scope.find(SUPER).get() return getProto ? superClass.prototype: superClass } export function* SpreadElement(node: estree.SpreadElement, scope: Scope) { return yield* evaluate(node.argument, scope) } /*<remove>*/ export function* YieldExpression(node: estree.YieldExpression, scope: Scope) { const res = yield* evaluate(node.argument, scope) return node.delegate ? yield* res : yield res } export function* AwaitExpression(node: estree.AwaitExpression, scope: Scope) { AWAIT.RES = yield* evaluate(node.argument, scope) return yield AWAIT } /*</remove>*/
the_stack
import {assert} from 'chai'; import * as ion from '../src/Ion'; import JSBI from 'jsbi'; import {Decimal, Writer} from "../src/Ion"; import {BinaryWriter, NullNode} from "../src/IonBinaryWriter"; import {Writeable} from "../src/IonWriteable"; import {getSystemSymbolTableImport} from "../src/IonSystemSymbolTable"; import {LocalSymbolTable} from "../src/IonLocalSymbolTable"; import {encodeUtf8} from "../src/IonUnicode"; import {LowLevelBinaryWriter} from "../src/IonLowLevelBinaryWriter"; const ivm = [0xe0, 0x01, 0x00, 0xea]; interface Test { name: string; instructions: (writer: Writer) => void; expected: number[]; skip?: boolean; } interface BadTest { name: string; instructions: (writer: Writer) => void; skip?: boolean; } let writerTest = function (name: string, instructions: (writer: Writer) => void, expected: number[]) { it(name, () => { let symbolTable = new LocalSymbolTable(getSystemSymbolTableImport()); let writeable = new Writeable(); let writer = new BinaryWriter(symbolTable, writeable); instructions(writer); writer.close(); let actual = writeable.getBytes(); assert.deepEqual(actual, new Uint8Array(ivm.concat(expected))); }); }; let badWriterTest = function (name: string, instructions: (writer: Writer) => void) { let test = () => { let symbolTable = new LocalSymbolTable(getSystemSymbolTableImport()); let writeable = new Writeable(); let writer = new BinaryWriter(symbolTable, writeable); instructions(writer); writer.close(); }; it(name, () => assert.throws(test, Error)); }; let blobWriterTests: Test[] = [ { name: "Writes blob", instructions: (writer) => writer.writeBlob(new Uint8Array([1, 2, 3])), expected: [0xa3, 1, 2, 3] }, { name: "Writes null blob 1", instructions: (writer) => writer.writeBlob(null), expected: [0xaf] }, { name: "Writes null blob 2", instructions: (writer) => writer.writeNull(ion.IonTypes.BLOB), expected: [0xaf] }, { name: "Writes blob with annotation", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeBlob(new Uint8Array([1])); }, expected: [ // '$ion_symbol_table':: 0xe7, 0x81, 0x83, // { 0xd4, // symbols: 0x87, // [ 0xb2, // "a" 0x81, 'a'.charCodeAt(0), // ] } // Annotations 0xe4, 0x81, 0x8a, // Blob 0xa1, 1, ] }, ]; let booleanWriterTests: Test[] = [ { name: "Writes boolean true", instructions: (writer) => writer.writeBoolean(true), expected: [0x11] }, { name: "Writes boolean false", instructions: (writer) => writer.writeBoolean(false), expected: [0x10] }, { name: "Writes null boolean by detecting null", instructions: (writer) => writer.writeBoolean(null), expected: [0x1f] }, { name: "Writes null boolean by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.BOOL), expected: [0x1f] }, { name: "Writes boolean with annotations", instructions: (writer) => { writer.setAnnotations(['a', 'b']); writer.writeBoolean(true); }, expected: [ // '$ion_symbol_table':: 0xe9, 0x81, 0x83, // { symbols: [ 0xd6, 0x87, 0xb4, // 'a' 0x81, 'a'.charCodeAt(0), // 'b' 0x81, 'b'.charCodeAt(0), // Annotations 0xe4, 0x82, 0x8a, 0x8b, // Boolean 0x11, ] }, ]; let clobWriterTests: Test[] = [ { name: "Writes clob", instructions: (writer) => writer.writeClob(new Uint8Array([1, 2, 3])), expected: [0x93, 1, 2, 3] }, { name: "Writes null clob by detecting null", instructions: (writer) => writer.writeClob(null), expected: [0x9f] }, { name: "Writes null clob by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.CLOB), expected: [0x9f] }, { name: "Writes clob with annotation", instructions: (writer) => { writer.setAnnotations(['foo']); writer.writeClob(new Uint8Array([1, 2, 3])); }, expected: [ // Symbol table // // '$ion_symbol_table' 0xe9, 0x81, 0x83, // // { symbols: [ 0xd6, 0x87, 0xb4, // // "foo" ] } 0x83, 'f'.charCodeAt(0), 'o'.charCodeAt(0), 'o'.charCodeAt(0), // Annotation 0xe6, 0x81, 0x8A, // Clob 0x93, 1, 2, 3 ] }, ]; let decimalWriterTests: Test[] = [ { name: "Writes null decimal by detecting null", instructions: (writer) => writer.writeDecimal(null), expected: [0x5f] }, { name: "Writes null decimal by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.DECIMAL), expected: [0x5f] }, { name: "Writes implicitly positive zero decimal as single byte", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("0")), expected: [0x50] }, { name: "Writes explicitly positive zero decimal as single byte", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("+0")), expected: [0x50] }, { name: "Writes 0d-0 as equiv 0d0 decimal", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("0d-0")), expected: [0x50] }, { name: "Writes negative zero decimal", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("-0")), expected: [0x52, 0x80, 0x80] }, { name: "Writes -0d-0 as equiv -0d0 decimal", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("-0d-0")), expected: [0x52, 0x80, 0x80] }, { name: "Writes null decimal with annotation", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeNull(ion.IonTypes.DECIMAL); }, expected: [ 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), 0xe3, 0x81, 0x8a, 0x5f ] }, { name: "Writes decimal -1", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("-1")), expected: [0x52, 0x80, 0x81] }, { name: "Writes decimal 123.456", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("123.456")), expected: [0x54, 0xc3, 0x01, 0xe2, 0x40] }, { name: "Writes decimal 123456000", instructions: (writer) => writer.writeDecimal(ion.Decimal.parse("123456000")), expected: [0x55, 0x80, 0x07, 0x5b, 0xca, 0x00] }, ]; let floatWriterTests: Test[] = [ { name: "Writes null float by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.FLOAT), expected: [0x4f] }, { name: "Writes null 32-bit float by detecting null", instructions: (writer) => writer.writeFloat32(null), expected: [0x4f] }, { name: "Writes null 32-bit float with annotations", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeFloat32(null) }, expected: [ 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), 0xe3, 0x81, 0x8a, 0x4f ] }, { name: "Writes 32-bit float 1.0", instructions: (writer) => writer.writeFloat32(1.0), expected: [0x44, 0x3f, 0x80, 0x00, 0x00] }, { name: "Writes 32-bit float 0.0", instructions: (writer) => writer.writeFloat32(0), expected: [0x40] }, { name: "Writes 32-bit float -0.0", instructions: (writer) => writer.writeFloat32(-0), expected: [0x44, 0x80, 0x00, 0x00, 0x00] }, { name: "Writes 32-bit float -8.125", instructions: (writer) => writer.writeFloat32(-8.125), expected: [0x44, 0xc1, 0x02, 0x00, 0x00] }, { name: "Writes null 64-bit float by detecting null", instructions: (writer) => writer.writeFloat64(null), expected: [0x4f] }, { name: "Writes null 64-bit float with annotations", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeFloat64(null) }, expected: [ 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), 0xe3, 0x81, 0x8a, 0x4f ] }, { name: "Writes 64-bit float 1.0", instructions: (writer) => writer.writeFloat64(1.0), expected: [0x48, 0x3f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, { name: "Writes 64-bit float 0.0", instructions: (writer) => writer.writeFloat64(0), expected: [0x40] }, { name: "Writes 64-bit float -0.0", instructions: (writer) => writer.writeFloat64(-0), expected: [0x48, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] }, { name: "Writes 64-bit float -8.125", instructions: (writer) => writer.writeFloat64(-8.125), expected: [0x48, 0xc0, 0x20, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00] }, ]; let intWriterTests: Test[] = [ { name: "Writes null int by detecting null", instructions: (writer) => writer.writeInt(null), expected: [0x2f] }, { name: "Writes null int by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.INT), expected: [0x2f] }, { name: "Writes int +0", instructions: (writer) => writer.writeInt(0), expected: [0x20] }, { name: "Writes int 123456", instructions: (writer) => writer.writeInt(123456), expected: [0x23, 0x01, 0xe2, 0x40] }, { name: "Writes BigInt 0", instructions: (writer) => writer.writeInt(JSBI.BigInt('0')), expected: [0x20] }, { name: "Writes BigInt 12345678901234567890", instructions: (writer) => writer.writeInt(JSBI.BigInt('12345678901234567890')), expected: [0x28, 0xab, 0x54, 0xa9, 0x8c, 0xeb, 0x1f, 0x0a, 0xd2] }, { name: "Writes BigInt -12345678901234567890", instructions: (writer) => writer.writeInt(JSBI.BigInt('-12345678901234567890')), expected: [0x38, 0xab, 0x54, 0xa9, 0x8c, 0xeb, 0x1f, 0x0a, 0xd2] }, { name: "Writes int 123456 with annotations", instructions: (writer) => { writer.setAnnotations(['a', 'b', 'c']); writer.writeInt(123456); }, expected: [ 0xeb, 0x81, 0x83, 0xd8, 0x87, 0xb6, 0x81, 'a'.charCodeAt(0), 0x81, 'b'.charCodeAt(0), 0x81, 'c'.charCodeAt(0), 0xe8, 0x83, 0x8a, 0x8b, 0x8c, 0x23, 0x01, 0xe2, 0x40 ] }, ]; let listWriterTests: Test[] = [ { name: "Writes null list by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.LIST), expected: [0xbf] }, { name: "Writes null list with annotations", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeNull(ion.IonTypes.LIST); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // Annotation 0xe3, 0x81, 0x8a, // List 0xbf, ] }, { name: "Writes empty list", instructions: (writer) => { writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); }, expected: [0xb0] }, { name: "Writes nested lists", instructions: (writer) => { writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); writer.stepOut(); }, expected: [0xb2, 0xb1, 0xb0] }, { name: "Writes pyramid lists", instructions: (writer) => { writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); writer.stepOut(); }, expected: [0xb8, 0xb3, 0xb0, 0xb0, 0xb0, 0xb3, 0xb0, 0xb0, 0xb0] }, { name: "Writes list with annotation", instructions: (writer) => { writer.setAnnotations(['a']); writer.stepIn(ion.IonTypes.LIST); writer.stepOut() }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // List 0xe3, 0x81, 0x8a, 0xb0, ] }, { name: "Writes nested list with annotation", instructions: (writer) => { writer.stepIn(ion.IonTypes.LIST); writer.setAnnotations(['a']); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // Outer list 0xb4, // Inner list 0xe3, 0x81, 0x8a, 0xb0, ] }, { name: "Writes pyramid lists with deep annotations", instructions: (writer) => { writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.setAnnotations(['a']); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.setAnnotations(['b']); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); writer.stepOut(); }, expected: [ // Symbol table 0xe9, 0x81, 0x83, 0xd6, 0x87, 0xb4, 0x81, 'a'.charCodeAt(0), 0x81, 'b'.charCodeAt(0), // Top-level list 0xbe, 0x8e, // First child 0xb6, 0xb0, 0xe3, 0x81, 0x8a, 0xb0, 0xb0, // Second child 0xb6, 0xb0, 0xe3, 0x81, 0x8b, 0xb0, 0xb0 ] }, ]; let nullWriterTests: Test[] = [ { name: "Writes explicit null", instructions: (writer) => writer.writeNull(ion.IonTypes.NULL), expected: [0x0f] }, ]; let sexpWriterTests: Test[] = [ { name: "Writes null sexp by direct call", instructions: (writer) => writer.writeNull(ion.IonTypes.SEXP), expected: [0xcf] }, { name: "Writes null sexp with annotation", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeNull(ion.IonTypes.SEXP); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // Annotation 0xe3, 0x81, 0x8a, // Sexp 0xcf, ] }, { name: "Writes empty sexp", instructions: (writer) => { writer.stepIn(ion.IonTypes.SEXP); writer.stepOut(); }, expected: [0xc0] }, { name: "Writes nested sexps", instructions: (writer) => { writer.stepIn(ion.IonTypes.SEXP); writer.stepIn(ion.IonTypes.SEXP); writer.stepIn(ion.IonTypes.SEXP); writer.stepOut(); writer.stepOut(); writer.stepOut(); }, expected: [0xc2, 0xc1, 0xc0] }, ]; let stringWriterTests: Test[] = [ { name: "Writes null string by detecting null", instructions: (writer) => { writer.writeString(null); }, expected: [0x8f] }, { name: "Writes null string by direct call", instructions: (writer) => { writer.writeNull(ion.IonTypes.STRING); }, expected: [0x8f] }, { name: "Writes two top-level strings, one of which has an annotation", instructions: (writer) => { writer.writeString("foo"); writer.setAnnotations(['a']); writer.writeString("bar"); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // First string 0x83, 'f'.charCodeAt(0), 'o'.charCodeAt(0), 'o'.charCodeAt(0), // Second string with annotation 0xe6, 0x81, 0x8a, 0x83, 'b'.charCodeAt(0), 'a'.charCodeAt(0), 'r'.charCodeAt(0) ] }, { name: "Writes valid UTF-8", instructions: (writer) => { writer.writeString("$¢€" + String.fromCodePoint(0x10348)) }, expected: [ 0x8a, // Dollar sign 0x24, // Cent sign 0xc2, 0xa2, // Euro sign 0xe2, 0x82, 0xac, // Gothic letter hwair 0xf0, 0x90, 0x8d, 0x88 ] }, ]; let structWriterTests: Test[] = [ { name: "Writes null struct by direct call", instructions: (writer) => { writer.writeNull(ion.IonTypes.STRUCT); }, expected: [0xdf] }, { name: "Writes empty struct", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.stepOut(); }, expected: [0xd0] }, { name: "Writes nested structs", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.writeFieldName('a'); writer.stepIn(ion.IonTypes.STRUCT); writer.stepOut(); writer.stepOut(); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // Structs 0xd2, 0x8a, 0xd0 ] }, { name: "Writes struct with duplicate field names", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.writeFieldName('a'); writer.writeNull(ion.IonTypes.NULL); writer.writeFieldName('a'); writer.writeNull(ion.IonTypes.NULL); writer.stepOut(); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // Struct 0xd4, 0x8a, 0x0f, 0x8a, 0x0f ] }, { name: "Writes kitchen sink struct", instructions: (writer) => { writer.setAnnotations(['x']); writer.stepIn(ion.IonTypes.STRUCT); writer.writeFieldName('b'); writer.writeBoolean(true); writer.writeFieldName('b'); writer.writeBoolean(false); writer.writeFieldName('b'); writer.writeBlob(encodeUtf8('foo')); writer.writeFieldName('c'); writer.writeClob(encodeUtf8('bar')); writer.writeFieldName('d'); writer.writeDecimal(Decimal.parse("123.456")); writer.writeFieldName('f'); writer.writeFloat32(8.125); writer.writeFieldName('f'); writer.writeFloat64(8.125); writer.writeFieldName('i'); writer.writeInt(123456); writer.writeFieldName('l'); writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.writeFieldName('n'); writer.writeNull(ion.IonTypes.NULL); writer.writeFieldName('s'); writer.stepIn(ion.IonTypes.SEXP); writer.stepOut(); writer.writeFieldName('s'); writer.writeString('baz'); writer.writeFieldName('s'); writer.stepIn(ion.IonTypes.STRUCT); writer.stepOut(); writer.writeFieldName('s'); writer.writeSymbol('qux'); writer.writeFieldName('t'); writer.writeTimestamp(new ion.Timestamp(0, 2000, 1, 1)); writer.stepOut(); }, expected: [ // Symbol table 0xee, // 4 0x9f, // Length 31 // 5 0x81, // 6 0x83, // 7 0xde, // 8 0x9b, // Length 27 // 9 0x87, // 10 0xbe, // 11 0x98, // Length 24 // 12 0x81, 'x'.charCodeAt(0), 0x81, 'b'.charCodeAt(0), 0x81, 'c'.charCodeAt(0), 0x81, 'd'.charCodeAt(0), 0x81, 'f'.charCodeAt(0), 0x81, 'i'.charCodeAt(0), 0x81, 'l'.charCodeAt(0), 0x81, 'n'.charCodeAt(0), 0x81, 's'.charCodeAt(0), 0x83, 'q'.charCodeAt(0), 'u'.charCodeAt(0), 'x'.charCodeAt(0), 0x81, 't'.charCodeAt(0), // 'x':: 0xee, // 37 0xc4, // Length ??? 0x81, 0x8a, // 40 // { 0xde, 0xc0, // Length ??? // 'b': 0x8b, // Boolean true 0x11, // 'b': 0x8b, // Boolean false 0x10, // 46 // 'b': 0x8b, // Blob 0xa3, 'f'.charCodeAt(0), 'o'.charCodeAt(0), 'o'.charCodeAt(0), // 'c': 0x8c, // Clob 0x93, 'b'.charCodeAt(0), 'a'.charCodeAt(0), 'r'.charCodeAt(0), // 'd': 0x8d, // Decimal 0x54, 0xc3, 0x01, 0xe2, 0x40, // 'f': 0x8e, // 63 // 32-bit float 0x44, 0x41, 0x02, 0x00, 0x00, // 'f': 0x8e, // 64-bit float 0x48, 0x40, 0x20, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, // 'i': 0x8f, // Int 0x23, 0x01, 0xe2, 0x40, // 'l': 0x90, // List 0xb0, // 'n': 0x91, // Null 0x0f, // 87 // 's': 0x92, // Sexp 0xc0, // 's': 0x92, // "baz" 0x83, 'b'.charCodeAt(0), 'a'.charCodeAt(0), 'z'.charCodeAt(0), // 's': 0x92, // Struct 0xd0, // 96 // 's': 0x92, // 'qux' 0x71, 0x13, // 't': 0x94, // Timestamp 0x65, 0xc0, 0x0f, 0xd0, 0x81, 0x81 ] }, ]; let symbolWriterTests: Test[] = [ { name: "Writes null symbol by detecting null", instructions: (writer) => { writer.writeSymbol(null); }, expected: [0x7f] }, { name: "Writes null symbol by direct call", instructions: (writer) => { writer.writeNull(ion.IonTypes.SYMBOL); }, expected: [0x7f] }, { name: "Writes symbol with identical annotation", instructions: (writer) => { writer.setAnnotations(['a']); writer.writeSymbol('a'); }, expected: [ // Symbol table 0xe7, 0x81, 0x83, 0xd4, 0x87, 0xb2, 0x81, 'a'.charCodeAt(0), // Symbol 0xe4, 0x81, 0x8a, 0x71, 0x0a ] }, { name: "Writes two top-level symbols", instructions: (writer) => { writer.writeSymbol('a'); writer.writeSymbol('b'); }, expected: [ // Symbol table 0xe9, 0x81, 0x83, 0xd6, 0x87, 0xb4, 0x81, 'a'.charCodeAt(0), 0x81, 'b'.charCodeAt(0), // Symbols 0x71, 0x0a, 0x71, 0x0b ] }, ]; let timestampWriterTests: Test[] = [ { name: "Writes null timestamp by detecting null", instructions: (writer) => { writer.writeTimestamp(null); }, expected: [0x6f] }, { name: "Writes null timestamp by direct call", instructions: (writer) => { writer.writeNull(ion.IonTypes.TIMESTAMP); }, expected: [0x6f] }, { name: "Writes 2000T", instructions: (writer) => { writer.writeTimestamp(new ion.Timestamp(0, 2000)); }, expected: [ 0x63, // Offset 0xc0, // Year 0x0f, 0xd0, ] }, { name: "Writes 2000T-01T", instructions: (writer) => { writer.writeTimestamp(new ion.Timestamp(0, 2000, 1)); }, expected: [ 0x64, // Offset 0xc0, // Year 0x0f, 0xd0, // Month 0x81, ] }, { name: "Writes 2000T-01-01T", instructions: (writer) => { writer.writeTimestamp(new ion.Timestamp(0, 2000, 1, 1)); }, expected: [ 0x65, // Offset 0xc0, // Year 0x0f, 0xd0, // Month 0x81, // Day 0x81, ] }, { name: "Writes 2000T-01-01T12:34", instructions: (writer) => { writer.writeTimestamp(new ion.Timestamp(0, 2000, 1, 1, 12, 34)); }, expected: [ 0x67, // Offset 0x80, // Year 0x0f, 0xd0, // Month 0x81, // Day 0x81, // Hour 0x8c, // Minute 0xa2, ] }, { name: "Writes 2000-01-01T12:34:56.789 with fraction precision", instructions: (writer) => { writer.writeTimestamp(new ion.Timestamp(0, 2000, 1, 1, 12, 34, ion.Decimal.parse('56.789'))); }, expected: [ 0x6b, // Offset 0x80, // Year 0x0f, 0xd0, // Month 0x81, // Day 0x81, // Hour 0x8c, // Minute 0xa2, // Second (56) 0xb8, // Fraction exponent (-3) 0xc3, // Fraction (789) 0x03, 0x15, ] }, { name: "Writes 2000-01-01T12:34:00-08:00 with second precision", instructions: (writer) => { writer.writeTimestamp(new ion.Timestamp(-8 * 60, 2000, 1, 1, 12, 34, ion.Decimal.parse('0'))); }, expected: [ 0x69, 0x43, 0xe0, 0x0f, 0xd0, 0x81, 0x81, 0x94, 0xa2, 0x80, ] }, ]; let badWriterTests: BadTest[] = [ { name: "Cannot step into struct with missing field value", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.stepIn(ion.IonTypes.STRUCT); } }, { name: "Cannot step into sexp with missing field value", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.stepIn(ion.IonTypes.SEXP); } }, { name: "Cannot step into list with missing field value", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.stepIn(ion.IonTypes.LIST); } }, { name: "Cannot write a struct value without setting the field name", instructions: (writer) => { writer.stepIn(ion.IonTypes.STRUCT); writer.writeInt(0); } }, { name: "Cannot write a top-level field name", instructions: (writer) => { writer.writeFieldName('foo'); } }, { name:'Should throw when passing a single string as an annotation.', instructions: (writer) => { // @ts-ignore writer.setAnnotations('taco'); writer.writeInt(5); } }, { name:'Should throw when setting annotations to null.', instructions: (writer) => { // @ts-ignore writer.setAnnotations(null); writer.writeInt(5); } }, { name:'Should throw when passing annotations array without a string.', instructions: (writer) => { // @ts-ignore writer.setAnnotations([5]); writer.writeInt(5) } }, { name:'Should throw when adding an int as annotation.', instructions: (writer) => { // @ts-ignore writer.addAnnotation(5), writer.writeInt(5) } }, { name:'Should throw when adding array of chars.', instructions: (writer) => { // @ts-ignore writer.addAnnotation(['t', 'a', 'c', 'o']); writer.writeInt(5); } }, { name:'Should throw when passing annotations array containing a non string value.', instructions: (writer) => { // @ts-ignore writer.setAnnotations(['a', 5,'t']); writer.writeInt(5); } }, { name:'Should throw when adding a non string annotation.', instructions: (writer) => { // @ts-ignore writer.addAnnotation(null); writer.writeInt(5); } }, { name:'Should throw when adding a non string annotation.', instructions: (writer) => { // @ts-ignore writer.addAnnotation(undefined); writer.writeInt(5); } }, { name:'Should throw when passing annotations array containing undefined.', instructions: (writer) => { // @ts-ignore writer.setAnnotations([undefined]); writer.writeInt(5); } }, { name:'Should throw when passing annotations array containing null.', instructions: (writer) => { // @ts-ignore writer.setAnnotations([null]); writer.writeInt(5); } }, { name:'Should throw when passing undefined as annotations.', instructions: (writer) => { // @ts-ignore writer.setAnnotations(undefined); writer.writeInt(5); } }, { name:'Should throw when writing top-level field name.', instructions: (writer) => { writer.writeFieldName('foo'); } }, { name: "Cannot stepOut() of the top level", instructions: (writer) => { writer.stepOut(); } }, { name: "Cannot stepOut() more times than you have stepped in", instructions: (writer) => { writer.stepIn(ion.IonTypes.LIST); writer.stepOut(); writer.stepOut(); } }, ]; function runWriterTests(tests: Test[]) { tests.forEach(({name, instructions, expected, skip}) => { if (skip) { it.skip(name, () => {}); return; } writerTest(name, instructions, expected); }); } function runBadWriterTests(tests: BadTest[]) { tests.forEach(({name, instructions, skip}) => { if (skip) { it.skip(name, () => {}); return; } badWriterTest(name, instructions); }); } describe('Binary Writer', () => { describe('Writing Ion Values', () => { describe('Null', () => runWriterTests(nullWriterTests)); describe('Boolean', () => runWriterTests(booleanWriterTests)); describe('Int', () => runWriterTests(intWriterTests)); describe('Float', () => runWriterTests(floatWriterTests)); describe('Decimal', () => runWriterTests(decimalWriterTests)); describe('Timestamp', () => runWriterTests(timestampWriterTests)); describe('Symbol', () => runWriterTests(symbolWriterTests)); describe('String', () => runWriterTests(stringWriterTests)); describe('Clob', () => runWriterTests(clobWriterTests)); describe('Blob', () => runWriterTests(blobWriterTests)); describe('List', () => runWriterTests(listWriterTests)); describe('S-Expression', () => runWriterTests(sexpWriterTests)); describe('Struct', () => runWriterTests(structWriterTests)); }); describe('Catching illegal behavior', () => { runBadWriterTests(badWriterTests); }); it('Calculates node lenghts correctly', () => { let writeable = new Writeable(); let writer = new LowLevelBinaryWriter(writeable); let node = new NullNode(writer, null, ion.IonTypes.LIST, new Uint8Array([10 | 0x80])); assert.equal(node.getAnnotatedContainerLength(), 3); assert.equal(node.getAnnotationsLength(), 3); assert.equal(node.getLength(), 4); assert.equal(node.getContainedValueLength(), 1); assert.equal(node.getValueLength(), 0); node.write(); let bytes = writeable.getBytes(); assert.deepEqual(bytes, new Uint8Array([0xe3, 0x81, 0x8a, 0xbf])); }); });
the_stack
import { Pos, NoPos, SrcFile, Position } from "../pos"; import { token } from "../token"; import { ByteStr } from "../bytestr"; import { Int64 } from "../int64"; import { Num } from "../num"; import { numconv } from "../numconv"; import { StrWriter } from "../util"; import { Scope, Ent, nilScope } from "./scope"; import { NodeVisitor } from "./visit"; import { ReprVisitor, ReprOptions } from "./repr"; // -------------------------------------------------------------------------------- export interface TypedNode { type: Type; } export class Node { constructor(public pos: Pos) { } _scope?: Scope; toString(): string { return this.constructor.name; } // repr returns a human-readable and machine-parsable string representation // of the tree represented by this node. // If a custom writer is provided via options.w, the empty string is returned. repr(options?: ReprOptions): string { let v = new ReprVisitor(options); v.visitNode(this); return v.toString(); } isUnresolved(): this is UnresolvedType | TypedNode { // isUnresolved returns true for any node that references something which is // not yet resolved. TODO: consider adding node UnresolvedIdent return (this.isUnresolvedType() || (!this.isType() && (this as any).type instanceof UnresolvedType)); } // Auto-generated methods: // isTYPE() :this is TYPE isType(): this is Type { return (this instanceof Type && (this instanceof Template ? this.base.isType() : this instanceof TemplateInvocation ? this.template.isType() : true)); } // convertToNodeInPlace is a destructive action which transforms the receiver // to become a copy of otherNode. convertToNodeInPlace<T extends Node>(otherNode: T): T { let dst = this as any; let src = otherNode as any; dst.__proto__ = src.__proto__; for (let k in dst) { delete dst[k]; } for (let k in src) { dst[k] = src[k]; } return dst as T; } visit(v: NodeVisitor) { } isPackage(): this is Package { return this instanceof Package; } isFile(): this is File { return this instanceof File; } isComment(): this is Comment { return this instanceof Comment; } isBad(): this is Bad { return this instanceof Bad; } isFunSig(): this is FunSig { return this instanceof FunSig; } isStmt(): this is Stmt { return this instanceof Stmt; } isExpr(): this is Expr { return this instanceof Expr; } isVoidType(): this is VoidType { return this instanceof VoidType; } isUnresolvedType(): this is UnresolvedType { return this instanceof UnresolvedType; } isOptionalType(): this is OptionalType { return this instanceof OptionalType; } isPrimType(): this is PrimType { return this instanceof PrimType; } isNilType(): this is NilType { return this instanceof NilType; } isBoolType(): this is BoolType { return this instanceof BoolType; } isNumType(): this is NumType { return this instanceof NumType; } isFloatType(): this is FloatType { return this instanceof FloatType; } isIntType(): this is IntType { return this instanceof IntType; } isSIntType(): this is SIntType { return this instanceof SIntType; } isUIntType(): this is UIntType { return this instanceof UIntType; } isMemType(): this is MemType { return this instanceof MemType; } isStrType(): this is StrType { return this instanceof StrType; } isUnionType(): this is UnionType { return this instanceof UnionType; } isAliasType(): this is AliasType { return this instanceof AliasType; } isTupleType(): this is TupleType { return this instanceof TupleType; } isListType(): this is ListType { return this instanceof ListType; } isRestType(): this is RestType { return this instanceof RestType; } isStructType(): this is StructType { return this instanceof StructType; } isFunType(): this is FunType { return this instanceof FunType; } isTemplate(): this is Template { return this instanceof Template; } isTemplateInvocation(): this is TemplateInvocation { return this instanceof TemplateInvocation; } isTemplateVar(): this is TemplateVar { return this instanceof TemplateVar; } isReturnStmt(): this is ReturnStmt { return this instanceof ReturnStmt; } isForStmt(): this is ForStmt { return this instanceof ForStmt; } isWhileStmt(): this is WhileStmt { return this instanceof WhileStmt; } isBranchStmt(): this is BranchStmt { return this instanceof BranchStmt; } isDecl(): this is Decl { return this instanceof Decl; } isImportDecl(): this is ImportDecl { return this instanceof ImportDecl; } isMultiDecl(): this is MultiDecl { return this instanceof MultiDecl; } isVarDecl(): this is VarDecl { return this instanceof VarDecl; } isTypeDecl(): this is TypeDecl { return this instanceof TypeDecl; } isFieldDecl(): this is FieldDecl { return this instanceof FieldDecl; } isIdent(): this is Ident { return this instanceof Ident; } isBlock(): this is Block { return this instanceof Block; } isIfExpr(): this is IfExpr { return this instanceof IfExpr; } isCollectionExpr(): this is CollectionExpr { return this instanceof CollectionExpr; } isTupleExpr(): this is TupleExpr { return this instanceof TupleExpr; } isListExpr(): this is ListExpr { return this instanceof ListExpr; } isSelectorExpr(): this is SelectorExpr { return this instanceof SelectorExpr; } isIndexExpr(): this is IndexExpr { return this instanceof IndexExpr; } isSliceExpr(): this is SliceExpr { return this instanceof SliceExpr; } isLiteralExpr(): this is LiteralExpr { return this instanceof LiteralExpr; } isNumLit(): this is NumLit { return this instanceof NumLit; } isIntLit(): this is IntLit { return this instanceof IntLit; } isRuneLit(): this is RuneLit { return this instanceof RuneLit; } isFloatLit(): this is FloatLit { return this instanceof FloatLit; } isStringLit(): this is StringLit { return this instanceof StringLit; } isAssignment(): this is Assignment { return this instanceof Assignment; } isOperation(): this is Operation { return this instanceof Operation; } isCallExpr(): this is CallExpr { return this instanceof CallExpr; } isFunExpr(): this is FunExpr { return this instanceof FunExpr; } isTypeConvExpr(): this is TypeConvExpr { return this instanceof TypeConvExpr; } isAtom(): this is Atom { return this instanceof Atom; } } export class Package extends Node { constructor(public name: string, public _scope: Scope) { super(NoPos); } files: File[] = []; toString(): string { return `(Package ${JSON.stringify(this.name)})`; } visit(v: NodeVisitor) { v.visitField("name", this.name); v.visitFieldNA("files", this.files); } } export class File extends Node { constructor(public sfile: SrcFile, public _scope: Scope, public imports: ImportDecl[] // imports in this file , public decls: (Decl | FunExpr)[] // top-level declarations , public unresolved: null | Set<Ident> // unresolved references , public endPos: Position | null // when non-null, the position of #end "data tail" , public endMeta: Expr[] // Any metadata as part of #end ) { super(NoPos); } toString(): string { return `(File ${JSON.stringify(this.sfile.name)})`; } visit(v: NodeVisitor) { v.visitField("sfile", this.sfile); v.visitFieldNA("imports", this.imports); v.visitFieldNA("decls", this.decls); if (this.unresolved !== null && this.unresolved !== undefined) v.visitField("unresolved", this.unresolved); if (this.endPos !== null && this.endPos !== undefined) v.visitField("endPos", this.endPos); v.visitFieldNA("endMeta", this.endMeta); } } export class Comment extends Node { constructor(pos: Pos, public value: Uint8Array) { super(pos); } visit(v: NodeVisitor) { v.visitField("value", this.value); } } export class Bad extends Node { constructor(pos: Pos, public message: string) { super(pos); } visit(v: NodeVisitor) { v.visitField("message", this.message); } } export class FunSig extends Node { constructor(pos: Pos, public params: FieldDecl[], public result: null | Type // null = auto ) { super(pos); } visit(v: NodeVisitor) { v.visitFieldNA("params", this.params); if (this.result) v.visitFieldN("result", this.result); } } export class Stmt extends Node { constructor(pos: Pos, public _scope: Scope) { super(pos); } visit(v: NodeVisitor) { } } export class Expr extends Stmt { type: null | Type = null; // effective type of expression. null until resolved. visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); } } // ----------------------------------------------------------------------------- // Types export class Type extends Expr { constructor(pos: Pos) { super(pos, nilScope // Note: "type" property on a type has a different meaning than for other // node classes. "type" is used to describe a subtype in some classes, // like for instance OptionalType. // accepts returns true if the other type is compatible with this type. // essentially: "this >= other" // For instance, if the receiver is the same as `other` // or a superset of `other`, true is returned. ); } // Note: "type" property on a type has a different meaning than for other // node classes. "type" is used to describe a subtype in some classes, // like for instance OptionalType. // accepts returns true if the other type is compatible with this type. // essentially: "this >= other" // For instance, if the receiver is the same as `other` // or a superset of `other`, true is returned. accepts(other: Type): bool { return this.equals(other); } // equals returns true if the receiver is equivalent to `other` equals(other: Type): bool { return this === other; } // canonicalType returns the underlying canonical type for // classes that wraps a type, like AliasType. canonicalType(): Type { return this; } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); } } export class VoidType extends Type { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); } } export const t_void = new VoidType(NoPos); export class UnresolvedType extends Type { constructor(pos: Pos, public def: Expr) { super(pos); } // UnresolvedType represents a type that is not yet known, but may be // known later (i.e. during bind/resolve.) // // Whenever something refers to this type, you must call addRef(x) where // x is the thing that uses/refers to this type. This makes it possible // for the TypeResolver to--when resolving this type--go in and edit all // the uses of this type, updating them with a concrete, resolved type. refs: null | Set<Node> = null; // things that references this type addRef(x: Node) { assert(x !== this.def, "addRef called with own definition"); if (!this.refs) { this.refs = new Set<Node>([x]); } else { this.refs.add(x); } } repr(options?: ReprOptions) { return "~" + this.def.repr(options); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); if (this.refs !== null && this.refs !== undefined) v.visitField("refs", this.refs); v.visitFieldN("def", this.def); } } export class OptionalType extends Type { constructor(pos: Pos, public type: Type) { super(pos); } equals(t: Type): bool { return this === t || (t.isOptionalType() && this.type.equals(t.type)); } accepts(t: Type): bool { return (this.equals(t) || // e.g. "x T?; y T?; x = y" this.type.accepts(t) || // e.g. "x T?; y T; x = y" t === t_nil // e.g. "x T?; x = nil" ); } toString(): string { return `${this.type}?`; } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); } } // Storage denotes the storage type needed for a primitive type export enum Storage { None = 0, Ptr, Int, Bool, i8, i16, i32, i64, f32, f64 } const StorageSize = { [Storage.None]: 0, [Storage.Ptr]: 4, [Storage.Int]: 4, [Storage.Bool]: 4, [Storage.i8]: 1, [Storage.i16]: 2, [Storage.i32]: 4, [Storage.i64]: 8, [Storage.f32]: 4, [Storage.f64]: 8, }; export class PrimType extends Type { constructor(public name: string, public storage: Storage // type of underlying storage ) { super(NoPos); } _storageSize = StorageSize[this.storage]; // size in bytes // storageSize returns the underlying storage size in bytes storageSize(): int { return this._storageSize; } // simplified type te isType(): this is Type { return true; } // convenience function used by arch rewrite rules isI8(): bool { return this.storage == Storage.i8; } isI16(): bool { return this.storage == Storage.i16; } isI32(): bool { return this.storage == Storage.i32; } isI64(): bool { return this.storage == Storage.i64; } isF32(): bool { return this.storage == Storage.f32; } isF64(): bool { return this.storage == Storage.f64; } isBool(): bool { return this.storage == Storage.Bool; } isPtr(): bool { return this.storage == Storage.Ptr; } isNil(): bool { return this.storage == Storage.None; } toString(): string { return this.name; } repr(options?: ReprOptions): string { return this.name; } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class NilType extends PrimType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class BoolType extends PrimType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class NumType extends PrimType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } // all number types export class FloatType extends NumType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class IntType extends NumType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class SIntType extends IntType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class UIntType extends IntType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } export class MemType extends UIntType { visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("name", this.name); v.visitFieldE("storage", this.storage, Storage); } } // used by SSA IR to represent memory state // predefined constant of all primitive types. // string names should match exported constant name sans "t_". export const t_nil = new NilType("nil", Storage.None); export const t_bool = new BoolType("bool", Storage.Bool); export const t_rune = new UIntType("rune", Storage.i32); export const t_byte = new UIntType("byte", Storage.i8); export const t_u8 = new UIntType("u8", Storage.i8); export const t_i8 = new SIntType("i8", Storage.i8); export const t_u16 = new UIntType("u16", Storage.i16); export const t_i16 = new SIntType("i16", Storage.i16); export const t_u32 = new UIntType("u32", Storage.i32); export const t_i32 = new SIntType("i32", Storage.i32); export const t_u64 = new UIntType("u64", Storage.i64); export const t_i64 = new SIntType("i64", Storage.i64); export const t_uint = new UIntType("uint", Storage.Int); export const t_int = new SIntType("int", Storage.Int); export const t_uintptr = new UIntType("uintptr", Storage.Ptr); export const t_mem = new MemType("mem", Storage.Ptr); export const t_f32 = new FloatType("f32", Storage.f32); export const t_f64 = new FloatType("f64", Storage.f64); export class StrType extends Type { constructor(pos: Pos, public len: int // -1 means length only known at runtime ) { super(pos); } toString(): string { return this.len == -1 ? "str" : `str<${this.len}>`; } equals(t: Type): bool { return this === t || t.isStrType(); } repr(options?: ReprOptions): string { return this.toString(); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("len", this.len); } } export class UnionType extends Type { constructor(pos: Pos, public types: Set<Type>) { super(pos); } add(t: Type) { assert(!(t instanceof UnionType), "adding union type to union type"); this.types.add(t); } toString(): string { let s = "(", first = true; for (let t of this.types) { if (first) { first = false; } else { s += "|"; } s += t.toString(); } return s + ")"; } equals(other: Type): bool { if (this === other) { return true; } if (!(other instanceof UnionType) || other.types.size != this.types.size) { return false; } // Note: This relies on type instances being singletons (being interned) for (let t of this.types) { if (!other.types.has(t)) { return false; } } return true; } accepts(other: Type): bool { if (this === other) { return true; } if (!(other instanceof UnionType)) { // e.g. (int|i32|i64) accepts i32 return this.types.has(other); } // Note: This relies on type instances being singletons (being interned) // make sure that we have at least the types of `other`. // e.g. // (int|f32|bool) accepts (int|f32) => true // (int|f32) accepts (int|f32|bool) => false for (let t of other.types) { if (!this.types.has(t)) { return false; } } return true; } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("types", this.types); } } export class AliasType extends Type { constructor(pos: Pos, public name: ByteStr // alias name , public type: Type // type this is an alias of ) { super(pos); } equals(other: Type): bool { return this === other || (other.isAliasType() && this.type.equals(other.type)); } canonicalType(): Type { let t: Type = this.type; while (t instanceof AliasType) { t = t.type; } return t; } toString(): string { return `(AliasType ${this.type})`; } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); v.visitField("name", this.name); } } export class TupleType extends Type { constructor(public types: Type[]) { super(NoPos); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("types", this.types); } } export class ListType extends Type { constructor(public type: Type // element type ) { super(NoPos); } equals(t: Type): bool { return this === t || (t instanceof ListType && this.type.equals(t.type)); } accepts(t: Type): bool { // Note: This way, ListType <= RestType, e.g. // fun foo(x ...int) { y int[] = x } return t instanceof ListType && this.type.equals(t.type); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); } } export class RestType extends ListType { // RestType = "..." Type // Specialized generic type instance. // Rest is really a list, but represented as a subclass toString(): string { return `...${super.toString()}`; } equals(t: Type): bool { return this === t || (t instanceof RestType && this.type.equals(t.type)); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); } } export class StructType extends Type { constructor(pos: Pos, public _scope: Scope, public name: Ident | null, public decls: Decl[]) { super(pos); } toString(): string { return this.name ? this.name.toString() : "{anon}"; } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); if (this.name) v.visitFieldN("name", this.name); v.visitFieldNA("decls", this.decls); } } export class FunType extends Type { constructor(pos: Pos, public args: Type[], public result: Type) { super(pos); } equals(t: Type): bool { return (this === t || (t.isFunType() && this.args.length == t.args.length && this.result.equals(t.result) && this.args.every((at, i) => at.equals(t.args[i])))); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("args", this.args); v.visitFieldN("result", this.result); } } // ----------------------------------------------------------------------------- // Template export class Template<T extends Node = Node> extends Type { constructor(pos: Pos, public _scope: Scope, public vars: TemplateVar[] // never empty. position and name are both important , public base: T | TemplateInvocation<T> // node this template can instantiate ) { super(pos); } // bottomBase returns the bottom-most base bottomBase(): Node { return this.base instanceof Template ? this.base.bottomBase() : this.base; } // aliases returns a possibly-empty list of Templates which this template // uses as its base. // // Example: // type A<T> {x T} // type B<X> A<X> // type C<Y> B<Y> // // Template(A).aliases() => [] // none // Template(B).aliases() => [ Template(A) ] // Template(C).aliases() => [ Template(B), Template(A) ] // aliases(): Template[] { let a: Template[] = []; let bn: Node = this.base; while (true) { if (bn instanceof TemplateInvocation) { bn = bn.template; } else if (bn instanceof Template) { a.push(bn); bn = bn.base; } else { break; } } return a; } toString(): string { return (this.bottomBase() + "<" + this.vars.map(v => v.name).join(",") + ">"); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("vars", this.vars); v.visitField("base", this.base); } } export class TemplateInvocation<T extends Node = Node> extends Type { constructor(pos: Pos, public _scope: Scope, public name: Ident | null // e.g "Foo2" from "Foo2<X> Foo<X>" , public args: Node[], public template: Template<T>) { super(pos); } toString(): string { return ((this.name ? this.name.toString() : this.template.bottomBase().toString()) + "<" + this.args.join(",") + ">"); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); if (this.name) v.visitFieldN("name", this.name); v.visitFieldNA("args", this.args); v.visitFieldN("template", this.template); } } export class TemplateVar<T extends Node = Node> extends Type { constructor(pos: Pos, public _scope: Scope, public name: Ident, public constraint: null | Node // e.g. "T is ConstraintType" , public def: null | T // e.g. "T = int" ) { super(pos); } equals(t: TemplateVar): bool { return this === t; } toString(): string { return `(TemplateVar ${this.name})`; } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldN("name", this.name); if (this.constraint) v.visitFieldN("constraint", this.constraint); if (this.def !== null && this.def !== undefined) v.visitField("def", this.def); } } // ----------------------------------------------------------------------------- // Flow control export class ReturnStmt extends Stmt { constructor(pos: Pos, _scope: Scope, public result: Expr // t_nil means no explicit return values , public type: Type | null // effective type. null until resolved. ) { super(pos, _scope); } visit(v: NodeVisitor) { v.visitFieldN("result", this.result); if (this.type) v.visitFieldN("type", this.type); } } export class ForStmt extends Stmt { constructor(pos: Pos, _scope: Scope, public init: Stmt | null // initializer , public cond: Expr | null // condition for executing the body. null=unconditional , public incr: Stmt | null // incrementor , public body: Expr) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.init) v.visitFieldN("init", this.init); if (this.cond) v.visitFieldN("cond", this.cond); if (this.incr) v.visitFieldN("incr", this.incr); v.visitFieldN("body", this.body); } } export class WhileStmt extends ForStmt { constructor(pos: Pos, _scope: Scope, cond: Expr | null // condition for executing the body. null=unconditional , body: Expr) { super(pos, _scope, null, cond, null, body); } visit(v: NodeVisitor) { if (this.cond) v.visitFieldN("cond", this.cond); v.visitFieldN("body", this.body); } } export class BranchStmt extends Stmt { constructor(pos: Pos, _scope: Scope, public tok: token // BREAK | CONTINUE ) { super(pos, _scope); } label: Ident | null = null; visit(v: NodeVisitor) { v.visitFieldE("tok", this.tok, token); if (this.label) v.visitFieldN("label", this.label); } } // end of flow control // ----------------------------------------------------------------------------- // Declarations export class Decl extends Stmt { visit(v: NodeVisitor) { } } export class ImportDecl extends Decl { constructor(pos: Pos, _scope: Scope, public path: StringLit, public localIdent: Ident | null) { super(pos, _scope); } visit(v: NodeVisitor) { v.visitFieldN("path", this.path); if (this.localIdent) v.visitFieldN("localIdent", this.localIdent); } } export class MultiDecl extends Decl { constructor(pos: Pos, _scope: Scope, public decls: Decl[]) { super(pos, _scope); } visit(v: NodeVisitor) { v.visitFieldNA("decls", this.decls); } } export class VarDecl extends Decl { constructor(pos: Pos, _scope: Scope, public group: Object | null // null means not part of a group , public idents: Ident[], public type: Type | null // null means no type , public values: Expr[] | null // null means no values ) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.group !== null && this.group !== undefined) v.visitField("group", this.group); v.visitFieldNA("idents", this.idents); if (this.type) v.visitFieldN("type", this.type); if (this.values) v.visitFieldNA("values", this.values); } } export class TypeDecl extends Decl { constructor(pos: Pos, _scope: Scope, public ident: Ident, public type: Type, public group: Object | null // nil = not part of a group ) { super(pos, _scope); } visit(v: NodeVisitor) { v.visitFieldN("ident", this.ident); v.visitFieldN("type", this.type); if (this.group !== null && this.group !== undefined) v.visitField("group", this.group); } } export class FieldDecl extends Decl { constructor(pos: Pos, _scope: Scope, public type: Type, public name: null | Ident // null means anonymous field/parameter ) { super(pos, _scope); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); if (this.name) v.visitFieldN("name", this.name); } } // ----------------------------------------------------------------------------- // Expressions export class Ident extends Expr { constructor(pos: Pos, _scope: Scope, public value: ByteStr // interned value ) { super(pos, _scope); } ent: null | Ent = null; // what this name references incrWrite() { assert(this.ent != null); this.ent!.writes++; } // ref registers a reference to this ent from an identifier refEnt(ent: Ent) { assert(this !== ent.value, "ref declaration"); ent.nreads++; this.ent = ent; } // ref unregisters a reference to this ent from an identifier unrefEnt() { assert(this.ent, "null ent"); this.ent!.nreads--; this.ent = null; } toString(): string { return this.value.toString(); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); if (this.ent !== null && this.ent !== undefined) v.visitField("ent", this.ent); v.visitField("value", this.value); } } export class Block extends Expr { constructor(pos: Pos, _scope: Scope, public list: Stmt[]) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("list", this.list); } } export class IfExpr extends Expr { constructor(pos: Pos, _scope: Scope, public cond: Expr, public then: Expr, public els_: Expr | null) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldN("cond", this.cond); v.visitFieldN("then", this.then); if (this.els_) v.visitFieldN("els_", this.els_); } } export class CollectionExpr extends Expr { constructor(pos: Pos, _scope: Scope, public entries: Expr[]) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("entries", this.entries); } } export class TupleExpr extends CollectionExpr { // TupleExpr = "(" Expr ("," Expr)+ ")" // e.g. (1, true, "three") type: null | TupleType = null; visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("entries", this.entries); } } export class ListExpr extends CollectionExpr { constructor(pos: Pos, _scope: Scope, entries: Expr[], public type: null | ListType) { super(pos, _scope, entries); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldNA("entries", this.entries); } } export class SelectorExpr extends Expr { constructor(pos: Pos, _scope: Scope, public lhs: Expr, public rhs: Expr // Ident or SelectorExpr ) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldN("lhs", this.lhs); v.visitFieldN("rhs", this.rhs); } } export class IndexExpr extends Expr { constructor(pos: Pos, _scope: Scope, public operand: Expr, public index: Expr) { super(pos, _scope); } indexnum: Num = -1; // used by resolver. >=0 : resolved, -1 : invalid or unresolved visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldN("operand", this.operand); v.visitFieldN("index", this.index); v.visitField("indexnum", this.indexnum); } } export class SliceExpr extends Expr { constructor(pos: Pos, _scope: Scope, public operand: Expr, public start: Expr | null, public end: Expr | null) { super(pos, _scope); } // SliceExpr = Expr "[" Expr? ":" Expr? "]" // e.g. foo[1:4] type: null | (ListType | TupleType) = null; startnum: Num = -1; // used by resolver. >=0 : resolved, -1 : invalid or unresolved endnum: Num = -1; // used by resolver. >=0 : resolved, -1 : invalid or unresolved visit(v: NodeVisitor) { if (this.type !== null && this.type !== undefined) v.visitField("type", this.type); v.visitFieldN("operand", this.operand); if (this.start) v.visitFieldN("start", this.start); if (this.end) v.visitFieldN("end", this.end); v.visitField("startnum", this.startnum); v.visitField("endnum", this.endnum); } } export class LiteralExpr extends Expr { constructor(pos: Pos, public value: Int64 | number | Uint8Array) { super(pos, nilScope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitField("value", this.value); } } export class NumLit extends LiteralExpr { constructor(pos: Pos, public value: Int64 | number, public type: NumType) { super(pos, value); } // convertToType coverts the value of the literal to the provided basic type. // Returns null if the conversion would be lossy. // convertToType(t: NumType): NumLit | null { if (t === this.type) { return this; } let [v, lossless] = numconv(this.value, t); if (lossless) { if (t instanceof FloatType) { return new FloatLit(this.pos, v as number, t); } if (t instanceof IntType) { return new IntLit(this.pos, v, t, token.INT); } throw new Error(`unexpected NumType ${t.constructor}`); } return null; } toString(): string { return this.value.toString(); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); v.visitField("value", this.value); } } export class IntLit extends NumLit { constructor(pos: Pos, value: Int64 | number, public type: IntType // type is always known , public format: token.INT | token.INT_BIN | token.INT_OCT | token.INT_HEX) { super(pos, value, type); } base(): int { switch (this.format) { case token.INT_HEX: return 16; case token.INT_OCT: return 8; case token.INT_BIN: return 2; default: return 10; } } convertToType(t: NumType): NumLit | null { // specialization of NumLit.convertToType that carries over format let n = super.convertToType(t); if (n && n !== this && n instanceof IntLit) { n.format = this.format; } return n; } toString(): string { switch (this.format) { case token.INT_HEX: return "0x" + this.value.toString(16); case token.INT_OCT: return "0o" + this.value.toString(8); case token.INT_BIN: return "0b" + this.value.toString(2); default: return this.value.toString(10); } } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); v.visitField("value", this.value); v.visitFieldE("format", this.format, token); } } const zeros = "00000000"; export class RuneLit extends NumLit { constructor(pos: Pos, public value: int // codepoint ) { super(pos, value, t_rune); } // 'a', '\n', '\x00', '\u0000', '\U00000000' toString(): string { let c = this.value; switch (c) { // see scanner/scanEscape case 0: return "'\\0'"; case 7: return "'\\a'"; case 8: return "'\\b'"; case 9: return "'\\t'"; case 10: return "'\\n'"; case 11: return "'\\v'"; case 12: return "'\\f'"; case 13: return "'\\r'"; case 39: return "'\\''"; case 92: return "'\\\\'"; } if (c >= 32 && c <= 126) { // visible printable ASCII return `'${String.fromCharCode(c)}'`; } let s = c.toString(16).toUpperCase(), z = s.length; return (z > 4 ? ("'\\U" + (z < 8 ? zeros.substr(0, 8 - z) : "")) : z > 2 ? ("'\\u" + (z < 4 ? zeros.substr(0, 4 - z) : "")) : ("'\\x" + (z < 4 ? zeros.substr(0, 2 - z) : ""))) + s + "'"; } visit(v: NodeVisitor) { v.visitField("value", this.value); } } export class FloatLit extends NumLit { constructor(pos: Pos, public value: number, public type: FloatType) { super(pos, value, type); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); v.visitField("value", this.value); } } export class StringLit extends LiteralExpr { constructor(pos: Pos, public value: Uint8Array, public type: StrType) { super(pos, value); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); v.visitField("value", this.value); } } export class Assignment extends Expr { constructor(pos: Pos, _scope: Scope, public op: token // ILLEGAL means no operation , public lhs: Expr[], public rhs: Expr[] // empty == lhs++ or lhs-- , public decls: bool[] // index => bool: new declaration? ) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldE("op", this.op, token); v.visitFieldNA("lhs", this.lhs); v.visitFieldNA("rhs", this.rhs); v.visitFieldA("decls", this.decls); } } export class Operation extends Expr { constructor(pos: Pos, _scope: Scope, public op: token // [token.operator_beg .. token.operator_end] , public x: Expr // left-hand side , public y: Expr | null // right-hand size. nil means unary expression ) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldE("op", this.op, token); v.visitFieldN("x", this.x); if (this.y) v.visitFieldN("y", this.y); } } export class CallExpr extends Expr { constructor(pos: Pos, _scope: Scope, public receiver: Expr, public args: Expr[], public hasRest: bool // last argument is followed by ... ) { super(pos, _scope); } visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldN("receiver", this.receiver); v.visitFieldNA("args", this.args); v.visitField("hasRest", this.hasRest); } } export class FunExpr extends Expr { constructor(pos: Pos, _scope: Scope, public sig: FunSig, public name: null | Ident // null = anonymous func expression , public isInit: bool // true for special "init" funs at file level ) { super(pos, _scope); } type: null | FunType = null; body: null | Expr = null; // null = forward declaration visit(v: NodeVisitor) { if (this.type) v.visitFieldN("type", this.type); v.visitFieldN("sig", this.sig); if (this.name) v.visitFieldN("name", this.name); v.visitField("isInit", this.isInit); if (this.body) v.visitFieldN("body", this.body); } } export class TypeConvExpr extends Expr { constructor(pos: Pos, _scope: Scope, public expr: Expr, public type: Type) { super(pos, _scope); } visit(v: NodeVisitor) { v.visitFieldN("type", this.type); v.visitFieldN("expr", this.expr); } } export class Atom extends Expr { constructor(public name: string, public type: BoolType | NilType) { super(NoPos, nilScope); } visit(v: NodeVisitor) { v.visitField("type", this.type); v.visitField("name", this.name); } }
the_stack
import {LOCALES} from '../locales'; export default { property: { weight: 'weight', label: 'label', fillColor: 'fill color', color: 'color', coverage: 'coverage', strokeColor: 'stroke color', radius: 'radius', outline: 'outline', stroke: 'stroke', density: 'density', height: 'height', sum: 'sum', pointCount: 'Point Count' }, placeholder: { search: 'Search', selectField: 'Select a field', yAxis: 'Y Axis', selectType: 'Select A Type', selectValue: 'Select A Value', enterValue: 'Enter a value', empty: 'empty' }, misc: { by: '', valuesIn: 'Values in', valueEquals: 'Value equals', dataSource: 'Data Source', brushRadius: 'Brush Radius (km)', empty: ' ' }, mapLayers: { title: 'Map Layers', label: 'Label', road: 'Road', border: 'Border', building: 'Building', water: 'Water', land: 'Land', '3dBuilding': '3d Building' }, panel: { text: { label: 'label', labelWithId: 'Label {labelId}', fontSize: 'Font size', fontColor: 'Font color', textAnchor: 'Text anchor', alignment: 'Alignment', addMoreLabel: 'Add More Label' } }, sidebar: { panels: { layer: 'Layers', filter: 'Filters', interaction: 'Interactions', basemap: 'Base map' } }, layer: { required: 'Required*', radius: 'Radius', color: 'Color', fillColor: 'Fill Color', outline: 'Outline', weight: 'Weight', propertyBasedOn: '{property} based on', coverage: 'Coverage', stroke: 'Stroke', strokeWidth: 'Stroke Width', strokeColor: 'Stroke Color', basic: 'Basic', trailLength: 'Trail Length', trailLengthDescription: 'Number of seconds for a path to completely fade out', newLayer: 'new layer', elevationByDescription: 'When off, height is based on count of points', colorByDescription: 'When off, color is based on count of points', aggregateBy: 'Aggregate {field} by', '3DModel': '3D Model', '3DModelOptions': '3D Model Options', type: { point: 'point', arc: 'arc', line: 'line', grid: 'grid', hexbin: 'hexbin', polygon: 'polygon', geojson: 'geojson', cluster: 'cluster', icon: 'icon', heatmap: 'heatmap', hexagon: 'hexagon', hexagonid: 'H3', trip: 'trip', s2: 'S2', '3d': '3D' } }, layerVisConfigs: { angle: 'Angle', strokeWidth: 'Stroke Width (Pixels)', strokeWidthRange: 'Stroke Width Range', radius: 'Radius', fixedRadius: 'Fixed Radius to meter', fixedRadiusDescription: 'Map radius to absolute radius in meters, e.g. 5 to 5 meters', radiusRange: 'Radius Range', clusterRadius: 'Cluster Radius in Pixels', radiusRangePixels: 'Radius Range in pixels', opacity: 'Opacity', coverage: 'Coverage', outline: 'Outline', colorRange: 'Color range', stroke: 'Stroke', strokeColor: 'Stroke Color', strokeColorRange: 'Stroke Color range', targetColor: 'Target Color', colorAggregation: 'Color Aggregation', heightAggregation: 'Height Aggregation', resolutionRange: 'Resolution range', sizeScale: 'Size Scale', worldUnitSize: 'World Unit Size', elevationScale: 'Elevation Scale', enableElevationZoomFactor: 'Use elevation zoom factor', enableElevationZoomFactorDescription: 'Adjust height/elevation based on current zoom factor', enableHeightZoomFactor: 'Use height zoom factor', heightScale: 'Height Scale', coverageRange: 'Coverage Range', highPrecisionRendering: 'High Precision Rendering', highPrecisionRenderingDescription: 'High precision will result in slower performance', height: 'Height', heightDescription: 'Click button at top right of the map to switch to 3d view', fill: 'Fill', enablePolygonHeight: 'Enable Polygon Height', showWireframe: 'Show Wireframe', weightIntensity: 'Weight Intensity', zoomScale: 'Zoom Scale', heightRange: 'Height Range', heightMultiplier: 'Height Multiplier' }, layerManager: { addData: 'Add Data', addLayer: 'Add Layer', layerBlending: 'Layer Blending' }, mapManager: { mapStyle: 'Map style', addMapStyle: 'Add Map Style', '3dBuildingColor': '3D Building Color' }, layerConfiguration: { defaultDescription: 'Calculate {property} based on selected field', howTo: 'How to' }, filterManager: { addFilter: 'Add Filter' }, datasetTitle: { showDataTable: 'Show data table', removeDataset: 'Remove dataset' }, datasetInfo: { rowCount: '{rowCount} rows' }, tooltip: { hideLayer: 'hide layer', showLayer: 'show layer', hideFeature: 'Hide Feature', showFeature: 'Show feature', hide: 'hide', show: 'show', removeLayer: 'Remove layer', duplicateLayer: 'Duplicate layer', layerSettings: 'Layer settings', closePanel: 'Close current panel', switchToDualView: 'Switch to dual map view', showLegend: 'Show legend', disable3DMap: 'Disable 3D Map', DrawOnMap: 'Draw on map', selectLocale: 'Select locale', hideLayerPanel: 'Hide layer panel', showLayerPanel: 'Show layer panel', moveToTop: 'Move to top of data layers', selectBaseMapStyle: 'Select Base Map Style', delete: 'Delete', timePlayback: 'Time Playback', cloudStorage: 'Cloud Storage', '3DMap': '3D Map', animationByWindow: 'Moving Time Window', animationByIncremental: 'Incremental Time Window', speed: 'speed', play: 'play', pause: 'pause', reset: 'reset' }, toolbar: { exportImage: 'Export Image', exportData: 'Export Data', exportMap: 'Export Map', shareMapURL: 'Share Map URL', saveMap: 'Save Map', select: 'Select', polygon: 'Polygon', rectangle: 'Rectangle', hide: 'Hide', show: 'Show', ...LOCALES }, editor: { filterLayer: 'Filter Layers', copyGeometry: 'Copy Geometry' }, modal: { title: { deleteDataset: 'Delete Dataset', addDataToMap: 'Add Data To Map', exportImage: 'Export Image', exportData: 'Export Data', exportMap: 'Export Map', addCustomMapboxStyle: 'Add Custom Map Style', saveMap: 'Save Map', shareURL: 'Share URL' }, button: { delete: 'Delete', download: 'Download', export: 'Export', addStyle: 'Add Style', save: 'Save', defaultCancel: 'Cancel', defaultConfirm: 'Confirm' }, exportImage: { ratioTitle: 'Ratio', ratioDescription: 'Choose the ratio for various usages.', ratioOriginalScreen: 'Original Screen', ratioCustom: 'Custom', ratio4_3: '4:3', ratio16_9: '16:9', resolutionTitle: 'Resolution', resolutionDescription: 'High resolution is better for prints.', mapLegendTitle: 'Map Legend', mapLegendAdd: 'Add legend on map' }, exportData: { datasetTitle: 'Dataset', datasetSubtitle: 'Choose the datasets you want to export', allDatasets: 'All', dataTypeTitle: 'Data Type', dataTypeSubtitle: 'Choose the type of data you want to export', filterDataTitle: 'Filter Data', filterDataSubtitle: 'You can choose exporting original data or filtered data', filteredData: 'Filtered data', unfilteredData: 'Unfiltered Data', fileCount: '{fileCount} Files', rowCount: '{rowCount} Rows' }, deleteData: { warning: 'you are going to delete this dataset. It will affect {length} layers' }, addStyle: { publishTitle: '2. If entered mapbox style url in step.1, publish your style at mapbox or provide access token. (Optional)', publishSubtitle1: 'You can create your own map style at', publishSubtitle2: 'and', publishSubtitle3: 'publish', publishSubtitle4: 'it.', publishSubtitle5: 'To use private style, paste your', publishSubtitle6: 'access token', publishSubtitle7: 'here. *kepler.gl is a client-side application, data stays in your browser..', exampleToken: 'e.g. pk.abcdefg.xxxxxx', pasteTitle: '1. Paste style url', pasteSubtitle0: 'Style url can be a mapbox', pasteSubtitle1: 'What is a', pasteSubtitle2: 'style URL', pasteSubtitle3: 'or a style.json using the', pasteSubtitle4: 'Mapbox GL Style Spec', namingTitle: '3. Name your style' }, shareMap: { shareUriTitle: 'Share Map Url', shareUriSubtitle: 'Generate a map url to share with others', cloudTitle: 'Cloud storage', cloudSubtitle: 'Login and upload map data to your personal cloud storage', shareDisclaimer: 'kepler.gl will save your map data to your personal cloud storage, only people with the URL can access your map and data. ' + 'You can edit/delete the data file in your cloud account anytime.', gotoPage: 'Go to your Kepler.gl {currentProvider} page' }, statusPanel: { mapUploading: 'Map Uploading', error: 'Error' }, saveMap: { title: 'Cloud storage', subtitle: 'Login to save map to your personal cloud storage' }, exportMap: { formatTitle: 'Map format', formatSubtitle: 'Choose the format to export your map to', html: { selection: 'Export your map into an interactive html file.', tokenTitle: 'Mapbox access token', tokenSubtitle: 'Use your own Mapbox access token in the html (optional)', tokenPlaceholder: 'Paste your Mapbox access token', tokenMisuseWarning: '* If you do not provide your own token, the map may fail to display at any time when we replace ours to avoid misuse. ', tokenDisclaimer: 'You can change the Mapbox token later using the following instructions: ', tokenUpdate: 'How to update an existing map token.', modeTitle: 'Map Mode', modeSubtitle1: 'Select the app mode. More ', modeSubtitle2: 'info', modeDescription: 'Allow users to {mode} the map', read: 'read', edit: 'edit' }, json: { configTitle: 'Map Config', configDisclaimer: 'Map config will be included in the Json file. If you are using kepler.gl in your own app. You can copy this config and pass it to ', selection: 'Export current map data and config into a single Json file. You can later open the same map by uploading this file to kepler.gl.', disclaimer: '* Map config is coupled with loaded datasets. ‘dataId’ is used to bind layers, filters, and tooltips to a specific dataset. ' + 'When passing this config to addDataToMap, make sure the dataset id matches the dataId/s in this config.' } }, loadingDialog: { loading: 'Loading...' }, loadData: { upload: 'Load Files', storage: 'Load from Storage' }, tripInfo: { title: 'How to enable trip animation', description1: 'In order to animate the path, the geoJSON data needs to contain `LineString` in its feature geometry, and the coordinates in the LineString need to have 4 elements in the formats of', code: ' [longitude, latitude, altitude, timestamp] ', description2: 'with the last element being a timestamp. Valid timestamp formats include unix in seconds such as `1564184363` or in milliseconds such as `1564184363000`.', example: 'Example:' }, iconInfo: { title: 'How to draw icons', description1: 'In your csv, create a column, put the name of the icon you want to draw in it. You can leave the cell empty if you do not want the icon to show for some points. When the column is named', code: 'icon', description2: ' kepler.gl will automatically create a icon layer for you.', example: 'Example:', icons: 'Icons' }, storageMapViewer: { lastModified: 'Last modified {lastUpdated} ago', back: 'Back' }, overwriteMap: { title: 'Saving map...', alreadyExists: 'already exists in your {mapSaved}. Would you like to overwrite it?' }, loadStorageMap: { back: 'Back', goToPage: 'Go to your Kepler.gl {displayName} page', storageMaps: 'Storage / Maps', noSavedMaps: 'No saved maps yet' } }, header: { visibleLayers: 'Visible layers', layerLegend: 'Legend' }, interactions: { tooltip: 'Tooltip', brush: 'Brush', coordinate: 'Coordinates', geocoder: 'Geocoder' }, layerBlending: { title: 'Layer Blending', additive: 'additive', normal: 'normal', subtractive: 'subtractive' }, columns: { title: 'Columns', lat: 'lat', lng: 'lon', altitude: 'altitude', icon: 'icon', geojson: 'geojson', token: 'token', arc: { lat0: 'source lat', lng0: 'source lng', lat1: 'target lat', lng1: 'target lng' }, line: { alt0: 'source altitude', alt1: 'target altitude' }, grid: { worldUnitSize: 'Grid Size (km)' }, hexagon: { worldUnitSize: 'Hexagon Radius (km)' }, hex_id: 'hex id' }, color: { customPalette: 'Custom Palette', steps: 'steps', type: 'type', reversed: 'reversed' }, scale: { colorScale: 'Color Scale', sizeScale: 'Size Scale', strokeScale: 'Stroke Scale', scale: 'Scale' }, fileUploader: { message: 'Drag & Drop Your File(s) Here', chromeMessage: '*Chrome user: Limit file size to 250mb, if need to upload larger file, try Safari', disclaimer: '*kepler.gl is a client-side application with no server backend. Data lives only on your machine/browser. ' + 'No information or map data is sent to any server.', configUploadMessage: 'Upload {fileFormatNames} or saved map **Json**. Read more about [**supported file formats**]', browseFiles: 'browse your files', uploading: 'Uploading', fileNotSupported: 'File {errorFiles} is not supported.', or: 'or' }, geocoder: { title: 'Enter an address or coordinates, ex 37.79,-122.40' }, fieldSelector: { clearAll: 'Clear All', formatting: 'Formatting' }, compare: { modeLabel: 'Comparison Mode', typeLabel: 'Comparison Type', types: { absolute: 'Absolute', relative: 'Relative' } }, mapPopover: { primary: 'Primary' }, density: 'density', 'Bug Report': 'Bug Report', 'User Guide': 'User Guide', Save: 'Save', Share: 'Share' };
the_stack
import { fileExists } from 'common-utils/file.js'; import * as fs from 'fs-extra'; import { homedir } from 'os'; import * as vscode from 'vscode'; import { Uri } from 'vscode'; import { Utils as UriUtils } from 'vscode-uri'; import { CSpellClient } from '../client'; import { getCSpellDiags } from '../diags'; import type { CSpellUserSettings, CustomDictionaries, CustomDictionary, CustomDictionaryEntry, CustomDictionaryScope, DictionaryDefinitionCustom, } from '../client'; import { scrollToText } from '../util/textEditor'; import { ClientConfigTarget } from './clientConfigTarget'; import { ConfigFields } from './configFields'; import { ConfigRepository, CSpellConfigRepository, VSCodeRepository } from './configRepository'; import { dictionaryTargetBestMatches, MatchTargetsFn } from './configTargetHelper'; import { configUpdaterForKeys } from './configUpdater'; import { cspellConfigDirectory, normalizeWords } from './CSpellSettings'; import { createDictionaryTargetForConfigRep, DictionaryTarget } from './DictionaryTarget'; import { configTargetsToDictionaryTargets } from './DictionaryTargetHelper'; import { mapConfigTargetToClientConfigTarget } from './mappers/configTarget'; import { configurationTargetToDictionaryScope } from './targetAndScope'; const defaultCustomDictionaryName = 'custom-dictionary'; const dictionaryTemplate = '# Custom Dictionary Words\n'; export class DictionaryHelper { constructor(public client: CSpellClient) {} /** * Add word or words to the configuration * @param words - a single word or multiple words separated with a space or an array of words. * @param target - where the word should be written: ClientConfigTarget or a matching function. * @param docUri - the related document (helps to determine the configuration location) * @returns the promise resolves upon completion. */ public async addWordsToTargets( words: string | string[], target: ClientConfigTarget[] | MatchTargetsFn, docUri: Uri | undefined ): Promise<void> { const cfgTarget = await this.resolveTargets(target, docUri); if (!cfgTarget) return; return this.addWordToDictionaries(words, cfgTarget); } /** * Add words to the configuration * @param words - a single word or multiple words separated with a space or an array of words. * @param rep - configuration to add the words to * @returns */ public addWordsToConfigRep(words: string | string[], rep: ConfigRepository): Promise<void> { const dict = createDictionaryTargetForConfigRep(rep); return this.addWordToDictionary(words, dict); } /** * Add words to a dictionary (configuration or dictionary file) * @param words - a single word or multiple words separated with a space or an array of words. * @param dictTarget - where to add the words */ public addWordToDictionaries(words: string | string[], dictTarget: DictionaryTarget[]): Promise<void> { const all = Promise.all(dictTarget.map((t) => this.addWordToDictionary(words, t))); return all.then(); } /** * Add words to a dictionary (configuration or dictionary file) * @param words - a single word or multiple words separated with a space or an array of words. * @param dictTarget - where to add the words */ public async addWordToDictionary(words: string | string[], dictTarget: DictionaryTarget): Promise<void> { words = normalizeWords(words); try { await dictTarget.addWords(words); } catch (e) { throw new UnableToAddWordError(`Unable to add "${words}"`, dictTarget, words, e); } } /** * Remove word or words from the configuration * @param words - a single word or multiple words separated with a space or an array of words. * @param target - where the word should be written: ClientConfigTarget or a matching function. * @param docUri - the related document (helps to determine the configuration location) * @returns the promise resolves upon completion. */ public async removeWordsFromTargets( words: string | string[], target: ClientConfigTarget[] | MatchTargetsFn, docUri: Uri | undefined ): Promise<void> { words = normalizeWords(words); const dictTarget = await this.resolveTargets(target, docUri); if (!dictTarget) return; return this.removeWordFromDictionaries(words, dictTarget); } /** * Remove words from the configuration * @param words - a single word or multiple words separated with a space or an array of words. * @param rep - configuration to add the words to * @returns the promise resolves upon completion. */ public removeWordsFromConfigRep(words: string | string[], rep: ConfigRepository): Promise<void> { const dict = createDictionaryTargetForConfigRep(rep); return this.removeWordFromDictionary(words, dict); } /** * Remove words from a dictionary file or configuration * @param words - a single word or multiple words separated with a space or an array of words. * @param dictTargets - where to remove the words * @returns the promise resolves upon completion. */ public removeWordFromDictionaries(words: string | string[], dictTargets: DictionaryTarget[]): Promise<void> { const all = Promise.all(dictTargets.map((t) => this.removeWordFromDictionary(words, t))); return all.then(); } /** * Remove words from a dictionary file or configuration * @param words - a single word or multiple words separated with a space or an array of words. * @param dictTarget - where to remove the words * @returns the promise resolves upon completion. */ public async removeWordFromDictionary(words: string | string[], dictTarget: DictionaryTarget): Promise<void> { words = normalizeWords(words); try { await dictTarget.removeWords(words); } catch (e) { throw new DictionaryTargetError(`Unable to remove "${words}" from "${dictTarget.name}"`, dictTarget, e); } } /** * Add issues in the current document to the best location * @param source - optional source where that has issues defaults to the current open document. * @returns resolves when finished. */ public async addIssuesToDictionary(source?: vscode.TextDocument | vscode.Uri): Promise<void> { source = source || vscode.window.activeTextEditor?.document; if (!source) return; const doc = isTextDocument(source) ? source : await vscode.workspace.openTextDocument(source); const diags = getCSpellDiags(doc.uri); if (!diags.length) return; const words = new Set(diags.map((d) => doc.getText(d.range))); return this.addWordsToTargets([...words], dictionaryTargetBestMatches, doc.uri); } /** * createCustomDictionary */ public async createCustomDictionary(cfgRep: ConfigRepository, name?: string): Promise<void> { const dictInfo = await createCustomDictionaryForConfigRep(cfgRep); if (!dictInfo) throw new Error('Unable to determine location to create dictionary.'); await this.addCustomDictionaryToConfig(cfgRep, dictInfo.relPath, name || dictInfo.name, dictInfo.scope); if (CSpellConfigRepository.isCSpellConfigRepository(cfgRep)) { const editor = await vscode.window.showTextDocument(cfgRep.configFileUri, { viewColumn: vscode.ViewColumn.Active }); scrollToText(editor, 'dictionaryDefinitions'); } await vscode.window.showTextDocument(dictInfo.uri, { viewColumn: vscode.ViewColumn.Beside }); } /** * addCustomDictionaryToConfig */ public addCustomDictionaryToConfig( cfgRep: ConfigRepository, relativePathToDictionary: string, name: string, scope?: CustomDictionaryScope ): Promise<void> { const def: DictionaryDefinitionCustom = { name, path: relativePathToDictionary, addWords: true, scope: scope ?? cfgRep.defaultDictionaryScope, }; return addCustomDictionaryToConfig(cfgRep, def); } private async getDocConfig(uri: Uri | undefined) { if (uri) { const doc = await vscode.workspace.openTextDocument(uri); return this.client.getConfigurationForDocument(doc); } return this.client.getConfigurationForDocument(undefined); } private async resolveTargets( target: ClientConfigTarget[] | MatchTargetsFn, docUri: Uri | undefined ): Promise<DictionaryTarget[] | undefined> { if (typeof target !== 'function') return configTargetsToDictionaryTargets(target); const docConfig = await this.getDocConfig(docUri); const targets = docConfig.configTargets.map(mapConfigTargetToClientConfigTarget); const cfgTarget = await target(targets); return cfgTarget && configTargetsToDictionaryTargets(cfgTarget); } } function isTextDocument(d: vscode.TextDocument | vscode.Uri): d is vscode.TextDocument { return !!(<vscode.TextDocument>d).uri; } interface DictInfo { uri: Uri; relPath: string; name: string; scope: CustomDictionaryScope | undefined; } async function createCustomDictionaryForConfigRep(configRep: ConfigRepository): Promise<DictInfo | undefined> { const dictInfo = calcDictInfoForConfigRep(configRep); if (!dictInfo) return; await createCustomDictionaryFile(dictInfo.uri); return dictInfo; } function calcDictInfoForConfigRep(configRep: ConfigRepository): DictInfo | undefined { const dictInfo = CSpellConfigRepository.isCSpellConfigRepository(configRep) ? calcDictInfoForConfigRepCSpell(configRep) : VSCodeRepository.isVSCodeRepository(configRep) ? calcDictInfoForConfigRepVSCode(configRep) : undefined; return dictInfo; } function calcDictInfoForConfigRepCSpell(cfgRep: CSpellConfigRepository): DictInfo | undefined { const scope = cfgRep.defaultDictionaryScope; const name = scopeToName(scope); const dir = UriUtils.dirname(cfgRep.configFileUri); const path = `${cspellConfigDirectory}/${name}.txt`; const dictUri = Uri.joinPath(dir, path); const relPath = './' + path; return { uri: dictUri, relPath, name, scope }; } function calcDictInfoForConfigRepVSCode(configRep: VSCodeRepository): DictInfo | undefined { const scope = configurationTargetToDictionaryScope(configRep.target); if (configRep.target === vscode.ConfigurationTarget.Global) { const name = scopeToName(scope); const path = `${cspellConfigDirectory}/${name}.txt`; const dir = Uri.file(homedir()); const uri = Uri.joinPath(dir, path); const relPath = '~/' + path; return { uri, relPath, name, scope }; } const folder = configRep.getWorkspaceFolder(); if (!folder) return; const suffix = scope === 'folder' ? '-' + cleanFolderName(folder.name) : ''; const name = scopeToName(configurationTargetToDictionaryScope(configRep.target)) + suffix; const path = `${cspellConfigDirectory}/${name}.txt`; const uri = Uri.joinPath(folder.uri, path); const relPath = `\${workspaceFolder:${folder.name}}/${path}`; return { uri, relPath, name, scope }; } function scopeToName(scope: CustomDictionaryScope | undefined): string { return scope ? `${defaultCustomDictionaryName}-${scope}` : defaultCustomDictionaryName; } function cleanFolderName(name: string): string { return name.toLowerCase().replace(/[^\w]/g, '-'); } async function createCustomDictionaryFile(dictUri: Uri, overwrite = false): Promise<void> { overwrite = overwrite || !(await fileExists(dictUri)); if (!overwrite) return; await fs.mkdirp(UriUtils.dirname(dictUri).fsPath); await fs.writeFile(dictUri.fsPath, dictionaryTemplate, 'utf8'); } async function addCustomDictionaryToConfig(cfgRep: ConfigRepository, def: DictionaryDefinitionCustom): Promise<void> { const updater = CSpellConfigRepository.isCSpellConfigRepository(cfgRep) ? updaterForCustomDictionaryToConfigCSpell(def) : VSCodeRepository.isVSCodeRepository(cfgRep) ? updaterForCustomDictionaryToConfigVSCode(def) : undefined; if (!updater) throw Error(`Unsupported config ${cfgRep.kind}`); return cfgRep.update(updater); } function updaterForCustomDictionaryToConfigCSpell(def: DictionaryDefinitionCustom) { const name = def.name; return configUpdaterForKeys([ConfigFields.dictionaries, ConfigFields.dictionaryDefinitions], (cfg) => { const { dictionaries = [], dictionaryDefinitions = [] } = cfg; const defsByName = new Map(dictionaryDefinitions.map((d) => [d.name, d])); const dictNames = new Set(dictionaries); defsByName.set(name, def); dictNames.add(name); return { dictionaries: [...dictNames], dictionaryDefinitions: [...defsByName.values()], }; }); } function updaterForCustomDictionaryToConfigVSCode(def: DictionaryDefinitionCustom) { const name = def.name; return configUpdaterForKeys( [ ConfigFields.customDictionaries, ConfigFields.customFolderDictionaries, ConfigFields.customWorkspaceDictionaries, ConfigFields.customUserDictionaries, ], (cfg) => { const { customDictionaries, ...rest } = combineCustomDictionaries(cfg); customDictionaries[name] = def; return { ...rest, customDictionaries, }; } ); } interface CombineCustomDictionariesResult extends Required<Pick<CSpellUserSettings, 'customDictionaries'>> { customFolderDictionaries: undefined; customWorkspaceDictionaries: undefined; customUserDictionaries: undefined; } function combineCustomDictionaries(s: CSpellUserSettings): CombineCustomDictionariesResult { const { customDictionaries = {}, customFolderDictionaries = [], customWorkspaceDictionaries = [], customUserDictionaries = [] } = s; const cdLegacy = [ customUserDictionaries.map(mapScopeToCustomDictionaryEntry('user')), customWorkspaceDictionaries.map(mapScopeToCustomDictionaryEntry('workspace')), customFolderDictionaries.map(mapScopeToCustomDictionaryEntry('folder')), ].reduce(combineDictionaryEntries, customDictionaries); return { customDictionaries: { ...cdLegacy, ...customDictionaries }, customFolderDictionaries: undefined, customWorkspaceDictionaries: undefined, customUserDictionaries: undefined, }; } function mapScopeToCustomDictionaryEntry(scope: CustomDictionary['scope']): (c: CustomDictionaryEntry) => CustomDictionaryEntry { return (c: CustomDictionaryEntry) => { if (typeof c === 'string') return c; return { ...c, scope: c.scope || scope }; }; } function combineDictionaryEntries(c: CustomDictionaries, entries: CustomDictionaryEntry[]): CustomDictionaries { return entries.reduce(combineDictionaryEntry, c); } function combineDictionaryEntry(c: CustomDictionaries, entry: CustomDictionaryEntry): CustomDictionaries { const r = { ...c }; if (typeof entry === 'string') { r[entry] = true; } else { r[entry.name] = entry; } return r; } export class DictionaryTargetError extends Error { constructor(msg: string, readonly dictTarget: DictionaryTarget, readonly cause: Error | unknown) { super(msg); } } export class UnableToAddWordError extends DictionaryTargetError { constructor(msg: string, dictTarget: DictionaryTarget, readonly words: string | string[], readonly cause: Error | unknown) { super(msg, dictTarget, cause); } } export const __testing__ = { addCustomDictionaryToConfig, calcDictInfoForConfigRep, combineCustomDictionaries, createCustomDictionaryFile, createCustomDictionaryForConfigRep, isTextDocument, };
the_stack
import { defaultAPIMocks, MOCK_TEAM_ID, mockAPI } from 'lib/api.mock' import { expectLogic, partial } from 'kea-test-utils' import { initKeaTests } from '~/test/init' import { insightLogic } from './insightLogic' import { AvailableFeature, InsightShortId, InsightType, ItemMode, PropertyOperator } from '~/types' import { eventUsageLogic } from 'lib/utils/eventUsageLogic' import { combineUrl, router } from 'kea-router' import { dashboardLogic } from 'scenes/dashboard/dashboardLogic' import { cleanFilters } from 'scenes/insights/utils/cleanFilters' import { savedInsightsLogic } from 'scenes/saved-insights/savedInsightsLogic' import { urls } from 'scenes/urls' import * as Sentry from '@sentry/browser' jest.mock('lib/api') jest.mock('@sentry/browser') const API_FILTERS = { insight: InsightType.TRENDS as InsightType, events: [{ id: 3 }], properties: [{ value: 'a', operator: PropertyOperator.Exact, key: 'a', type: 'a' }], } const Insight12 = '12' as InsightShortId const Insight42 = '42' as InsightShortId const Insight43 = '43' as InsightShortId const Insight44 = '44' as InsightShortId const Insight500 = '500' as InsightShortId describe('insightLogic', () => { let logic: ReturnType<typeof insightLogic.build> beforeEach(initKeaTests) mockAPI(async (url) => { const { pathname, searchParams, method, data } = url const throwAPIError = (): void => { throw { status: 0, statusText: 'error from the API' } } if ( [ `api/projects/${MOCK_TEAM_ID}/insights`, `api/projects/${MOCK_TEAM_ID}/insights/42`, `api/projects/${MOCK_TEAM_ID}/insights/43`, `api/projects/${MOCK_TEAM_ID}/insights/44`, ].includes(pathname) ) { return { result: pathname.endsWith('42') ? ['result from api'] : null, id: pathname.endsWith('42') ? 42 : 43, short_id: pathname.endsWith('42') ? Insight42 : Insight43, filters: data?.filters || API_FILTERS, } } else if (pathname === 'api/projects/997/insights/' && url.searchParams.short_id) { if (url.searchParams.short_id === 500) { throwAPIError() } return { results: [ { result: parseInt(url.searchParams.short_id) === 42 ? ['result from api'] : null, id: parseInt(url.searchParams.short_id), short_id: url.searchParams.short_id.toString(), filters: data?.filters || API_FILTERS, }, ], } } else if ([`api/projects/${MOCK_TEAM_ID}/dashboards/33/`].includes(pathname)) { return { id: 33, filters: {}, items: [ { id: 42, short_id: Insight42, result: 'result!', filters: { insight: InsightType.TRENDS, interval: 'month' }, tags: ['bla'], }, ], } } else if ([`api/projects/${MOCK_TEAM_ID}/insights/500`].includes(pathname)) { throwAPIError() } else if (pathname === 'api/projects/997/insights/' && url.searchParams.saved) { return { results: [ { id: 42, short_id: Insight42, result: ['result 42'], filters: API_FILTERS }, { id: 43, short_id: Insight43, result: ['result 43'], filters: API_FILTERS }, ], } } else if (method === 'create' && pathname === `api/projects/${MOCK_TEAM_ID}/insights/`) { return { id: 12, short_id: Insight12, name: data?.name } } else if ( [ `api/projects/${MOCK_TEAM_ID}/insights`, `api/projects/${MOCK_TEAM_ID}/insights/session/`, `api/projects/${MOCK_TEAM_ID}/insights/trend/`, `api/projects/${MOCK_TEAM_ID}/insights/path/`, `api/projects/${MOCK_TEAM_ID}/insights/path`, `api/projects/${MOCK_TEAM_ID}/insights/funnel/`, `api/projects/${MOCK_TEAM_ID}/insights/retention/`, ].includes(pathname) ) { if (searchParams?.events?.[0]?.throw) { throwAPIError() } return { result: ['result from api'] } } return defaultAPIMocks(url, { availableFeatures: [AvailableFeature.DASHBOARD_COLLABORATION] }) }) it('requires props', () => { expect(() => { insightLogic() }).toThrow('Must init with dashboardItemId, even if undefined') }) describe('when there is no props id', () => { it('has the key set to "new"', () => { logic = insightLogic({ dashboardItemId: undefined, }) expect(logic.key).toEqual('new') }) }) describe('insight legend', () => { it('toggles insight legend', () => { logic = insightLogic({ dashboardItemId: undefined, filters: { legend_hidden: false }, }) expectLogic(logic, () => { logic.actions.toggleInsightLegend() }) .toDispatchActions(['toggleInsightLegend', 'setFilter']) .toMatchValues({ filters: partial({ legend_hidden: true }), }) }) }) describe('analytics', () => { it('reports insight changes on setFilter', async () => { logic = insightLogic({ dashboardItemId: undefined, filters: { insight: InsightType.TRENDS }, }) logic.mount() await expectLogic(logic, () => { logic.actions.setFilters({ insight: InsightType.FUNNELS }) }).toDispatchActions([ eventUsageLogic.actionCreators.reportInsightViewed( { insight: InsightType.FUNNELS }, ItemMode.View, true, false, 0, { changed_insight: InsightType.TRENDS, } ), ]) }) }) describe('as dashboard item', () => { describe('props with filters and cached results', () => { beforeEach(() => { logic = insightLogic({ dashboardItemId: Insight42, cachedResults: ['cached result'], filters: { insight: InsightType.TRENDS, events: [{ id: 2 }], properties: [{ value: 'lol', operator: PropertyOperator.Exact, key: 'lol', type: 'lol' }], }, }) logic.mount() }) it('has the key set to the id', () => { expect(logic.key).toEqual('42') }) it('no query to load results', async () => { await expectLogic(logic) .toMatchValues({ insight: partial({ short_id: Insight42, result: ['cached result'] }), filters: partial({ events: [{ id: 2 }], properties: [partial({ type: 'lol' })], }), }) .toNotHaveDispatchedActions(['loadResultsSuccess']) // this took the cached results }) }) describe('props with filters, no cached results', () => { it('makes a query to load the results', async () => { logic = insightLogic({ dashboardItemId: Insight42, cachedResults: undefined, filters: { insight: InsightType.TRENDS, events: [{ id: 3 }], properties: [{ value: 'a', operator: PropertyOperator.Exact, key: 'a', type: 'a' }], }, }) logic.mount() await expectLogic(logic) .toDispatchActions(['loadResults', 'loadResultsSuccess']) .toMatchValues({ insight: partial({ short_id: Insight42, result: ['result from api'] }), filters: partial({ events: [{ id: 3 }], properties: [partial({ value: 'a' })], }), }) .delay(1) // do not override the insight if querying with different filters .toNotHaveDispatchedActions(['updateInsight', 'updateInsightSuccess']) }) }) describe('props with filters, no cached results, error from API', () => { it('makes a query to load the results', async () => { logic = insightLogic({ dashboardItemId: Insight42, cachedResults: undefined, filters: { insight: InsightType.TRENDS, events: [{ id: 3, throw: true }], properties: [{ value: 'a', operator: PropertyOperator.Exact, key: 'a', type: 'a' }], }, }) logic.mount() await expectLogic(logic) .toDispatchActions(['loadResults', 'loadResultsFailure']) .toMatchValues({ insight: partial({ short_id: Insight42, result: null }), filters: partial({ events: [partial({ id: 3 })], properties: [partial({ value: 'a' })], }), }) .delay(1) .toNotHaveDispatchedActions(['loadResults', 'setFilters', 'updateInsight']) }) }) describe('props with filters, no cached results, respects doNotLoad', () => { it('does not make a query', async () => { logic = insightLogic({ dashboardItemId: Insight42, cachedResults: undefined, filters: { insight: InsightType.TRENDS, events: [{ id: 3, throw: true }], properties: [{ value: 'a', operator: PropertyOperator.Exact, key: 'a', type: 'a' }], }, doNotLoad: true, }) logic.mount() await expectLogic(logic) .toMatchValues({ insight: partial({ short_id: Insight42, result: null }), filters: partial({ events: [partial({ id: 3 })], properties: [partial({ value: 'a' })], }), }) .delay(1) .toNotHaveDispatchedActions(['loadResults', 'setFilters', 'updateInsight']) }) }) describe('props with no filters, no cached results, results from API', () => { it('makes a query to load the results', async () => { logic = insightLogic({ dashboardItemId: Insight42, cachedResults: undefined, filters: undefined, }) logic.mount() await expectLogic(logic) .toDispatchActions(['loadInsight', 'loadInsightSuccess']) .toMatchValues({ insight: partial({ short_id: Insight42, result: ['result from api'] }), filters: partial({ events: [{ id: 3 }], properties: [partial({ value: 'a' })], }), }) .toNotHaveDispatchedActions(['loadResults']) // does not fetch results as there was no filter }) }) describe('props with no filters, no cached results, no results from API', () => { it('makes a query to load the results', async () => { logic = insightLogic({ dashboardItemId: Insight43, // 43 --> result: null cachedResults: undefined, filters: undefined, }) logic.mount() await expectLogic(logic) .toDispatchActions(['loadInsight', 'loadInsightSuccess']) .toMatchValues({ insight: partial({ id: 43, result: null }), filters: partial({ events: [{ id: 3 }], properties: [partial({ value: 'a' })], }), }) .toDispatchActions(['loadResults', 'loadResultsSuccess']) .toMatchValues({ insight: partial({ id: 43, result: ['result from api'] }), filters: partial({ events: [{ id: 3 }], properties: [partial({ value: 'a' })], }), }) }) }) describe('props with no filters, no cached results, API throws', () => { it('makes a query to load the results', async () => { logic = insightLogic({ dashboardItemId: Insight500, // 500 --> result: throws cachedResults: undefined, filters: undefined, }) logic.mount() await expectLogic(logic) .toDispatchActions(['loadInsight', 'loadInsightFailure']) .toMatchValues({ insight: partial({ short_id: '500', result: null, filters: {} }), filters: {}, }) .delay(1) .toNotHaveDispatchedActions(['loadResults', 'setFilters', 'updateInsight']) }) }) }) describe('syncWithUrl: true persists state in the URL', () => { beforeEach(async () => { logic = insightLogic({ syncWithUrl: true, dashboardItemId: Insight44, }) logic.mount() await expectLogic(logic).toFinishAllListeners().clearHistory() }) it('redirects when opening /insight/new', async () => { router.actions.push(urls.insightEdit(Insight42)) await expectLogic(router) .delay(1) .toMatchValues({ location: partial({ pathname: urls.insightEdit(Insight42) }), searchParams: partial({ insight: 'TRENDS' }), }) router.actions.push(urls.insightNew({ insight: InsightType.FUNNELS })) await expectLogic(router) .delay(1) .toMatchValues({ location: partial({ pathname: urls.insightEdit(Insight43) }), searchParams: partial({ insight: 'FUNNELS' }), }) }) it('sets filters from the URL', async () => { const url = urls.insightEdit(Insight44, { insight: InsightType.TRENDS, interval: 'minute' }) router.actions.push(url) await expectLogic(logic) .toDispatchActions([router.actionCreators.push(url), 'setFilters']) .toMatchValues({ filters: partial({ insight: InsightType.TRENDS, interval: 'minute' }), }) // setting the same URL twice doesn't call `setFilters` router.actions.push(url) await expectLogic(logic) .toDispatchActions([router.actionCreators.push(url)]) .toNotHaveDispatchedActions(['setFilters']) .toMatchValues({ filters: partial({ insight: InsightType.TRENDS, interval: 'minute' }), }) // calls when the values changed const url2 = urls.insightEdit(Insight44, { insight: InsightType.TRENDS, interval: 'week' }) router.actions.push(url2) await expectLogic(logic) .toDispatchActions([router.actionCreators.push(url2), 'setFilters']) .toMatchValues({ filters: partial({ insight: InsightType.TRENDS, interval: 'week' }), }) }) it('takes the dashboardItemId from the URL', async () => { const url = urls.insightView(Insight42, { insight: InsightType.TRENDS }) router.actions.push(url) await expectLogic(logic) .toDispatchActions([router.actionCreators.push(url), 'loadInsight', 'loadInsightSuccess']) .toNotHaveDispatchedActions(['loadResults']) .toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), insight: partial({ short_id: Insight42, result: ['result from api'] }), }) // changing the ID, does not query twice router.actions.push(urls.insightView(Insight43, { insight: InsightType.FUNNELS })) await expectLogic(logic) .toDispatchActions(['loadInsight', 'setFilters', 'loadResults', 'loadInsightSuccess']) .toMatchValues({ filters: partial({ insight: InsightType.FUNNELS }), insight: partial({ id: 43, result: null }), }) .toDispatchActions(['loadResultsSuccess']) .toMatchValues({ insight: partial({ id: 43, result: ['result from api'] }), }) }) it('sets the URL when changing filters', async () => { // make sure we're on the right page router.actions.push(urls.insightNew()) await expectLogic(router).toDispatchActions(['push', 'locationChanged', 'replace', 'locationChanged']) logic.actions.setFilters({ insight: InsightType.TRENDS, interval: 'minute' }) await expectLogic() .toDispatchActions(logic, [ logic.actionCreators.setFilters({ insight: InsightType.TRENDS, interval: 'minute' }), ]) .toDispatchActions(router, ['replace', 'locationChanged']) .toMatchValues(router, { searchParams: partial({ interval: 'minute' }) }) // no change in filters, doesn't change the URL logic.actions.setFilters({ insight: InsightType.TRENDS, interval: 'minute' }) await expectLogic() .toDispatchActions(logic, [ logic.actionCreators.setFilters({ insight: InsightType.TRENDS, interval: 'minute' }), ]) .toNotHaveDispatchedActions(router, ['replace', 'locationChanged']) .toMatchValues(router, { searchParams: partial({ interval: 'minute' }) }) logic.actions.setFilters({ insight: InsightType.TRENDS, interval: 'month' }) await expectLogic(router) .toDispatchActions(['replace', 'locationChanged']) .toMatchValues({ searchParams: partial({ insight: InsightType.TRENDS, interval: 'month' }), }) }) it('persists edit mode in the url', async () => { const viewUrl = combineUrl(urls.insightView(Insight42, cleanFilters({ insight: InsightType.TRENDS }))) const editUrl = combineUrl(urls.insightEdit(Insight42, cleanFilters({ insight: InsightType.TRENDS }))) router.actions.push(viewUrl.url) await expectLogic(logic) .toNotHaveDispatchedActions(['setInsightMode']) .toDispatchActions(['loadInsightSuccess']) .toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), insight: partial({ short_id: Insight42, result: ['result from api'] }), insightMode: ItemMode.View, }) router.actions.push(editUrl.url) await expectLogic(logic) .toDispatchActions([ ({ type, payload }) => type === logic.actionTypes.setFilters && payload.insightMode === ItemMode.Edit, ]) .toMatchValues({ insightMode: ItemMode.Edit, }) logic.actions.setInsightMode(ItemMode.View, null) expectLogic(router).toMatchValues({ location: partial({ pathname: viewUrl.pathname, search: viewUrl.search, hash: viewUrl.hash }), }) logic.actions.setInsightMode(ItemMode.Edit, null) expectLogic(router).toMatchValues({ location: partial({ pathname: editUrl.pathname, search: editUrl.search, hash: editUrl.hash }), }) }) }) describe('takes data from other logics if available', () => { it('dashboardLogic', async () => { // 1. the URL must have the dashboard and insight IDs router.actions.push(urls.insightView(Insight42), {}, { fromDashboard: 33 }) // 2. the dashboard is mounted const dashLogic = dashboardLogic({ id: 33 }) dashLogic.mount() await expectLogic(dashLogic).toDispatchActions(['loadDashboardItemsSuccess']) // 3. mount the insight logic = insightLogic({ dashboardItemId: Insight42 }) logic.mount() // 4. verify it didn't make any API calls await expectLogic(logic) .toDispatchActions(['setInsight']) .toNotHaveDispatchedActions(['setFilters', 'loadResults', 'loadInsight', 'updateInsight']) .toMatchValues({ insight: partial({ id: 42, result: 'result!', filters: { insight: InsightType.TRENDS, interval: 'month' }, }), }) }) it('savedInsightLogic', async () => { // 1. open saved insights router.actions.push(urls.savedInsights(), {}, {}) savedInsightsLogic.mount() // 2. the insights are loaded await expectLogic(savedInsightsLogic).toDispatchActions(['loadInsights', 'loadInsightsSuccess']) // 3. mount the insight logic = insightLogic({ dashboardItemId: Insight42 }) logic.mount() // 4. verify it didn't make any API calls await expectLogic(logic) .toDispatchActions(['setInsight']) .toNotHaveDispatchedActions(['setFilters', 'loadResults', 'loadInsight', 'updateInsight']) .toMatchValues({ insight: partial({ id: 42, result: ['result 42'], filters: API_FILTERS, }), }) }) }) test('keeps saved filters', async () => { logic = insightLogic({ dashboardItemId: Insight42, filters: { insight: InsightType.FUNNELS }, }) logic.mount() // `setFilters` only changes `filters`, does not change `savedFilters` await expectLogic(logic, () => { logic.actions.setFilters({ insight: InsightType.TRENDS }) }).toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), savedFilters: partial({ insight: InsightType.FUNNELS }), filtersChanged: true, }) // results from search don't change anything await expectLogic(logic, () => { logic.actions.loadResultsSuccess({ short_id: Insight42, filters: { insight: InsightType.PATHS }, }) }).toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), savedFilters: partial({ insight: InsightType.FUNNELS }), filtersChanged: true, }) // results from API GET and POST calls change saved filters await expectLogic(logic, () => { logic.actions.loadInsightSuccess({ short_id: Insight42, filters: { insight: InsightType.PATHS }, }) }).toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), savedFilters: partial({ insight: InsightType.PATHS }), filtersChanged: true, }) await expectLogic(logic, () => { logic.actions.updateInsightSuccess({ short_id: Insight42, filters: { insight: InsightType.RETENTION }, }) }).toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), savedFilters: partial({ insight: InsightType.RETENTION }), filtersChanged: true, }) // saving persists the in-flight filters await expectLogic(logic, () => { logic.actions.setFilters(API_FILTERS) }).toFinishAllListeners() await expectLogic(logic).toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), loadedFilters: partial({ insight: InsightType.TRENDS }), savedFilters: partial({ insight: InsightType.RETENTION }), filtersChanged: true, }) await expectLogic(logic, () => { logic.actions.saveInsight() }).toFinishAllListeners() await expectLogic(logic).toMatchValues({ filters: partial({ insight: InsightType.TRENDS }), loadedFilters: partial({ insight: InsightType.TRENDS }), savedFilters: partial({ insight: InsightType.TRENDS }), filtersChanged: false, }) }) test('saveInsight and updateInsight reload the saved insights list', async () => { savedInsightsLogic.mount() logic = insightLogic({ dashboardItemId: Insight42, filters: { insight: InsightType.FUNNELS }, cachedResults: {}, }) logic.mount() logic.actions.saveInsight() await expectLogic(savedInsightsLogic).toDispatchActions(['loadInsights']) logic.actions.updateInsight({ filters: { insight: InsightType.FUNNELS } }) await expectLogic(savedInsightsLogic).toDispatchActions(['loadInsights']) }) test('save as new insight', async () => { const url = combineUrl('/insights/42', { insight: InsightType.FUNNELS }).url router.actions.push(url) savedInsightsLogic.mount() logic = insightLogic({ dashboardItemId: Insight42, filters: { insight: InsightType.FUNNELS }, syncWithUrl: true, }) logic.mount() await expectLogic(logic, () => { logic.actions.saveAsNamingSuccess('New Insight (copy)') }) .toDispatchActions(['setInsight']) .toDispatchActions(savedInsightsLogic, ['loadInsights']) .toMatchValues({ filters: partial({ insight: InsightType.FUNNELS }), insight: partial({ id: 12, short_id: Insight12, name: 'New Insight (copy)' }), filtersChanged: true, syncWithUrl: true, }) await expectLogic(router) .toDispatchActions(['push', 'locationChanged']) .toMatchValues({ location: partial({ pathname: '/insights/12/edit' }), }) }) test('will not save with empty filters', async () => { logic = insightLogic({ dashboardItemId: Insight42, filters: { insight: InsightType.FUNNELS }, }) logic.mount() logic.actions.setInsight({ id: 42, short_id: Insight42, filters: {} }, {}) logic.actions.saveInsight() expect(Sentry.captureException).toHaveBeenCalledWith( new Error('Will not override empty filters in saveInsight.'), expect.any(Object) ) }) })
the_stack
import { join, normalize } from '@angular-devkit/core'; import type { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; import { chain, noop } from '@angular-devkit/schematics'; import type { Linter } from 'eslint'; import type { TSLintRuleOptions } from 'tslint-to-eslint-config'; import { addESLintTargetToProject, createESLintConfigForProject, determineTargetProjectName, getProjectConfig, getWorkspacePath, isTSLintUsedInWorkspace, offsetFromRoot, readJsonInTree, removeTSLintJSONForProject, setESLintProjectBasedOnProjectType, updateJsonInTree, } from '../utils'; import { convertTSLintDisableCommentsForProject, createConvertToESLintConfig, } from './convert-to-eslint-config'; import type { Schema } from './schema'; import { ensureESLintPluginsAreInstalled, uninstallTSLintAndCodelyzer, updateArrPropAndRemoveDuplication, updateObjPropAndRemoveDuplication, } from './utils'; // eslint-disable-next-line @typescript-eslint/no-var-requires const eslintPlugin = require('@angular-eslint/eslint-plugin'); // eslint-disable-next-line @typescript-eslint/no-var-requires const eslintPluginTemplate = require('@angular-eslint/eslint-plugin-template'); const eslintPluginConfigBaseOriginal = eslintPlugin.configs.base; const eslintPluginConfigNgCliCompatOriginal = eslintPlugin.configs['ng-cli-compat']; const eslintPluginConfigNgCliCompatFormattingAddOnOriginal = eslintPlugin.configs['ng-cli-compat--formatting-add-on']; const eslintPluginTemplateConfigRecommendedOriginal = eslintPluginTemplate.configs.recommended; export default function convert(schema: Schema): Rule { return (tree: Tree) => { if (tree.exists('tsconfig.base.json')) { throw new Error( '\nError: Angular CLI v10.1.0 and later (and no `tsconfig.base.json`) is required in order to run this schematic. Please update your workspace and try again.\n', ); } const projectName = determineTargetProjectName(tree, schema.project); if (!projectName) { throw new Error( '\n' + ` Error: You must specify a project to convert because you have multiple projects in your angular.json E.g. npx ng g @angular-eslint/schematics:convert-tslint-to-eslint {{YOUR_PROJECT_NAME_GOES_HERE}} `.trim(), ); } const { root: projectRoot, projectType } = getProjectConfig( tree, projectName, ); // Default Angular CLI project at the root of the workspace const isRootAngularProject: boolean = projectRoot === ''; // May or may not exist yet depending on if this is the root project, or a later one from projects/ const rootESLintrcJsonPath = join( normalize(tree.root.path), '.eslintrc.json', ); // Already exists, will be converted const projectTSLintJsonPath = join(normalize(projectRoot), 'tslint.json'); return chain([ // Overwrite the "lint" target directly for the selected project in the angular.json addESLintTargetToProject(projectName, 'lint'), ensureRootESLintConfig(schema, tree, projectName, rootESLintrcJsonPath), convertTSLintDisableCommentsForProject(projectName), isRootAngularProject || schema.ignoreExistingTslintConfig ? noop() : removeExtendsFromProjectTSLintConfigBeforeConverting( tree, projectTSLintJsonPath, ), isRootAngularProject ? noop() : schema.ignoreExistingTslintConfig ? chain([ // Create the latest recommended ESLint config file for the project createESLintConfigForProject(projectName), // Delete the TSLint config file for the project removeTSLintJSONForProject(projectName), ]) : convertNonRootTSLintConfig( schema, projectRoot, projectType, projectTSLintJsonPath, rootESLintrcJsonPath, ), function cleanUpTSLintIfNoLongerInUse(tree) { if ( schema.removeTslintIfNoMoreTslintTargets && !isTSLintUsedInWorkspace(tree) ) { tree.delete(join(normalize(tree.root.path), 'tslint.json')); return chain([ /** * Update the default schematics collection to @angular-eslint so that future projects within * the same workspace will also use ESLint */ updateJsonInTree(getWorkspacePath(tree), (json) => { json.cli = json.cli || {}; json.cli.defaultCollection = '@angular-eslint/schematics'; return json; }), uninstallTSLintAndCodelyzer(), ]); } return undefined; }, ]); }; } /** * Because the Angular CLI supports multi-project workspaces we could be in a situation * where the user is converting a project which is not the standard one at the root of * the workspace, and they have not previously converted their root project (or it doesn't * exist because they generated their workspace with no default app and only use the projects/ * directory). * * We therefore need to ensure that, before we convert a specific project, we have a root level * .eslintrc.json available to us to extend from. */ function ensureRootESLintConfig( schema: Schema, tree: Tree, projectName: string, rootESLintrcJsonPath: string, ): Rule { const hasExistingRootESLintrcConfig = tree.exists(rootESLintrcJsonPath); if (hasExistingRootESLintrcConfig) { return noop(); } /** * When ignoreExistingTslintConfig is set, Do not perform a conversion of the root * TSLint config and instead switch the workspace directly to using the latest * recommended ESLint config. */ if (schema.ignoreExistingTslintConfig) { const workspaceJson = readJsonInTree(tree, getWorkspacePath(tree)); const prefix = workspaceJson.projects[projectName].prefix || 'app'; return updateJsonInTree(rootESLintrcJsonPath, () => ({ root: true, // Each additional project is linted independently ignorePatterns: ['projects/**/*'], overrides: [ { files: ['*.ts'], parserOptions: { project: ['tsconfig.json', 'e2e/tsconfig.json'], createDefaultProgram: true, }, extends: [ 'plugin:@angular-eslint/recommended', 'plugin:@angular-eslint/template/process-inline-templates', ], rules: { '@angular-eslint/component-selector': [ 'error', { prefix, style: 'kebab-case', type: 'element', }, ], '@angular-eslint/directive-selector': [ 'error', { prefix, style: 'camelCase', type: 'attribute', }, ], }, }, { files: ['*.html'], extends: ['plugin:@angular-eslint/template/recommended'], rules: {}, }, ], })); } return convertRootTSLintConfig(schema, 'tslint.json', rootESLintrcJsonPath); } function convertRootTSLintConfig( schema: Schema, rootTSLintJsonPath: string, rootESLintrcJsonPath: string, ): Rule { return async (tree, context) => { const rawRootTSLintJson = readJsonInTree(tree, rootTSLintJsonPath); const convertToESLintConfig = createConvertToESLintConfig(context); const convertedRoot = await convertToESLintConfig( 'tslint.json', rawRootTSLintJson, ); const convertedRootESLintConfig = convertedRoot.convertedESLintConfig; warnInCaseOfUnconvertedRules( context, rootTSLintJsonPath, convertedRoot.unconvertedTSLintRules, ); // We mutate these as part of the transformations, so make copies first const eslintPluginConfigBase = { ...eslintPluginConfigBaseOriginal }; const eslintPluginConfigNgCliCompat = { ...eslintPluginConfigNgCliCompatOriginal, }; const eslintPluginConfigNgCliCompatFormattingAddOn = { ...eslintPluginConfigNgCliCompatFormattingAddOnOriginal, }; const eslintPluginTemplateConfigRecommended = { ...eslintPluginTemplateConfigRecommendedOriginal, }; /** * Force these 2 rules to be defined in the user's .eslintrc.json by removing * them from the comparison config before deduping */ delete eslintPluginConfigNgCliCompat.rules[ '@angular-eslint/directive-selector' ]; delete eslintPluginConfigNgCliCompat.rules[ '@angular-eslint/component-selector' ]; removeUndesiredRulesFromConfig(convertedRootESLintConfig); adjustSomeRuleConfigs(convertedRootESLintConfig); handleFormattingRules(schema, context, convertedRootESLintConfig); /** * To avoid users' configs being bigger and more verbose than necessary, we perform some * deduplication against our underlying ng-cli-compat configuration that they will extend from. */ dedupePluginsAgainstConfigs(convertedRootESLintConfig, [ eslintPluginConfigBase, eslintPluginConfigNgCliCompat, eslintPluginConfigNgCliCompatFormattingAddOn, { plugins: [ '@angular-eslint/eslint-plugin', // this is another alias to consider when deduping '@angular-eslint/eslint-plugin-template', // will be handled in separate overrides block '@typescript-eslint/tslint', // see note on not depending on not wanting to depend on TSLint fallback ], }, ]); updateArrPropAndRemoveDuplication( convertedRootESLintConfig, { /** * For now, extending from these is too different to what the CLI ships with today, so * we remove them from the converted results. We should look to move towards extending * from these once we have more influence over the generated code. We don't want users * to have lint errors from OOTB generated code. */ extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', ], }, 'extends', true, ); dedupeRulesAgainstConfigs(convertedRootESLintConfig, [ eslintPluginConfigBase, eslintPluginConfigNgCliCompat, eslintPluginConfigNgCliCompatFormattingAddOn, ]); dedupeEnvAgainstConfigs(convertedRootESLintConfig, [ eslintPluginConfigBase, eslintPluginConfigNgCliCompat, eslintPluginConfigNgCliCompatFormattingAddOn, ]); const { codeRules, templateRules } = separateCodeAndTemplateRules( convertedRootESLintConfig, ); updateObjPropAndRemoveDuplication( { rules: templateRules }, eslintPluginTemplateConfigRecommended, 'rules', false, ); convertedRootESLintConfig.root = true; // Each additional project is linted independently convertedRootESLintConfig.ignorePatterns = ['projects/**/*']; convertedRootESLintConfig.overrides = [ { files: ['*.ts'], parserOptions: { project: ['tsconfig.json', 'e2e/tsconfig.json'], createDefaultProgram: true, }, extends: [ 'plugin:@angular-eslint/ng-cli-compat', 'plugin:@angular-eslint/ng-cli-compat--formatting-add-on', 'plugin:@angular-eslint/template/process-inline-templates', ...(convertedRootESLintConfig.extends || []), ], plugins: convertedRootESLintConfig.plugins || undefined, rules: codeRules, }, { files: ['*.html'], extends: ['plugin:@angular-eslint/template/recommended'], rules: templateRules, }, ]; // No longer relevant/required delete convertedRootESLintConfig.parser; delete convertedRootESLintConfig.parserOptions; // All applied in the .ts overrides block so should no longer be at the root of the config delete convertedRootESLintConfig.rules; delete convertedRootESLintConfig.plugins; delete convertedRootESLintConfig.extends; return chain([ ensureESLintPluginsAreInstalled( Array.from( new Set([ /** * These three plugins are needed for the ng-cli-compat config */ 'eslint-plugin-import', 'eslint-plugin-jsdoc', 'eslint-plugin-prefer-arrow', ...convertedRoot.ensureESLintPlugins, ]), ), ), // Create the .eslintrc.json file in the tree using the finalized config updateJsonInTree(rootESLintrcJsonPath, () => convertedRootESLintConfig), ]); }; } function convertNonRootTSLintConfig( schema: Schema, projectRoot: string, projectType: 'application' | 'library', projectTSLintJsonPath: string, rootESLintrcJsonPath: string, ): Rule { return async (tree, context) => { const rawProjectTSLintJson = readJsonInTree(tree, projectTSLintJsonPath); const rawRootESLintrcJson = readJsonInTree(tree, rootESLintrcJsonPath); const convertToESLintConfig = createConvertToESLintConfig(context); const convertedProject = await convertToESLintConfig( projectTSLintJsonPath, rawProjectTSLintJson, ); const convertedProjectESLintConfig = convertedProject.convertedESLintConfig; warnInCaseOfUnconvertedRules( context, projectTSLintJsonPath, convertedProject.unconvertedTSLintRules, ); // We mutate these as part of the transformations, so make copies first const eslintPluginConfigBase = { ...eslintPluginConfigBaseOriginal }; const eslintPluginConfigNgCliCompat = { ...eslintPluginConfigNgCliCompatOriginal, }; const eslintPluginConfigNgCliCompatFormattingAddOn = { ...eslintPluginConfigNgCliCompatFormattingAddOnOriginal, }; const eslintPluginTemplateConfigRecommended = { ...eslintPluginTemplateConfigRecommendedOriginal, }; /** * Force these 2 rules to be defined in the user's .eslintrc.json by removing * them from the comparison config before deduping */ delete eslintPluginConfigNgCliCompat.rules[ '@angular-eslint/directive-selector' ]; delete eslintPluginConfigNgCliCompat.rules[ '@angular-eslint/component-selector' ]; removeUndesiredRulesFromConfig(convertedProjectESLintConfig); adjustSomeRuleConfigs(convertedProjectESLintConfig); handleFormattingRules(schema, context, convertedProjectESLintConfig); /** * To avoid users' configs being bigger and more verbose than necessary, we perform some * deduplication against our underlying ng-cli-compat configuration that they will extend from, * as well as the root config. */ dedupePluginsAgainstConfigs(convertedProjectESLintConfig, [ eslintPluginConfigBase, eslintPluginConfigNgCliCompat, eslintPluginConfigNgCliCompatFormattingAddOn, { plugins: [ '@angular-eslint/eslint-plugin', // this is another alias to consider when deduping '@angular-eslint/eslint-plugin-template', // will be handled in separate overrides block '@typescript-eslint/tslint', // see note on not depending on not wanting to depend on TSLint fallback ], }, ]); updateArrPropAndRemoveDuplication( convertedProjectESLintConfig, { /** * For now, extending from these is too different to what the CLI ships with today, so * we remove them from the converted results. We should look to move towards extending * from these once we have more influence over the generated code. We don't want users * to have lint errors from OOTB generated code. */ extends: [ 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', ], }, 'extends', true, ); dedupeRulesAgainstConfigs(convertedProjectESLintConfig, [ eslintPluginConfigBase, eslintPluginConfigNgCliCompat, eslintPluginConfigNgCliCompatFormattingAddOn, rawRootESLintrcJson, ]); dedupeEnvAgainstConfigs(convertedProjectESLintConfig, [ eslintPluginConfigBase, eslintPluginConfigNgCliCompat, eslintPluginConfigNgCliCompatFormattingAddOn, rawRootESLintrcJson, ]); const { codeRules, templateRules } = separateCodeAndTemplateRules( convertedProjectESLintConfig, ); updateObjPropAndRemoveDuplication( { rules: templateRules }, eslintPluginTemplateConfigRecommended, 'rules', false, ); const convertedExtends = convertedProjectESLintConfig.extends; delete convertedProjectESLintConfig.extends; // Extend from the workspace's root config at the top level const relativeOffestToRootESLintrcJson = `${offsetFromRoot( tree.root.path, )}.eslintrc.json`; convertedProjectESLintConfig.extends = relativeOffestToRootESLintrcJson; convertedProjectESLintConfig.ignorePatterns = ['!**/*']; convertedProjectESLintConfig.overrides = [ { files: ['*.ts'], parserOptions: { project: setESLintProjectBasedOnProjectType( projectRoot, projectType, true, ), createDefaultProgram: true, }, extends: convertedExtends || undefined, plugins: convertedProjectESLintConfig.plugins || undefined, rules: codeRules, }, { files: ['*.html'], rules: templateRules, }, ]; // No longer relevant/required delete convertedProjectESLintConfig.parser; delete convertedProjectESLintConfig.parserOptions; // All applied in the .ts overrides block so should no longer be at the root of the config delete convertedProjectESLintConfig.rules; delete convertedProjectESLintConfig.plugins; return chain([ ensureESLintPluginsAreInstalled(convertedProject.ensureESLintPlugins), // Create the .eslintrc.json file in the tree using the finalized config updateJsonInTree( join(normalize(projectRoot), '.eslintrc.json'), () => convertedProjectESLintConfig, ), // Delete the project's tslint.json, it's no longer needed (host) => host.delete(projectTSLintJsonPath), ]); }; } /** * Remove the relative extends to the root TSLint config before converting, * otherwise all the root config will be included inline in the project config. * * NOTE: We have to write this update to disk because part of the conversion logic * executes the TSLint CLI which reads from disk - there is no equivalent API within * TSLint as a library. */ function removeExtendsFromProjectTSLintConfigBeforeConverting( tree: Tree, projectTSLintJsonPath: string, ): Rule { return updateJsonInTree(projectTSLintJsonPath, (json) => { if (!json.extends) { return json; } const extendsFromRoot = `${offsetFromRoot(tree.root.path)}tslint.json`; if (Array.isArray(json.extends) && json.extends.length) { json.extends = json.extends.filter( (ext: string) => ext !== extendsFromRoot, ); } if (typeof json.extends === 'string' && json.extends === extendsFromRoot) { delete json.extends; } return json; }); } /** * Templates and source code require different ESLint config (parsers, plugins etc), so it is * critical that we leverage the "overrides" capability in ESLint. * * We therefore need to split out rules which are intended for Angular Templates and apply them * in a dedicated config block which targets HTML files. */ function separateCodeAndTemplateRules(convertedESLintConfig: Linter.Config) { const codeRules = convertedESLintConfig.rules || {}; const templateRules: Linter.Config['rules'] = {}; Object.keys(codeRules).forEach((ruleName) => { if ( ruleName.startsWith('@angular-eslint/template') || ruleName.startsWith('@angular-eslint/eslint-plugin-template') ) { templateRules[ruleName] = codeRules[ruleName]; } }); Object.keys(templateRules).forEach((ruleName) => { delete codeRules[ruleName]; }); return { codeRules, templateRules, }; } function handleFormattingRules( schema: Schema, context: SchematicContext, convertedConfig: Linter.Config, ) { if (!convertedConfig.rules) { return; } if (!schema.convertIndentationRules) { delete convertedConfig.rules['@typescript-eslint/indent']; return; } /** * We really don't want to encourage the practice of using a linter * for formatting concerns. Please use prettier y'all! */ if (convertedConfig.rules['@typescript-eslint/indent']) { context.logger.warn( `\nWARNING: You are currently using a linting rule to deal with indentation. Linters are not well suited to purely code formatting concerns, such as indentation.`, ); context.logger.warn( '\nPer your instructions we have migrated your TSLint indentation configuration to its equivalent in ESLint, but we strongly recommend switching to a dedicated code formatter such as https://prettier.io\n', ); } } function adjustSomeRuleConfigs(convertedConfig: Linter.Config) { if (!convertedConfig.rules) { return; } /** * Adjust the quotes rule to always add allowTemplateLiterals as it is most common and can * always be removed by the user if undesired in their case. */ if (convertedConfig.rules['@typescript-eslint/quotes']) { if (!Array.isArray(convertedConfig.rules['@typescript-eslint/quotes'])) { convertedConfig.rules['@typescript-eslint/quotes'] = [ convertedConfig.rules['@typescript-eslint/quotes'], 'single', ]; } if (!convertedConfig.rules['@typescript-eslint/quotes'][2]) { convertedConfig.rules['@typescript-eslint/quotes'].push({ allowTemplateLiterals: true, }); } } } function removeUndesiredRulesFromConfig(convertedConfig: Linter.Config) { if (!convertedConfig.rules) { return; } delete convertedConfig.rules['@typescript-eslint/tslint/config']; /** * BOTH OF THESE RULES CREATE A LOT OF NOISE ON OOTB POLYFILLS.TS */ // WAS -> "spaced-comment": [ // "error", // "always", // { // "markers": ["/"] // } // ], delete convertedConfig.rules['spaced-comment']; // WAS -> "jsdoc/check-indentation": "error", delete convertedConfig.rules['jsdoc/check-indentation']; /** * We want to use these ones differently (with different rule config) to how they * are converted. Because they exist with different config, they wouldn't be cleaned * up by our deduplication logic and we have to manually remove them. */ delete convertedConfig.rules['no-restricted-imports']; /** * We have handled this in eslint-plugin ng-cli-compat.json, any subtle differences that would * cause the deduplication logic not to find a match can be addressed via PRs to the ng-cli-compat * config in the plugin. */ delete convertedConfig.rules['no-console']; } function dedupeEnvAgainstConfigs( convertedConfig: Linter.Config, otherConfigs: Linter.Config[], ) { otherConfigs.forEach((againstConfig) => { updateObjPropAndRemoveDuplication( convertedConfig, againstConfig, 'env', true, ); }); } function dedupeRulesAgainstConfigs( convertedConfig: Linter.Config, otherConfigs: Linter.Config[], ) { otherConfigs.forEach((againstConfig) => { updateObjPropAndRemoveDuplication( convertedConfig, againstConfig, 'rules', false, ); }); } function dedupePluginsAgainstConfigs( convertedConfig: Linter.Config, otherConfigs: Linter.Config[], ) { otherConfigs.forEach((againstConfig) => { updateArrPropAndRemoveDuplication( convertedConfig, againstConfig, 'plugins', true, ); }); } /** * We don't want the user to depend on the TSLint fallback plugin, we will instead * explicitly inform them of the rules that could not be converted automatically and * advise them on what to do next. */ function warnInCaseOfUnconvertedRules( context: SchematicContext, tslintConfigPath: string, unconvertedTSLintRules: TSLintRuleOptions[], ): void { /* * The following rules are known to be missing from the Angular CLI equivalent TSLint * setup, so they will be part of our convertedRoot data: * * // FORMATTING! Please use prettier y'all! * "import-spacing": true * * // POSSIBLY NOT REQUIRED - typescript-eslint provides explicit-function-return-type (not yet enabled) * "typedef": [ * true, * "call-signature", * ] * * // FORMATTING! Please use prettier y'all! * "whitespace": [ * true, * "check-branch", * "check-decl", * "check-operator", * "check-separator", * "check-type", * "check-typecast", * ] */ const unconvertedTSLintRuleNames = unconvertedTSLintRules .filter( (unconverted) => !['import-spacing', 'whitespace', 'typedef'].includes( unconverted.ruleName, ), ) .map((unconverted) => unconverted.ruleName); if (unconvertedTSLintRuleNames.length > 0) { context.logger.warn( `\nWARNING: Within "${tslintConfigPath}", the following ${unconvertedTSLintRuleNames.length} rule(s) did not have known converters in https://github.com/typescript-eslint/tslint-to-eslint-config`, ); context.logger.warn('\n - ' + unconvertedTSLintRuleNames.join('\n - ')); context.logger.warn( '\nYou will need to decide on how to handle the above manually, but everything else has been handled for you automatically.\n', ); } }
the_stack
import { GetState, PartialState, SetState, State, StateCreator, StoreApi, } from './vanilla' const DEVTOOLS = Symbol() export const redux = <S extends State, A extends { type: unknown }>( reducer: (state: S, action: A) => S, initial: S ) => ( set: SetState<S>, get: GetState<S>, api: StoreApi<S> & { dispatch?: (a: A) => A devtools?: any } ): S & { dispatch: (a: A) => A } => { api.dispatch = (action: A) => { set((state: S) => reducer(state, action)) if (api.devtools) { api.devtools.send(api.devtools.prefix + action.type, get()) } return action } return { dispatch: api.dispatch, ...initial } } export type NamedSet<T extends State> = { < K1 extends keyof T, K2 extends keyof T = K1, K3 extends keyof T = K2, K4 extends keyof T = K3 >( partial: PartialState<T, K1, K2, K3, K4>, replace?: boolean, name?: string ): void } export const devtools = <S extends State>( fn: (set: NamedSet<S>, get: GetState<S>, api: StoreApi<S>) => S, options?: | string | { name?: string serialize?: { options: | boolean | { date?: boolean regex?: boolean undefined?: boolean nan?: boolean infinity?: boolean error?: boolean symbol?: boolean map?: boolean set?: boolean } } } ) => ( set: SetState<S>, get: GetState<S>, api: StoreApi<S> & { dispatch?: unknown; devtools?: any } ): S => { let extension try { extension = (window as any).__REDUX_DEVTOOLS_EXTENSION__ || (window as any).top.__REDUX_DEVTOOLS_EXTENSION__ } catch {} if (!extension) { if ( process.env.NODE_ENV === 'development' && typeof window !== 'undefined' ) { console.warn('Please install/enable Redux devtools extension') } api.devtools = null return fn(set, get, api) } const namedSet: NamedSet<S> = (state, replace, name) => { set(state, replace) if (!api.dispatch) { api.devtools.send(api.devtools.prefix + (name || 'action'), get()) } } const initialState = fn(namedSet, get, api) if (!api.devtools) { const savedSetState = api.setState api.setState = < K1 extends keyof S = keyof S, K2 extends keyof S = K1, K3 extends keyof S = K2, K4 extends keyof S = K3 >( state: PartialState<S, K1, K2, K3, K4>, replace?: boolean ) => { const newState = api.getState() if (state !== newState) { savedSetState(state, replace) if (state !== (newState as any)[DEVTOOLS]) { api.devtools.send(api.devtools.prefix + 'setState', api.getState()) } } } options = typeof options === 'string' ? { name: options } : options api.devtools = extension.connect({ ...options }) api.devtools.prefix = options?.name ? `${options.name} > ` : '' api.devtools.subscribe((message: any) => { if (message.type === 'DISPATCH' && message.state) { const jumpState = message.payload.type === 'JUMP_TO_ACTION' || message.payload.type === 'JUMP_TO_STATE' const newState = api.getState() ;(newState as any)[DEVTOOLS] = JSON.parse(message.state) if (!api.dispatch && !jumpState) { api.setState(newState) } else if (jumpState) { api.setState((newState as any)[DEVTOOLS]) } else { savedSetState(newState) } } else if ( message.type === 'DISPATCH' && message.payload?.type === 'COMMIT' ) { api.devtools.init(api.getState()) } else if ( message.type === 'DISPATCH' && message.payload?.type === 'IMPORT_STATE' ) { const actions = message.payload.nextLiftedState?.actionsById const computedStates = message.payload.nextLiftedState?.computedStates || [] computedStates.forEach( ({ state }: { state: PartialState<S> }, index: number) => { const action = actions[index] || 'No action found' if (index === 0) { api.devtools.init(state) } else { savedSetState(state) api.devtools.send(action, api.getState()) } } ) } }) api.devtools.init(initialState) } return initialState } type Combine<T, U> = Omit<T, keyof U> & U export const combine = <PrimaryState extends State, SecondaryState extends State>( initialState: PrimaryState, create: ( set: SetState<PrimaryState>, get: GetState<PrimaryState>, api: StoreApi<PrimaryState> ) => SecondaryState ): StateCreator<Combine<PrimaryState, SecondaryState>> => (set, get, api) => Object.assign( {}, initialState, create( set as unknown as SetState<PrimaryState>, get as unknown as GetState<PrimaryState>, api as unknown as StoreApi<PrimaryState> ) ) type DeepPartial<T extends Object> = { [P in keyof T]?: DeepPartial<T[P]> } export type StateStorage = { getItem: (name: string) => string | null | Promise<string | null> setItem: (name: string, value: string) => void | Promise<void> } type StorageValue<S> = { state: DeepPartial<S>; version?: number } export type PersistOptions< S, PersistedState extends Partial<S> = Partial<S> > = { /** Name of the storage (must be unique) */ name: string /** * A function returning a storage. * The storage must fit `window.localStorage`'s api (or an async version of it). * For example the storage could be `AsyncStorage` from React Native. * * @default () => localStorage */ getStorage?: () => StateStorage /** * Use a custom serializer. * The returned string will be stored in the storage. * * @default JSON.stringify */ serialize?: (state: StorageValue<S>) => string | Promise<string> /** * Use a custom deserializer. * Must return an object matching StorageValue<State> * * @param str The storage's current value. * @default JSON.parse */ deserialize?: ( str: string ) => StorageValue<PersistedState> | Promise<StorageValue<PersistedState>> /** * Prevent some items from being stored. * * @deprecated This options is deprecated and will be removed in the next version. Please use the `partialize` option instead. */ blacklist?: (keyof S)[] /** * Only store the listed properties. * * @deprecated This options is deprecated and will be removed in the next version. Please use the `partialize` option instead. */ whitelist?: (keyof S)[] /** * Filter the persisted value. * * @params state The state's value */ partialize?: (state: S) => DeepPartial<S> /** * A function returning another (optional) function. * The main function will be called before the state rehydration. * The returned function will be called after the state rehydration or when an error occurred. */ onRehydrateStorage?: (state: S) => ((state?: S, error?: Error) => void) | void /** * If the stored state's version mismatch the one specified here, the storage will not be used. * This is useful when adding a breaking change to your store. */ version?: number /** * A function to perform persisted state migration. * This function will be called when persisted state versions mismatch with the one specified here. */ migrate?: (persistedState: any, version: number) => S | Promise<S> /** * A function to perform custom hydration merges when combining the stored state with the current one. * By default, this function does a shallow merge. */ merge?: (persistedState: any, currentState: S) => S } interface Thenable<Value> { then<V>( onFulfilled: (value: Value) => V | Promise<V> | Thenable<V> ): Thenable<V> catch<V>( onRejected: (reason: Error) => V | Promise<V> | Thenable<V> ): Thenable<V> } const toThenable = <Result, Input>( fn: (input: Input) => Result | Promise<Result> | Thenable<Result> ) => (input: Input): Thenable<Result> => { try { const result = fn(input) if (result instanceof Promise) { return result as Thenable<Result> } return { then(onFulfilled) { return toThenable(onFulfilled)(result as Result) }, catch(_onRejected) { return this as Thenable<any> }, } } catch (e: any) { return { then(_onFulfilled) { return this as Thenable<any> }, catch(onRejected) { return toThenable(onRejected)(e) }, } } } export const persist = <S extends State>(config: StateCreator<S>, options: PersistOptions<S>) => (set: SetState<S>, get: GetState<S>, api: StoreApi<S>): S => { const { name, getStorage = () => localStorage, serialize = JSON.stringify as (state: StorageValue<S>) => string, deserialize = JSON.parse as (str: string) => StorageValue<Partial<S>>, blacklist, whitelist, partialize = (state: S) => state, onRehydrateStorage, version = 0, migrate, merge = (persistedState: any, currentState: S) => ({ ...currentState, ...persistedState, }), } = options || {} if (blacklist || whitelist) { console.warn( `The ${ blacklist ? 'blacklist' : 'whitelist' } option is deprecated and will be removed in the next version. Please use the 'partialize' option instead.` ) } let storage: StateStorage | undefined try { storage = getStorage() } catch (e) { // prevent error if the storage is not defined (e.g. when server side rendering a page) } if (!storage) { return config( (...args) => { console.warn( `Persist middleware: unable to update ${name}, the given storage is currently unavailable.` ) set(...args) }, get, api ) } const thenableSerialize = toThenable(serialize) const setItem = (): Thenable<void> => { const state = partialize({ ...get() }) if (whitelist) { ;(Object.keys(state) as (keyof S)[]).forEach((key) => { !whitelist.includes(key) && delete state[key] }) } if (blacklist) { blacklist.forEach((key) => delete state[key]) } let errorInSync: Error | undefined const thenable = thenableSerialize({ state, version }) .then((serializedValue) => (storage as StateStorage).setItem(name, serializedValue) ) .catch((e) => { errorInSync = e }) if (errorInSync) { throw errorInSync } return thenable } const savedSetState = api.setState api.setState = (state, replace) => { savedSetState(state, replace) void setItem() } const configResult = config( (...args) => { set(...args) void setItem() }, get, api ) // rehydrate initial state with existing stored state // a workaround to solve the issue of not storing rehydrated state in sync storage // the set(state) value would be later overridden with initial state by create() // to avoid this, we merge the state from localStorage into the initial state. let stateFromStorage: S | undefined const postRehydrationCallback = onRehydrateStorage?.(get()) || undefined // bind is used to avoid `TypeError: Illegal invocation` error toThenable(storage.getItem.bind(storage))(name) .then((storageValue) => { if (storageValue) { return deserialize(storageValue) } }) .then((deserializedStorageValue) => { if (deserializedStorageValue) { if ( typeof deserializedStorageValue.version === 'number' && deserializedStorageValue.version !== version ) { if (migrate) { return migrate( deserializedStorageValue.state, deserializedStorageValue.version ) } console.error( `State loaded from storage couldn't be migrated since no migrate function was provided` ) } else { return deserializedStorageValue.state } } }) .then((migratedState) => { stateFromStorage = merge(migratedState as S, configResult) set(stateFromStorage as S, true) return setItem() }) .then(() => { postRehydrationCallback?.(stateFromStorage, undefined) }) .catch((e: Error) => { postRehydrationCallback?.(undefined, e) }) return stateFromStorage || configResult }
the_stack
const _API_BLACKLIST = [ 'animate', 'animateChild', 'AnimateChildOptions', 'AnimateTimings', 'animation', 'AnimationAnimateChildMetadata', 'AnimationAnimateMetadata', 'AnimationAnimateRefMetadata', 'AnimationBuilder', 'AnimationEvent', 'AnimationFactory', 'AnimationGroupMetadata', 'AnimationKeyframesSequenceMetadata', 'AnimationMetadata', 'AnimationMetadataType', 'AnimationOptions', 'AnimationPlayer', 'AnimationQueryMetadata', 'AnimationQueryOptions', 'AnimationReferenceMetadata', 'AnimationSequenceMetadata', 'AnimationStaggerMetadata', 'AnimationStateMetadata', 'AnimationStyleMetadata', 'AnimationTransitionMetadata', 'AnimationTriggerMetadata', 'AUTO_STYLE', 'group', 'keyframes', 'NoopAnimationPlayer', 'query', 'sequence', 'stagger', 'state', 'style', 'transition', 'trigger', 'useAnimation', 'AnimationDriver', 'MockAnimationDriver', 'MockAnimationPlayer', 'HTTP_INTERCEPTORS', 'HttpBackend', 'HttpClient', 'HttpClientJsonpModule', 'HttpClientModule', 'HttpClientXsrfModule', 'HttpDownloadProgressEvent', 'HttpErrorResponse', 'HttpEvent', 'HttpEventType', 'HttpHandler', 'HttpHeaderResponse', 'HttpHeaders', 'HttpInterceptor', 'HttpParameterCodec', 'HttpParams', 'HttpProgressEvent', 'HttpRequest', 'HttpResponse', 'HttpResponseBase', 'HttpSentEvent', 'HttpUploadProgressEvent', 'HttpUrlEncodingCodec', 'HttpUserEvent', 'HttpXhrBackend', 'HttpXsrfTokenExtractor', 'JsonpClientBackend', 'JsonpInterceptor', 'XhrFactory', 'HttpClientTestingModule', 'HttpTestingController', 'RequestMatch', 'TestRequest', 'APP_BASE_HREF', 'AsyncPipe', 'CommonModule', 'CurrencyPipe', 'DatePipe', 'DecimalPipe', 'DOCUMENT', 'formatCurrency', 'formatDate', 'formatNumber', 'formatPercent', 'FormatWidth', 'FormStyle', 'getCurrencySymbol', 'getLocaleCurrencyName', 'getLocaleCurrencySymbol', 'getLocaleDateFormat', 'getLocaleDateTimeFormat', 'getLocaleDayNames', 'getLocaleDayPeriods', 'getLocaleDirection', 'getLocaleEraNames', 'getLocaleExtraDayPeriodRules', 'getLocaleExtraDayPeriods', 'getLocaleFirstDayOfWeek', 'getLocaleId', 'getLocaleMonthNames', 'getLocaleNumberFormat', 'getLocaleNumberSymbol', 'getLocalePluralCase', 'getLocaleTimeFormat', 'getLocaleWeekEndRange', 'getNumberOfCurrencyDigits', 'HashLocationStrategy', 'I18nPluralPipe', 'I18nSelectPipe', 'isPlatformBrowser', 'isPlatformServer', 'isPlatformWorkerApp', 'isPlatformWorkerUi', 'JsonPipe', 'KeyValue', 'KeyValuePipe', 'Location', 'LOCATION_INITIALIZED', 'LocationChangeEvent', 'LocationChangeListener', 'LocationStrategy', 'LowerCasePipe', 'NgClass', 'NgClassBase', 'NgComponentOutlet', 'NgForOf', 'NgForOfContext', 'NgIf', 'NgIfContext', 'NgLocaleLocalization', 'NgLocalization', 'NgPlural', 'NgPluralCase', 'NgStyle', 'NgStyleBase', 'NgSwitch', 'NgSwitchCase', 'NgSwitchDefault', 'NgTemplateOutlet', 'NumberFormatStyle', 'NumberSymbol', 'PathLocationStrategy', 'PercentPipe', 'PlatformLocation', 'Plural', 'PopStateEvent', 'registerLocaleData', 'SlicePipe', 'Time', 'TitleCasePipe', 'TranslationWidth', 'UpperCasePipe', 'ViewportScroller', 'WeekDay', 'MOCK_PLATFORM_LOCATION_CONFIG', 'MockLocationStrategy', 'MockPlatformLocation', 'MockPlatformLocationConfig', 'SpyLocation', '$locationShim', '$locationShimProvider', 'AngularJSUrlCodec', 'LOCATION_UPGRADE_CONFIGURATION', 'LocationUpgradeConfig', 'LocationUpgradeModule', 'UrlCodec', 'AbstractType', 'AfterContentChecked', 'AfterContentInit', 'AfterViewChecked', 'AfterViewInit', 'ANALYZE_FOR_ENTRY_COMPONENTS', 'APP_BOOTSTRAP_LISTENER', 'APP_ID', 'APP_INITIALIZER', 'ApplicationInitStatus', 'ApplicationModule', 'ApplicationRef', 'asNativeElements', 'assertPlatform', 'Attribute', 'ChangeDetectionStrategy', 'ChangeDetectorRef', 'ClassProvider', 'ClassSansProvider', 'CollectionChangeRecord', 'Compiler', 'COMPILER_OPTIONS', 'CompilerFactory', 'CompilerOptions', 'Component', 'ComponentFactory', 'ComponentFactoryResolver', 'ComponentRef', 'ConstructorProvider', 'ConstructorSansProvider', 'ContentChild', 'ContentChildren', 'createPlatform', 'createPlatformFactory', 'CUSTOM_ELEMENTS_SCHEMA', 'DebugElement', 'DebugEventListener', 'DebugNode', 'DEFAULT_CURRENCY_CODE', 'DefaultIterableDiffer', 'defineInjectable', 'destroyPlatform', 'Directive', 'DoBootstrap', 'DoCheck', 'ElementRef', 'EmbeddedViewRef', 'enableProdMode', 'ErrorHandler', 'EventEmitter', 'ExistingProvider', 'ExistingSansProvider', 'FactoryProvider', 'FactorySansProvider', 'forwardRef', 'ForwardRefFn', 'getDebugNode', 'getModuleFactory', 'getPlatform', 'GetTestability', 'Host', 'HostBinding', 'HostListener', 'Inject', 'inject', 'Injectable', 'InjectableProvider', 'InjectableType', 'InjectFlags', 'InjectionToken', 'INJECTOR', 'Injector', 'InjectorType', 'Input', 'isDevMode', 'IterableChangeRecord', 'IterableChanges', 'IterableDiffer', 'IterableDifferFactory', 'IterableDiffers', 'KeyValueChangeRecord', 'KeyValueChanges', 'KeyValueDiffer', 'KeyValueDifferFactory', 'KeyValueDiffers', 'LOCALE_ID', 'MissingTranslationStrategy', 'ModuleWithComponentFactories', 'ModuleWithProviders', 'NgIterable', 'NgModule', 'NgModuleFactory', 'NgModuleFactoryLoader', 'NgModuleRef', 'NgProbeToken', 'NgZone', 'NO_ERRORS_SCHEMA', 'OnChanges', 'OnDestroy', 'OnInit', 'Optional', 'Output', 'PACKAGE_ROOT_URL', 'Pipe', 'PipeTransform', 'PLATFORM_ID', 'PLATFORM_INITIALIZER', 'platformCore', 'PlatformRef', 'Predicate', 'Provider', 'Query', 'QueryList', 'ReflectiveInjector', 'ReflectiveKey', 'Renderer2', 'RendererFactory2', 'RendererStyleFlags2', 'RendererType2', 'ResolvedReflectiveFactory', 'ResolvedReflectiveProvider', 'resolveForwardRef', 'Sanitizer', 'SchemaMetadata', 'SecurityContext', 'Self', 'setTestabilityGetter', 'SimpleChange', 'SimpleChanges', 'SkipSelf', 'StaticClassProvider', 'StaticClassSansProvider', 'StaticProvider', 'SystemJsNgModuleLoader', 'SystemJsNgModuleLoaderConfig', 'TemplateRef', 'Testability', 'TestabilityRegistry', 'TrackByFunction', 'TRANSLATIONS', 'TRANSLATIONS_FORMAT', 'Type', 'TypeDecorator', 'TypeProvider', 'ValueProvider', 'ValueSansProvider', 'Version', 'ViewChild', 'ViewChildren', 'ViewContainerRef', 'ViewEncapsulation', 'ViewRef', 'WrappedValue', 'async', 'ComponentFixture', 'ComponentFixtureAutoDetect', 'ComponentFixtureNoNgZone', 'discardPeriodicTasks', 'fakeAsync', 'flush', 'flushMicrotasks', 'getTestBed', 'inject', 'InjectSetupWrapper', 'MetadataOverride', 'resetFakeAsyncZone', 'TestBed', 'TestBedStatic', 'TestComponentRenderer', 'TestModuleMetadata', 'tick', 'withModule', 'createCustomElement', 'NgElement', 'NgElementConfig', 'NgElementConstructor', 'NgElementStrategy', 'NgElementStrategyEvent', 'NgElementStrategyFactory', 'WithProperties', 'AbstractControl', 'AbstractControlDirective', 'AbstractControlOptions', 'AbstractFormGroupDirective', 'AsyncValidator', 'AsyncValidatorFn', 'CheckboxControlValueAccessor', 'CheckboxRequiredValidator', 'COMPOSITION_BUFFER_MODE', 'ControlContainer', 'ControlValueAccessor', 'DefaultValueAccessor', 'EmailValidator', 'Form', 'FormArray', 'FormArrayName', 'FormBuilder', 'FormControl', 'FormControlDirective', 'FormControlName', 'FormGroup', 'FormGroupDirective', 'FormGroupName', 'FormsModule', 'MaxLengthValidator', 'MinLengthValidator', 'NG_ASYNC_VALIDATORS', 'NG_VALIDATORS', 'NG_VALUE_ACCESSOR', 'NgControl', 'NgControlStatus', 'NgControlStatusGroup', 'NgForm', 'NgModel', 'NgModelGroup', 'NgSelectOption', 'NumberValueAccessor', 'PatternValidator', 'RadioControlValueAccessor', 'RangeValueAccessor', 'ReactiveFormsModule', 'RequiredValidator', 'SelectControlValueAccessor', 'SelectMultipleControlValueAccessor', 'ValidationErrors', 'Validator', 'ValidatorFn', 'Validators', 'BrowserModule', 'BrowserTransferStateModule', 'By', 'disableDebugTools', 'DomSanitizer', 'enableDebugTools', 'EVENT_MANAGER_PLUGINS', 'EventManager', 'HAMMER_GESTURE_CONFIG', 'HAMMER_LOADER', 'HammerGestureConfig', 'HammerLoader', 'HammerModule', 'makeStateKey', 'Meta', 'MetaDefinition', 'platformBrowser', 'SafeHtml', 'SafeResourceUrl', 'SafeScript', 'SafeStyle', 'SafeUrl', 'SafeValue', 'StateKey', 'Title', 'TransferState', 'ANIMATION_MODULE_TYPE', 'BrowserAnimationsModule', 'NoopAnimationsModule', 'BrowserTestingModule', 'platformBrowserTesting', 'JitCompilerFactory', 'platformBrowserDynamic', 'RESOURCE_CACHE_PROVIDER', 'BrowserDynamicTestingModule', 'platformBrowserDynamicTesting', 'BEFORE_APP_SERIALIZED', 'INITIAL_CONFIG', 'PlatformConfig', 'platformDynamicServer', 'platformServer', 'PlatformState', 'renderModule', 'renderModuleFactory', 'ServerModule', 'ServerTransferStateModule', 'platformServerTesting', 'ServerTestingModule', 'bootstrapWorkerUi', 'ClientMessageBroker', 'ClientMessageBrokerFactory', 'FnArg', 'MessageBus', 'MessageBusSink', 'MessageBusSource', 'platformWorkerApp', 'platformWorkerUi', 'ReceivedMessage', 'SerializerTypes', 'ServiceMessageBroker', 'ServiceMessageBrokerFactory', 'UiArguments', 'WORKER_APP_LOCATION_PROVIDERS', 'WORKER_UI_LOCATION_PROVIDERS', 'WorkerAppModule', 'platformWorkerAppDynamic', 'ActivatedRoute', 'ActivatedRouteSnapshot', 'ActivationEnd', 'ActivationStart', 'CanActivate', 'CanActivateChild', 'CanDeactivate', 'CanLoad', 'ChildActivationEnd', 'ChildActivationStart', 'ChildrenOutletContexts', 'convertToParamMap', 'Data', 'DefaultUrlSerializer', 'DeprecatedLoadChildren', 'DetachedRouteHandle', 'Event', 'ExtraOptions', 'GuardsCheckEnd', 'GuardsCheckStart', 'InitialNavigation', 'LoadChildren', 'LoadChildrenCallback', 'Navigation', 'NavigationCancel', 'NavigationEnd', 'NavigationError', 'NavigationExtras', 'NavigationStart', 'NoPreloading', 'OutletContext', 'ParamMap', 'Params', 'PreloadAllModules', 'PreloadingStrategy', 'PRIMARY_OUTLET', 'provideRoutes', 'QueryParamsHandling', 'Resolve', 'ResolveData', 'ResolveEnd', 'ResolveStart', 'Route', 'RouteConfigLoadEnd', 'RouteConfigLoadStart', 'Router', 'ROUTER_CONFIGURATION', 'ROUTER_INITIALIZER', 'RouteReuseStrategy', 'RouterEvent', 'RouterLink', 'RouterLinkActive', 'RouterLinkWithHref', 'RouterModule', 'RouterOutlet', 'RouterPreloader', 'RouterState', 'RouterStateSnapshot', 'Routes', 'ROUTES', 'RoutesRecognized', 'RunGuardsAndResolvers', 'Scroll', 'UrlHandlingStrategy', 'UrlMatcher', 'UrlMatchResult', 'UrlSegment', 'UrlSegmentGroup', 'UrlSerializer', 'UrlTree', 'RouterTestingModule', 'setupTestingRouter', 'SpyNgModuleFactoryLoader', 'RouterUpgradeInitializer', 'setUpLocationSync', 'ServiceWorkerModule', 'SwPush', 'SwRegistrationOptions', 'SwUpdate', 'UpdateActivatedEvent', 'UpdateAvailableEvent', 'UpgradeAdapter', 'UpgradeAdapterRef', 'downgradeComponent', 'downgradeInjectable', 'downgradeModule', 'getAngularJSGlobal', 'getAngularLib', 'setAngularJSGlobal', 'setAngularLib', 'UpgradeComponent', 'UpgradeModule', 'createAngularJSTestingModule', 'createAngularTestingModule' ]; // Only contains exposed Angular ngModules, used for performance purposes // when we only want to filter modules const _MODULE_BLACKLIST = [ 'HttpClientJsonpModule', 'HttpClientModule', 'HttpClientXsrfModule', 'HttpClientTestingModule', 'CommonModule', 'LocationUpgradeModule', 'ApplicationModule', 'FormsModule', 'ReactiveFormsModule', 'BrowserModule', 'BrowserTransferStateModule', 'HammerModule', 'BrowserAnimationsModule', 'NoopAnimationsModule', 'BrowserTestingModule', 'BrowserDynamicTestingModule', 'ServerModule', 'ServerTransferStateModule', 'ServerTestingModule', 'WorkerAppModule', 'RouterModule', 'RouterTestingModule', 'ServiceWorkerModule', 'UpgradeModule' ]; export const filterApiList = (arrayToFilter: Array<string>, modulesOnly = false): Array<string> => { return arrayToFilter.filter(api => !(modulesOnly ? _MODULE_BLACKLIST : _API_BLACKLIST).includes(api)); };
the_stack
import { CancellationToken, CodeAction, CodeActionContext, CodeActionKind, CodeActionProvider, CompletionContext, CompletionItem, CompletionItemKind, CompletionItemProvider, Diagnostic, DiagnosticSeverity, MarkdownString, Position, QuickPickItem, Range, SnippetString, TextDocument, window, workspace } from 'vscode'; import { insertContentToEditor, matchAll, naturalLanguageCompare, noActiveEditorMessage } from './common'; export function insertLanguageCommands() { return [{ command: insertLanguageIdentifier.name, callback: insertLanguageIdentifier }]; } export interface HighlightLanguage { readonly language: string; readonly aliases: string[]; readonly extensions?: string[]; } export type HighlightLanguages = HighlightLanguage[]; /** * The various syntax highlighting languages available. * Source langs: https://raw.githubusercontent.com/DuncanmaMSFT/highlight.js/master/README.md * If this changes, we need to update "contributes/configuration/markdown.docsetLanguages" schema. */ export const languages: HighlightLanguages = [ { language: '.NET Core CLI', aliases: ['dotnetcli'] }, { language: 'AL', aliases: ['al'] }, { language: 'Apache', aliases: ['apache', 'apacheconf'] }, { language: 'ARM assembler', aliases: ['armasm', 'arm'] }, { language: 'ASPX', aliases: ['aspx'] }, { language: 'ASP.NET (C#)', aliases: ['aspx-csharp'] }, { language: 'ASP.NET (VB)', aliases: ['aspx-vb'] }, { language: 'AzCopy', aliases: ['azcopy'] }, { language: 'Azure CLI', aliases: ['azurecli'] }, { language: 'Azure CLI (Interactive)', aliases: ['azurecli-interactive'] }, { language: 'Azure Powershell', aliases: ['azurepowershell'] }, { language: 'Azure Powershell (Interactive)', aliases: ['azurepowershell-interactive'] }, { language: 'Bash', aliases: ['bash', 'sh', 'zsh'], extensions: ['.sh', '.bash'] }, { language: 'C', aliases: ['c'], extensions: ['.c'] }, { language: 'C#', aliases: ['csharp', 'cs'], extensions: ['.cs'] }, { language: 'C# (Interactive)', aliases: ['csharp-interactive'] }, { language: 'C++', aliases: ['cpp', 'c', 'cc', 'h', 'c++', 'h++', 'hpp'], extensions: ['.cpp', '.h', '.hpp', '.cc'] }, { language: 'C++/CX', aliases: ['cppcx'] }, { language: 'C++/WinRT', aliases: ['cppwinrt'] }, { language: 'CSS', aliases: ['css'] }, { language: 'DAX Power BI', aliases: ['dax'] }, { language: 'DOS', aliases: ['dos', 'bat', 'cmd'], extensions: ['.bat', '.cmd'] }, { language: 'Dockerfile', aliases: ['dockerfile', 'docker'] }, { language: 'F#', aliases: ['fsharp', 'fs'], extensions: ['.fs', '.fsi', '.fsx'] }, { language: 'Go', aliases: ['go', 'golang'], extensions: ['.go'] }, { language: 'Gradle', aliases: ['gradle'] }, { language: 'Groovy', aliases: ['groovy'] }, { language: 'HashiCorp Configuration Language (HCL)', aliases: ['terraform', 'tf', 'hcl'] }, { language: 'HTML', aliases: ['html', 'xhtml'], extensions: ['.html', '.xhtml'] }, { language: 'HTTP', aliases: ['http', 'https'] }, { language: 'Ini', aliases: ['ini'], extensions: ['.ini'] }, { language: 'JSON', aliases: ['json'], extensions: ['.json'] }, { language: 'Java', aliases: ['java', 'jsp'], extensions: ['.java', '.jsp'] }, { language: 'JavaScript', aliases: ['javascript', 'js', 'jsx'], extensions: ['.js', '.jsx'] }, { language: 'Kotlin', aliases: ['kotlin', 'kt'] }, { language: 'Kusto', aliases: ['kusto'] }, { language: 'Makefile', aliases: ['makefile', 'mk', 'mak'], extensions: ['.gmk', '.mk', '.mak'] }, { language: 'Markdown', aliases: ['markdown', 'md', 'mkdown', 'mkd'], extensions: ['.md', '.markdown', '.mdown', '.mkd', '.mdwn', '.mdtxt', '.mdtext', '.rmd'] }, { language: 'Managed Object Format', aliases: ['mof'] }, { language: 'MS Graph (Interactive)', aliases: ['msgraph-interactive'] }, { language: 'Nginx', aliases: ['nginx', 'nginxconf'] }, { language: 'Node.js', aliases: ['nodejs'] }, { language: 'Objective C', aliases: ['objectivec', 'mm', 'objc', 'obj-c'], extensions: ['.m', '.h'] }, { language: 'Odata', aliases: ['odata'] }, { language: 'PHP', aliases: ['php', 'php3', 'php4', 'php5', 'php6'], extensions: ['.php', '.php3', '.php4', '.php5', '.phtml'] }, { language: 'PowerApps Formula', aliases: ['powerappsfl'] }, { language: 'PowerShell', aliases: ['powershell', 'ps'], extensions: ['.ps', '.ps1', '.psd1', '.psm1'] }, { language: 'PowerShell (Interactive)', aliases: ['powershell-interactive'] }, { language: 'Properties', aliases: ['properties'] }, { language: 'Protocol Buffers', aliases: ['protobuf'] }, { language: 'Python', aliases: ['python', 'py', 'gyp'], extensions: ['.py'] }, { language: 'Q#', aliases: ['qsharp'] }, { language: 'R', aliases: ['r'], extensions: ['.r'] }, { language: 'Razor CSHTML', aliases: ['razor', 'cshtml', 'razor-cshtml'], extensions: ['.cshtml', '.razor'] }, { language: 'REST API', aliases: ['rest'] }, { language: 'Ruby', aliases: ['ruby', 'rb', 'gemspec', 'podspec', 'thor', 'irb'], extensions: ['.rb'] }, { language: 'SQL', aliases: ['sql'], extensions: ['.sql'] }, { language: 'Scala', aliases: ['scala'], extensions: ['.scala', '.sc'] }, { language: 'Solidity', aliases: ['solidity', 'sol'] }, { language: 'Swift', aliases: ['swift'], extensions: ['.swift'] }, { language: 'Transact-SQL', aliases: ['tsql'] }, { language: 'TypeScript', aliases: ['typescript', 'ts'], extensions: ['.ts', '.d.ts'] }, { language: 'VB.NET', aliases: ['vbnet', 'vb'], extensions: ['.vb', '.bas', '.vba'] }, { language: 'VB for Applications', aliases: ['vba'], extensions: ['.vba'] }, { language: 'VBScript', aliases: ['vbscript', 'vbs'], extensions: ['.vbs'] }, { language: 'VSTS CLI', aliases: ['vstscli'] }, { language: 'XAML', aliases: ['xaml'], extensions: ['.xaml'] }, { language: 'XML', aliases: ['xml', 'xhtml', 'rss', 'atom', 'xjb', 'xsd', 'xsl', 'plist'], extensions: [ '.xml', '.xhtml', '.rss', '.atom', '.xjb', '.xsd', '.xsl', '.plist', '.xml', '.csdl', '.edmx', '.xslt', '.wsdl' ] }, { language: 'X++', aliases: ['xpp'], extensions: ['.xpp'] }, { language: 'YAML', aliases: ['yml', 'yaml'], extensions: ['yml', 'yaml'] } ]; /** * All of the possible aliases concatenated together. */ const allAliases: string[] = languages.reduce((aliases, lang) => aliases.concat(lang.aliases), [ '' ]); /** * Validates whether or not a given language is going to render correctly with syntax highlighting. */ function isValidCodeLang(language: string) { return allAliases.some(alias => alias === language.toLowerCase()); } export async function insertLanguageIdentifier(range: Range) { const editor = window.activeTextEditor; if (!editor) { noActiveEditorMessage(); return; } const selection = range || editor.selection; if (selection) { const items = getLanguageIdentifierQuickPickItems(); const item = await window.showQuickPick(items); if (item) { const language = languages.find(lang => lang.language === item.label); if (language) { const alias = language.aliases[0]; insertContentToEditor(editor, alias, true, selection); } } } else { window.showWarningMessage('Please first make a selection to insert a language identifier.'); } } export function getLanguageIdentifierQuickPickItems() { const items: QuickPickItem[] = []; const langs = getConfiguredLanguages(); if (langs) { langs.forEach(lang => { const item: QuickPickItem = { description: `Use the "${lang.language.trim()}" language identifer (alias: ${ lang.aliases[0] }).`, label: lang.language }; items.push(item); }); } return items; } function getLanguageIdentifierCompletionItems( range: Range | undefined, isCancellationRequested: boolean ) { if (range) { const completionItems: CompletionItem[] = []; const langs = getConfiguredLanguages(); if (langs) { langs.forEach(lang => { const langId = lang.aliases[0]; const markdownSample = new MarkdownString('Output:'); markdownSample.appendCodeblock('', langId); const item = new CompletionItem(lang.language, CompletionItemKind.Value); item.detail = markdownSample.value; item.documentation = new MarkdownString( `Use the _${lang.language}_ language identifer (alias: _${langId}_).` ); item.insertText = new SnippetString(`${langId}\n$0\n\`\`\``); item.sortText = lang.language; completionItems.push(item); }); } return isCancellationRequested ? undefined : completionItems; } return undefined; } function getConfiguredLanguages() { const configuration = workspace.getConfiguration('markdown'); if (!configuration) { return languages; } const docsetLanguages = configuration.docsetLanguages as string[]; const result = configuration.allAvailableLanguages || !docsetLanguages || !docsetLanguages.length ? languages : languages.filter(lang => docsetLanguages.some(langId => langId === lang.language)); result.sort((lang1, lang2) => naturalLanguageCompare(lang1.language, lang2.language)); return result; } export const markdownCompletionItemsProvider: CompletionItemProvider = { provideCompletionItems( document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext ) { const range = document.getWordRangeAtPosition(position, /```/); if (range) { const text = document.getText(); if (text) { const TRIPLE_BACKTICK_RE = /```/gm; const results = matchAll(TRIPLE_BACKTICK_RE, text); if (results) { for (let i = 0; i < results.length; ++i) { if (i % 2 === 0) { const match = results[i]; if (match) { const index = match.index || -1; const pos = document.positionAt(index); const positionIsInRange = (pos.line === range.start.line && pos.character >= range.start.character) || (pos.line === range.end.line && pos.character <= range.end.character); if (index >= 0 && positionIsInRange) { return getLanguageIdentifierCompletionItems(range, token.isCancellationRequested); } } } } } } } return undefined; } }; export const markdownCodeActionProvider: CodeActionProvider = { provideCodeActions( document: TextDocument, _: Range, context: CodeActionContext, token: CancellationToken ) { const CODE_FENCE_RE = /`{3,4}(.*?[^```])$/gm; const text = document.getText(); const results: CodeAction[] = []; for (const matches of matchAll(CODE_FENCE_RE, text).filter(ms => !!ms)) { if (matches) { const lang = matches[1] || undefined; if (!!lang && lang !== '\r' && lang !== '\n') { const index = matches.index || -1; if (lang && index >= 0) { if (!isValidCodeLang(lang)) { const action = new CodeAction( `Click to fix unrecognized "${lang}" code-fence language identifer`, CodeActionKind.QuickFix ); const indexWithOffset = index + 3; // Account for "```". const startPosition = document.positionAt(indexWithOffset); const endPosition = document.positionAt(indexWithOffset + lang.length); const range = new Range(startPosition, endPosition); const diagnostics = new Diagnostic( range, 'Select from available code-fence language identifiers', DiagnosticSeverity.Warning ); (action.diagnostics || (action.diagnostics = [])).push(diagnostics); action.command = { arguments: [range], command: 'insertLanguageIdentifier', title: 'Insert language identifier', tooltip: 'Select from the available language identifiers.' }; results.push(action); } } } } } return token.isCancellationRequested ? undefined : results; } };
the_stack
import mdbid from "mdbid"; import { CmsModelFieldInput, CmsGroup, CmsModelField } from "~/types"; import { useContentGqlHandler } from "../utils/useContentGqlHandler"; import * as helpers from "../utils/helpers"; import models from "./mocks/contentModels"; import { useCategoryManageHandler } from "../utils/useCategoryManageHandler"; import { pubSubTracker, assignModelEvents } from "./mocks/lifecycleHooks"; import { useBugManageHandler } from "../utils/useBugManageHandler"; const getTypeFields = (type: any) => { return type.fields.filter((f: any) => f.name !== "_empty").map((f: any) => f.name); }; const getTypeObject = (schema: any, type: string) => { return schema.types.find((t: any) => t.name === type); }; const createPermissions = ({ models, groups }: { models?: string[]; groups?: string[] }) => [ { name: "cms.settings" }, { name: "cms.contentModelGroup", rwd: "rwd", groups: groups ? { "en-US": groups } : undefined }, { name: "cms.contentModel", rwd: "rwd", models: models ? { "en-US": models } : undefined }, { name: "cms.endpoint.read" }, { name: "cms.endpoint.manage" }, { name: "cms.endpoint.preview" }, { name: "content.i18n", locales: ["en-US"] } ]; jest.setTimeout(100000); describe("content model test", () => { const readHandlerOpts = { path: "read/en-US" }; const manageHandlerOpts = { path: "manage/en-US" }; const { createContentModelGroupMutation } = useContentGqlHandler(manageHandlerOpts); let contentModelGroup: CmsGroup; beforeEach(async () => { const [createCMG] = await createContentModelGroupMutation({ data: { name: "Group", slug: "group", icon: "ico/ico", description: "description" } }); contentModelGroup = createCMG.data.createContentModelGroup.data; // we need to reset this since we are using a singleton pubSubTracker.reset(); }); test("base schema should only contain relevant queries and mutations", async () => { // create a "read" and "manage" endpoints const readAPI = useContentGqlHandler(readHandlerOpts); const manageAPI = useContentGqlHandler(manageHandlerOpts); const [read] = await readAPI.introspect(); const [manage] = await manageAPI.introspect(); const readSchema = read.data.__schema; const manageSchema = manage.data.__schema; const ReadQuery = getTypeObject(readSchema, "Query"); const ManageQuery = getTypeObject(manageSchema, "Query"); const ReadMutation = getTypeObject(readSchema, "Mutation"); const ManageMutation = getTypeObject(manageSchema, "Mutation"); expect(getTypeFields(ReadQuery)).toEqual(["getContentModel", "listContentModels"]); expect(getTypeFields(ManageQuery)).toEqual([ "getContentModel", "listContentModels", "searchContentEntries", "getContentEntry", "getLatestContentEntry", "getPublishedContentEntry", "getContentEntries", "getLatestContentEntries", "getPublishedContentEntries", "getContentModelGroup", "listContentModelGroups" ]); expect(getTypeFields(ReadMutation)).toEqual([]); expect(getTypeFields(ManageMutation)).toEqual([ "createContentModel", "createContentModelFrom", "updateContentModel", "deleteContentModel", "createContentModelGroup", "updateContentModelGroup", "deleteContentModelGroup" ]); }); test("create, read, update, delete and list content models", async () => { const { createContentModelMutation, getContentModelQuery, updateContentModelMutation, listContentModelsQuery, deleteContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); expect(createResponse).toEqual({ data: { createContentModel: { data: { name: "Test Content model", description: "", titleFieldId: "id", modelId: "testContentModel", createdBy: helpers.identity, createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), fields: [], layout: [], plugin: false, group: { id: contentModelGroup.id, name: contentModelGroup.name } }, error: null } } }); const createdContentModel = createResponse.data.createContentModel.data; const [getResponse] = await getContentModelQuery({ modelId: createdContentModel.modelId }); expect(getResponse).toEqual({ data: { getContentModel: { data: { ...createResponse.data.createContentModel.data, description: null }, error: null } } }); // nothing is changed in this update - just the date const [updateResponse] = await updateContentModelMutation({ modelId: createdContentModel.modelId, data: { fields: [], layout: [] } }); expect(updateResponse).toEqual({ data: { updateContentModel: { data: { ...createResponse.data.createContentModel.data, description: null, savedOn: expect.stringMatching(/^20/) }, error: null } } }); // change some values in content model const [changedUpdateResponse] = await updateContentModelMutation({ modelId: createdContentModel.modelId, data: { name: "changed name", description: "changed description", fields: [], layout: [] } }); const updatedContentModel = { ...createdContentModel, name: "changed name", description: "changed description", savedOn: expect.stringMatching(/^20/) }; expect(changedUpdateResponse).toEqual({ data: { updateContentModel: { data: updatedContentModel, error: null } } }); const [listResponse] = await listContentModelsQuery(); expect(listResponse).toEqual({ data: { listContentModels: { data: [updatedContentModel], error: null } } }); const [deleteResponse] = await deleteContentModelMutation({ modelId: updatedContentModel.modelId }); expect(deleteResponse).toEqual({ data: { deleteContentModel: { data: true, error: null } } }); }); test("delete existing content model", async () => { const { createContentModelMutation, deleteContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const contentModel = createResponse.data.createContentModel.data; const [response] = await deleteContentModelMutation({ modelId: contentModel.modelId }); expect(response).toEqual({ data: { deleteContentModel: { data: true, error: null } } }); }); test("cannot delete content model that has entries", async () => { const { createContentModelMutation, updateContentModelMutation, deleteContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const { createCategory, until, listCategories } = useCategoryManageHandler(manageHandlerOpts); const category = models.find(m => m.modelId === "category"); if (!category) { throw new Error("Could not find model `category`."); } // Create initial record const [createContentModelResponse] = await createContentModelMutation({ data: { name: category.name, modelId: category.modelId, group: contentModelGroup.id } }); const [updateContentModelResponse] = await updateContentModelMutation({ modelId: createContentModelResponse.data.createContentModel.data.modelId, data: { fields: category.fields, layout: category.layout } }); const model = updateContentModelResponse.data.updateContentModel.data; await createCategory({ data: { title: "Category", slug: "title" } }); // If this `until` resolves successfully, we know entry is accessible via the "read" API await until( () => listCategories().then(([data]) => data), ({ data }: any) => data.listCategories.data.length > 0, { name: "list categories to check that categories are available" } ); const [response] = await deleteContentModelMutation({ modelId: model.modelId }); expect(response).toEqual({ data: { deleteContentModel: { data: null, error: { message: `Cannot delete content model "${model.modelId}" because there are existing entries.`, code: "CONTENT_MODEL_BEFORE_DELETE_HOOK_FAILED", data: null } } } }); }); test("get existing content model", async () => { const { createContentModelMutation, getContentModelQuery } = useContentGqlHandler(manageHandlerOpts); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const contentModel = createResponse.data.createContentModel.data; const [response] = await getContentModelQuery({ modelId: contentModel.modelId }); expect(response).toEqual({ data: { getContentModel: { data: { ...contentModel, description: null }, error: null } } }); }); test("error when getting non-existing model", async () => { const { getContentModelQuery } = useContentGqlHandler(manageHandlerOpts); const modelId = "nonExistingId"; const [response] = await getContentModelQuery({ modelId }); expect(response).toEqual({ data: { getContentModel: { data: null, error: { message: `Content model "${modelId}" was not found!`, code: "NOT_FOUND", data: null } } } }); }); test("error when updating non-existing model", async () => { const { updateContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const modelId = "nonExistingId"; const [response] = await updateContentModelMutation({ modelId, data: { name: "new name", fields: [], layout: [] } }); expect(response).toEqual({ data: { updateContentModel: { data: null, error: { message: `Content model "${modelId}" was not found!`, code: "NOT_FOUND", data: null } } } }); }); test("error when deleting non-existing model", async () => { const { deleteContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const modelId = "nonExistingId"; const [response] = await deleteContentModelMutation({ modelId }); expect(response).toEqual({ data: { deleteContentModel: { data: null, error: { message: `Content model "${modelId}" was not found!`, code: "NOT_FOUND", data: null } } } }); }); test("update content model with new fields", async () => { const { createContentModelMutation, updateContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const contentModel = createResponse.data.createContentModel.data; const textField: CmsModelFieldInput = { id: mdbid(), fieldId: "textField", label: "Text field", helpText: "help text", multipleValues: false, placeholderText: "placeholder text", predefinedValues: { enabled: false, values: [] }, renderer: { name: "rendererName" }, settings: {}, type: "text", validation: [], listValidation: [] }; const numberField: CmsModelFieldInput = { id: mdbid(), fieldId: "numberField", label: "Number field", helpText: "number help text", multipleValues: false, placeholderText: "number placeholder text", predefinedValues: { enabled: false, values: [] }, renderer: { name: "rendererName" }, settings: {}, type: "number", validation: [], listValidation: [] }; const fields = [textField, numberField]; const [response] = await updateContentModelMutation({ modelId: contentModel.modelId, data: { name: "new name", fields, layout: fields.map(field => { return [field.id]; }) } }); expect(response).toEqual({ data: { updateContentModel: { data: { savedOn: expect.stringMatching(/^20/), createdBy: helpers.identity, createdOn: expect.stringMatching(/^20/), description: null, titleFieldId: "textField", fields: [textField, numberField], group: { id: contentModelGroup.id, name: "Group" }, modelId: contentModel.modelId, layout: [[textField.id], [numberField.id]], name: "new name", plugin: false }, error: null } } }); }); test("error when assigning titleFieldId on non existing field", async () => { const { createContentModelMutation, updateContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const contentModel = createResponse.data.createContentModel.data; const field: CmsModelFieldInput = { id: mdbid(), fieldId: "field1", label: "Field 1", helpText: "help text", multipleValues: false, placeholderText: "placeholder text", predefinedValues: { enabled: false, values: [] }, renderer: { name: "rendererName" }, settings: {}, type: "text", validation: [], listValidation: [] }; const [response] = await updateContentModelMutation({ modelId: contentModel.modelId, data: { name: "new name", titleFieldId: "nonExistingTitleFieldId", fields: [field], layout: [[field.id]] } }); expect(response).toEqual({ data: { updateContentModel: { data: null, error: { code: "VALIDATION_ERROR", message: `Field does not exist in the model.`, data: { fieldId: "nonExistingTitleFieldId", fields: expect.any(Array) } } } } }); }); test("should execute hooks on create", async () => { const { createContentModelMutation } = useContentGqlHandler({ ...manageHandlerOpts, plugins: [assignModelEvents()] }); const [response] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); expect(response).toEqual({ data: { createContentModel: { data: expect.any(Object), error: null } } }); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreate")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreate")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreateFrom")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreateFrom")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeUpdate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterUpdate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeDelete")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterDelete")).toEqual(false); }); test("should execute hooks on create from", async () => { const { createContentModelMutation, createContentModelFromMutation } = useContentGqlHandler( { ...manageHandlerOpts, plugins: [assignModelEvents()] } ); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const { modelId } = createResponse.data.createContentModel.data; // need to reset because hooks for create have been fired pubSubTracker.reset(); const [response] = await createContentModelFromMutation({ modelId, data: { name: "Cloned model", modelId: "clonedTestModel", description: "Cloned model description", group: contentModelGroup.id } }); expect(response).toMatchObject({ data: { createContentModelFrom: { data: { name: "Cloned model", description: "Cloned model description", modelId: "clonedTestModel", group: { id: contentModelGroup.id, name: contentModelGroup.name }, fields: [], layout: [], plugin: false }, error: null } } }); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreateFrom")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreateFrom")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:beforeUpdate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterUpdate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeDelete")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterDelete")).toEqual(false); }); test("should execute hooks on update", async () => { const { createContentModelMutation, updateContentModelMutation } = useContentGqlHandler({ ...manageHandlerOpts, plugins: [assignModelEvents()] }); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const { modelId } = createResponse.data.createContentModel.data; // need to reset because hooks for create have been fired pubSubTracker.reset(); const [response] = await updateContentModelMutation({ modelId, data: { name: "Updated content model", fields: [], layout: [] } }); expect(response).toEqual({ data: { updateContentModel: { data: expect.any(Object), error: null } } }); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreateFrom")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreateFrom")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeUpdate")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:afterUpdate")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:beforeDelete")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterDelete")).toEqual(false); }); test("should execute hooks on delete", async () => { const { createContentModelMutation, deleteContentModelMutation } = useContentGqlHandler({ ...manageHandlerOpts, plugins: [assignModelEvents()] }); const [createResponse] = await createContentModelMutation({ data: { name: "Test Content model", modelId: "test-content-model", group: contentModelGroup.id } }); const { modelId } = createResponse.data.createContentModel.data; // need to reset because hooks for create have been fired pubSubTracker.reset(); const [response] = await deleteContentModelMutation({ modelId }); expect(response).toEqual({ data: { deleteContentModel: { data: true, error: null } } }); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeCreateFrom")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterCreateFrom")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeUpdate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:afterUpdate")).toEqual(false); expect(pubSubTracker.isExecutedOnce("contentModel:beforeDelete")).toEqual(true); expect(pubSubTracker.isExecutedOnce("contentModel:afterDelete")).toEqual(true); }); test("should refresh the schema when added new field", async () => { const { createContentModelMutation, updateContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const { listBugs } = useBugManageHandler(manageHandlerOpts); const bugModel = models.find(m => m.modelId === "bug"); if (!bugModel) { throw new Error("Could not find model `bug`."); } // Create initial record const [createBugModelResponse] = await createContentModelMutation({ data: { name: bugModel.name, modelId: bugModel.modelId, group: contentModelGroup.id } }); const removedFields: CmsModelField[] = []; const initialFields = Array.from(bugModel.fields); const initialLayouts = Array.from(bugModel.layout); removedFields.push(initialFields.pop() as CmsModelField); removedFields.push(initialFields.pop() as CmsModelField); initialLayouts.pop(); initialLayouts.pop(); await updateContentModelMutation({ modelId: createBugModelResponse.data.createContentModel.data.modelId, data: { fields: initialFields, layout: initialLayouts } }); const [listResponse] = await listBugs({ where: { name: "test" }, sort: ["createdOn_DESC"] }); // should not be able to query bugType or bugValue fields (they are defined in the graphql query) expect(listResponse).toEqual({ errors: [ { message: `Cannot query field "bugValue" on type "Bug". Did you mean "bugType"?`, locations: expect.any(Array) }, { message: `Cannot query field "bugFixed" on type "Bug". Did you mean "bugType"?`, locations: expect.any(Array) } ] }); // update model with new field so it can regenerate the schema const [updateFieldsBugModelResponse] = await updateContentModelMutation({ modelId: createBugModelResponse.data.createContentModel.data.modelId, data: { fields: initialFields.concat(removedFields), layout: initialLayouts.concat(removedFields.map(f => [f.id])) } }); expect(updateFieldsBugModelResponse).toEqual({ data: { updateContentModel: { data: expect.any(Object), error: null } } }); // make sure that we can query newly added fields const [listResponseAfterUpdate] = await listBugs({ where: { name: "test", bugType: "t1", bugValue: 3, bugFixed: 2 }, sort: ["createdOn_DESC"] }); expect(listResponseAfterUpdate).toEqual({ data: { listBugs: { data: [], meta: { totalCount: 0, hasMoreItems: false, cursor: null }, error: null } } }); }); test("should list only specific content models", async () => { const { createContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const createdContentModels = []; for (let i = 0; i < 3; i++) { const [createResponse] = await createContentModelMutation({ data: { name: `Test Content model instance-${i}`, modelId: `test-content-model-${i}`, group: contentModelGroup.id } }); createdContentModels.push(createResponse.data.createContentModel.data); } const { listContentModelsQuery: listModels } = useContentGqlHandler({ ...manageHandlerOpts, permissions: createPermissions({ models: [createdContentModels[0].modelId] }) }); const [response] = await listModels(); expect(response.data.listContentModels.data.length).toEqual(1); }); test("error when getting model without specific group permission", async () => { const { createContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const createdContentModels = []; for (let i = 0; i < 3; i++) { const [createResponse] = await createContentModelMutation({ data: { name: `Test Content model instance-${i}`, modelId: `test-content-model-${i}`, group: contentModelGroup.id } }); createdContentModels.push(createResponse.data.createContentModel.data); } // Get model with group permissions const permissions = createPermissions({ models: [createdContentModels[0].modelId], groups: ["some-group-id"] }); const { getContentModelQuery: getModel } = useContentGqlHandler({ ...manageHandlerOpts, permissions }); // Should return an error while getting a model without required group permission. const [response] = await getModel({ modelId: createdContentModels[0].modelId }); expect(response.data.getContentModel.data).toEqual(null); expect(response.data.getContentModel.error).toEqual({ code: "SECURITY_NOT_AUTHORIZED", data: { reason: 'Not allowed to access model "testContentModel0".' }, message: "Not authorized!" }); }); test("should be able to get model with specific group permission", async () => { const { createContentModelMutation } = useContentGqlHandler(manageHandlerOpts); const createdContentModels = []; for (let i = 0; i < 3; i++) { const [createResponse] = await createContentModelMutation({ data: { name: `Test Content model instance-${i}`, modelId: `test-content-model-${i}`, group: contentModelGroup.id } }); createdContentModels.push(createResponse.data.createContentModel.data); } // Get model with group permissions const permissions = createPermissions({ models: [createdContentModels[0].modelId], groups: [contentModelGroup.id] }); const { getContentModelQuery: getModelB } = useContentGqlHandler({ ...manageHandlerOpts, permissions }); // Should return an error while getting a model without required group permission. const [response] = await getModelB({ modelId: createdContentModels[0].modelId }); expect(response.data.getContentModel.data).toEqual({ ...createdContentModels[0], description: null }); expect(response.data.getContentModel.error).toEqual(null); }); });
the_stack
import { Component, ViewChild, ElementRef, OnInit, Input, AfterViewInit, } from '@angular/core'; import { FileUploader, FileUploaderOptions, FileItem } from 'ng2-file-upload'; import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import WarehouseProduct from '@modules/server.common/entities/WarehouseProduct'; import { IProductDescription, IProductTitle, IProductImage, } from '@modules/server.common/interfaces/IProduct'; import { ProductRouter } from '@modules/client.common.angular2/routers/product-router.service'; import Product from '@modules/server.common/entities/Product'; import { WarehouseProductsRouter } from '@modules/client.common.angular2/routers/warehouse-products-router.service'; import { ProductLocalesService } from '@modules/client.common.angular2/locale/product-locales.service'; import { TranslateService } from '@ngx-translate/core'; import { ILocaleMember } from '@modules/server.common/interfaces/ILocale'; import { environment } from '../../../environments/environment'; import ProductsCategory from '@modules/server.common/entities/ProductsCategory'; import { first } from 'rxjs/operators'; import { ProductsCategoryService } from '../../../services/products-category.service'; import DeliveryType from '@modules/server.common/enums/DeliveryType'; import { ModalController, ActionSheetController } from '@ionic/angular'; import { ProductImagesPopup } from '../product-pictures-popup/product-images-popup.component'; @Component({ selector: 'page-edit-product-type-popup', templateUrl: 'edit-product-type-popup.html', styleUrls: ['./edit-product-type-popup.scss'], }) export class EditProductTypePopupPage implements OnInit, AfterViewInit { OK: string = 'OK'; CANCEL: string = 'CANCEL'; SELECT_CATEGORIES: string = 'SELECT_CATEGORIES'; PREFIX: string = 'WAREHOUSE_VIEW.SELECT_POP_UP.'; selectOptionsObj: object; takaProductDelivery: boolean = true; takaProductTakeaway: boolean; isAvailable: boolean; @Input() warehouseProduct: WarehouseProduct; product: Product; readyToUpdate: boolean = false; uploader: FileUploader; translLang: string; productsCategories: ProductsCategory[]; selectedProductCategories: string[] = []; hasImage: boolean = true; private lastProductTitle: IProductTitle[]; private lastProductDescription: IProductDescription[]; private lastProductPrice: number; private lastProductCount: number; private imagesData: IProductImage[]; @ViewChild('fileInput', { static: true }) private fileInput: ElementRef; constructor( // public navParams: NavParams, private warehouseProductRouter: WarehouseProductsRouter, private productRouter: ProductRouter, private warehouseProductsRouter: WarehouseProductsRouter, private readonly _productsCategorySrvice: ProductsCategoryService, public modalController: ModalController, private camera: Camera, public actionSheetCtrl: ActionSheetController, public readonly localeTranslateService: ProductLocalesService, private translate: TranslateService ) { const uploaderOptions: FileUploaderOptions = { url: environment.API_FILE_UPLOAD_URL, // Use xhrTransport in favor of iframeTransport isHTML5: true, // Calculate progress independently for each uploaded file removeAfterUpload: true, // XHR request headers headers: [ { name: 'X-Requested-With', value: 'XMLHttpRequest', }, ], }; this.uploader = new FileUploader(uploaderOptions); this.uploader.onBuildItemForm = ( fileItem: any, form: FormData ): any => { // Add Cloudinary's unsigned upload preset to the upload form form.append('upload_preset', 'everbie-products-images'); // Add built-in and custom tags for displaying the uploaded photo in the list let tags = 'myphotoalbum'; if (this.product.title) { form.append('context', `photo=${this.product.title}`); tags = `myphotoalbum,${this.product.title}`; } // Upload to a custom folder // Note that by default, when uploading via the API, folders are not automatically created in your Media Library. // In order to automatically create the folders based on the API requests, // please go to your account upload settings and set the 'Auto-create folders' option to enabled. // TODO: use settings from .env file form.append('folder', 'angular_sample'); // Add custom tags form.append('tags', tags); // Add file to upload form.append('file', fileItem); // Use default "withCredentials" value for CORS requests fileItem.withCredentials = false; return { fileItem, form }; }; } @ViewChild('imageHolder', { static: true }) private _imageHolder: ElementRef; imageUrlChanged(ev) { const reader = new FileReader(); reader.addEventListener('load', (e) => { const imageBase64 = e.target['result']; this.hasImage = true; this._setImageHolderBackground(<string>imageBase64); }); reader.readAsDataURL(ev.target.files[0]); } get buttonOK() { return this._translate(this.PREFIX + this.OK); } get buttonCancel() { return this._translate(this.PREFIX + this.CANCEL); } get selectOptionTitle() { const title = this._translate(this.PREFIX + this.SELECT_CATEGORIES); this.selectOptionsObj = { subTitle: title }; return this.selectOptionsObj; } get isReadyToUpdate() { return ( this.localeTranslateService.isServiceStateValid && this.warehouseProduct.price !== null && this.warehouseProduct.count !== null && this.warehouseProduct.price !== 0 && this.warehouseProduct.count >= 0 ); } get warehouseId() { return localStorage.getItem('_warehouseId'); } get isBrowser() { return localStorage.getItem('_platform') === 'browser'; } get currentLocale() { return this.localeTranslateService.currentLocale; } set currentLocale(locale: string) { this.localeTranslateService.currentLocale = locale; } get productTitle() { return this.localeTranslateService.getMemberValue(this.product.title); } set productTitle(memberValue: string) { this.localeTranslateService.setMemberValue('title', memberValue); } get productDescription() { return this.localeTranslateService.getMemberValue( this.product.description ); } set productDescription(memberValue: string) { this.localeTranslateService.setMemberValue('description', memberValue); } async ngOnInit() { this.isAvailable = this.warehouseProduct.isProductAvailable; this.product = this.warehouseProduct.product as Product; this.lastProductCount = this.warehouseProduct.count; this.lastProductPrice = this.warehouseProduct.price; this.lastProductDescription = this.product.description; this.lastProductTitle = this.product.title; this.translLang = this.translate.currentLang; this.takaProductDelivery = this.warehouseProduct.isDeliveryRequired; this.takaProductTakeaway = this.warehouseProduct.isTakeaway; this.currentLocale = this.localeTranslateService.takeSelectedLang(this.translLang) || 'en-US'; this._setupLocaleServiceValidationState(); this._selectExistingProductCategories(); await this._loadProductsCategories(); } ngAfterViewInit(): void { const currentProductImage = this.localeTranslateService.getTranslate( this.product.images ); if (currentProductImage) { this.hasImage = true; } else { this.hasImage = false; } this._setImageHolderBackground(currentProductImage); } getProductTypeChange(type: string) { if (DeliveryType[type] === DeliveryType.Delivery) { if (!this.takaProductDelivery && !this.takaProductTakeaway) { this.takaProductTakeaway = true; } } else { if (!this.takaProductDelivery && !this.takaProductTakeaway) { this.takaProductDelivery = true; } } } localeTranslate(member: ILocaleMember[]): string { return this.localeTranslateService.getTranslate(member); } async showPicturesPopup() { let images = this.product.images.filter( (i) => i.locale === this.currentLocale ); if (this.imagesData) { const imagesDataLocale = this.imagesData[0].locale; if (imagesDataLocale === this.currentLocale) { images = this.imagesData; } } const modal = await this.modalController.create({ component: ProductImagesPopup, componentProps: { images, }, backdropDismiss: false, cssClass: 'mutation-product-images-modal', }); await modal.present(); const res = await modal.onDidDismiss(); const imageArray = res.data; if (imageArray && imageArray.length > 0) { const firstImgUrl = imageArray[0].url; this._setImageHolderBackground(firstImgUrl); this.imagesData = imageArray; } } takePicture(sourceType: number) { const options: CameraOptions = { quality: 50, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE, correctOrientation: true, sourceType, }; this.camera.getPicture(options).then(async (imageData) => { const base64Image = 'data:image/jpeg;base64,' + imageData; const file = await this.urltoFile( base64Image, this.createFileName(), 'image/jpeg' ); const fileItem = new FileItem(this.uploader, file, {}); this.uploader.queue.push(fileItem); }); } urltoFile(url, filename, mimeType) { return fetch(url) .then(function (res) { return res.arrayBuffer(); }) .then(function (buf) { return new File([buf], filename, { type: mimeType }); }); } async presentActionSheet() { const actionSheet = await this.actionSheetCtrl.create({ header: 'Select Image Source', buttons: [ { text: 'Load from Library', handler: () => { this.takePicture( this.camera.PictureSourceType.PHOTOLIBRARY ); }, }, { text: 'Use Camera', handler: () => { this.takePicture(this.camera.PictureSourceType.CAMERA); }, }, { text: 'Cancel', role: 'cancel' }, ], }); await actionSheet.present(); } cancelModal() { this.warehouseProduct.count = this.lastProductCount; this.warehouseProduct.price = this.lastProductPrice; this.product.description = this.lastProductDescription; this.product.title = this.lastProductTitle; this.modalController.dismiss(); } updateProduct() { if (this.uploader.queue.length >= 1) { this.uploader.queue[this.uploader.queue.length - 1].upload(); this.uploader.response.subscribe((res) => { res = JSON.parse(res); const locale = this.currentLocale; const width = res.width; const height = res.height; const orientation = width !== height ? (width > height ? 2 : 1) : 0; const url = res.url; const newImage = { locale, url, width, height, orientation, }; if (this.product.images.length > 0) { this.product.images.forEach((img, index) => { if (img.locale === locale) { this.product.images[index] = newImage; } }); } else { this.product.images.push(newImage); } this.uploadProduct(); }); } else { this.uploadProduct(); } } uploadProduct() { if (this.imagesData && this.imagesData.length > 0) { // Because all images in "imgLocale" has same local value we get first one const imgLocale = this.imagesData[0].locale; if (imgLocale === this.currentLocale) { this.product.images = this.product.images.filter( (i) => i.locale !== imgLocale ); this.product.images.push(...this.imagesData); } } this.localeTranslateService.assignPropertyValue( this.product.title, 'title' ); this.localeTranslateService.assignPropertyValue( this.product.description, 'description' ); this.product.categories = this.productsCategories .filter( (category) => this.selectedProductCategories && this.selectedProductCategories.some( (categoryId) => categoryId === category.id ) ) .map((category) => { return { _id: category.id, _createdAt: null, _updatedAt: null, name: category.name, }; }); this.productRouter.save(this.product).then((product: Product) => { this.product = product; this.warehouseProduct.product = product.id; this.warehouseProduct.isDeliveryRequired = this.takaProductDelivery; this.warehouseProduct.isTakeaway = this.takaProductTakeaway; this.warehouseProduct.isProductAvailable = this.isAvailable; this.warehouseProductsRouter .saveUpdated(this.warehouseId, this.warehouseProduct) .then((warehouse) => { this.modalController.dismiss(); }); }); } private _setImageHolderBackground(imageUrl: string) { const gradient = `linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)), url(${imageUrl})`; this._imageHolder.nativeElement.style.background = gradient; this._imageHolder.nativeElement.style.backgroundSize = `cover`; this._imageHolder.nativeElement.style.backgroundRepeat = 'no-repeat'; this._imageHolder.nativeElement.style.color = `white`; } private _translate(key: string): string { let translationResult = ''; this.translate.get(key).subscribe((res) => { translationResult = res; }); return translationResult; } private _selectExistingProductCategories() { this.selectedProductCategories = this.product.categories.map((category) => `${category}`) || []; } private _setupLocaleServiceValidationState() { this.localeTranslateService.setMemberValue('title', this.productTitle); this.localeTranslateService.setMemberValue( 'description', this.productDescription ); } private async _loadProductsCategories() { this.productsCategories = await this._productsCategorySrvice .getCategories() .pipe(first()) .toPromise(); } private createFileName() { const newFileName = new Date().getTime() + '.jpg'; return newFileName; } async clickHandler() { this.isAvailable != this.isAvailable; await this.warehouseProductRouter.changeProductAvailability( this.warehouseId, this.warehouseProduct.productId, this.isAvailable ); } }
the_stack
import { LongFormPage, PageOverrides } from "../site/LongFormPage" import { BlogIndexPage } from "../site/BlogIndexPage" import { FrontPage } from "../site/FrontPage" import { ChartsIndexPage, ChartIndexItem } from "../site/ChartsIndexPage" import { CovidPage } from "../site/CovidPage" import { SearchPage } from "../site/SearchPage" import { NotFoundPage } from "../site/NotFoundPage" import { DonatePage } from "../site/DonatePage" import * as React from "react" import * as ReactDOMServer from "react-dom/server" import * as lodash from "lodash" import { extractFormattingOptions, formatCountryProfile } from "./formatting" import { bakeGrapherUrls, getGrapherExportsByUrl, GrapherExports, } from "../baker/GrapherBakingUtils" import * as cheerio from "cheerio" import { Post } from "../db/model/Post" import { BAKED_BASE_URL, BLOG_POSTS_PER_PAGE } from "../settings/serverSettings" import { RECAPTCHA_SITE_KEY } from "../settings/clientSettings" import { EntriesByYearPage, EntriesForYearPage, } from "../site/EntriesByYearPage" import { VariableCountryPage } from "../site/VariableCountryPage" import { FeedbackPage } from "../site/FeedbackPage" import { getCountry, Country } from "../clientUtils/countries" import { memoize } from "../clientUtils/Util" import { CountryProfileSpec } from "../site/countryProfileProjects" import { FormattedPost, FormattingOptions, FullPost, JsonError, PostRow, } from "../clientUtils/owidTypes" import { formatPost } from "./formatWordpressPost" import { getBlogIndex, getEntriesByCategory, getFullPost, getLatestPostRevision, getPostBySlug, getPosts, isPostCitable, } from "../db/wpdb" import { mysqlFirst, queryMysql, knexTable } from "../db/db" import { getPageOverrides, isPageOverridesCitable } from "./pageOverrides" export const renderToHtmlPage = (element: any) => `<!doctype html>${ReactDOMServer.renderToStaticMarkup(element)}` export const renderChartsPage = async () => { const chartItems = (await queryMysql(` SELECT id, config->>"$.slug" AS slug, config->>"$.title" AS title, config->>"$.variantName" AS variantName FROM charts WHERE is_indexable IS TRUE AND publishedAt IS NOT NULL AND config->"$.isPublished" IS TRUE `)) as ChartIndexItem[] const chartTags = await queryMysql(` SELECT ct.chartId, ct.tagId, t.name as tagName, t.parentId as tagParentId FROM chart_tags ct JOIN charts c ON c.id=ct.chartId JOIN tags t ON t.id=ct.tagId `) for (const c of chartItems) { c.tags = [] } const chartsById = lodash.keyBy(chartItems, (c) => c.id) for (const ct of chartTags) { const c = chartsById[ct.chartId] if (c) c.tags.push({ id: ct.tagId, name: ct.tagName }) } return renderToHtmlPage( <ChartsIndexPage chartItems={chartItems} baseUrl={BAKED_BASE_URL} /> ) } // Only used in the dev server export const renderCovidPage = () => renderToHtmlPage(<CovidPage baseUrl={BAKED_BASE_URL} />) export const renderPageBySlug = async (slug: string) => { const post = await getPostBySlug(slug) return renderPost(post) } export const renderPreview = async (postId: number): Promise<string> => { const postApi = await getLatestPostRevision(postId) return renderPost(postApi) } export const renderMenuJson = async () => { const categories = await getEntriesByCategory() return JSON.stringify({ categories: categories }) } export const renderPost = async ( post: FullPost, baseUrl: string = BAKED_BASE_URL, grapherExports?: GrapherExports ) => { let exportsByUrl = grapherExports if (!grapherExports) { const $ = cheerio.load(post.content) const grapherUrls = $("iframe") .toArray() .filter((el) => (el.attribs["src"] || "").match(/\/grapher\//)) .map((el) => el.attribs["src"].trim()) // This can be slow if uncached! await bakeGrapherUrls(grapherUrls) exportsByUrl = await getGrapherExportsByUrl() } // Extract formatting options from post HTML comment (if any) const formattingOptions = extractFormattingOptions(post.content) const formatted = await formatPost(post, formattingOptions, exportsByUrl) const pageOverrides = await getPageOverrides(post, formattingOptions) const citationStatus = (await isPostCitable(post)) || isPageOverridesCitable(pageOverrides) return renderToHtmlPage( <LongFormPage withCitation={citationStatus} post={formatted} overrides={pageOverrides} formattingOptions={formattingOptions} baseUrl={baseUrl} /> ) } export const renderFrontPage = async () => { const entries = await getEntriesByCategory() const posts = await getBlogIndex() const totalCharts = ( await queryMysql( `SELECT COUNT(*) AS count FROM charts WHERE is_indexable IS TRUE AND publishedAt IS NOT NULL AND config -> "$.isPublished" IS TRUE` ) )[0].count as number return renderToHtmlPage( <FrontPage entries={entries} posts={posts} totalCharts={totalCharts} baseUrl={BAKED_BASE_URL} /> ) } export const renderDonatePage = () => renderToHtmlPage( <DonatePage baseUrl={BAKED_BASE_URL} recaptchaKey={RECAPTCHA_SITE_KEY} /> ) export const renderBlogByPageNum = async (pageNum: number) => { const allPosts = await getBlogIndex() const numPages = Math.ceil(allPosts.length / BLOG_POSTS_PER_PAGE) const posts = allPosts.slice( (pageNum - 1) * BLOG_POSTS_PER_PAGE, pageNum * BLOG_POSTS_PER_PAGE ) return renderToHtmlPage( <BlogIndexPage posts={posts} pageNum={pageNum} numPages={numPages} baseUrl={BAKED_BASE_URL} /> ) } export const renderSearchPage = () => renderToHtmlPage(<SearchPage baseUrl={BAKED_BASE_URL} />) export const renderNotFoundPage = () => renderToHtmlPage(<NotFoundPage baseUrl={BAKED_BASE_URL} />) export async function makeAtomFeed() { const postsApi = await getPosts(["post"], 10) const posts = await Promise.all( postsApi.map((postApi) => getFullPost(postApi, true)) ) const feed = `<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Our World in Data</title> <subtitle>Research and data to make progress against the world’s largest problems</subtitle> <id>${BAKED_BASE_URL}/</id> <link type="text/html" rel="alternate" href="${BAKED_BASE_URL}"/> <link type="application/atom+xml" rel="self" href="${BAKED_BASE_URL}/atom.xml"/> <updated>${posts[0].date.toISOString()}</updated> ${posts .map((post) => { const postUrl = `${BAKED_BASE_URL}/${post.path}` const image = post.imageUrl ? `<br><br><a href="${postUrl}" target="_blank"><img src="${post.imageUrl}"/></a>` : "" return `<entry> <title><![CDATA[${post.title}]]></title> <id>${postUrl}</id> <link rel="alternate" href="${postUrl}"/> <published>${post.date.toISOString()}</published> <updated>${post.modifiedDate.toISOString()}</updated> ${post.authors .map( (author: string) => `<author><name>${author}</name></author>` ) .join("")} <summary><![CDATA[${post.excerpt}${image}]]></summary> </entry>` }) .join("\n")} </feed> ` return feed } // These pages exist largely just for Google Scholar export const entriesByYearPage = async (year?: number) => { const entries = (await knexTable(Post.table) .where({ status: "publish" }) .join("post_tags", { "post_tags.post_id": "posts.id" }) .join("tags", { "tags.id": "post_tags.tag_id" }) .where({ "tags.name": "Entries" }) .select("title", "slug", "published_at")) as Pick< PostRow, "title" | "slug" | "published_at" >[] if (year !== undefined) return renderToHtmlPage( <EntriesForYearPage entries={entries} year={year} baseUrl={BAKED_BASE_URL} /> ) return renderToHtmlPage( <EntriesByYearPage entries={entries} baseUrl={BAKED_BASE_URL} /> ) } export const pagePerVariable = async ( variableId: number, countryName: string ) => { const variable = await mysqlFirst( ` SELECT v.id, v.name, v.unit, v.shortUnit, v.description, v.sourceId, u.fullName AS uploadedBy, v.display, d.id AS datasetId, d.name AS datasetName, d.namespace AS datasetNamespace FROM variables v JOIN datasets d ON d.id=v.datasetId JOIN users u ON u.id=d.dataEditedByUserId WHERE v.id = ? `, [variableId] ) if (!variable) throw new JsonError(`No variable by id '${variableId}'`, 404) variable.display = JSON.parse(variable.display) variable.source = await mysqlFirst( `SELECT id, name FROM sources AS s WHERE id = ?`, variable.sourceId ) const country = await knexTable("entities") .select("id", "name") .whereRaw("lower(name) = ?", [countryName]) .first() return renderToHtmlPage( <VariableCountryPage variable={variable} country={country} baseUrl={BAKED_BASE_URL} /> ) } export const feedbackPage = () => renderToHtmlPage(<FeedbackPage baseUrl={BAKED_BASE_URL} />) const getCountryProfilePost = memoize( async ( profileSpec: CountryProfileSpec, grapherExports?: GrapherExports ): Promise<[FormattedPost, FormattingOptions]> => { // Get formatted content from generic covid country profile page. const genericCountryProfilePost = await getPostBySlug( profileSpec.genericProfileSlug ) const profileFormattingOptions = extractFormattingOptions( genericCountryProfilePost.content ) const formattedPost = await formatPost( genericCountryProfilePost, profileFormattingOptions, grapherExports ) return [formattedPost, profileFormattingOptions] } ) // todo: we used to flush cache of this thing. const getCountryProfileLandingPost = memoize( async (profileSpec: CountryProfileSpec) => { return getPostBySlug(profileSpec.landingPageSlug) } ) export const renderCountryProfile = async ( profileSpec: CountryProfileSpec, country: Country, grapherExports?: GrapherExports ) => { const [formatted, formattingOptions] = await getCountryProfilePost( profileSpec, grapherExports ) const formattedCountryProfile = formatCountryProfile(formatted, country) const landing = await getCountryProfileLandingPost(profileSpec) const overrides: PageOverrides = { pageTitle: `${country.name}: ${profileSpec.pageTitle} Country Profile`, citationTitle: landing.title, citationSlug: landing.slug, citationCanonicalUrl: `${BAKED_BASE_URL}/${landing.slug}`, citationAuthors: landing.authors, citationPublicationDate: landing.date, canonicalUrl: `${BAKED_BASE_URL}/${profileSpec.rootPath}/${country.slug}`, excerpt: `${country.name}: ${formattedCountryProfile.excerpt}`, } return renderToHtmlPage( <LongFormPage withCitation={true} post={formattedCountryProfile} overrides={overrides} formattingOptions={formattingOptions} baseUrl={BAKED_BASE_URL} /> ) } export const countryProfileCountryPage = async ( profileSpec: CountryProfileSpec, countrySlug: string ) => { const country = getCountry(countrySlug) if (!country) throw new JsonError(`No such country ${countrySlug}`, 404) // Voluntarily not dealing with grapherExports on devServer for simplicity return renderCountryProfile(profileSpec, country) } export const flushCache = () => getCountryProfilePost.cache.clear?.()
the_stack
import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { INotebookTracker } from '@jupyterlab/notebook'; import { WidgetTracker, showDialog, Dialog, InputDialog } from '@jupyterlab/apputils'; import { CodeCell } from '@jupyterlab/cells'; import { Dashboard, DashboardDocumentFactory, DashboardTracker, IDashboardTracker } from './dashboard'; import { DashboardWidget } from './widget'; import { IDocumentManager } from '@jupyterlab/docmanager'; import { IMainMenu } from '@jupyterlab/mainmenu'; import { Widget, Menu } from '@lumino/widgets'; import { DocumentRegistry } from '@jupyterlab/docregistry'; import { ILauncher } from '@jupyterlab/launcher'; import { DashboardIcons } from './icons'; import { DashboardModel, DashboardModelFactory } from './model'; import { undoIcon, redoIcon, copyIcon, cutIcon, pasteIcon, runIcon, saveIcon } from '@jupyterlab/ui-components'; import { CommandIDs } from './commands'; import { ReadonlyJSONObject } from '@lumino/coreutils'; import { DashboardLayout } from './layout'; import { Widgetstore, WidgetInfo } from './widgetstore'; import { getMetadata } from './utils'; const extension: JupyterFrontEndPlugin<IDashboardTracker> = { id: 'jupyterlab-interactive-dashboard-editor', autoStart: true, requires: [INotebookTracker, IMainMenu, IDocumentManager, ILauncher], provides: IDashboardTracker, activate: ( app: JupyterFrontEnd, notebookTracker: INotebookTracker, mainMenu: IMainMenu, docManager: IDocumentManager, launcher: ILauncher ): IDashboardTracker => { // Tracker for Dashboard const dashboardTracker = new DashboardTracker({ namespace: 'dashboards' }); //Tracker for DashboardWidgets const outputTracker = new WidgetTracker<DashboardWidget>({ namespace: 'dashboard-outputs' }); // Clipboard for copy/pasting outputs. const clipboard = new Set<Widgetstore.WidgetInfo>(); // Define dashboard file type. const dashboardFiletype: Partial<DocumentRegistry.IFileType> = { name: 'dashboard', displayName: 'Dashboard', contentType: 'file', extensions: ['.dashboard', '.dash'], fileFormat: 'text', icon: DashboardIcons.tealDashboard, iconLabel: 'Dashboard', mimeTypes: ['application/json'] }; // Add dashboard file type to the doc registry. app.docRegistry.addFileType(dashboardFiletype); addCommands( app, dashboardTracker, outputTracker, clipboard, docManager, notebookTracker ); // Create a new model factory. const modelFactory = new DashboardModelFactory({ notebookTracker }); // Create a new widget factory. const widgetFactory = new DashboardDocumentFactory({ name: 'dashboard', modelName: 'dashboard', fileTypes: ['dashboard'], defaultFor: ['dashboard'], commandRegistry: app.commands, outputTracker }); app.docRegistry.addModelFactory(modelFactory); app.docRegistry.addWidgetFactory(widgetFactory); // Add newly created dashboards to the tracker, set their icon and label, // and set the default width, height, and scrollMode. widgetFactory.widgetCreated.connect((_sender, widget) => { void dashboardTracker.add(widget.content); widget.title.icon = dashboardFiletype.icon; widget.title.iconClass = dashboardFiletype.iconClass || ''; widget.title.iconLabel = dashboardFiletype.iconLabel || ''; const model = widget.content.model; // TODO: Make scrollMode changable in JL. Default 'infinite' for now. model.scrollMode = 'infinite'; model.width = Dashboard.DEFAULT_WIDTH; model.height = Dashboard.DEFAULT_HEIGHT; }); // Add commands to context menus. app.contextMenu.addItem({ command: CommandIDs.save, selector: '.pr-JupyterDashboard', rank: 3 }); app.contextMenu.addItem({ command: CommandIDs.undo, selector: '.pr-JupyterDashboard', rank: 1 }); app.contextMenu.addItem({ command: CommandIDs.redo, selector: '.pr-JupyterDashboard', rank: 2 }); app.contextMenu.addItem({ command: CommandIDs.cut, selector: '.pr-JupyterDashboard', rank: 3 }); app.contextMenu.addItem({ command: CommandIDs.copy, selector: '.pr-JupyterDashboard', rank: 4 }); app.contextMenu.addItem({ command: CommandIDs.paste, selector: '.pr-JupyterDashboard', rank: 5 }); const experimentalMenu = new Menu({ commands: app.commands }); experimentalMenu.title.label = 'Experimental'; experimentalMenu.addItem({ command: CommandIDs.saveToMetadata }); experimentalMenu.addItem({ command: CommandIDs.toggleInfiniteScroll }); experimentalMenu.addItem({ command: CommandIDs.trimDashboard }); app.contextMenu.addItem({ type: 'submenu', submenu: experimentalMenu, selector: '.pr-JupyterDashboard', rank: 6 }); app.contextMenu.addItem({ command: CommandIDs.deleteOutput, selector: '.pr-EditableWidget', rank: 0 }); app.contextMenu.addItem({ command: CommandIDs.toggleFitContent, selector: '.pr-EditableWidget', rank: 1 }); app.contextMenu.addItem({ command: CommandIDs.toggleWidgetMode, selector: '.pr-EditableWidget', rank: 2 }); app.contextMenu.addItem({ type: 'separator', selector: '.pr-EditableWidget', rank: 3 }); app.contextMenu.addItem({ command: CommandIDs.openFromMetadata, selector: '.jp-Notebook', rank: 16 }); // Add commands to key bindings app.commands.addKeyBinding({ command: CommandIDs.deleteOutput, args: {}, keys: ['Backspace'], selector: '.pr-EditableWidget' }); app.commands.addKeyBinding({ command: CommandIDs.undo, args: {}, keys: ['Z'], selector: '.pr-JupyterDashboard' }); app.commands.addKeyBinding({ command: CommandIDs.redo, args: {}, keys: ['Shift Z'], selector: '.pr-JupyterDashboard' }); app.commands.addKeyBinding({ command: CommandIDs.cut, args: {}, keys: ['Accel X'], selector: '.pr-JupyterDashboard' }); app.commands.addKeyBinding({ command: CommandIDs.copy, args: {}, keys: ['Accel C'], selector: '.pr-JupyterDashboard' }); app.commands.addKeyBinding({ command: CommandIDs.paste, args: {}, keys: ['Accel V'], selector: '.pr-JupyterDashboard' }); app.commands.addKeyBinding({ command: CommandIDs.toggleFitContent, args: {}, keys: ['K'], selector: '.pr-EditableWidget' }); // Add commands to edit menu. mainMenu.fileMenu.addGroup([ { command: CommandIDs.setDimensions }, { command: CommandIDs.setTileSize } ]); mainMenu.fileMenu.newMenu.addGroup([ { command: CommandIDs.createNew } ]); launcher.add({ command: CommandIDs.createNew, category: 'Other', rank: 1 }); return dashboardTracker; } }; /** * Add commands to the main JupyterLab command registry. * * @param app - the JupyterLab instance. * * @param dashboardTracker - a tracker for dashboards. * * @param outputTracker - a tracker for dashboard outputs. * * @param clipboard - a set used to keep track of widgets for copy/pasting. * * @param docManager - a document manager used to create/rename files. * * @param notebookTracker - a tracker for notebooks. */ function addCommands( app: JupyterFrontEnd, dashboardTracker: WidgetTracker<Dashboard>, outputTracker: WidgetTracker<DashboardWidget>, clipboard: Set<Widgetstore.WidgetInfo>, docManager: IDocumentManager, notebookTracker: INotebookTracker ): void { const { commands } = app; /** * Whether there is an active dashboard. */ function hasDashboard(): boolean { return dashboardTracker.currentWidget !== null; } /** * Whether there is a dashboard output. */ function hasOutput(): boolean { return outputTracker.currentWidget !== null; } function inToolbar(args: ReadonlyJSONObject): boolean { return args.toolbar as boolean; } /** * Deletes a selected DashboardWidget. */ commands.addCommand(CommandIDs.deleteOutput, { label: 'Delete Output', execute: args => { const widget = outputTracker.currentWidget; const dashboard = dashboardTracker.currentWidget; dashboard.deleteWidget(widget); } }); /** * Undo the last change to a dashboard. */ commands.addCommand(CommandIDs.undo, { label: args => (inToolbar(args) ? '' : 'Undo'), icon: undoIcon, execute: args => { dashboardTracker.currentWidget.undo(); }, isEnabled: args => inToolbar(args) || (dashboardTracker.currentWidget && dashboardTracker.currentWidget.model.widgetstore.hasUndo()) }); /** * Redo the last undo to a dashboard. */ commands.addCommand(CommandIDs.redo, { label: args => (inToolbar(args) ? '' : 'Redo'), icon: redoIcon, execute: args => { dashboardTracker.currentWidget.redo(); }, isEnabled: args => inToolbar(args) || (dashboardTracker.currentWidget && dashboardTracker.currentWidget.model.widgetstore.hasRedo()) }); commands.addCommand(CommandIDs.toggleFitContent, { label: args => 'Fit To Content', execute: args => { const widget = outputTracker.currentWidget; widget.fitToContent = !widget.fitToContent; if (widget.fitToContent) { widget.fitContent(); } }, isVisible: args => outputTracker.currentWidget.mode === 'free-edit', isToggled: args => outputTracker.currentWidget.fitToContent }); commands.addCommand(CommandIDs.toggleMode, { icon: args => { const mode = dashboardTracker.currentWidget?.model.mode || 'present'; if (mode === 'present') { return DashboardIcons.edit; } else { return DashboardIcons.view; } }, label: args => { if (inToolbar(args)) { return ''; } const mode = dashboardTracker.currentWidget?.model.mode || 'present'; if (mode === 'present') { return 'Switch To Edit Mode'; } else { return 'Switch To Presentation Mode'; } }, execute: args => { const dashboard = dashboardTracker.currentWidget; if (dashboard.model.mode === 'present') { dashboard.model.mode = 'free-edit'; } else { dashboard.model.mode = 'present'; } } }); commands.addCommand(CommandIDs.runOutput, { label: args => (inToolbar(args) ? '' : 'Run Output'), icon: runIcon, execute: args => { const widget = outputTracker.currentWidget; const sessionContext = widget.notebook.sessionContext; CodeCell.execute(widget.cell as CodeCell, sessionContext); } }); commands.addCommand(CommandIDs.setDimensions, { label: 'Set Dashboard Dimensions', execute: async args => { const model = dashboardTracker.currentWidget.model; const width = model.width ? model.width : Dashboard.DEFAULT_WIDTH; const height = model.height ? model.height : Dashboard.DEFAULT_HEIGHT; await showDialog({ title: 'Enter Dimensions', body: new Private.ResizeHandler(width, height), focusNodeSelector: 'input', buttons: [Dialog.cancelButton(), Dialog.okButton()] }).then(result => { const value = result.value; let newWidth = value[0]; let newHeight = value[1]; if (value === null && model.width && model.height) { return; } if (!newWidth) { if (!model.width) { newWidth = Dashboard.DEFAULT_WIDTH; } else { newWidth = model.width; } } if (!newHeight) { if (!model.height) { newHeight = Dashboard.DEFAULT_HEIGHT; } else { newHeight = model.height; } } model.width = newWidth; model.height = newHeight; }); }, isEnabled: hasDashboard }); commands.addCommand(CommandIDs.setTileSize, { label: 'Set Grid Dimensions', execute: async args => { const newSize = await InputDialog.getNumber({ title: 'Enter Grid Size' }); if (newSize.value) { const layout = dashboardTracker.currentWidget.layout as DashboardLayout; layout.setTileSize(newSize.value); } }, isEnabled: hasDashboard }); commands.addCommand(CommandIDs.copy, { label: args => (inToolbar(args) ? '' : 'Copy'), icon: copyIcon, execute: args => { const info = outputTracker.currentWidget.info; clipboard.clear(); clipboard.add(info); }, isEnabled: args => inToolbar(args) || hasOutput() }); commands.addCommand(CommandIDs.cut, { label: args => (inToolbar(args) ? '' : 'Cut'), icon: cutIcon, execute: args => { const widget = outputTracker.currentWidget; const info = widget.info; const dashboard = dashboardTracker.currentWidget; clipboard.clear(); clipboard.add(info); dashboard.deleteWidget(widget); }, isEnabled: args => inToolbar(args) || hasOutput() }); commands.addCommand(CommandIDs.paste, { label: args => (inToolbar(args) ? '' : 'Paste'), icon: pasteIcon, execute: args => { const id = args.dashboardId; let dashboard: Dashboard; if (id) { dashboard = dashboardTracker.find(widget => widget.id === id); } else { dashboard = dashboardTracker.currentWidget; } const widgetstore = dashboard.model.widgetstore; clipboard.forEach(info => { const widgetId = DashboardWidget.createDashboardWidgetId(); const pos = info.pos; pos.left = Math.max(pos.left - 10, 0); pos.top = Math.max(pos.top - 10, 0); const newWidget = widgetstore.createWidget({ ...info, widgetId, pos }); dashboard.addWidget(newWidget, pos); }); }, isEnabled: args => inToolbar(args) || (hasOutput() && clipboard.size !== 0) }); commands.addCommand(CommandIDs.saveToMetadata, { label: 'Save Dashboard To Notebook Metadata', execute: args => { const dashboard = dashboardTracker.currentWidget; dashboard.saveToNotebookMetadata(); } }); commands.addCommand(CommandIDs.createNew, { label: 'Dashboard', icon: DashboardIcons.tealDashboard, execute: async args => { // A new file is created and opened separately to override the default // opening behavior when there's a notebook and open the dashboard in a // split pane instead of a tab. const notebook = notebookTracker.currentWidget; const newModel = await docManager.newUntitled({ ext: 'dash', path: '/', type: 'file' }); const path = newModel.path; if (notebook) { docManager.openOrReveal(`/${path}`, undefined, undefined, { mode: 'split-left', ref: notebook.id }); } else { docManager.openOrReveal(`/${path}`); } } }); // TODO: Make this optionally saveAs (based on filename?) commands.addCommand(CommandIDs.save, { label: args => (inToolbar(args) ? '' : 'Save'), icon: saveIcon, execute: args => { const dashboard = dashboardTracker.currentWidget; dashboard.context.save(); }, isEnabled: args => inToolbar(args) || hasDashboard() }); commands.addCommand(CommandIDs.openFromMetadata, { label: 'Open Metadata Dashboard', execute: args => { const notebook = notebookTracker.currentWidget; const notebookMetadata = getMetadata(notebook); const notebookId = notebookMetadata.id; const cells = notebook.content.widgets; const widgetstore = new Widgetstore({ id: 0, notebookTracker }); widgetstore.startBatch(); for (const cell of cells) { const metadata = getMetadata(cell); if (metadata !== undefined && !metadata.hidden) { const widgetInfo: WidgetInfo = { widgetId: DashboardWidget.createDashboardWidgetId(), notebookId, cellId: metadata.id, pos: metadata.pos }; widgetstore.addWidget(widgetInfo); } } widgetstore.endBatch(); const model = new DashboardModel({ widgetstore, notebookTracker }); const dashboard = new Dashboard({ outputTracker, model }); dashboard.updateLayoutFromWidgetstore(); dashboard.model.mode = 'present'; notebook.context.addSibling(dashboard, { mode: 'split-left' }); }, isEnabled: args => { const notebook = notebookTracker.currentWidget; const metadata = getMetadata(notebook); if (metadata !== undefined && metadata.hasDashboard !== undefined) { return metadata.hasDashboard; } return false; } }); commands.addCommand(CommandIDs.toggleWidgetMode, { label: 'Snap to Grid', isToggled: args => { const widget = outputTracker.currentWidget; return widget.mode === 'grid-edit'; }, execute: args => { const widget = outputTracker.currentWidget; if (widget.mode === 'grid-edit') { widget.mode = 'free-edit'; } else if (widget.mode === 'free-edit') { widget.mode = 'grid-edit'; } } }); commands.addCommand(CommandIDs.toggleInfiniteScroll, { label: 'Infinite Scroll', isToggled: args => dashboardTracker.currentWidget?.model.scrollMode === 'infinite', execute: args => { const dashboard = dashboardTracker.currentWidget; if (dashboard.model.scrollMode === 'infinite') { dashboard.model.scrollMode = 'constrained'; } else { dashboard.model.scrollMode = 'infinite'; } } }); commands.addCommand(CommandIDs.trimDashboard, { label: 'Trim Dashboard', execute: args => { const dashboard = dashboardTracker.currentWidget; (dashboard.layout as DashboardLayout).trimDashboard(); } }); } /** * A namespace for private functionality. */ namespace Private { /** * A dialog with two boxes for setting a dashboard's width and height. */ export class ResizeHandler extends Widget { constructor(oldWidth: number, oldHeight: number) { const node = document.createElement('div'); const name = document.createElement('label'); name.textContent = 'Enter New Width/Height'; const width = document.createElement('input'); const height = document.createElement('input'); width.type = 'number'; height.type = 'number'; width.min = '0'; width.max = '10000'; height.min = '0'; height.max = '10000'; width.required = true; height.required = true; width.placeholder = `Width (${oldWidth})`; height.placeholder = `Height (${oldHeight})`; node.appendChild(name); node.appendChild(width); node.appendChild(height); super({ node }); } getValue(): number[] { const inputs = this.node.getElementsByTagName('input'); const widthInput = inputs[0]; const heightInput = inputs[1]; return [+widthInput.value, +heightInput.value]; } } } export default extension;
the_stack
import * as generators from "../utils/generators"; import { RenderModes } from "constants/WidgetConstants"; import { migrateChartDataFromArrayToObject, migrateToNewLayout, migrateInitialValues, migrateToNewMultiSelect, } from "./DSLMigrations"; import { buildChildren, widgetCanvasFactory, buildDslWithChildren, } from "test/factories/WidgetFactoryUtils"; import { cloneDeep } from "lodash"; import { GRID_DENSITY_MIGRATION_V1 } from "widgets/constants"; import { extractCurrentDSL } from "./WidgetPropsUtils"; describe("WidgetProps tests", () => { it("it checks if array to object migration functions for chart widget ", () => { const input = { type: "CANVAS_WIDGET", widgetId: "0", widgetName: "canvas", parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, version: 17, isLoading: false, renderMode: RenderModes.CANVAS, children: [ { widgetId: "some-random-id", widgetName: "chart1", parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, version: 17, isLoading: false, renderMode: RenderModes.CANVAS, type: "CHART_WIDGET", chartData: [ { seriesName: "seris1", data: [{ x: 1, y: 2 }], }, ], }, ], }; // mocking implementation of our generateReactKey function const generatorReactKeyMock = jest.spyOn(generators, "generateReactKey"); generatorReactKeyMock.mockImplementation(() => "some-random-key"); const result = migrateChartDataFromArrayToObject(input); const output = { type: "CANVAS_WIDGET", widgetId: "0", widgetName: "canvas", parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, version: 17, isLoading: false, renderMode: RenderModes.CANVAS, children: [ { widgetId: "some-random-id", widgetName: "chart1", parentColumnSpace: 1, parentRowSpace: 1, leftColumn: 0, rightColumn: 0, topRow: 0, bottomRow: 0, version: 17, isLoading: false, renderMode: RenderModes.CANVAS, type: "CHART_WIDGET", dynamicBindingPathList: [], chartData: { "some-random-key": { seriesName: "seris1", data: [{ x: 1, y: 2 }], }, }, }, ], }; expect(result).toStrictEqual(output); }); it("Grid density migration - Main container widgets", () => { const dsl: any = buildDslWithChildren([{ type: "TABS_WIDGET" }]); const newMigratedDsl: any = migrateToNewLayout(cloneDeep(dsl)); expect(dsl.children[0].topRow * GRID_DENSITY_MIGRATION_V1).toBe( newMigratedDsl.children[0].topRow, ); expect(dsl.children[0].bottomRow * GRID_DENSITY_MIGRATION_V1).toBe( newMigratedDsl.children[0].bottomRow, ); expect(dsl.children[0].rightColumn * GRID_DENSITY_MIGRATION_V1).toBe( newMigratedDsl.children[0].rightColumn, ); expect(dsl.children[0].leftColumn * GRID_DENSITY_MIGRATION_V1).toBe( newMigratedDsl.children[0].leftColumn, ); }); it("Grid density migration - widgets inside a container", () => { const childrenInsideContainer = buildChildren([ { type: "SWITCH_WIDGET" }, { type: "FORM_WIDGET" }, { type: "CONTAINER_WIDGET" }, ]); const dslWithContainer: any = buildDslWithChildren([ { type: "CONTAINER_WIDGET", children: childrenInsideContainer }, ]); const newMigratedDsl: any = migrateToNewLayout(cloneDeep(dslWithContainer)); // Container migrated checks const containerWidget = dslWithContainer.children[0]; const migratedContainer = newMigratedDsl.children[0]; expect(containerWidget.topRow * GRID_DENSITY_MIGRATION_V1).toBe( migratedContainer.topRow, ); expect(containerWidget.bottomRow * GRID_DENSITY_MIGRATION_V1).toBe( migratedContainer.bottomRow, ); expect(containerWidget.rightColumn * GRID_DENSITY_MIGRATION_V1).toBe( migratedContainer.rightColumn, ); expect(containerWidget.leftColumn * GRID_DENSITY_MIGRATION_V1).toBe( migratedContainer.leftColumn, ); // Children inside container miragted containerWidget.children.forEach((eachChild: any, index: any) => { const migratedChild = migratedContainer.children[index]; expect(eachChild.topRow * GRID_DENSITY_MIGRATION_V1).toBe( migratedChild.topRow, ); expect(eachChild.bottomRow * GRID_DENSITY_MIGRATION_V1).toBe( migratedChild.bottomRow, ); expect(eachChild.rightColumn * GRID_DENSITY_MIGRATION_V1).toBe( migratedChild.rightColumn, ); expect(eachChild.leftColumn * GRID_DENSITY_MIGRATION_V1).toBe( migratedChild.leftColumn, ); }); }); }); describe("Initial value migration test", () => { const containerWidget = { widgetName: "MainContainer", backgroundColor: "none", rightColumn: 1118, snapColumns: 16, detachFromLayout: true, widgetId: "0", topRow: 0, bottomRow: 560, snapRows: 33, isLoading: false, parentRowSpace: 1, type: "CANVAS_WIDGET", renderMode: RenderModes.CANVAS, canExtend: true, version: 18, minHeight: 600, parentColumnSpace: 1, dynamicTriggerPathList: [], dynamicBindingPathList: [], leftColumn: 0, }; it("Input widget", () => { const input = { ...containerWidget, children: [ { widgetName: "Input1", rightColumn: 8, widgetId: "ra3vyy3nt2", topRow: 1, bottomRow: 2, parentRowSpace: 40, isVisible: true, label: "", type: "INPUT_WIDGET", version: 1, parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 3, inputType: "TEXT", renderMode: RenderModes.CANVAS, resetOnSubmit: false, }, ], }; const output = { ...containerWidget, children: [ { widgetName: "Input1", rightColumn: 8, widgetId: "ra3vyy3nt2", topRow: 1, bottomRow: 2, parentRowSpace: 40, isVisible: true, label: "", type: "INPUT_WIDGET", version: 1, parentId: "0", isLoading: false, parentColumnSpace: 67.375, renderMode: "CANVAS", leftColumn: 3, inputType: "TEXT", // will not override existing property resetOnSubmit: false, // following properties get added isRequired: false, isDisabled: false, }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("DROP_DOWN_WIDGET", () => { const input = { ...containerWidget, children: [ { widgetName: "Select1", rightColumn: 6, selectionType: "SINGLE_SELECT", widgetId: "1e3ytl2pl9", topRow: 3, bottomRow: 4, parentRowSpace: 40, isVisible: true, label: "", type: "DROP_DOWN_WIDGET", version: 1, parentId: "0", isLoading: false, defaultOptionValue: "GREEN", parentColumnSpace: 67.375, renderMode: RenderModes.CANVAS, leftColumn: 1, options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], }, ], }; const output = { ...containerWidget, children: [ { widgetName: "Select1", rightColumn: 6, widgetId: "1e3ytl2pl9", topRow: 3, bottomRow: 4, parentRowSpace: 40, isVisible: true, label: "", selectionType: "SINGLE_SELECT", type: "DROP_DOWN_WIDGET", version: 1, parentId: "0", isLoading: false, defaultOptionValue: "GREEN", parentColumnSpace: 67.375, renderMode: "CANVAS", leftColumn: 1, options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], // following properties get added isRequired: false, isDisabled: false, }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("MULTI_SELECT_WIDGET", () => { const input = { ...containerWidget, children: [ { widgetName: "Select2", rightColumn: 59, isFilterable: true, widgetId: "zvgz9h4fh4", topRow: 10, bottomRow: 14, parentRowSpace: 10, isVisible: true, label: "", type: "DROP_DOWN_WIDGET", version: 1, parentId: "0y8sg136kg", isLoading: false, defaultOptionValue: "GREEN", selectionType: "MULTI_SELECT", parentColumnSpace: 8.35546875, dynamicTriggerPathList: [], leftColumn: 39, dynamicBindingPathList: [], renderMode: RenderModes.CANVAS, options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], }, ], }; const output = { ...containerWidget, children: [ { renderMode: RenderModes.CANVAS, type: "MULTI_SELECT_WIDGET", widgetName: "Select2", rightColumn: 59, widgetId: "zvgz9h4fh4", topRow: 10, bottomRow: 14, parentRowSpace: 10, isVisible: true, label: "", version: 1, parentId: "0y8sg136kg", isLoading: false, defaultOptionValue: "GREEN", parentColumnSpace: 8.35546875, dynamicTriggerPathList: [], leftColumn: 39, dynamicBindingPathList: [], options: [ { label: "Blue", value: "BLUE", }, { label: "Green", value: "GREEN", }, { label: "Red", value: "RED", }, ], }, ], }; expect(migrateToNewMultiSelect(input)).toEqual(output); }); it("DATE_PICKER_WIDGET2", () => { const input = { ...containerWidget, children: [ { widgetName: "DatePicker1", defaultDate: "2021-05-12T06:50:51.743Z", rightColumn: 7, dateFormat: "YYYY-MM-DD HH:mm", widgetId: "5jbfazqnca", topRow: 2, bottomRow: 3, parentRowSpace: 40, isVisible: true, datePickerType: "DATE_PICKER", label: "", type: "DATE_PICKER_WIDGET2", renderMode: RenderModes.CANVAS, version: 2, parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 2, isDisabled: false, }, ], }; const output = { ...containerWidget, children: [ { widgetName: "DatePicker1", defaultDate: "2021-05-12T06:50:51.743Z", rightColumn: 7, dateFormat: "YYYY-MM-DD HH:mm", widgetId: "5jbfazqnca", topRow: 2, bottomRow: 3, parentRowSpace: 40, isVisible: true, datePickerType: "DATE_PICKER", label: "", type: "DATE_PICKER_WIDGET2", renderMode: RenderModes.CANVAS, version: 2, parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 2, isDisabled: false, // following properties get added isRequired: false, minDate: "2001-01-01 00:00", maxDate: "2041-12-31 23:59", }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("SWITCH_WIDGET", () => { const input = { ...containerWidget, children: [ { widgetName: "Switch1", rightColumn: 5, widgetId: "4ksqurxmwn", topRow: 2, bottomRow: 3, parentRowSpace: 40, isVisible: true, label: "Label", type: "SWITCH_WIDGET", renderMode: RenderModes.CANVAS, defaultSwitchState: true, version: 1, alignWidget: "LEFT", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 3, }, ], }; const output = { ...containerWidget, children: [ { widgetName: "Switch1", rightColumn: 5, widgetId: "4ksqurxmwn", topRow: 2, bottomRow: 3, parentRowSpace: 40, isVisible: true, label: "Label", type: "SWITCH_WIDGET", renderMode: RenderModes.CANVAS, defaultSwitchState: true, version: 1, alignWidget: "LEFT", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 3, // following properties get added isDisabled: false, }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("Video widget", () => { const input = { ...containerWidget, children: [ { widgetName: "Video1", rightColumn: 9, dynamicPropertyPathList: [], widgetId: "ti5b5f5hvq", topRow: 3, bottomRow: 10, parentRowSpace: 40, isVisible: true, type: "VIDEO_WIDGET", renderMode: RenderModes.CANVAS, version: 1, onPlay: "", url: "https://www.youtube.com/watch?v=mzqK0QIZRLs", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 2, autoPlay: false, }, ], }; const output = { ...containerWidget, children: [ { widgetName: "Video1", rightColumn: 9, dynamicPropertyPathList: [], widgetId: "ti5b5f5hvq", topRow: 3, bottomRow: 10, parentRowSpace: 40, isVisible: true, type: "VIDEO_WIDGET", renderMode: RenderModes.CANVAS, version: 1, onPlay: "", url: "https://www.youtube.com/watch?v=mzqK0QIZRLs", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 2, autoPlay: false, // following properties get added isRequired: false, isDisabled: false, }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("CHECKBOX_WIDGET", () => { const input = { ...containerWidget, children: [ { widgetName: "Checkbox1", rightColumn: 8, widgetId: "djxhhl1p7t", topRow: 4, bottomRow: 5, parentRowSpace: 40, isVisible: true, label: "Label", type: "CHECKBOX_WIDGET", renderMode: RenderModes.CANVAS, version: 1, alignWidget: "LEFT", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 5, defaultCheckedState: true, }, ], }; const output = { ...containerWidget, children: [ { widgetName: "Checkbox1", rightColumn: 8, widgetId: "djxhhl1p7t", topRow: 4, bottomRow: 5, parentRowSpace: 40, isVisible: true, label: "Label", type: "CHECKBOX_WIDGET", renderMode: RenderModes.CANVAS, version: 1, alignWidget: "LEFT", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 5, defaultCheckedState: true, // following properties get added isDisabled: false, isRequired: false, }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("RADIO_GROUP_WIDGET", () => { const input = { ...containerWidget, children: [ { widgetName: "RadioGroup1", rightColumn: 5, widgetId: "4ixyqnw2no", topRow: 3, bottomRow: 5, parentRowSpace: 40, isVisible: true, label: "", type: "RADIO_GROUP_WIDGET", renderMode: RenderModes.CANVAS, version: 1, parentId: "0", isLoading: false, defaultOptionValue: "Y", parentColumnSpace: 67.375, leftColumn: 2, options: [ { label: "Yes", value: "Y", }, { label: "No", value: "N", }, ], }, ], }; const output = { ...containerWidget, children: [ { widgetName: "RadioGroup1", rightColumn: 5, widgetId: "4ixyqnw2no", topRow: 3, bottomRow: 5, parentRowSpace: 40, isVisible: true, label: "", type: "RADIO_GROUP_WIDGET", renderMode: RenderModes.CANVAS, version: 1, parentId: "0", isLoading: false, defaultOptionValue: "Y", parentColumnSpace: 67.375, leftColumn: 2, options: [ { label: "Yes", value: "Y", }, { label: "No", value: "N", }, ], // following properties get added isDisabled: false, isRequired: false, }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("FILE_PICKER_WIDGET", () => { const input = { ...containerWidget, children: [ { widgetName: "FilePicker1", rightColumn: 5, isDefaultClickDisabled: true, widgetId: "fzajyy8qft", topRow: 4, bottomRow: 5, parentRowSpace: 40, isVisible: true, label: "Select Files", maxFileSize: 5, type: "FILE_PICKER_WIDGET", renderMode: RenderModes.CANVAS, version: 1, fileDataType: "Base64", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 1, files: [], maxNumFiles: 1, }, ], }; const output = { ...containerWidget, children: [ { widgetName: "FilePicker1", rightColumn: 5, isDefaultClickDisabled: true, widgetId: "fzajyy8qft", topRow: 4, bottomRow: 5, parentRowSpace: 40, isVisible: true, label: "Select Files", maxFileSize: 5, type: "FILE_PICKER_WIDGET", renderMode: RenderModes.CANVAS, version: 1, fileDataType: "Base64", parentId: "0", isLoading: false, parentColumnSpace: 67.375, leftColumn: 1, files: [], maxNumFiles: 1, // following properties get added isDisabled: false, isRequired: false, allowedFileTypes: [], }, ], }; expect(migrateInitialValues(input)).toEqual(output); }); it("", () => { const tabsWidgetDSL: any = (version = 1) => { const children: any = buildChildren([ { version, type: "TABS_WIDGET", children: [ { type: "CANVAS_WIDGET", tabId: "tab1212332", tabName: "Newly Added Tab", widgetId: "o9ody00ep7", parentId: "jd83uvbkmp", detachFromLayout: true, children: [], parentRowSpace: 1, parentColumnSpace: 1, // leftColumn: 0, // rightColumn: 592, // Commenting these coz they are not provided for a newly added tab in the Tabs widget version 2 // bottomRow: 280, topRow: 0, isLoading: false, widgetName: "Canvas1", renderMode: "CANVAS", }, ], }, ]); const dsl: any = widgetCanvasFactory.build({ children, }); return { data: { layouts: [{ dsl }], }, }; }; const migratedDslV2: any = extractCurrentDSL(tabsWidgetDSL()); expect(migratedDslV2.children[0].children[0].leftColumn).toBeNaN(); const migratedDslV3: any = extractCurrentDSL(tabsWidgetDSL(2)); expect(migratedDslV3.children[0].version).toBe(3); expect(migratedDslV3.children[0].children[0].leftColumn).not.toBeNaN(); expect(migratedDslV3.children[0].children[0].leftColumn).toBe(0); }); });
the_stack
import type {Mutable} from "@swim/util"; import type {TestOptions} from "./Test"; import type {SpecTest} from "./SpecTest"; import type {SpecUnit} from "./SpecUnit"; import type {Proof} from "./Proof"; import type {Report} from "./Report"; import {ConsoleReport} from "./ConsoleReport"; import {Exam} from "./Exam"; /** @public */ export interface SpecClass { /** @internal */ tests?: SpecTest[]; /** @internal */ units?: SpecUnit[]; } /** * Specification for testing a unit of code functionality. A `Spec` evaluates * [[TestFunc test functions]], registered with [[Test `@Test`]] method * decorators. A `Spec` also executes child specs, instantiated by [[UnitSpec * unit factory functions]] that are registered with [[Unit `@Unit`]] method * decorators. * @public */ export class Spec { constructor() { this.name = this.constructor.name; this.parent = null; } /** * The name of this `Spec`; either a custom `name` set via the [[withName]] * method, or the name of this spec's constructor function. */ readonly name: string; /** * Sets the name of this `Spec`, and returns `this`. If `name` is `undefined`, * sets this spec's name to the name of its constructor function. */ withName(name: string | undefined): this { (this as Mutable<this>).name = name !== void 0 ? name : this.constructor.name; return this; } /** * The `Spec` that instantiated this spec via one of the parent's * [[UnitFunc child unit factory functions]], or `null` if this is * a root spec. */ readonly parent: Spec | null; /** @internal */ setParent(parent: Spec | null): void { (this as Mutable<this>).parent = parent; } /** * Evaluates all [[TestFunc test functions]] registered with this `Spec`, * then executes any child specs returned by [[UnitFunc unit factory * functions]] registered with this `Spec`. Returns a `Promise` that * completes with the test report. */ run(report?: Report): Promise<Report> { return Spec.run(report, Object.getPrototypeOf(this), this); } /** * Returns a new [[Exam]] to be passed to the [[TestFunc test function]] with * the given `name`. `Spec` subclasses can override `createExam` to return a * custome `Exam` subclass with added functionality. */ createExam(report: Report, name: string, options: TestOptions): Exam { return new Exam(report, this, name, options); } /** * Lifecycle callback invoked before running this `Spec`. */ willRunSpec(report: Report): void { // hook } /** * Lifecycle callback invoked before running any [[TestFunc test functions]] * registered with this `Spec`. */ willRunTests(report: Report): void { // hook } /** * Lifecycle callback invoked before evaluating the `exam`'s [[TestFunc test * function]]. */ willRunTest(report: Report, exam: Exam): void { // hook } /** * Lifecycle callback invoked every time a test function attempts to proove * an assertion. */ onProof(report: Report, exam: Exam, proof: Proof): void { // hook } /** * Lifecycle callback invoked every time a test function makes a comment. */ onComment(report: Report, exam: Exam, message: string): void { // hook } /** * Lifecycle callback invoked after evaluating the `exam`'s [[TestFunc test * function]], passing in the returned value of the test function–or a thrown * exception–in `result`. */ didRunTest(report: Report, exam: Exam, result: unknown): void { // hook } /** * Lifecycle callback invoked after all [[TestFunc test functions]] * registered with this `Spec` have been evaluated. */ didRunTests(report: Report): void { // hook } /** * Lifecycle callback invoked before executing any child specs returned by * [[TestUnit unit factory functions]] registered with this `Spec`. */ willRunUnits(report: Report): void { // hook } /** * Lifecycle callback invoked before executing a child `unit` spec. */ willRunUnit(report: Report, unit: Spec): void { // hook } /** * Lifecycle callback invoked after executing a child `unit` spec. */ didRunUnit(report: Report, unit: Spec): void { // hook } /** * Lifecycle callback invoked after all child specs returned by [[TestUnit * unit factory functions]] registered with this `Spec` have been executed. */ didRunUnits(report: Report): void { // hook } /** * Lifecycle callback invoked after all [[TestFunc test functions]] and child * specs returned by [[UnitFunc unit factory functions]] registered with this * `Spec` have been evaluated. */ didRunSpec(report: Report): void { // hook } /** * Initializes the prototype of a `Spec` subclass. * @internal */ static init(specClass: SpecClass): void { if (!Object.prototype.hasOwnProperty.call(specClass, "tests")) { specClass.tests = []; } if (!Object.prototype.hasOwnProperty.call(specClass, "units")) { specClass.units = []; } } /** * Evaluates all [[TestFunc test functions]] registered with a `spec`, * then executes any child specs returned by [[UnitFunc unit factory * functions]] registered with this `Spec`. Returns a `Promise` that * completes with the test report. Instantiates `spec` from the given * `specClass`, if `spec` is undefined. Uses the constructor function of * the `Spec` class on which `run` is invoked, if `specClass` is undefined. * Creates a new `ConsoleReport` if `report` is undefined. */ static run(report?: Report, specClass: SpecClass | null = null, spec?: Spec): Promise<Report> { if (report === void 0) { report = new ConsoleReport(); } if (specClass === null) { specClass = this.prototype as unknown as SpecClass; } if (spec === void 0) { spec = new (specClass as any).constructor() as Spec; } let tests = new Array<SpecTest>(); let units = new Array<SpecUnit>(); do { if (Object.prototype.hasOwnProperty.call(specClass, "tests")) { tests = tests.concat(specClass.tests!); } if (Object.prototype.hasOwnProperty.call(specClass, "units")) { units = units.concat(specClass.units!); } specClass = Object.getPrototypeOf(specClass); } while (specClass !== null); if (typeof spec.willRunSpec === "function") { spec.willRunSpec(report); } report.willRunSpec(spec); return Spec.runTests(report, spec, tests) .then(Spec.runUnits.bind(void 0, report, spec, units)) .then(Spec.runSuccess.bind(void 0, report, spec), Spec.runFailure.bind(void 0, report, spec)); } /** * Asynchronously evaluates a list of `tests`. * @internal */ static runTests(report: Report, spec: Spec, tests: SpecTest[]): Promise<Spec> { if (typeof spec.willRunTests === "function") { spec.willRunTests(report); } report.willRunTests(spec); return Spec.runTest(report, spec, tests, 0) .then(Spec.runTestSuccess.bind(void 0, report, spec), Spec.runTestFailure.bind(void 0, report, spec)); } /** * Asynchronously executes the next test in a list `tests`. * @internal */ static runTest(report: Report, spec: Spec, tests: SpecTest[], index: number): Promise<SpecTest[]> { if (index < tests.length) { const testCase = tests[index]!; return testCase.run(report, spec) .then(Spec.runTest.bind(void 0, report, spec, tests, index + 1)); } else { return Promise.resolve(tests); } } /** * Asynchronously completes the evaluation of a successful test. * @internal */ static runTestSuccess(report: Report, spec: Spec, result: unknown): Spec { report.didRunTests(spec); if (typeof spec.didRunTests === "function") { spec.didRunTests(report); } return spec; } /** * Asynchronously completes the evaluation of a failed test. * @internal */ static runTestFailure(report: Report, spec: Spec, error: unknown): never { report.didRunTests(spec); if (typeof spec.didRunTests === "function") { spec.didRunTests(report); } throw error; } /** * Asynchronously evaluates a list of child `units`. * @internal */ static runUnits(report: Report, spec: Spec, units: SpecUnit[]): Promise<Spec> { if (typeof spec.willRunUnits === "function") { spec.willRunUnits(report); } report.willRunUnits(spec); return Spec.runUnit(report, spec, units, 0) .then(Spec.runUnitsSuccess.bind(void 0, report, spec), Spec.runUnitsFailure.bind(void 0, report, spec)); } /** * Asynchronously executes the next unit in a list `units`. * @internal */ static runUnit(report: Report, spec: Spec, units: SpecUnit[], index: number): Promise<SpecUnit[]> { if (index < units.length) { const testUnit = units[index]!; return testUnit.run(report, spec) .then(Spec.runUnit.bind(void 0, report, spec, units, index + 1)); } else { return Promise.resolve(units); } } /** * Asynchronously completes the execution of a successful child unit. * @internal */ static runUnitsSuccess(report: Report, spec: Spec, result: unknown): Spec { report.didRunUnits(spec); if (typeof spec.didRunUnits === "function") { spec.didRunUnits(report); } return spec; } /** * Asynchronously completes the execution of a failed child unit. * @internal */ static runUnitsFailure(report: Report, spec: Spec, error: unknown): never { report.didRunUnits(spec); if (typeof spec.didRunUnits === "function") { spec.didRunUnits(report); } throw error; } /** * Asynchronously completes the successful execution of a `spec`. * @internal */ static runSuccess(report: Report, spec: Spec, result: unknown): Report { report.didRunSpec(spec); if (typeof spec.didRunSpec === "function") { spec.didRunSpec(report); } return report; } /** * Asynchronously completes the failed execution of a `spec`. * @internal */ static runFailure(report: Report, spec: Spec, error: unknown): Report { report.didRunSpec(spec); if (typeof spec.didRunSpec === "function") { spec.didRunSpec(report); } return report; } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/signalRSharedPrivateLinkResourcesMappers"; import * as Parameters from "../models/parameters"; import { SignalRManagementClientContext } from "../signalRManagementClientContext"; /** Class representing a SignalRSharedPrivateLinkResources. */ export class SignalRSharedPrivateLinkResources { private readonly client: SignalRManagementClientContext; /** * Create a SignalRSharedPrivateLinkResources. * @param {SignalRManagementClientContext} client Reference to the service client. */ constructor(client: SignalRManagementClientContext) { this.client = client; } /** * List shared private link resources * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param [options] The optional parameters * @returns Promise<Models.SignalRSharedPrivateLinkResourcesListResponse> */ list( resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase ): Promise<Models.SignalRSharedPrivateLinkResourcesListResponse>; /** * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param callback The callback */ list( resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.SharedPrivateLinkResourceList> ): void; /** * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param options The optional parameters * @param callback The callback */ list( resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedPrivateLinkResourceList> ): void; list( resourceGroupName: string, resourceName: string, options?: | msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedPrivateLinkResourceList>, callback?: msRest.ServiceCallback<Models.SharedPrivateLinkResourceList> ): Promise<Models.SignalRSharedPrivateLinkResourcesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, listOperationSpec, callback ) as Promise<Models.SignalRSharedPrivateLinkResourcesListResponse>; } /** * Get the specified shared private link resource * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param [options] The optional parameters * @returns Promise<Models.SignalRSharedPrivateLinkResourcesGetResponse> */ get( sharedPrivateLinkResourceName: string, resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase ): Promise<Models.SignalRSharedPrivateLinkResourcesGetResponse>; /** * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param callback The callback */ get( sharedPrivateLinkResourceName: string, resourceGroupName: string, resourceName: string, callback: msRest.ServiceCallback<Models.SharedPrivateLinkResource> ): void; /** * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param options The optional parameters * @param callback The callback */ get( sharedPrivateLinkResourceName: string, resourceGroupName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedPrivateLinkResource> ): void; get( sharedPrivateLinkResourceName: string, resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedPrivateLinkResource>, callback?: msRest.ServiceCallback<Models.SharedPrivateLinkResource> ): Promise<Models.SignalRSharedPrivateLinkResourcesGetResponse> { return this.client.sendOperationRequest( { sharedPrivateLinkResourceName, resourceGroupName, resourceName, options }, getOperationSpec, callback ) as Promise<Models.SignalRSharedPrivateLinkResourcesGetResponse>; } /** * Create or update a shared private link resource * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param parameters The shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param [options] The optional parameters * @returns Promise<Models.SignalRSharedPrivateLinkResourcesCreateOrUpdateResponse> */ createOrUpdate( sharedPrivateLinkResourceName: string, parameters: Models.SharedPrivateLinkResource, resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase ): Promise<Models.SignalRSharedPrivateLinkResourcesCreateOrUpdateResponse> { return this.beginCreateOrUpdate( sharedPrivateLinkResourceName, parameters, resourceGroupName, resourceName, options ).then((lroPoller) => lroPoller.pollUntilFinished()) as Promise< Models.SignalRSharedPrivateLinkResourcesCreateOrUpdateResponse >; } /** * Delete the specified shared private link resource * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod( sharedPrivateLinkResourceName: string, resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase ): Promise<msRest.RestResponse> { return this.beginDeleteMethod( sharedPrivateLinkResourceName, resourceGroupName, resourceName, options ).then((lroPoller) => lroPoller.pollUntilFinished()); } /** * Create or update a shared private link resource * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param parameters The shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate( sharedPrivateLinkResourceName: string, parameters: Models.SharedPrivateLinkResource, resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { sharedPrivateLinkResourceName, parameters, resourceGroupName, resourceName, options }, beginCreateOrUpdateOperationSpec, options ); } /** * Delete the specified shared private link resource * @param sharedPrivateLinkResourceName The name of the shared private link resource * @param resourceGroupName The name of the resource group that contains the resource. You can * obtain this value from the Azure Resource Manager API or the portal. * @param resourceName The name of the resource. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod( sharedPrivateLinkResourceName: string, resourceGroupName: string, resourceName: string, options?: msRest.RequestOptionsBase ): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { sharedPrivateLinkResourceName, resourceGroupName, resourceName, options }, beginDeleteMethodOperationSpec, options ); } /** * List shared private link resources * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.SignalRSharedPrivateLinkResourcesListNextResponse> */ listNext( nextPageLink: string, options?: msRest.RequestOptionsBase ): Promise<Models.SignalRSharedPrivateLinkResourcesListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext( nextPageLink: string, callback: msRest.ServiceCallback<Models.SharedPrivateLinkResourceList> ): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext( nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SharedPrivateLinkResourceList> ): void; listNext( nextPageLink: string, options?: | msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SharedPrivateLinkResourceList>, callback?: msRest.ServiceCallback<Models.SharedPrivateLinkResourceList> ): Promise<Models.SignalRSharedPrivateLinkResourcesListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback ) as Promise<Models.SignalRSharedPrivateLinkResourcesListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources", urlParameters: [Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResourceList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", urlParameters: [ Parameters.sharedPrivateLinkResourceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResource }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", urlParameters: [ Parameters.sharedPrivateLinkResourceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.SharedPrivateLinkResource, required: true } }, responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResource }, 201: { bodyMapper: Mappers.SharedPrivateLinkResource }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SignalRService/signalR/{resourceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}", urlParameters: [ Parameters.sharedPrivateLinkResourceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [Parameters.nextPageLink], queryParameters: [Parameters.apiVersion], headerParameters: [Parameters.acceptLanguage], responses: { 200: { bodyMapper: Mappers.SharedPrivateLinkResourceList }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
import { localize } from 'vs/nls'; import product from 'vs/platform/product/common/product'; import { isMacintosh, isLinux, language } from 'vs/base/common/platform'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { URI } from 'vs/base/common/uri'; import { MenuId, Action2, registerAction2 } from 'vs/platform/actions/common/actions'; import { KeyChord, KeyMod, KeyCode } from 'vs/base/common/keyCodes'; import { IProductService } from 'vs/platform/product/common/productService'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { CATEGORIES } from 'vs/workbench/common/actions'; class KeybindingsReferenceAction extends Action2 { static readonly ID = 'workbench.action.keybindingsReference'; static readonly AVAILABLE = !!(isLinux ? product.keyboardShortcutsUrlLinux : isMacintosh ? product.keyboardShortcutsUrlMac : product.keyboardShortcutsUrlWin); constructor() { super({ id: KeybindingsReferenceAction.ID, title: { value: localize('keybindingsReference', "Keyboard Shortcuts Reference"), mnemonicTitle: localize({ key: 'miKeyboardShortcuts', comment: ['&& denotes a mnemonic'] }, "&&Keyboard Shortcuts Reference"), original: 'Keyboard Shortcuts Reference' }, category: CATEGORIES.Help, f1: true, keybinding: { weight: KeybindingWeight.WorkbenchContrib, when: null, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KeyK, KeyMod.CtrlCmd | KeyCode.KeyR) }, menu: { id: MenuId.MenubarHelpMenu, group: '2_reference', order: 1 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); const url = isLinux ? productService.keyboardShortcutsUrlLinux : isMacintosh ? productService.keyboardShortcutsUrlMac : productService.keyboardShortcutsUrlWin; if (url) { openerService.open(URI.parse(url)); } } } class OpenIntroductoryVideosUrlAction extends Action2 { static readonly ID = 'workbench.action.openVideoTutorialsUrl'; static readonly AVAILABLE = !!product.introductoryVideosUrl; constructor() { super({ id: OpenIntroductoryVideosUrlAction.ID, title: { value: localize('openVideoTutorialsUrl', "Video Tutorials"), mnemonicTitle: localize({ key: 'miVideoTutorials', comment: ['&& denotes a mnemonic'] }, "&&Video Tutorials"), original: 'Video Tutorials' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '2_reference', order: 2 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.introductoryVideosUrl) { openerService.open(URI.parse(productService.introductoryVideosUrl)); } } } class OpenTipsAndTricksUrlAction extends Action2 { static readonly ID = 'workbench.action.openTipsAndTricksUrl'; static readonly AVAILABLE = !!product.tipsAndTricksUrl; constructor() { super({ id: OpenTipsAndTricksUrlAction.ID, title: { value: localize('openTipsAndTricksUrl', "Tips and Tricks"), mnemonicTitle: localize({ key: 'miTipsAndTricks', comment: ['&& denotes a mnemonic'] }, "Tips and Tri&&cks"), original: 'Tips and Tricks' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '2_reference', order: 3 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.tipsAndTricksUrl) { openerService.open(URI.parse(productService.tipsAndTricksUrl)); } } } class OpenDocumentationUrlAction extends Action2 { static readonly ID = 'workbench.action.openDocumentationUrl'; static readonly AVAILABLE = !!product.documentationUrl; constructor() { super({ id: OpenDocumentationUrlAction.ID, title: { value: localize('openDocumentationUrl', "Documentation"), mnemonicTitle: localize({ key: 'miDocumentation', comment: ['&& denotes a mnemonic'] }, "&&Documentation"), original: 'Documentation' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '1_welcome', order: 3 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.documentationUrl) { openerService.open(URI.parse(productService.documentationUrl)); } } } class OpenNewsletterSignupUrlAction extends Action2 { static readonly ID = 'workbench.action.openNewsletterSignupUrl'; static readonly AVAILABLE = !!product.newsletterSignupUrl; constructor() { super({ id: OpenNewsletterSignupUrlAction.ID, title: { value: localize('newsletterSignup', "Signup for the VS Code Newsletter"), original: 'Signup for the VS Code Newsletter' }, category: CATEGORIES.Help, f1: true }); } async run(accessor: ServicesAccessor): Promise<void> { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); const telemetryService = accessor.get(ITelemetryService); const info = await telemetryService.getTelemetryInfo(); openerService.open(URI.parse(`${productService.newsletterSignupUrl}?machineId=${encodeURIComponent(info.machineId)}`)); } } class OpenTwitterUrlAction extends Action2 { static readonly ID = 'workbench.action.openTwitterUrl'; static readonly AVAILABLE = !!product.twitterUrl; constructor() { super({ id: OpenTwitterUrlAction.ID, title: { value: localize('openTwitterUrl', "Join Us on Twitter"), mnemonicTitle: localize({ key: 'miTwitter', comment: ['&& denotes a mnemonic'] }, "&&Join Us on Twitter"), original: 'Join Us on Twitter' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '3_feedback', order: 1 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.twitterUrl) { openerService.open(URI.parse(productService.twitterUrl)); } } } class OpenRequestFeatureUrlAction extends Action2 { static readonly ID = 'workbench.action.openRequestFeatureUrl'; static readonly AVAILABLE = !!product.requestFeatureUrl; constructor() { super({ id: OpenRequestFeatureUrlAction.ID, title: { value: localize('openUserVoiceUrl', "Search Feature Requests"), mnemonicTitle: localize({ key: 'miUserVoice', comment: ['&& denotes a mnemonic'] }, "&&Search Feature Requests"), original: 'Search Feature Requests' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '3_feedback', order: 2 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.requestFeatureUrl) { openerService.open(URI.parse(productService.requestFeatureUrl)); } } } class OpenLicenseUrlAction extends Action2 { static readonly ID = 'workbench.action.openLicenseUrl'; static readonly AVAILABLE = !!product.licenseUrl; constructor() { super({ id: OpenLicenseUrlAction.ID, title: { value: localize('openLicenseUrl', "View License"), mnemonicTitle: localize({ key: 'miLicense', comment: ['&& denotes a mnemonic'] }, "View &&License"), original: 'View License' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '4_legal', order: 1 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.licenseUrl) { if (language) { const queryArgChar = productService.licenseUrl.indexOf('?') > 0 ? '&' : '?'; openerService.open(URI.parse(`${productService.licenseUrl}${queryArgChar}lang=${language}`)); } else { openerService.open(URI.parse(productService.licenseUrl)); } } } } class OpenPrivacyStatementUrlAction extends Action2 { static readonly ID = 'workbench.action.openPrivacyStatementUrl'; static readonly AVAILABE = !!product.privacyStatementUrl; constructor() { super({ id: OpenPrivacyStatementUrlAction.ID, title: { value: localize('openPrivacyStatement', "Privacy Statement"), mnemonicTitle: localize({ key: 'miPrivacyStatement', comment: ['&& denotes a mnemonic'] }, "Privac&&y Statement"), original: 'Privacy Statement' }, category: CATEGORIES.Help, f1: true, menu: { id: MenuId.MenubarHelpMenu, group: '4_legal', order: 2 } }); } run(accessor: ServicesAccessor): void { const productService = accessor.get(IProductService); const openerService = accessor.get(IOpenerService); if (productService.privacyStatementUrl) { openerService.open(URI.parse(productService.privacyStatementUrl)); } } } // --- Actions Registration if (KeybindingsReferenceAction.AVAILABLE) { registerAction2(KeybindingsReferenceAction); } if (OpenIntroductoryVideosUrlAction.AVAILABLE) { registerAction2(OpenIntroductoryVideosUrlAction); } if (OpenTipsAndTricksUrlAction.AVAILABLE) { registerAction2(OpenTipsAndTricksUrlAction); } if (OpenDocumentationUrlAction.AVAILABLE) { registerAction2(OpenDocumentationUrlAction); } if (OpenNewsletterSignupUrlAction.AVAILABLE) { registerAction2(OpenNewsletterSignupUrlAction); } if (OpenTwitterUrlAction.AVAILABLE) { registerAction2(OpenTwitterUrlAction); } if (OpenRequestFeatureUrlAction.AVAILABLE) { registerAction2(OpenRequestFeatureUrlAction); } if (OpenLicenseUrlAction.AVAILABLE) { registerAction2(OpenLicenseUrlAction); } if (OpenPrivacyStatementUrlAction.AVAILABE) { registerAction2(OpenPrivacyStatementUrlAction); }
the_stack
import { DocPlainText, DocLinkTag, TSDocConfiguration, DocParagraph, DocNode, DocBlock, DocComment, DocSection, DocCodeSpan, StandardTags, DocNodeKind } from '@microsoft/tsdoc'; import { ApiItem, ApiItemKind, ApiParameterListMixin, ApiPackage, ApiReleaseTagMixin, ReleaseTag, ApiDocumentedItem, ApiEntryPoint, ApiStaticMixin, ApiEnum } from 'api-extractor-model-me'; import { DocEmphasisSpan } from '../nodes/DocEmphasisSpan'; import { DocHeading } from '../nodes/DocHeading'; import { DocTable } from '../nodes/DocTable'; import { Utilities } from '../utils/Utilities'; import { PackageName } from '@rushstack/node-core-library'; import { DocNoteBox } from '../nodes/DocNoteBox'; import { DocTableRow } from '../nodes/DocTableRow'; import { DocTableCell } from '../nodes/DocTableCell'; export function getLinkForApiItem( apiItem: ApiItem, addFileNameSuffix: boolean ) { const fileName = getFilenameForApiItem(apiItem, addFileNameSuffix); const headingAnchor = getHeadingAnchorForApiItem(apiItem); return `./${fileName}#${headingAnchor}`; } export function getFilenameForApiItem( apiItem: ApiItem, addFileNameSuffix: boolean ): string { if (apiItem.kind === ApiItemKind.Model) { return 'index.md'; } let baseName: string = ''; let multipleEntryPoints: boolean = false; for (const hierarchyItem of apiItem.getHierarchy()) { // For overloaded methods, add a suffix such as "MyClass.myMethod_2". let qualifiedName: string = Utilities.getSafeFilenameForName( hierarchyItem.displayName ); if (ApiParameterListMixin.isBaseClassOf(hierarchyItem)) { if (hierarchyItem.overloadIndex > 1) { // Subtract one for compatibility with earlier releases of API Documenter. // (This will get revamped when we fix GitHub issue #1308) qualifiedName += `_${hierarchyItem.overloadIndex - 1}`; } } switch (hierarchyItem.kind) { case ApiItemKind.Model: break; case ApiItemKind.EntryPoint: const packageName: string = hierarchyItem.parent!.displayName; let entryPointName: string = PackageName.getUnscopedName(packageName); if (multipleEntryPoints) { entryPointName = `${PackageName.getUnscopedName(packageName)}/${ hierarchyItem.displayName }`; } baseName = Utilities.getSafeFilenameForName(entryPointName); break; case ApiItemKind.Package: baseName = Utilities.getSafeFilenameForName( PackageName.getUnscopedName(hierarchyItem.displayName) ); if ((hierarchyItem as ApiPackage).entryPoints.length > 1) { multipleEntryPoints = true; } break; case ApiItemKind.Namespace: baseName += '.' + qualifiedName; if (addFileNameSuffix) { baseName += '_n'; } break; case ApiItemKind.Class: case ApiItemKind.Interface: baseName += '.' + qualifiedName; break; } } return baseName + '.md'; } // TODO: handle method overloads and namespace? function getHeadingAnchorForApiItem(apiItem: ApiItem): string { const scopedName: string = lowercaseAndRemoveSymbols( apiItem.getScopedNameWithinPackage() ); switch (apiItem.kind) { case ApiItemKind.Function: return `${scopedName}`; case ApiItemKind.Variable: return `${scopedName}`; case ApiItemKind.TypeAlias: return `${scopedName}`; case ApiItemKind.Enum: return `${scopedName}`; case ApiItemKind.Method: case ApiItemKind.MethodSignature: return `${scopedName}`; case ApiItemKind.Property: case ApiItemKind.PropertySignature: return `${scopedName}`; case ApiItemKind.Constructor: case ApiItemKind.ConstructSignature: return `${scopedName}`; case ApiItemKind.Class: return `${scopedName}_class`; case ApiItemKind.Interface: return `${scopedName}_interface`; case ApiItemKind.Model: return `api-reference`; case ApiItemKind.Namespace: return `${scopedName}_namespace`; case ApiItemKind.Package: const unscopedPackageName: string = lowercaseAndRemoveSymbols( PackageName.getUnscopedName(apiItem.displayName) ); return `${unscopedPackageName}_package`; case ApiItemKind.EntryPoint: const packageName: string = apiItem.parent!.displayName; return lowercaseAndRemoveSymbols( `${packageName}${apiItem.displayName && '/' + apiItem.displayName}` ); case ApiItemKind.EnumMember: return `${scopedName}_enummember`; default: throw new Error( 'Unsupported API item kind:3 ' + apiItem.kind + apiItem.displayName ); } } function lowercaseAndRemoveSymbols(input: string): string { return input.replace(/[\.()]/g, '').toLowerCase(); } export function createBetaWarning(configuration: TSDocConfiguration): DocNode { const betaWarning: string = 'This API is provided as a preview for developers and may change' + ' based on feedback that we receive. Do not use this API in a production environment.'; return new DocNoteBox({ configuration }, [ new DocParagraph({ configuration }, [ new DocPlainText({ configuration, text: betaWarning }) ]) ]); } export function createRemarksSection( apiItem: ApiItem, configuration: TSDocConfiguration ): DocNode[] { const nodes: DocNode[] = []; if (apiItem instanceof ApiDocumentedItem) { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; if (tsdocComment) { // Write the @remarks block if (tsdocComment.remarksBlock) { nodes.push(...tsdocComment.remarksBlock.content.nodes); } } } return nodes; } export function createExampleSection( apiItem: ApiItem, configuration: TSDocConfiguration ): DocNode[] { const nodes: DocNode[] = []; if (apiItem instanceof ApiDocumentedItem) { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; if (tsdocComment) { // Write the @example blocks const exampleBlocks: DocBlock[] = tsdocComment.customBlocks.filter( x => x.blockTag.tagNameWithUpperCase === StandardTags.example.tagNameWithUpperCase ); let exampleNumber: number = 1; for (const exampleBlock of exampleBlocks) { const heading: string = exampleBlocks.length > 1 ? `Example ${exampleNumber}` : 'Example'; nodes.push(new DocHeading({ configuration, title: heading, level: 2 })); nodes.push(...exampleBlock.content.nodes); ++exampleNumber; } } } return nodes; } export function createTitleCell( apiItem: ApiItem, configuration: TSDocConfiguration, addFileNameSuffix: boolean ): DocTableCell { return new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ new DocLinkTag({ configuration, tagName: '@link', linkText: Utilities.getConciseSignature(apiItem), urlDestination: getLinkForApiItem(apiItem, addFileNameSuffix) }) ]) ]); } /** * This generates a DocTableCell for an ApiItem including the summary section and "(BETA)" annotation. * * @remarks * We mostly assume that the input is an ApiDocumentedItem, but it's easier to perform this as a runtime * check than to have each caller perform a type cast. */ export function createDescriptionCell( apiItem: ApiItem, configuration: TSDocConfiguration ): DocTableCell { const section: DocSection = new DocSection({ configuration }); if (ApiReleaseTagMixin.isBaseClassOf(apiItem)) { if (apiItem.releaseTag === ReleaseTag.Beta) { section.appendNodesInParagraph([ new DocEmphasisSpan({ configuration, bold: true, italic: true }, [ new DocPlainText({ configuration, text: '(BETA)' }) ]), new DocPlainText({ configuration, text: ' ' }) ]); } } if (apiItem instanceof ApiDocumentedItem) { if (apiItem.tsdocComment !== undefined) { appendAndMergeSection(section, apiItem.tsdocComment.summarySection); } } return new DocTableCell({ configuration }, section.nodes); } export function createModifiersCell( apiItem: ApiItem, configuration: TSDocConfiguration ): DocTableCell { const section: DocSection = new DocSection({ configuration }); if (ApiStaticMixin.isBaseClassOf(apiItem)) { if (apiItem.isStatic) { section.appendNodeInParagraph( new DocCodeSpan({ configuration, code: 'static' }) ); } } return new DocTableCell({ configuration }, section.nodes); } function appendAndMergeSection( output: DocSection, docSection: DocSection ): void { let firstNode: boolean = true; for (const node of docSection.nodes) { if (firstNode) { if (node.kind === DocNodeKind.Paragraph) { output.appendNodesInParagraph(node.getChildNodes()); firstNode = false; continue; } } firstNode = false; output.appendNode(node); } } export function createThrowsSection( apiItem: ApiItem, configuration: TSDocConfiguration ): DocNode[] { const output: DocNode[] = []; if (apiItem instanceof ApiDocumentedItem) { const tsdocComment: DocComment | undefined = apiItem.tsdocComment; if (tsdocComment) { // Write the @throws blocks const throwsBlocks: DocBlock[] = tsdocComment.customBlocks.filter( x => x.blockTag.tagNameWithUpperCase === StandardTags.throws.tagNameWithUpperCase ); if (throwsBlocks.length > 0) { const heading: string = 'Exceptions'; output.push(new DocHeading({ configuration, title: heading })); for (const throwsBlock of throwsBlocks) { output.push(...throwsBlock.content.nodes); } } } } return output; } export function createEntryPointTitleCell( apiItem: ApiEntryPoint, configuration: TSDocConfiguration, addFileNameSuffix: boolean ): DocTableCell { return new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ new DocLinkTag({ configuration, tagName: '@link', linkText: `/${apiItem.displayName}`, urlDestination: getLinkForApiItem(apiItem, addFileNameSuffix) }) ]) ]); } /** * GENERATE PAGE: ENUM */ export function createEnumTables( apiEnum: ApiEnum, configuration: TSDocConfiguration ): DocNode[] { const output: DocNode[] = []; const enumMembersTable: DocTable = new DocTable({ configuration, headerTitles: ['Member', 'Value', 'Description'] }); for (const apiEnumMember of apiEnum.members) { enumMembersTable.addRow( new DocTableRow({ configuration }, [ new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ new DocPlainText({ configuration, text: Utilities.getConciseSignature(apiEnumMember) }) ]) ]), new DocTableCell({ configuration }, [ new DocParagraph({ configuration }, [ new DocCodeSpan({ configuration, code: apiEnumMember.initializerExcerpt.text }) ]) ]), createDescriptionCell(apiEnumMember, configuration) ]) ); } if (enumMembersTable.rows.length > 0) { output.push( new DocHeading({ configuration, title: 'Enumeration Members' }) ); output.push(enumMembersTable); } return output; }
the_stack
import { EnumeratorBase } from "../System/Collections/Enumeration/EnumeratorBase"; import { DisposableBase } from "../System/Disposable/DisposableBase"; import { IEnumerator } from "../System/Collections/Enumeration/IEnumerator"; import { IEnumerable } from "../System/Collections/Enumeration/IEnumerable"; import { Action, ActionWithIndex, Closure, Comparison, EqualityComparison, HashSelector, PredicateWithIndex, Selector, SelectorWithIndex } from "../System/FunctionTypes"; import { IDictionary, IMap } from "../System/Collections/Dictionaries/IDictionary"; import { Comparable } from "../System/IComparable"; import { Order } from "../System/Collections/Sorting/Order"; import { EnumerableAction } from "./EnumerableAction"; import { Primitive } from "../System/Primitive"; import { ForEachEnumerable } from "../System/Collections/Enumeration/ForEachEnumerable"; import { InfiniteValueFactory } from "../System/Collections/Enumeration/InfiniteEnumerator"; export declare class InfiniteLinqEnumerable<T> extends DisposableBase { protected _enumeratorFactory: () => IEnumerator<T>; constructor(_enumeratorFactory: () => IEnumerator<T>, finalizer?: Closure | null); protected _isEndless: boolean | undefined; readonly isEndless: boolean | undefined; getEnumerator(): IEnumerator<T>; protected _onDispose(): void; asEnumerable(): this; /** * Similar to forEach, but executes an action for each time a value is enumerated. * If the action explicitly returns false or 0 (EnumerationAction.Break), the enumeration will complete. * If it returns a 2 (EnumerationAction.Skip) it will move on to the next item. * This also automatically handles disposing the enumerator. * @param action * @param initializer * @param isEndless Special case where isEndless can be null in order to negate inheritance. * @param onComplete Executes just before the enumerator releases when there is no more entries. * @returns {any} */ doAction(action: ActionWithIndex<T> | PredicateWithIndex<T> | SelectorWithIndex<T, number> | SelectorWithIndex<T, EnumerableAction>, initializer: Closure | null, isEndless: true, onComplete?: Action<number>): InfiniteLinqEnumerable<T>; doAction(action: ActionWithIndex<T> | PredicateWithIndex<T> | SelectorWithIndex<T, number> | SelectorWithIndex<T, EnumerableAction>, initializer?: Closure | null, isEndless?: boolean | null | undefined, onComplete?: Action<number>): LinqEnumerable<T>; force(): void; skip(count: number): this; take(count: number): FiniteEnumerable<T>; elementAt(index: number): T; elementAtOrDefault(index: number): T | undefined; elementAtOrDefault(index: number, defaultValue: T): T; first(): T; firstOrDefault(): T | undefined; firstOrDefault(defaultValue: T): T; single(): T; singleOrDefault(): T | undefined; singleOrDefault(defaultValue: T): T; any(): boolean; isEmpty(): boolean; traverseDepthFirst(childrenSelector: (element: T) => ForEachEnumerable<T> | null | undefined): LinqEnumerable<T>; traverseDepthFirst<TNode>(childrenSelector: (element: T | TNode) => ForEachEnumerable<TNode> | null | undefined): LinqEnumerable<TNode>; traverseDepthFirst<TResult>(childrenSelector: (element: T) => ForEachEnumerable<T> | null | undefined, resultSelector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; traverseDepthFirst<TNode, TResult>(childrenSelector: (element: T | TNode) => ForEachEnumerable<TNode> | null | undefined, resultSelector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; flatten<TFlat>(): InfiniteLinqEnumerable<TFlat>; flatten(): InfiniteLinqEnumerable<any>; pairwise<TSelect>(selector: (previous: T, current: T, index: number) => TSelect): InfiniteLinqEnumerable<TSelect>; scan(func: (previous: T, current: T, index: number) => T, seed?: T): this; select<TResult>(selector: SelectorWithIndex<T, TResult>): InfiniteLinqEnumerable<TResult>; map<TResult>(selector: SelectorWithIndex<T, TResult>): InfiniteLinqEnumerable<TResult>; protected _selectMany<TElement, TResult>(collectionSelector: SelectorWithIndex<T, ForEachEnumerable<TElement> | null | undefined>, resultSelector?: (collection: T, element: TElement) => TResult): LinqEnumerable<TResult>; selectMany<TResult>(collectionSelector: SelectorWithIndex<T, ForEachEnumerable<TResult> | null | undefined>): InfiniteLinqEnumerable<TResult>; selectMany<TElement, TResult>(collectionSelector: SelectorWithIndex<T, ForEachEnumerable<TElement> | null | undefined>, resultSelector: (collection: T, element: TElement) => TResult): InfiniteLinqEnumerable<TResult>; protected _filterSelected(selector?: SelectorWithIndex<T, T>, filter?: PredicateWithIndex<T>): LinqEnumerable<T>; protected _filterSelected<TResult>(selector: SelectorWithIndex<T, TResult>, filter?: PredicateWithIndex<TResult>): LinqEnumerable<TResult>; /** * Returns selected values that are not null or undefined. */ choose(): InfiniteLinqEnumerable<T>; choose<TResult>(selector?: Selector<T, TResult>): InfiniteLinqEnumerable<TResult>; where(predicate: PredicateWithIndex<T>): this; filter(predicate: PredicateWithIndex<T>): this; nonNull(): this; ofType<TType>(type: { new (...params: any[]): TType; }): InfiniteLinqEnumerable<TType>; except(second: ForEachEnumerable<T>, compareSelector?: HashSelector<T>): this; distinct(compareSelector?: HashSelector<T>): this; distinctUntilChanged(compareSelector?: HashSelector<T>): this; /** * Returns a single default value if empty. * @param defaultValue * @returns {Enumerable} */ defaultIfEmpty(defaultValue?: T): this; zip<TSecond, TResult>(second: ForEachEnumerable<TSecond>, resultSelector: (first: T, second: TSecond, index: number) => TResult): LinqEnumerable<TResult>; zipMultiple<TSecond, TResult>(second: ArrayLike<ForEachEnumerable<TSecond>>, resultSelector: (first: T, second: TSecond, index: number) => TResult): LinqEnumerable<TResult>; join<TInner, TKey, TResult>(inner: ForEachEnumerable<TInner>, outerKeySelector: Selector<T, TKey>, innerKeySelector: Selector<TInner, TKey>, resultSelector: (outer: T, inner: TInner) => TResult, compareSelector?: HashSelector<TKey>): LinqEnumerable<TResult>; groupJoin<TInner, TKey, TResult>(inner: ForEachEnumerable<TInner>, outerKeySelector: Selector<T, TKey>, innerKeySelector: Selector<TInner, TKey>, resultSelector: (outer: T, inner: TInner[] | null) => TResult, compareSelector?: HashSelector<TKey>): LinqEnumerable<TResult>; merge(enumerables: ArrayLike<ForEachEnumerable<T>>): this; concat(...enumerables: Array<ForEachEnumerable<T>>): this; union(second: ForEachEnumerable<T>, compareSelector?: HashSelector<T>): this; insertAt(index: number, other: ForEachEnumerable<T>): this; alternateMultiple(sequence: ForEachEnumerable<T>): this; alternateSingle(value: T): this; alternate(...sequence: T[]): this; catchError(handler: (e: any) => void): this; finallyAction(action: Closure): this; buffer(size: number): InfiniteLinqEnumerable<T[]>; share(): this; memoize(): InfiniteLinqEnumerable<T>; } /** * Enumerable<T> is a wrapper class that allows more primitive enumerables to exhibit LINQ behavior. * * In C# Enumerable<T> is not an instance but has extensions for IEnumerable<T>. * In this case, we use Enumerable<T> as the underlying class that is being chained. */ export declare class LinqEnumerable<T> extends InfiniteLinqEnumerable<T> { constructor(enumeratorFactory: () => IEnumerator<T>, finalizer?: Closure | null, isEndless?: boolean); asEnumerable(): this; skipWhile(predicate: PredicateWithIndex<T>): LinqEnumerable<T>; takeWhile(predicate: PredicateWithIndex<T>): this; takeUntil(predicate: PredicateWithIndex<T>, includeUntilValue?: boolean): this; traverseBreadthFirst(childrenSelector: (element: T) => ForEachEnumerable<T> | null | undefined): LinqEnumerable<T>; traverseBreadthFirst<TNode>(childrenSelector: (element: T | TNode) => ForEachEnumerable<TNode> | null | undefined): LinqEnumerable<TNode>; traverseBreadthFirst<TResult>(childrenSelector: (element: T) => ForEachEnumerable<T> | null | undefined, resultSelector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; traverseBreadthFirst<TNode, TResult>(childrenSelector: (element: T | TNode) => ForEachEnumerable<TNode> | null | undefined, resultSelector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; forEach(action: ActionWithIndex<T>, max?: number): number; forEach(action: PredicateWithIndex<T>, max?: number): number; toArray(predicate?: PredicateWithIndex<T>): T[]; copyTo(target: T[], index?: number, count?: number): T[]; toLookup<TKey, TValue>(keySelector: SelectorWithIndex<T, TKey>, elementSelector?: SelectorWithIndex<T, TValue>, compareSelector?: HashSelector<TKey>): Lookup<TKey, TValue>; toMap<TResult>(keySelector: SelectorWithIndex<T, string | number | symbol>, elementSelector: SelectorWithIndex<T, TResult>): IMap<TResult>; toDictionary<TKey, TValue>(keySelector: SelectorWithIndex<T, TKey>, elementSelector: SelectorWithIndex<T, TValue>, compareSelector?: HashSelector<TKey>): IDictionary<TKey, TValue>; toJoinedString(separator?: string, selector?: Selector<T, string>): string; takeExceptLast(count?: number): this; skipToLast(count: number): this; select<TResult>(selector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; map<TResult>(selector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; selectMany<TResult>(collectionSelector: SelectorWithIndex<T, ForEachEnumerable<TResult> | null | undefined>): LinqEnumerable<TResult>; selectMany<TElement, TResult>(collectionSelector: SelectorWithIndex<T, ForEachEnumerable<TElement> | null | undefined>, resultSelector: (collection: T, element: TElement) => TResult): LinqEnumerable<TResult>; choose(): LinqEnumerable<T>; choose<TResult>(selector: SelectorWithIndex<T, TResult>): LinqEnumerable<TResult>; reverse(): this; shuffle(): this; count(predicate?: PredicateWithIndex<T>): number; all(predicate: PredicateWithIndex<T>): boolean; every(predicate: PredicateWithIndex<T>): boolean; any(predicate?: PredicateWithIndex<T>): boolean; some(predicate?: PredicateWithIndex<T>): boolean; contains(value: T, compareSelector?: Selector<T, any>): boolean; indexOf(value: T, compareSelector?: SelectorWithIndex<T, any>): number; lastIndexOf(value: T, compareSelector?: SelectorWithIndex<T, any>): number; intersect(second: ForEachEnumerable<T>, compareSelector?: HashSelector<T>): this; sequenceEqual(second: ForEachEnumerable<T>, equalityComparer?: EqualityComparison<T>): boolean; ofType<TType>(type: { new (...params: any[]): TType; }): LinqEnumerable<TType>; orderBy<TKey extends Comparable>(keySelector?: Selector<T, TKey>): IOrderedEnumerable<T>; orderUsing(comparison: Comparison<T>): IOrderedEnumerable<T>; orderUsingReversed(comparison: Comparison<T>): IOrderedEnumerable<T>; orderByDescending<TKey extends Comparable>(keySelector?: Selector<T, TKey>): IOrderedEnumerable<T>; buffer(size: number): LinqEnumerable<T[]>; groupBy<TKey>(keySelector: SelectorWithIndex<T, TKey>): LinqEnumerable<Grouping<TKey, T>>; groupBy<TKey>(keySelector: SelectorWithIndex<T, TKey>, elementSelector: SelectorWithIndex<T, T>, compareSelector?: HashSelector<TKey>): LinqEnumerable<Grouping<TKey, T>>; groupBy<TKey, TElement>(keySelector: SelectorWithIndex<T, TKey>, elementSelector: SelectorWithIndex<T, TElement>, compareSelector?: HashSelector<TKey>): LinqEnumerable<Grouping<TKey, TElement>>; partitionBy<TKey>(keySelector: Selector<T, TKey>): LinqEnumerable<Grouping<TKey, T>>; partitionBy<TKey, TElement>(keySelector: Selector<T, TKey>, elementSelector?: Selector<T, TElement>, resultSelector?: (key: TKey, element: TElement[]) => Grouping<TKey, TElement>, compareSelector?: Selector<TKey, any>): LinqEnumerable<Grouping<TKey, TElement>>; flatten<TFlat>(): LinqEnumerable<TFlat>; flatten(): LinqEnumerable<any>; pairwise<TSelect>(selector: (previous: T, current: T, index: number) => TSelect): LinqEnumerable<TSelect>; aggregate(reduction: (previous: T, current: T, index?: number) => T): T | undefined; aggregate<U>(reduction: (previous: U, current: T, index?: number) => U, initialValue: U): U; reduce<T>(reduction: (previous: T, current: T, index?: number) => T): T | undefined; reduce<U>(reduction: (previous: U, current: T, index?: number) => U, initialValue: U): U; average(selector?: SelectorWithIndex<T, number>): number; max(): T | undefined; min(): T | undefined; maxBy(keySelector?: Selector<T, Primitive>): T | undefined; minBy(keySelector?: Selector<T, Primitive>): T | undefined; sum(selector?: SelectorWithIndex<T, number>): number; product(selector?: SelectorWithIndex<T, number>): number; /** * Takes the first number and divides it by all following. * @param selector * @returns {number} */ quotient(selector?: SelectorWithIndex<T, number>): number; last(): T; lastOrDefault(): T | undefined; lastOrDefault(defaultValue: T): T; memoize(): LinqEnumerable<T>; throwWhenEmpty(): NotEmptyEnumerable<T>; } export interface NotEmptyEnumerable<T> extends LinqEnumerable<T> { aggregate(reduction: (previous: T, current: T, index?: number) => T): T; reduce(reduction: (previous: T, current: T, index?: number) => T): T; max(): T; min(): T; maxBy(keySelector?: Selector<T, Primitive>): T; minBy(keySelector?: Selector<T, Primitive>): T; } export declare class FiniteEnumerable<T> extends LinqEnumerable<T> { constructor(enumeratorFactory: () => IEnumerator<T>, finalizer?: Closure); } export interface IOrderedEnumerable<T> extends FiniteEnumerable<T> { thenBy(keySelector: (value: T) => any): IOrderedEnumerable<T>; thenByDescending(keySelector: (value: T) => any): IOrderedEnumerable<T>; thenUsing(comparison: Comparison<T>): IOrderedEnumerable<T>; thenUsingReversed(comparison: Comparison<T>): IOrderedEnumerable<T>; } export declare class ArrayEnumerable<T> extends FiniteEnumerable<T> { private _source; constructor(source: ArrayLike<T>); protected _onDispose(): void; readonly source: ArrayLike<T>; toArray(): T[]; asEnumerable(): this; forEach(action: ActionWithIndex<T>, max?: number): number; forEach(action: PredicateWithIndex<T>, max?: number): number; any(predicate?: PredicateWithIndex<T>): boolean; count(predicate?: PredicateWithIndex<T>): number; elementAtOrDefault(index: number): T | undefined; elementAtOrDefault(index: number, defaultValue: T): T; last(): T; lastOrDefault(): T | undefined; lastOrDefault(defaultValue: T): T; skip(count: number): this; takeExceptLast(count?: number): this; skipToLast(count: number): this; reverse(): this; memoize(): this; sequenceEqual(second: ForEachEnumerable<T>, equalityComparer?: EqualityComparison<T>): boolean; toJoinedString(separator?: string, selector?: Selector<T, string>): string; } export declare class Grouping<TKey, TElement> extends ArrayEnumerable<TElement> { private _groupKey; constructor(_groupKey: TKey, elements: TElement[]); readonly key: TKey; } export declare class Lookup<TKey, TElement> { private _dictionary; constructor(_dictionary: IDictionary<TKey, TElement[]>); readonly count: number; get(key: TKey): TElement[] | null; contains(key: TKey): boolean; getEnumerator(): IEnumerator<Grouping<TKey, TElement>>; } export declare class OrderedEnumerable<T, TOrderBy extends Comparable> extends FiniteEnumerable<T> { private source; keySelector: Selector<T, TOrderBy> | null; order: Order; parent?: OrderedEnumerable<T, any> | null | undefined; comparer: Comparison<T>; constructor(source: IEnumerable<T>, keySelector: Selector<T, TOrderBy> | null, order: Order, parent?: OrderedEnumerable<T, any> | null | undefined, comparer?: Comparison<T>); private createOrderedEnumerable; thenBy(keySelector: (value: T) => TOrderBy): IOrderedEnumerable<T>; thenUsing(comparison: Comparison<T>): IOrderedEnumerable<T>; thenByDescending(keySelector: (value: T) => TOrderBy): IOrderedEnumerable<T>; thenUsingReversed(comparison: Comparison<T>): IOrderedEnumerable<T>; getEnumerator(): EnumeratorBase<T>; protected _onDispose(): void; } export declare function Enumerable<T>(source: InfiniteValueFactory<T>): InfiniteLinqEnumerable<T>; export declare function Enumerable<T>(source: ForEachEnumerable<T>, ...additional: Array<ForEachEnumerable<T>>): LinqEnumerable<T>; export declare module Enumerable { /** * Universal method for converting a primitive enumerables into a LINQ enabled ones. * * Is not limited to TypeScript usages. */ function from<T>(source: InfiniteValueFactory<T>): InfiniteLinqEnumerable<T>; function from<T>(source: ForEachEnumerable<T>, ...additional: Array<ForEachEnumerable<T>>): LinqEnumerable<T>; function fromAny<T>(source: InfiniteValueFactory<T>): InfiniteLinqEnumerable<T>; function fromAny<T>(source: ForEachEnumerable<T>): LinqEnumerable<T>; function fromAny(source: any): LinqEnumerable<any> | undefined; function fromAny<T>(source: ForEachEnumerable<T>, defaultEnumerable: LinqEnumerable<T>): LinqEnumerable<T>; function fromThese<T>(sources: ForEachEnumerable<T>[]): LinqEnumerable<T>; function fromOrEmpty<T>(source: ForEachEnumerable<T>): LinqEnumerable<T>; /** * Static helper for converting enumerables to an array. * @param source * @returns {any} */ function toArray<T>(source: ForEachEnumerable<T>): T[]; function _choice<T>(values: T[]): InfiniteLinqEnumerable<T>; function choice<T>(values: ArrayLike<T>): InfiniteLinqEnumerable<T>; function chooseFrom<T>(arg: T, ...args: T[]): InfiniteLinqEnumerable<T>; function cycle<T>(values: ArrayLike<T>): InfiniteLinqEnumerable<T>; function cycleThrough<T>(arg: T, ...args: T[]): InfiniteLinqEnumerable<T>; function empty<T>(): FiniteEnumerable<T>; function repeat<T>(element: T): InfiniteLinqEnumerable<T>; function repeat<T>(element: T, count: number): FiniteEnumerable<T>; /** * DEPRECATED This method began to not make sense in so many ways. * @deprecated since version 4.2 * @param initializer * @param finalizer */ function repeatWithFinalize<T>(initializer: () => T, finalizer: Closure): InfiniteLinqEnumerable<T>; function repeatWithFinalize<T>(initializer: () => T, finalizer?: Action<T>): InfiniteLinqEnumerable<T>; /** * Creates an enumerable of one element. * @param element * @returns {FiniteEnumerable<T>} */ function make<T>(element: T): FiniteEnumerable<T>; function range(start: number, count: number, step?: number): FiniteEnumerable<number>; function rangeDown(start: number, count: number, step?: number): FiniteEnumerable<number>; function toInfinity(start?: number, step?: number): InfiniteLinqEnumerable<number>; function toNegativeInfinity(start?: number, step?: number): InfiniteLinqEnumerable<number>; function rangeTo(start: number, to: number, step?: number): FiniteEnumerable<number>; function matches(input: string, pattern: any, flags?: string): FiniteEnumerable<RegExpExecArray>; function generate<T>(factory: () => T): InfiniteLinqEnumerable<T>; function generate<T>(factory: () => T, count: number): FiniteEnumerable<T>; function generate<T>(factory: (index: number) => T): InfiniteLinqEnumerable<T>; function generate<T>(factory: (index: number) => T, count: number): FiniteEnumerable<T>; module random { function floats(maxExclusive?: number): InfiniteLinqEnumerable<number>; function integers(boundary: number, inclusive?: boolean): InfiniteLinqEnumerable<number>; } function unfold<T>(seed: T, valueFactory: SelectorWithIndex<T, T>, skipSeed?: Boolean): InfiniteLinqEnumerable<T>; function forEach<T>(e: ForEachEnumerable<T>, action: ActionWithIndex<T>, max?: number): number; function forEach<T>(e: ForEachEnumerable<T>, action: PredicateWithIndex<T>, max?: number): number; function map<T, TResult>(enumerable: ForEachEnumerable<T>, selector: SelectorWithIndex<T, TResult>): TResult[]; function max(values: FiniteEnumerable<number>): number; function min(values: FiniteEnumerable<number>): number; /** * Takes any set of collections of the same type and weaves them together. * @param enumerables * @returns {Enumerable<T>} */ function weave<T>(enumerables: ForEachEnumerable<ForEachEnumerable<T>>): LinqEnumerable<T>; } export default Enumerable;
the_stack
import * as t from 'graphql/language'; import { uniqArray, unCapitalize, MemberTypeMap } from '../../utils'; const singleValueOperators = ['gt', 'gte', 'lt', 'lte']; const operatorsMap = { equals: 'in', notEquals: 'notIn', notSet: 'set', }; enum FilterKind { AND = 'AND', OR = 'OR', PLAIN = 'PLAIN', } function baseCubeQuery( args: t.ArgumentNode[], members: t.FieldNode[], name: string = 'CubeQuery' ): t.DocumentNode { return { kind: t.Kind.DOCUMENT, definitions: [ { kind: t.Kind.OPERATION_DEFINITION, name: { kind: t.Kind.NAME, value: name, }, operation: 'query', selectionSet: { kind: t.Kind.SELECTION_SET, selections: [ { kind: t.Kind.FIELD, name: { kind: t.Kind.NAME, value: 'cube', }, arguments: args, selectionSet: { kind: t.Kind.SELECTION_SET, selections: members, }, }, ], }, }, ], }; } type CubeField = { name: string; granularities?: string[]; }; type OrderBy = [string, 'asc' | 'desc'][]; type Cube = { fields: CubeField[]; filters: any; orderBy: OrderBy; }; type Cubes = { [cubeName: string]: Cube; }; export class CubeGraphQLConverter { private cubes: Cubes = {}; public constructor( private readonly cubeQuery: Record<string, any>, private readonly types: MemberTypeMap ) { this.prepareCubes(); } public convert() { return t.print( baseCubeQuery(this.getCubeArgs(), this.getFieldsSelections()) ); } private resolveFilter( filter: Record<string, any> | Record<string, any>[], parent?: any ) { const plainFilters = Object.values( filter.reduce((memo, f) => { if (f.or || f.and) { return memo; } const [cubeName, field] = (f.member || f.dimension).split('.'); if (!memo[cubeName]) { memo[cubeName] = { kind: FilterKind.PLAIN, cubeName, fields: [], filters: [], }; } memo[cubeName].fields.push(field); memo[cubeName].filters.push(f); return memo; }, {}) ); const booleanFilters = filter .map((f) => { if (f.and || f.or) { return { kind: f.and ? FilterKind.AND : FilterKind.OR, filters: f.and || f.or, }; } return false; }) .filter(Boolean); const groupedFilters: any[] = plainFilters.concat(booleanFilters); return groupedFilters.map((item) => { if (item.kind !== FilterKind.PLAIN) { if (parent) { return this.objectValue([ this.booleanFilter( item.kind, this.resolveFilter(item.filters, item) ), ]); } return this.booleanFilter( item.kind, this.resolveFilter(item.filters, item) ); } if (item.fields.length === uniqArray(item.fields).length) { if (parent) { return this.objectValue( this.objectFieldFilter(item.filters), unCapitalize(item.cubeName) ); } return this.objectFieldFilter( item.filters, unCapitalize(item.cubeName) ); } else { return this.objectField( this.booleanFilter( parent?.kind || 'AND', item.filters.map((f) => { if (f.and || f.or) { this.resolveFilter(item.filters, item.kind); } return this.objectValue(this.objectFieldFilter(f)); }) ), unCapitalize(item.cubeName) ); } }); } private objectValue( fields: t.ObjectFieldNode | t.ObjectFieldNode[], filedName?: string ): t.ObjectValueNode { if (filedName) { return { kind: t.Kind.OBJECT, fields: [ { kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, value: filedName, }, value: { kind: t.Kind.OBJECT, fields: Array.isArray(fields) ? fields : [fields], }, }, ], }; } return { kind: t.Kind.OBJECT, fields: Array.isArray(fields) ? fields : [fields], }; } private objectFieldFilter( filter: Record<string, any> | Record<string, any>[], parentName?: string ): t.ObjectFieldNode[] { const filters = Array.isArray(filter) ? filter : [filter]; const value = (f): t.ValueNode => { const kind = this.types[f.member || f.dimension] === 'number' ? t.Kind.FLOAT : t.Kind.STRING; if (['set', 'notSet'].includes(f.operator)) { return { kind: t.Kind.BOOLEAN, value: f.operator === 'set', }; } if (typeof f.values === 'string') { return { kind, value: f.values, }; } if (f.values.length === 1) { return { kind, value: f.values[0].toString(), }; } return { kind: t.Kind.LIST, values: f.values.map((v) => ({ kind, value: v, })), }; }; const fields = filters.map<t.ObjectFieldNode>((f) => { const memberName = f.member || f.dimension; if (!this.types[memberName]) { throw new Error( `Unknown member type for "${memberName}". Make sure "${memberName}" exists in the schema.` ); } if ( singleValueOperators.includes(f.operator) && (f.values || []).length > 1 ) { throw new Error( `Filter operator "${f.operator}" must have a single value` ); } return { kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, value: memberName.split('.')[1], }, value: { kind: t.Kind.OBJECT, fields: f.values === undefined && !['set', 'notSet'].includes(f.operator) ? [] : [ { kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, // A single value maps to "equals" // Whereas multiple values for "equals" operator maps to "in" // value: operatorsMap[f.operator] || f.operator, value: f.operator === 'equals' && (f.values || []).length <= 1 ? f.operator : operatorsMap[f.operator] || f.operator, }, value: value(f), }, ], }, }; }); if (parentName) { return [ { kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, value: parentName, }, value: { kind: t.Kind.OBJECT, fields, }, }, ]; } return fields; } private objectField( fields: t.ObjectFieldNode | t.ObjectFieldNode[], fieldName: string ) { return { kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, value: fieldName, }, value: { kind: t.Kind.OBJECT, fields: Array.isArray(fields) ? fields : [fields], }, }; } // OR: [{ orders: { status: { equals: "active"} }}] private booleanFilter( kind: FilterKind, values: t.ObjectValueNode[] ): t.ObjectFieldNode { return { kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, value: kind, }, value: { kind: t.Kind.LIST, values, }, }; } private orderByArg(orderBy: OrderBy): t.ArgumentNode { return { kind: t.Kind.ARGUMENT, name: { kind: t.Kind.NAME, value: 'orderBy', }, value: { kind: t.Kind.OBJECT, fields: orderBy.map(([field, value]) => ({ kind: t.Kind.OBJECT_FIELD, name: { kind: t.Kind.NAME, value: field, }, value: { kind: t.Kind.ENUM, value, }, })), }, }; } private getFieldsSelections() { const selections: t.FieldNode[] = []; Object.entries(this.cubes).forEach(([cubeName, { fields, orderBy }]) => { selections.push({ kind: t.Kind.FIELD, name: { kind: t.Kind.NAME, value: cubeName, }, arguments: orderBy.length ? [this.orderByArg(orderBy)] : [], selectionSet: { kind: t.Kind.SELECTION_SET, selections: fields.map((field) => { let granularitySelection: Partial<t.FieldNode> | null = null; if (field.granularities) { granularitySelection = { selectionSet: { kind: t.Kind.SELECTION_SET, selections: field.granularities.map((value) => ({ kind: t.Kind.FIELD, name: { kind: t.Kind.NAME, value, }, })), }, }; } return { kind: t.Kind.FIELD, name: { kind: t.Kind.NAME, value: field.name, }, ...granularitySelection, }; }), }, }); }); return selections; } private getCubeArgs() { const cubeArgsKeys: [ string, typeof t.Kind.STRING | typeof t.Kind.INT | typeof t.Kind.OBJECT ][] = [ ['timezone', t.Kind.STRING], ['limit', t.Kind.INT], ['offset', t.Kind.INT], ]; const cubeArgs: t.ArgumentNode[] = []; cubeArgsKeys.forEach(([key, kind]) => { if (this.cubeQuery[key]) { cubeArgs.push({ kind: t.Kind.ARGUMENT, name: { kind: t.Kind.NAME, value: key, }, value: { kind: <typeof t.Kind.STRING | typeof t.Kind.INT>kind, value: this.cubeQuery[key], }, }); } }); const filters = [...(this.cubeQuery.filters || [])]; (this.cubeQuery.timeDimensions || []).forEach((td) => { if (td.dateRange) { filters.push({ member: td.dimension, operator: 'inDateRange', values: td.dateRange, }); } }); if (filters.length) { cubeArgs.push({ kind: t.Kind.ARGUMENT, name: { kind: t.Kind.NAME, value: 'where', }, value: { kind: t.Kind.OBJECT, fields: this.resolveFilter(filters), }, }); } return cubeArgs; } private prepareCubes() { const initCube = (cubeName) => { if (!this.cubes[cubeName]) { this.cubes[cubeName] = { fields: [], filters: [], orderBy: [], }; } }; ['measures', 'dimensions', 'segments'].forEach((key) => { if (!this.cubeQuery[key]) { return; } this.cubeQuery[key].forEach((value) => { const [name, field, granularity] = value.split('.'); const cubeName = unCapitalize(name); let gqlGranularity = granularity; if (this.types[`${name}.${field}`] === 'time') { gqlGranularity = 'value'; } initCube(cubeName); // eslint-disable-next-line const currentField = this.cubes[cubeName].fields.find( ({ name }) => name === field ); this.cubes[cubeName].fields.push({ name: field, ...(gqlGranularity ? { granularities: [ ...(currentField?.granularities || []), gqlGranularity, ], } : null), }); }); }); const map: Record<string, string[]> = {}; this.cubeQuery.timeDimensions?.forEach((td) => { const [name, field] = td.dimension.split('.'); const cubeFieldName = `${name}.${field}`; if (td.granularity) { map[cubeFieldName] = (map[cubeFieldName] || []).concat([ td.granularity, ]); } }); Object.entries(map).forEach(([cubeField, granularities]) => { const [name, field] = cubeField.split('.'); const cubeName = unCapitalize(name); initCube(cubeName); const existingField = this.cubes[cubeName].fields.find( (f) => f.name === field ); if (existingField) { existingField.granularities = uniqArray([ ...(existingField.granularities || []), ...granularities, ]); } else { this.cubes[cubeName].fields.push({ name: field, granularities, }); } }); if (this.cubeQuery.order) { const orderBy = Array.isArray(this.cubeQuery.order) ? this.cubeQuery.order : Object.entries(this.cubeQuery.order); orderBy.forEach(([key, order]) => { const [cubeName, member] = key.split('.'); const gqlCubeName = unCapitalize(cubeName); if (!this.cubes[gqlCubeName]) { throw new Error( `Order without selecting the cube is not allowed. Did you forget to include the "${cubeName}" cube?` ); } const exists = this.cubes[gqlCubeName].fields.find( ({ name }) => name === member ); if (!exists) { throw new Error( `Order without selecting the member is not allowed. Did you forget to include the "${member}" member?` ); } this.cubes[gqlCubeName].orderBy.push([member, order]); }); } } }
the_stack
import {Index, HashIndex, DistinctIndex} from "./indexes"; import {Tracer, NoopTracer, TraceNode, TraceFrameType} from "./trace"; //------------------------------------------------------------------------ // debugging utilities //------------------------------------------------------------------------ const TRACE = false; // Turning this on causes all of the debug(.*) statements to print to the // console. This is useful to see exactly what the runtime is doing as it // evaluates a transaction, but it incurs both a pretty serious performance // cost and prints a lot of stuff. const DEBUG = false; export var debug:Function = () => {}; if(DEBUG) { debug = function() { console.log.apply(console, arguments); } } function indent(text:string, level:number) { let padding = new Array(level + 1).join(" "); return text.split("\n").join("\n" + padding); } export function printField(field:ScanField) { if(isRegister(field)) return "[" + field.offset + "]"; if(field === undefined || field === null) return field; let raw = maybeReverse(field); return typeof raw === "string" ? `"${raw}"` : raw; } export function printFieldArray(fields:ScanField[]) { return "[" + fields.map(printField).join(", ") + "]"; } export function printPrefix(prefix:Prefix) { return prefix.map((v) => GlobalInterner.reverse(v)); } function toString(x:any):string { if(x && x.toString) return x.toString(); console.warn("No toString specified for", x); return ""; } export function printBlock(block:Block):string { return block.toString(); } (global as any).printBlock = printBlock; export function maybeReverse(value?:ID):ID|RawValue|undefined { if(value === undefined) return value; let raw = GlobalInterner.reverse(value); return (""+raw).indexOf("|") === -1 ? raw : value; } //------------------------------------------------------------------------ // Allocations //------------------------------------------------------------------------ // As this is a language runtime, we want to get insight into how we're using // memory and what allocation costs we're eating as we run. To track that, we // use createHash and createArray to give us some rough numbers. The JIT will // inline these functions, so the cost over just using {} or [], is fairly // negligible. In a release build we can also strip the allocation tracking. export var ALLOCATION_COUNT:any = {}; export function createHash(place = "unknown-hash") { if(!ALLOCATION_COUNT[place]) ALLOCATION_COUNT[place] = 0; ALLOCATION_COUNT[place]++; return Object.create(null); } export function createArray(place = "unknown") { if(!ALLOCATION_COUNT[place]) ALLOCATION_COUNT[place] = 0; ALLOCATION_COUNT[place]++; return []; } export function copyArray(arr:any[], place = "unknown") { if(!ALLOCATION_COUNT[place]) ALLOCATION_COUNT[place] = 0; ALLOCATION_COUNT[place]++; return arr.slice(); } export function copyHash(hash:any, place = "unknown") { if(!ALLOCATION_COUNT[place]) ALLOCATION_COUNT[place] = 0; ALLOCATION_COUNT[place]++; let neue:any = {}; for(let key of Object.keys(hash)) { neue[key] = hash[key]; } return neue; } // given two arrays, append the second's items on to the first export function concatArray(arr:any[], arr2:any[]) { let ix = arr.length; for(let elem of arr2) { arr[ix] = elem; ix++; } return arr; } // overwrite the first array with the values of the second array // and fix the length if it's different export function moveArray(arr:any[], arr2:any[]) { let ix = 0; for(let elem of arr) { arr2[ix] = arr[ix]; } if(arr2.length !== arr.length) arr2.length = arr.length; return arr2; } //------------------------------------------------------------------------ // Iterator //------------------------------------------------------------------------ // To reduce allocations as much as possible, we want to reuse arrays as much // as possible. If we reused the array by setting its length to 0 or to some // new size that is smaller than its current length, we eat the cost of // deallocating some chunk of memory as well as the potential cost in // fragmentation. Instead, the Iterator class never changes the size of its // backing array, and instead keeps its own length. You iterate through the // array using the next() method: // // let current; // while((current = iterator.next()) !== undefined) { // ... // } // // Through the magic of the JIT, this has no performance penalty over using a // standard for loop. You can get some of those "zero-cost abstractions" in JS // too! export class Iterator<T> { array:T[] = []; length:number = 0; ix:number = 0; push(value:T) { this.array[this.length++] = value; } clear() { this.length = 0; this.reset(); } reset() { this.ix = 0; } next():T|undefined { if(this.ix < this.length) return this.array[this.ix++]; return; } iter():ReadOnlyIterator<T> { return new ReadOnlyIterator(this.array, this.length); } } export class ReadOnlyIterator<T> extends Iterator<T> { constructor(arr:T[], length:number) { super(); this.array = arr; this.length = length; } push(value:T) { throw new Error("Cannot write to a readonly iterator"); } } //------------------------------------------------------------------------ // Interning //------------------------------------------------------------------------ // Every value that touches the runtime is interned. While that may seem kind // of crazy, there are lots of good reasons for this. The first is that it // turns an infinite space of values into a bounded space of integers. This // gives us a lot more options in how we index values and dramatically improves // our memory layout. On top of that, every lookup and equality is now on // fixed-size integers, which computers can do near instantly. Similarly, // nearly every function in the runtime is now monomorphic, giving the JIT free // reign to compile our loops into very fast native code. // // This is of course a tradeoff. It means that when we need to do operations on // the actual values, we have to look them up. In practice all of the above // benefits have greatly outweighed the lookup cost, the cache-line savings // alone makes that pretty irrelevant. The main cost is that as values flow // out of the system, if we don't clean them up, we'll end up leaking ids. // Also, at current you can have a maximum of a 32bit integer's worth of unique // values in your program. Chances are that doesn't matter in practice on the // client side, but could be a problem in the server at some point. To combat // this, our intener keeps a ref-count, but we're not freeing any of the IDs at // the moment. // // @TODO: we don't ever release IDs in the current runtime because we're not // sure who might be holding onto a transaction, which contain references to // IDs. At some point we should probably reference count transactions as well // and when they are released, that gives us an opportunity to release any // associated IDs that are no longer in use. /** The union of value types we support in Eve. */ export type RawValue = string|number; /** An interned value's ID. */ export type ID = number; function isNumber(thing:any): thing is number { return typeof thing === "number"; } export class Interner { // IDs are only positive integers so that they can be used as array indexes // for efficient lookup. currentID: number = 0; // We currently only have two value types in Eve at the moment, strings and // numbers. Because keys in a javascript object are always converted to // strings, we have to keep dictionaries for the two types separate, // otherwise the number 1 and the string "1" would end up being the same // value; strings: {[value:string]: ID|undefined} = createHash(); numbers: {[value:number]: ID|undefined} = createHash(); // We use this array as a lookup from an integer ID to a RawValue since the // IDs are guaranteed to be densely packed, this gives us much better // performance than using another hash. IDs: RawValue[] = createArray(); // This is used as another lookup from ID to the number of references this ID // has in the system. As the ref count goes to zero, we can add the ID to the // free list so that it can be reused. IDRefCount: number[] = createArray(); IDFreeList: number[] = createArray(); // During the course of evaluation, we might allocate a bunch of intermediate // IDs whose values might just be thrown away. For example if we generate a // value just to use as a filter, there's no sense in us keeping the value in // the interned space. Arenas are named groups of allocations that we may // want to dereference all together. Note that just because we may // dereference it once, that doesn't mean the ID should be released - other // uses of the ID may exist. arenas: {[arena:string]: Iterator<ID>} = createHash(); constructor() { // The only arena we *know* we want from the beginning is for the output of functions. this.arenas["functionOutput"] = new Iterator<ID>(); } _getFreeID() { return this.IDFreeList.pop() || this.currentID++; } reference(id:ID) { this.IDRefCount[id]++; } // Intern takes a value and gives you the ID associated with it. If there isn't an // ID it should create one for this value and in either case it should add a reference. intern(value: RawValue): ID { let coll; if(isNumber(value)) { coll = this.numbers; } else { coll = this.strings; } let found = coll[value]; if(found === undefined) { found = this._getFreeID(); coll[value] = found; this.IDs[found] = value; this.IDRefCount[found] = 1; } else { this.IDRefCount[found]++; } return found; } // Get neither creates an ID nor adds a reference to the ID, it only looks up the // ID for a value if it exists. get(value: RawValue): ID|undefined { let coll; if(isNumber(value)) { coll = this.numbers; } else { coll = this.strings; } return coll[value]; } // Go from an ID to the RawValue reverse(id: ID): RawValue { return this.IDs[id]; } // Dereference an ID and if there are no remaining references, add it to the freelist. release(id: ID|undefined) { if(id === undefined) return; this.IDRefCount[id]--; if(!this.IDRefCount[id]) { let value = this.IDs[id]; let coll; if(isNumber(value)) { coll = this.numbers; } else { coll = this.strings; } coll[value] = undefined; this.IDs[id] = undefined as any; this.IDFreeList.push(id); } } arenaIntern(arenaName:string, value:RawValue):ID { // @FIXME: Unfortunately we can't use arena intern at the moment due to the // fact that while we can know what values end up in the primary indexes, // we don't know what values might be hiding in intermediate indexes that // runtime nodes sometimes need to keep. If we *did* deallocate an arena // and the value didn't make it to a primary index, but ended up in an // intermediate one, we'd have effectively corrupted our program. The ID // would be freed, and then used for some completely different value. Until // we can find an accurate (and cheap!) way to track what values are still // hanging around, we'll just have to eat the cost of interning all the // values we've seen. Keep in mind that this isn't as bad as it sounds, as // the only values that would actually be freed this way are values that // are calculated but never end up touching the primary indexes. This is // rare enough that in practice, this probably isn't a big deal. throw new Error("Arena interning isn't ready for primetime yet.") // let arena = this.arenas[arenaName]; // if(!arena) { // arena = this.arenas[arenaName] = new Iterator<ID>(); // } // // @NOTE: for performance reasons it might make more sense to prevent duplicates // // from ending up in the list. If that's the case, we could either keep a seen // // hash or do a get and only intern if it hasn't been seen. This is (probably?) // // a pretty big performance gain in the case where a bunch of rows might repeat // // the same function output over and over. // let id = this.intern(value); // arena.push(id); // return id; } releaseArena(arenaName:string) { let arena = this.arenas[arenaName]; if(!arena) { console.warn("Trying to release unknown arena: " + arenaName) return; } let id; while((id = arena.next()) !== undefined) { this.release(id); } arena.clear(); } } // The runtime uses a single global interner so that all values remain comparable. export var GlobalInterner = new Interner(); (global as any)["GlobalInterner"] = GlobalInterner; //------------------------------------------------------------------------ // Changes //------------------------------------------------------------------------ // Because Eve's runtime is incremental from the ground up, the primary unit of // information in the runtime is a Change. The content of a change is in the // form of "triples," a tuple of entity, attribute, and value (or in the RDF // world, subject, object, predicate). For example, if we wanted to talk about // my age, we might have a triple of ("chris", "age", 30). Beyond the content // of the change, we also want to know who created this change and what // transaction it came from. This gives us enough information to work out the // provenance of this information, which is very useful for debugging as well // as doing clever things around verification and trust. The final two pieces // of information in a change are the round and count, which are used to help // us maintain our program incrementally. Because Eve runs all blocks to // fixedpoint, a single change may cause multiple "rounds" of evaluation which // introduce more changes. By tracking what round these changes happened in, we // can do some clever reconciling to handle removal inside recursive rules // efficiently, which we'll go into more depth later. Count tells us how many // of these triples we are adding or, if the number is negative, removing from // the system. // We track counts as Multiplicities, which are just signed integers. export type Multiplicity = number; // It's often useful to know just the sign of a multiplicity function sign (x:number) { return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN; } // In a change entity, attribute, value, and node are stored as e, a, v, and n // respectively. We often need to look these up in loops or pass around // information about what property we might currently be talking about, so we // have a type representing those fields. export type EAVNField = "e"|"a"|"v"|"n"; export class Change { // Change expects that all values have already been interned. constructor(public e: ID, public a: ID, public v: ID, public n: ID, public transaction:number, public round:number, public count:Multiplicity) {} // As a convenience, you can generate a change from values that haven't been // interned yet. static fromValues(e: any, a: any, v: any, n: any, transaction: number, round: number, count:Multiplicity) { return new Change(GlobalInterner.intern(e), GlobalInterner.intern(a), GlobalInterner.intern(v), GlobalInterner.intern(n), transaction, round, count); } toString() { // let e = GlobalInterner.reverse(this.e); let e = this.e; return `Change(${e}, ${GlobalInterner.reverse(this.a)}, ${maybeReverse(this.v)}, ${this.n}, ${this.transaction}, ${this.round}, ${this.count})`; } // For testing purposes, you often want to compare two Changes ignoring their // node, as you don't know exactly what node will generate a value when you // run. withoutE is also used in testing to check if a triple whose entity // may have been generated by the program *could* match this change. equal(other:Change, withoutNode?:boolean, withoutE?:boolean) { return (withoutE || this.e == other.e) && this.a == other.a && this.v == other.v && (withoutNode || this.n == other.n) && this.transaction == other.transaction && this.round == other.round && this.count == other.count; } reverse(interner:Interner = GlobalInterner) { let {e, a, v, n, transaction, round, count} = this; return new RawChange(interner.reverse(e), interner.reverse(a), interner.reverse(v), interner.reverse(n), transaction, round, count); } toRawEAV(interner:Interner = GlobalInterner):RawEAV { let {e, a, v} = this; return [interner.reverse(e), interner.reverse(a), interner.reverse(v)]; } clone() { let {e, a, v, n, transaction, round, count} = this; return new Change(e, a, v, n, transaction, round, count); } } const BLOCK_REMOVE = new Change(0,0,0,0,0,0,-1); const BLOCK_ADD = new Change(0,0,0,0,0,0,1); export class RemoveChange extends Change { toString() { // let e = GlobalInterner.reverse(this.e); let e = this.e; return `RemoveChange(${e}, ${GlobalInterner.reverse(this.a)}, ${maybeReverse(this.v)}, ${this.n}, ${this.transaction}, ${this.round}, ${this.count})`; } clone() { let {e, a, v, n, transaction, round, count} = this; return new RemoveChange(e, a, v, n, transaction, round, count); } } export class RemoveVsChange extends RemoveChange { toRemoveChanges(context:EvaluationContext, changes:Change[]) { let {e,a,v,n} = this; let {index, distinctIndex} = context; let matches = index.get(e, a, IGNORE_REG, IGNORE_REG, this.transaction, Infinity); for(let {v} of matches) { let rounds = index.getDiffs(e, a, v, IGNORE_REG); for(let round of rounds) { let count = this.count * (round > 0 ? 1 : -1); let changeRound = Math.max(this.round, Math.abs(round) - 1); let change = new RemoveChange(e!, a!, v!, n!, this.transaction, changeRound, count); changes.push(change); } } } clone() { let {e, a, v, n, transaction, round, count} = this; return new RemoveVsChange(e, a, v, n, transaction, round, count); } } export class RemoveAVsChange extends RemoveVsChange { toRemoveChanges(context:EvaluationContext, changes:Change[]) { let {e,a,v,n} = this; let {index, distinctIndex} = context; let matches = index.get(e, IGNORE_REG, IGNORE_REG, IGNORE_REG, this.transaction, Infinity); for(let {a, v} of matches) { let rounds = index.getDiffs(e, a, v, IGNORE_REG); for(let round of rounds) { let count = this.count * (round > 0 ? 1 : -1); let changeRound = Math.max(this.round, Math.abs(round) - 1); let change = new RemoveChange(e!, a!, v!, n!, this.transaction, changeRound, count); changes.push(change); } } } clone() { let {e, a, v, n, transaction, round, count} = this; return new RemoveAVsChange(e, a, v, n, transaction, round, count); } } // When interacting with the outside world, we need to pass changes around that // are no longer interned. A RawChange is the same as Change, but all the // information in the triple has been converted back into RawValues instead of // interned IDs. export class RawChange { constructor(public e: RawValue, public a: RawValue, public v: RawValue, public n: RawValue, public transaction:number, public round:number, public count:Multiplicity) {} toString() { let {e, a, v, n, transaction, round, count} = this; let internedE = GlobalInterner.get(e); let internedV = GlobalInterner.get(v); return `RawChange(${internedE}, ${a}, ${maybeReverse(internedV) || v}, ${n}, ${transaction}, ${round}, ${count})`; } } //------------------------------------------------------------------------ // Joins //------------------------------------------------------------------------ // Buckle up, we're going for a ride. // // Now that we have a change representation, we need to actually do something // with it. Eve is a relational language, which means the primary action in // the language is to join tuples together. Unlike in most relational databases // where we might do joins by looking at full relations pair-wise and joining // them together, we need to operate on changes and we want to sidestep the // cost of figuring out a good query plan for the pair-wise joins. Both of // these properties require us to look at joins very differently than we // normally would in say Postgres. Instead, we're going to use a magical join // algorithm called Generic Join [1] and extend it to work on incremental // changes instead of just fully realized relations. // // The core idea behind Generic Join is that instead of breaking a query down // into a set of binary joins on relations, we look at each unique variable in // the query and have all of the relations that might say something about that // variable do an intersection. Let's look at an example: // // people(person-id, name) // dogs(person-id, dog-name, dog-age) // // Here we have two relations we want to join together: "people" and "dogs". // The people relation has two fields that are represented by the variables // "person-id" and "name." The dogs relation has three fields: "person-id", // "dog-name", and "dog-age." In postgres, we'd take these two relations and do // a hash or merge join based on the first column of each. In generic join we // look at all the variables we need to solve for, in this case four of them, // and then ask each relation which variable they could propose values for. // These proposals include not just what variable this relation could solve // for, but also an estimate of how many values the variable would have. In the // interest of doing the least amount of work possible, we select the proposal // with the smallest estimate and then for each proposed value of the variable, // we ask all the other relations if they "accept" the value. If they do, we // recursively solve for the rest of the variables in depth-first fashion. // // In this algorithm, each relation acts as a constraint on the space of // valid solutions. We don't just look at every row in the people table or // every row in the dogs table, but instead look at the unique values per // variable given some set of already solved variables. We call that // solved set of variables a "prefix". So when we ask a constraint to propose // values, we hand it the prefix and ask it which variable it would solve for // next. We then ask each constraint if they accept the new prefix and continue // to solve for the rest of the variables. By selecting the proposal with the // smallest estimate, we can make some interesting guarantees about the upper // bound [2] of the work we will do to satisfy our join and we side step the // need for the insanely complex query planners that exist in most commercial // databases. An interesting aspect of this algorithm is that it's basically // making planning decisions for every unique value of a variable, which means // that it is resilient to the high skew you often end up with in real-world // data. // // So the key parts of Generic Join are prefixes, constraints, and proposals, // which we'll start to layout below. We'll talk more about the ways we have // to change Generic Join to make it work incrementally later. // // [1]: Generic Join is presented in "Skew Strikes Back: New Developments in // the Theory of Join Algorithms" https://arxiv.org/abs/1310.3314 // [2]: "Worst-case Optimal Join Algorithms "https://arxiv.org/abs/1203.1952 //------------------------------------------------------------------------ // Prefixes and registers //------------------------------------------------------------------------ export type Prefix = ID[]; // A register is a numerical offset into a prefix. We can't just make this a // type alias to number because we need to be able to tell the difference between // IDs which represent static values and registers which represent dynamic values // in the prefix. For example I might have a constraint that looks for the // pattern (register1, "tag", "person"), which if we treated Registers as numbers // might just look like (1, 2, 3) after the values have been interned. Instead // we make Register a class. export class Register { constructor(public offset:number) {} } export function isRegister(x: any): x is Register { return x && x.constructor === Register; } // In some cases we have a constraint whose value we may want to ignore. // IGNORE_REG is a sentinel value that tells us we don't care what the value of // something is when we're solving. export var IGNORE_REG = null; export type IgnoreRegister = typeof IGNORE_REG; //------------------------------------------------------------------------ // Proposal //------------------------------------------------------------------------ export interface Proposal { cardinality:number, forFields:Iterator<EAVNField>, forRegisters:Iterator<Register>, proposer:Constraint, skip?:boolean, info?:any, } //------------------------------------------------------------------------ // Constraints //------------------------------------------------------------------------ export type RoundArray = number[]; export enum ApplyInputState { pass, fail, none, } export interface Constraint { isInput:boolean; toString():string; setup():void; getRegisters():Register[]; applyInput(input:Change, prefix:Prefix):ApplyInputState; isAffected(input:Change):ApplyInputState; propose(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:any[]):Proposal; resolveProposal(context:EvaluationContext, prefix:Prefix, proposal:Proposal, transaction:number, round:number, results:any[]):ID[][]; accept(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, solvingFor:Register[]):boolean; acceptInput(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number):boolean; getDiffs(context:EvaluationContext, prefix:Prefix):RoundArray; } //------------------------------------------------------------------------ // Resolved values //------------------------------------------------------------------------ /** A scan field may contain a register, a static interned value, or the IGNORE_REG sentinel value. */ export type ScanField = Register|ID|IgnoreRegister; /** A resolved value is a scan field that, if it contained a register, now contains the register's resolved value. */ export type ResolvedValue = ID|undefined|IgnoreRegister; export type ResolvedEAVN = {e:ResolvedValue, a:ResolvedValue, v:ResolvedValue, n:ResolvedValue}; export class EAVN { constructor(public e:ID, public a:ID, public v:ID, public n:ID) {} }; export type EAV = [ID, ID, ID]; export type RawEAV = [RawValue, RawValue, RawValue]; export type RawEAVC = [RawValue, RawValue, RawValue, number]; //------------------------------------------------------------------------ // Move Constraint //------------------------------------------------------------------------ export class MoveConstraint { constructor(public from:Register|ID, public to:Register) { } shouldApplyInput = false; proposal:Proposal = {cardinality: 1, forFields: new Iterator<EAVNField>(), forRegisters: new Iterator<Register>(), proposer: this}; registers:Register[] = createArray("MoveConstriantRegisters"); resolved:(ID|undefined)[] = createArray("MoveConstraintResolved"); isInput = false; isStatic = true; toString() { return `Move(${printField(this.from)}, ${printField(this.to)})`; } setup():void { if(isRegister(this.from)) { this.isStatic = false; } this.registers.push(this.to); // we are always only proposing for our to register this.proposal.forRegisters.clear(); this.proposal.forRegisters.push(this.to); } resolve(prefix:Prefix) { if(isRegister(this.from)) { this.resolved[0] = prefix[this.from.offset]; } else { this.resolved[0] = this.from; } this.resolved[1] = prefix[this.to.offset]; return this.resolved; } getRegisters():Register[] { return this.registers; } isAffected(input:Change):ApplyInputState { if(this.shouldApplyInput) { return ApplyInputState.pass; } return ApplyInputState.none; } applyInput(input:Change, prefix:Prefix):ApplyInputState { if(this.shouldApplyInput) { let value; if(isRegister(this.from)) { value = prefix[this.from.offset]; } else { value = this.from; } let current = prefix[this.to.offset]; if(value !== undefined && (current === undefined || current == value)) { prefix[this.to.offset] = value; } else { return ApplyInputState.fail; } return ApplyInputState.pass; } return ApplyInputState.none; } propose(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:any[]):Proposal { let [from, to] = this.resolve(prefix); this.proposal.skip = true; if(from !== undefined && to === undefined) { this.proposal.skip = false; } return this.proposal; } resolveProposal(context:EvaluationContext, prefix:Prefix, proposal:Proposal, transaction:number, round:number, results:any[]):ID[][] { let [from, to] = this.resolve(prefix); let arr = createArray("MoveResult") as Prefix; arr[0] = from!; return arr as any; } accept(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, solvingFor:Register[]):boolean { let [from, to] = this.resolve(prefix); if(from !== undefined && to !== undefined) { return from == to; } return true; } acceptInput(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number):boolean { return this.accept(context, prefix, transaction, round, this.registers); } getDiffs(context:EvaluationContext, prefix:Prefix):RoundArray { throw new Error("Asking for Diffs from MoveConstraint"); } } //------------------------------------------------------------------------ // Scans //------------------------------------------------------------------------ /** * A scan maps a set of bound variables to unbound variables. */ export class Scan implements Constraint { constructor(public e:ScanField, public a:ScanField, public v:ScanField, public n:ScanField) {} protected resolved:ResolvedEAVN = {e: undefined, a: undefined, v:undefined, n: undefined}; protected registers:Register[] = createArray(); protected registerLookup:boolean[] = createArray(); isInput:boolean = false; proposal:Proposal = {cardinality: 0, forFields: new Iterator<EAVNField>(), forRegisters: new Iterator<Register>(), proposer: this}; toString() { return `Scan(${printField(this.e)} ${printField(this.a)} ${printField(this.v)} ${printField(this.n)})`; } toKey() { let e = isRegister(this.e) ? `$reg(${this.e.offset})` : this.e; let a = isRegister(this.a) ? `$reg(${this.a.offset})` : this.a; let v = isRegister(this.v) ? `$reg(${this.v.offset})` : this.v; return `${e}|${a}|${v}` } /** * Resolve each scan field. * The resolved object may contain one of three possible value types: * - IGNORE_REG -- this field is entirely ignored by the scan. * - undefined -- this field is a register that hasn't been filled in yet. * We'll fill it if possible. * - ID -- this field contains a static or already solved value. */ resolve(prefix:Prefix) { let resolved = this.resolved; if(isRegister(this.e)) { resolved.e = prefix[this.e.offset]; } else { resolved.e = this.e; } if(isRegister(this.a)) { resolved.a = prefix[this.a.offset]; } else { resolved.a = this.a; } if(isRegister(this.v)) { resolved.v = prefix[this.v.offset]; } else { resolved.v = this.v; } if(isRegister(this.n)) { resolved.n = prefix[this.n.offset]; } else { resolved.n = this.n; } return resolved; } /** * A field is unresolved if it is completely ignored by the scan or * is an output of the scan. */ fieldUnresolved(resolved:ResolvedEAVN, key: keyof ResolvedEAVN) { return resolved[key] === IGNORE_REG || resolved[key] === undefined; } /** * A field is not a static match if it is ignored, not a static * field, or the input value does not match the static value. */ notStaticMatch(input:Change, key: "e"|"a"|"v"|"n") { return this[key] !== IGNORE_REG && !isRegister(this[key]) && this[key] !== input[key]; } isAffected(input:Change):ApplyInputState { // If this change isn't relevant to this scan, skip it. if(this.notStaticMatch(input, "e")) return ApplyInputState.none; if(this.notStaticMatch(input, "a")) return ApplyInputState.none; if(this.notStaticMatch(input, "v")) return ApplyInputState.none; if(this.notStaticMatch(input, "n")) return ApplyInputState.none; return ApplyInputState.pass; } /** * Apply new changes that may affect this scan to the prefix to * derive only the results affected by this change. If the change * was successfully applied or irrelevant we'll return true. If the * change was relevant but invalid (i.e., this scan could not be * satisfied due to proposals from previous scans) we'll return * false. */ applyInput(input:Change, prefix:Prefix):ApplyInputState { // For each register field of this scan: // if the required value is impossible fail, // else add this new value to the appropriate prefix register. // @NOTE: Technically, we republish existing values here too. // In practice, that's harmless and eliminates the need for a branch. if(isRegister(this.e)) { if(prefix[this.e.offset] !== undefined && prefix[this.e.offset] !== input.e) return ApplyInputState.fail; prefix[this.e.offset] = input.e; } if(isRegister(this.a)) { if(prefix[this.a.offset] !== undefined && prefix[this.a.offset] !== input.a) return ApplyInputState.fail; prefix[this.a.offset] = input.a; } if(isRegister(this.v)) { if(prefix[this.v.offset] !== undefined && prefix[this.v.offset] !== input.v) return ApplyInputState.fail; prefix[this.v.offset] = input.v; } if(isRegister(this.n)) { if(prefix[this.n.offset] !== undefined && prefix[this.n.offset] !== input.n) return ApplyInputState.fail; prefix[this.n.offset] = input.n; } return ApplyInputState.pass; } propose(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:any[]):Proposal { let {index} = context; let {e,a,v,n} = this.resolve(prefix); this.proposal.skip = false; let proposal = index.propose(this.proposal, e, a, v, n, transaction, round); let {forRegisters, forFields} = proposal; forRegisters.clear(); let field; while((field = forFields.next()) !== undefined) { forRegisters.push(this[field as EAVNField] as Register); } if(proposal.forFields.length === 0) proposal.skip = true; return proposal; } resolveProposal(context:EvaluationContext, prefix:Prefix, proposal:Proposal, transaction:number, round:number, results:any[]):ID[][] { let {index} = context; return index.resolveProposal(proposal); } accept(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, solvingFor:Register[]):boolean { // Before we start trying to accept, we check if we care about the // registers we are currently solving. let solving = false; for(let register of solvingFor) { if(this.registerLookup[register.offset]) { solving = true; break; } } // If we aren't looking at any of these registers, then we just // say we accept. if(!solving) return true; let {e,a,v,n} = this.resolve(prefix); return context.index.check(e, a, v, n, transaction, round); } acceptInput(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number):boolean { let {e,a,v,n} = this.resolve(prefix); if((e === IGNORE_REG || input.e === e) && (a === IGNORE_REG || input.a === a) && (v === IGNORE_REG || input.v === v) && (n === IGNORE_REG || input.n === n)) { return true; } else { return this.accept(context, prefix, transaction, round, this.registers); } } setupRegister(field:EAVNField, parts:string[]) { let value = this[field]; if(isRegister(value)) { this.registers.push(value); parts.push(`resolved.${field} = prefix[${value.offset}];`); } else { this.resolved[field] = value; } } setupIsAffected() { let fields:EAVNField[] = ["e", "a", "v", "n"]; let parts:string[] = []; for(let field of fields) { let value = this[field]; if(!isRegister(value) && value !== IGNORE_REG) { parts.push(`if(${value} !== change["${field}"]) return ${ApplyInputState.none};`) } } this.isAffected = new Function("change", parts.join("\n")) as (change:Change) => ApplyInputState; } setupApplyInput() { let fields:EAVNField[] = ["e", "a", "v", "n"]; let parts:string[] = []; for(let field of fields) { let value = this[field]; if(isRegister(value)) { parts.push(`if(prefix[${value.offset}] !== undefined && prefix[${value.offset}] !== input.${field}) return ${ApplyInputState.fail}; prefix[${value.offset}] = input.${field};`); } } parts.push(`return ${ApplyInputState.pass}`) this.applyInput = new Function("input", "prefix", parts.join("\n")) as (change:Change, prefix:Prefix) => ApplyInputState; } // We precompute the registers we're interested in for fast accepts. setup() { let parts = ["var resolved = this.resolved;"]; this.setupRegister("e", parts); this.setupRegister("a", parts); this.setupRegister("v", parts); this.setupRegister("n", parts); parts.push("return resolved"); this.resolve = new Function("prefix", parts.join("\n")) as (prefix:Prefix) => ResolvedEAVN; this.setupIsAffected(); this.setupApplyInput(); for(let register of this.registers) { this.registerLookup[register.offset] = true; } } getRegisters():Register[] { return this.registers; } getDiffs(context:EvaluationContext, prefix:Prefix):RoundArray { let {e,a,v,n} = this.resolve(prefix); return context.index.getDiffs(e,a,v,n); } } //------------------------------------------------------------------------ // Function constraint //------------------------------------------------------------------------ export type ConstraintFieldMap = {[name:string]: ScanField}; export type ResolvedFields = {[fieldName:string]: ResolvedValue}; export class FunctionConstraint implements Constraint { static registered: {[name:string]: typeof FunctionConstraint} = {}; static register(name:string, klass: typeof FunctionConstraint) { FunctionConstraint.registered[name] = klass; } static filter = false; static variadic = false; static argNames:string[]; static returnNames:string[]; static fetchInfo(name:string):typeof FunctionConstraint { let info = FunctionConstraint.registered[name]; if(!info) throw new Error("No function info for: " + name); return info; } static create(name:string, fields:ConstraintFieldMap, restFields:(ID|Register)[] = createArray()):FunctionConstraint|undefined { let cur = FunctionConstraint.registered[name]; if(!cur) { throw new Error(`No function named ${name} is registered.`); } if(restFields.length && !cur.variadic) { console.error(`The ${name} function is not variadic, so may not accept restFields.`); restFields = createArray(); } let created = new cur(fields, restFields); return created; } constructor(public fields:ConstraintFieldMap, public restFields:(ID|Register)[]) {} name:string; args:{[name:string]: string}; returns:{[name:string]: string}; argNames:string[]; returnNames:string[]; apply: (this: FunctionConstraint, ... things: any[]) => undefined|(number|string)[]|(number|string)[][]; estimate?:(context:EvaluationContext, prefix:Prefix, transaction:number, round:number) => number state?: any; multi:boolean = false; isInput:boolean = false; fieldNames:string[]; proposal:Proposal = {cardinality:0, forFields: new Iterator<EAVNField>(), forRegisters: new Iterator<Register>(), proposer: this}; protected resolved:ResolvedFields = {}; protected resolvedRest:(number|undefined)[] = createArray(); protected registers:Register[] = createArray(); protected registerLookup:boolean[] = createArray(); protected applyInputs:(RawValue|RawValue[])[] = createArray(); protected applyRestInputs:RawValue[] = createArray(); toString() { let params = this.fieldNames.map((v) => v + ": " + printField(this.fields[v])).join(", "); let restParams = this.restFields.map(printField).join(", "); return `FunctionConstraint("${this.name}", ${params} ${restParams ? `, [${restParams}]` : ""})`; } // We precompute the registers we're interested in for fast accepts. setup() { this.fieldNames = Object.keys(this.fields); for(let fieldName of this.fieldNames) { let field = this.fields[fieldName]; if(isRegister(field)) this.registers.push(field); } for(let field of this.restFields) { if(isRegister(field)) this.registers.push(field); } for(let register of this.registers) { this.registerLookup[register.offset] = true; } this.setupResolve(); this.setupResolveRest(); } setupResolve() { let {resolved} = this; let parts = ["var resolved = this.resolved;"]; for(let fieldName of this.fieldNames) { let field = this.fields[fieldName]; if(isRegister(field)) { parts.push(`resolved["${fieldName}"] = prefix[${field.offset}];`); } else { resolved[fieldName] = field; } } parts.push("return resolved"); this.resolve = new Function("prefix", parts.join("\n")) as (prefix:Prefix) => ResolvedEAVN; } setupResolveRest() { let {resolvedRest} = this; let parts = ["var resolvedRest = this.resolvedRest;"]; let ix = 0; for(let field of this.restFields) { if(isRegister(field)) { parts.push(`resolvedRest[${ix}] = prefix[${field.offset}]`); } else { resolvedRest[ix] = field; } ix++; } parts.push("return resolvedRest;"); this.resolveRest = new Function("prefix", parts.join("\n")) as (prefix:Prefix) => number[]; } getRegisters() { return this.registers; } /** * Similar to `Scan.resolve`, but resolving a map of the function's * fields rather than an EAVN. */ resolve(prefix:Prefix) { let resolved = this.resolved; for(let fieldName of this.fieldNames) { let field = this.fields[fieldName]; if(isRegister(field)) { resolved[fieldName] = prefix[field.offset]; } else { resolved[fieldName] = field; } } return resolved; } /** * If a function is variadic, we need to resolve its rest fields as well. */ resolveRest(prefix:Prefix) { let resolvedRest = this.resolvedRest; let ix = 0; for(let field of this.restFields) { if(isRegister(field)) { resolvedRest[ix] = prefix[field.offset]; } else { resolvedRest[ix] = field; } ix++; } return resolvedRest; } // Function constraints have nothing to apply to the input, so they // always return ApplyInputState.none isAffected(input:Change):ApplyInputState { return ApplyInputState.none; } applyInput(input:Change, prefix:Prefix):ApplyInputState { return ApplyInputState.none; } propose(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:any[]):Proposal { let proposal = this.proposal; proposal.forRegisters.clear(); let resolved = this.resolve(prefix); // If none of our returns are unbound // @NOTE: We don't need to worry about the filter case here, since he'll be let unresolvedOutput = false; for(let output of this.returnNames) { if(resolved[output] === undefined) { unresolvedOutput = true; let field = this.fields[output]; if(isRegister(field)) { proposal.forRegisters.push(field); } } } if(!unresolvedOutput) { proposal.skip = true; return proposal; } // If any of our args aren't resolved yet, we can't compute results either. // @NOTE: This'll need to be touched up when we add optional support if they // co-inhabit the args object. for(let input of this.argNames) { if(resolved[input] === undefined) { proposal.skip = true; return proposal; } } // Similarly, if we're variadic we need to check that all of our // variadic inputs bound to registers are resolved too. // @NOTE: We really need to bend over backwards at the moment to // convince TS to check a static member of the current class... if((this.constructor as (typeof FunctionConstraint)).variadic) { let resolvedRest = this.resolveRest(prefix); for(let field of resolvedRest) { if(field === undefined) { proposal.skip = true; return proposal; } } } // Otherwise, we're ready to propose. proposal.skip = false; if(this.estimate) { // If the function provides a cardinality estimator, invoke that. proposal.cardinality = this.estimate(context, prefix, transaction, round); } else { // Otherwise, we'll just return 1 for now, since computing a // function is almost always cheaper than a scan. // @NOTE: If this is an issue, we can just behave like scans and // compute ourselves here, caching the results. proposal.cardinality = 1; } return proposal; } /** * Pack the resolved register values for the functions argument * fields into an array. */ packInputs(prefix:Prefix) { let resolved = this.resolve(prefix); let inputs = this.applyInputs; let argIx = 0; for(let argName of this.argNames) { // If we're asked to resolve the propoal we know that we've // proposed, and we'll only propose if these are resolved. inputs[argIx] = GlobalInterner.reverse(resolved[argName]!); argIx++; } // If we're variadic, we also need to pack our var-args up and // attach them as the last argument. if((this.constructor as (typeof FunctionConstraint)).variadic) { let resolvedRest = this.resolveRest(prefix); let restInputs = this.applyRestInputs; restInputs.length = 0; let ix = 0; for(let value of resolvedRest) { if(value !== undefined) { restInputs[ix] = GlobalInterner.reverse(value); } ix++; } inputs[argIx] = restInputs; } return inputs; } unpackOutputs(outputs:RawValue[]) { for(let ix = 0; ix < outputs.length; ix++) { // @NOTE: we'd like to use arenaIntern here, but because of intermediate values // that's not currently a possibility. We should revisit this if a practical solution // for arenas surfaces. outputs[ix] = GlobalInterner.intern(outputs[ix]); } return outputs as Prefix; } getResult(prefix:Prefix, outputs:ID[]) { // Finally, if we had results, we create the result prefixes and pass them along. let result = createArray("functionResult") as Prefix; let ix = 0; for(let returnName of this.returnNames) { let field = this.fields[returnName]; if(isRegister(field) && !prefix[field.offset]) { result[ix] = outputs[ix]; } ix++; } return result; } checkResult(prefix:Prefix, outputs:ID[]) { // Finally, we make sure every return register matches up with our outputs. // @NOTE: If we just use solvingFor then we don't know the offsets into the outputs array, // so we check everything... let ix = 0; for(let returnName of this.returnNames) { let field = this.fields[returnName]; let value = isRegister(field) ? prefix[field.offset] : field; if(value !== outputs[ix]) { return false; } ix++; } return true; } resolveProposal(context:EvaluationContext, prefix:Prefix, proposal:Proposal, transaction:number, round:number, results:any[]):ID[][] { // First we build the args array to provide the apply function. let inputs = this.packInputs(prefix); // Then we actually apply it and then unpack the outputs. let computed = this.apply.apply(this, inputs); if(!computed) return results; if(!this.multi) { // If it's not a multi-returning function, it has a single result. let outputs = this.unpackOutputs(computed); let result = this.getResult(prefix, outputs); results.push(result); } else { for(let row of computed) { // Otherwise it has N results. let outputs = this.unpackOutputs(row); let result = this.getResult(prefix, outputs); results.push(result); } } return results; } accept(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, solvingFor:Register[]):boolean { // If none of the registers we're solving for intersect our inputs // or outputs, we're not relevant to the solution. let isRelevant = false; for(let register of solvingFor) { if(this.registerLookup[register.offset]) { isRelevant = true; break; } } if(!isRelevant) return true; // If we're missing a field, we can't verify our output yet so we preliminarily accept. for(let fieldName of this.fieldNames) { let field = this.fields[fieldName]; if(isRegister(field) && prefix[field.offset] === undefined) return true; } // First we build the args array to provide the apply function. let inputs = this.packInputs(prefix); // Then we actually apply it and then unpack the outputs. let computed = this.apply.apply(this, inputs); if(!computed) return false; if(!this.multi) { // If it's not a multi-returning function we only need to check against the single result. let outputs = this.unpackOutputs(computed); return this.checkResult(prefix, outputs); } else { // Otherwise we match against any of the results. for(let row of computed) { let outputs = this.unpackOutputs(row); if(this.checkResult(prefix, outputs)) return true; } return false; } } acceptInput(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number):boolean { return this.accept(context, prefix, transaction, round, this.registers); } getDiffs(context:EvaluationContext, prefix:Prefix):RoundArray { return []; } } export interface FunctionSetup { name:string, variadic?: boolean, args:{[argName:string]: string}, returns:{[argName:string]: string}, apply:(this: FunctionConstraint, ... things: any[]) => undefined|(number|string)[]|(number|string)[][], estimate?:(index:Index, prefix:Prefix, transaction:number, round:number) => number, initialState?:any, multi?: true|false; } export interface SingleFunctionSetup extends FunctionSetup { apply:(this: FunctionConstraint, ... things: any[]) => undefined|(number|string)[], multi?: false } export interface MultiFunctionSetup extends FunctionSetup { apply:(this: FunctionConstraint, ... things: any[]) => undefined|(number|string)[][], multi?: true } function _makeFunction({name, variadic = false, args, returns, apply, estimate, initialState, multi = false}:FunctionSetup) { class NewFunctionConstraint extends FunctionConstraint { static variadic = variadic; static filter = Object.keys(returns).length === 0; static argNames = Object.keys(args); static returnNames = Object.keys(returns); name = name; args = args; argNames = Object.keys(args); returnNames = Object.keys(returns); returns = returns; apply = apply; state = initialState; multi = multi } FunctionConstraint.register(name, NewFunctionConstraint); } export function makeFunction(args:SingleFunctionSetup) { return _makeFunction(args); } export function makeMultiFunction(args:MultiFunctionSetup) { args.multi = true; return _makeFunction(args); } //------------------------------------------------------------------------ // Nodes //------------------------------------------------------------------------ /** * Base class for nodes, the building blocks of blocks. */ export abstract class Node { static NodeID = 0; ID = Node.NodeID++; traceType:TraceNode; results = new Iterator<Prefix>(); toBranchString():string { return this.toString(); } /** * Evaluate the node in the context of the currently solved prefix, * returning a set of valid prefixes to continue the query as * results. */ abstract exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean; } /** * The JoinNode implements generic join across multiple constraints. * Since our system is incremental, we need to do something slightly * fancier than we did in the previous runtime. For each new change * that enters the system, we ask each of our constraints whether they * are capable of producing a new result. In the case where a single * constraint can, we presolve that constraint and then run the rest * normally, limited to only producing results that match the first * constraint. However, if multiple constraints might apply the input, * we need to run for each *combination* of heads. E.g.: * * Given a join node with constraints [A, B, C, and D], where A and D * can both apply the input, we must combine the results of the * following computations to get the full result set: * * Apply {A} -> Do {B, C, D} * Apply {A, D} -> Do {B, C} * Apply {D} -> Do {A, B, C} * * We calculate this using the power set in exec. * * We then apply each of these combinations by running a genericJoin * over the remaining unresolved registers. We ask each un-applied * constraint to propose a register to be solved. If a constraint is * capable of resolving one, it returns the set of registers it can * resolve and an estimate of the result set's cardinality. Generic * Join chooses the cheapest proposal, which the winning constraint * then fully computes (or retrieves from cache and returns). Next it * asks each other constraint to accept or reject the proposal. If the * constraint doesn't apply to the solved registers, it accepts. If * the solution contains results that match the output of the * constraint, it also accepts. Otherwise, it must reject the solution * and that particular run yields no results. */ export class JoinNode extends Node { traceType = TraceNode.Join; isStatic = false; dormant = false; registerLength = 0; registerLookup:boolean[]; registerArrays:Register[][]; proposedResultsArrays:ID[][]; emptyProposal:Proposal = {cardinality: Infinity, forFields: new Iterator<EAVNField>(), forRegisters: new Iterator<Register>(), skip: true, proposer: {} as Constraint}; inputCount:Multiplicity; protected affectedConstraints = new Iterator<Constraint>(); constructor(public constraints:Constraint[]) { super(); // We need to find all the registers contained in our scans so that // we know how many rounds of Generic Join we need to do. let registerLength = 0; let registerLookup = []; let registers = createArray() as Register[][]; let proposedResultsArrays = createArray() as ID[][]; let hasOnlyMoves = true; let hasNoScans = true; let onlyStatic = true; for(let constraint of constraints) { constraint.setup(); if(!(constraint instanceof MoveConstraint)) hasOnlyMoves = false; else if(!constraint.isStatic) onlyStatic = false; if(constraint instanceof Scan) hasNoScans = false; for(let register of constraint.getRegisters()) { if(!registerLookup[register.offset]) { registers.push(createArray() as Register[]); proposedResultsArrays.push(createArray() as Prefix); registerLookup[register.offset] = true; registerLength++; } } } if(hasOnlyMoves) { for(let constraint of constraints as MoveConstraint[]) { constraint.shouldApplyInput = true; } this.isStatic = onlyStatic; } if(hasNoScans) { this.exec = JoinNode.prototype.downStreamExec; } this.registerLookup = registerLookup; this.registerArrays = registers; this.registerLength = registerLength; this.proposedResultsArrays = proposedResultsArrays; } toString() { return "JoinNode([\n " + this.constraints.map(toString).join("\n ") + "\n])"; } findAffectedConstraints(input:Change, prefix:Prefix):Iterator<Constraint> { // @TODO: Hoist me out. let affectedConstraints = this.affectedConstraints; affectedConstraints.clear(); for(let ix = 0, len = this.constraints.length; ix < len; ix++) { let constraint = this.constraints[ix]; let result = constraint.isAffected(input); if(result !== ApplyInputState.none) { affectedConstraints.push(constraint); } } return affectedConstraints; } applyCombination(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>) { // debug(" Join combo:", prefix.slice()); let countOfSolved = 0; for(let ix = 0; ix < this.registerLookup.length; ix++) { if(!this.registerLookup[ix]) continue; if(prefix[ix] !== undefined) countOfSolved++; } let remainingToSolve = this.registerLength - countOfSolved; // context.tracer.tracker.blockTime("PresolveCheck"); let valid = this.presolveCheck(context, input, prefix, transaction, round); // context.tracer.tracker.blockTimeEnd("PresolveCheck"); // debug(" Join combo valid:", valid, remainingToSolve, countOfSolved, this.registerLength); if(!valid) { // do nothing return false; } else if(!remainingToSolve) { // if it is valid and there's nothing left to solve, then we've found // a full result and we should just continue this.prefixToResults(context, this.constraints, prefix, round, results); // debug(" Join combo result:", results); return true; } else { // debug(" GJ:", remainingToSolve, this.constraints); // For each node, find the new results that match the prefix. this.genericJoin(context, prefix, transaction, round, results, remainingToSolve); // context.tracer.tracker.blockTimeEnd("GenericJoin"); return true; } } unapplyConstraint(constraint:Constraint, prefix:Prefix) { for(let register of constraint.getRegisters()) { prefix[register.offset] = undefined as any; } } presolveCheck(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number):boolean { let {constraints} = this; // window["counts"][window["active"]]++; for(let constraint of constraints) { let valid = constraint.acceptInput(context, input, prefix, transaction, round); if(!valid) { // debug(" INVALID:", constraint); return false; } } return true; } computeMultiplicities(context: EvaluationContext, results:Iterator<Prefix>, prefix:Prefix, currentRound:number, diffs: RoundArray[], diffIndex:number = -1) { if(diffIndex === -1) { prefix[prefix.length - 2] = currentRound; prefix[prefix.length - 1] = this.inputCount; this.computeMultiplicities(context, results, prefix, currentRound, diffs, diffIndex + 1); prefix[prefix.length - 2] = undefined as any; prefix[prefix.length - 1] = undefined as any; } else if(diffIndex === diffs.length) { let result = copyArray(prefix, "gjResultsArray"); context.tracer.capturePrefix(result); //debug(" GJ -> ", result); results.push(result); } else { let startingRound = prefix[prefix.length - 2]; let startingMultiplicity = prefix[prefix.length - 1]; let rounds = diffs[diffIndex]; let roundToMultiplicity:{[round:number]: number} = {}; let maxRound = currentRound; let ix = 0; let currentRoundCount = 0; for(let round of rounds) { if(Math.abs(round) - 1 > currentRound) { break; } currentRoundCount += round > 0 ? 1 : -1; ix++; } if(currentRoundCount) { prefix[prefix.length - 2] = Math.max(currentRound, startingRound); prefix[prefix.length - 1] = startingMultiplicity * currentRoundCount; this.computeMultiplicities(context, results, prefix, currentRound, diffs, diffIndex + 1); } for(; ix < rounds.length; ix++) { let round = rounds[ix]; let count = round > 0 ? 1 : -1; prefix[prefix.length - 2] = Math.max(Math.abs(round) - 1, startingRound); prefix[prefix.length - 1] = startingMultiplicity * count; this.computeMultiplicities(context, results, prefix, currentRound, diffs, diffIndex + 1); } prefix[prefix.length - 2] = startingRound; prefix[prefix.length - 1] = startingMultiplicity; } return results; } prefixToResults(context:EvaluationContext, constraints:Constraint[], prefix:Prefix, round:number, results:Iterator<Prefix>) { let diffs = []; for(let constraint of constraints) { if(constraint.isInput || !(constraint instanceof Scan)) continue; let cur = constraint.getDiffs(context, prefix); diffs.push(cur); } this.computeMultiplicities(context, results, prefix, round, diffs); } genericJoin(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, roundIx:number = this.registerLength):Iterator<Prefix> { let {constraints, emptyProposal} = this; let proposedResults = this.proposedResultsArrays[roundIx - 1]; let forRegisters:Register[] = this.registerArrays[roundIx - 1]; proposedResults.length = 0; let bestProposal:Proposal = emptyProposal; for(let constraint of constraints) { let current = constraint.propose(context, prefix, transaction, round, proposedResults); if(!current.skip && current.cardinality === 0) { return results; } else if(current.cardinality < bestProposal.cardinality && !current.skip) { bestProposal = current; } } if(bestProposal.skip) { // debug(" BAILING", bestProposal); return results; } let {proposer} = bestProposal; // We have to copy here because we need to keep a reference to this even if later // rounds might overwrite the proposal moveArray(bestProposal.forRegisters.array, forRegisters); let resolved:any[] = proposer.resolveProposal(context, prefix, bestProposal, transaction, round, proposedResults); if(resolved[0] && resolved[0].constructor === Array) { resultLoop: for(let result of resolved) { let ix = 0; for(let register of forRegisters) { prefix[register.offset] = +result[ix]; ix++; } for(let constraint of constraints) { if(constraint === proposer) continue; if(!constraint.accept(context, prefix, transaction, round, forRegisters)) { // debug(" BAILING", printConstraint(constraint)); continue resultLoop; } } if(roundIx === 1) { this.prefixToResults(context, constraints, prefix, round, results); } else { this.genericJoin(context, prefix, transaction, round, results, roundIx - 1); } } } else { let register = forRegisters[0]; resultLoop: for(let result of resolved) { prefix[register.offset] = +result as ID; for(let constraint of constraints) { if(constraint === proposer) continue; if(!constraint.accept(context, prefix, transaction, round, forRegisters)) { // debug(" BAILING", printConstraint(constraint)); continue resultLoop; } } if(roundIx === 1) { this.prefixToResults(context, constraints, prefix, round, results); } else { this.genericJoin(context, prefix, transaction, round, results, roundIx - 1); } } } for(let register of forRegisters) { // @NOTE: marking this as any is spoopy at best, but since we should never // iterate over the prefix, but instead use it almost like a hash, this // should be fine. prefix[register.offset] = undefined as any; } return results; } downStreamExec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>) { if(this.isStatic && this.dormant) return false; this.inputCount = prefix[prefix.length - 1] !== undefined ? prefix[prefix.length - 1] : input.count; let inputRound = prefix[prefix.length - 2] !== undefined ? prefix[prefix.length - 2] : input.round; let didSomething = this.applyCombination(context, input, prefix, transaction, inputRound, results); if(this.isStatic && didSomething) { this.dormant = true; } return didSomething; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):boolean { let didSomething = false; this.inputCount = input.count; // if we are removing the block, we need the join to compute all the results currently // being generated by this block and undo them. We do this by sending a blank prefix // through with an input count of -1. if(input === BLOCK_REMOVE) { didSomething = this.applyCombination(context, input, prefix, transaction, round, results); } else if(this.isStatic && this.dormant) { return false; } else if(input === BLOCK_ADD) { didSomething = this.applyCombination(context, input, prefix, transaction, round, results); } else { this.inputCount = input.count; let affectedConstraints = this.findAffectedConstraints(input, prefix); let combinationCount = Math.pow(2, affectedConstraints.length); for(let comboIx = combinationCount - 1; comboIx > 0; comboIx--) { //console.log(" Combo:", comboIx); let shouldApply = true; for(let constraintIx = 0; constraintIx < affectedConstraints.length; constraintIx++) { let mask = 1 << constraintIx; let isIncluded = (comboIx & mask) !== 0; let constraint = affectedConstraints.array[constraintIx]; constraint.isInput = isIncluded; if(isIncluded) { let valid = constraint.applyInput(input, prefix); // debug(" included", printConstraint(constraint)); // If any member of the input constraints fails, this whole combination is doomed. if(valid === ApplyInputState.fail) { shouldApply = false; break; } //console.log(" " + printConstraint(constraint)); } } //console.log(" ", printPrefix(prefix)); if(shouldApply) { didSomething = this.applyCombination(context, input, prefix, transaction, round, results) || didSomething; } let constraint; affectedConstraints.reset(); while((constraint = affectedConstraints.next()) !== undefined) { this.unapplyConstraint(constraint, prefix); } } affectedConstraints.reset(); let constraint; while((constraint = affectedConstraints.next()) !== undefined) { constraint.isInput = false; } } if(this.isStatic && didSomething) { this.dormant = true; } return didSomething; } } export class DownstreamJoinNode extends JoinNode { exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):boolean { return this.downStreamExec(context, input, prefix, transaction, round, results); } } export class NoopJoinNode extends JoinNode { exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):boolean { if(!this.dormant) { this.prefixToResults(context, this.constraints, prefix, round, results); this.dormant = true; return true } return false; } } export class WatchNode extends Node { traceType = TraceNode.Watch; constructor(public e:ID|Register, public a:ID|Register, public v:ID|Register, public n:ID|Register, public blockId:number) { super(); } protected resolved:ResolvedFields = {}; resolve = Scan.prototype.resolve; toString() { return `WatchNode(${printField(this.e)}, ${printField(this.a)}, ${printField(this.v)}, ${printField(this.n)})`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transactionId:number, round:number, results:Iterator<Prefix>, transaction:Transaction):boolean { let resolved = this.resolve(prefix); let {e,a,v,n} = resolved; // @NOTE: This is wasteful. results.push(prefix); if(e === undefined || a === undefined || v === undefined || n === undefined) { throw new Error(`Unable to produce an output with an undefined EAVN field [${e}, ${a}, ${v}, ${n}]`); } let prefixRound = prefix[prefix.length - 2]; let prefixCount = prefix[prefix.length - 1]; // @FIXME: Make sure I still work now that I'm sending all my deltas. I think I still need to use local intermediates. let change = new Change(e!, a!, v!, n!, transactionId, prefixRound + 1, prefixCount); transaction.export(context, this.blockId, change); return true; } } export class OutputWrapperNode extends Node { traceType = TraceNode.Output; constructor(public nodes:OutputNode[]) { super(); } toString() { return `OutputWrapper([${this.nodes.length ? "\n " : ""}${indent(this.nodes.map(toString).join("\n"), 2)}])`; } binds = new Iterator<Change>(); commits = new Iterator<Change>(); exec(context:EvaluationContext, input:Change, prefix:Prefix, transactionId:number, round:number, results:Iterator<Prefix>, transaction:Transaction):boolean { let {tracer} = context; let {binds, commits} = this; binds.clear(); commits.clear(); for(let node of this.nodes) { node.exec(context, input, prefix, transactionId, round, binds, commits); } binds.reset(); let change; while(change = binds.next()) { transaction.output(context, change); } commits.reset(); while(change = commits.next()) { transaction.commit(context, change); } return true; } } export interface OutputNode { exec(context:EvaluationContext, input:Change, prefix:Prefix, transactionId:number, round:number, binds:Iterator<Change>, commits:Iterator<Change>):void; } export class InsertNode implements OutputNode { multiplier:number = 1; resolve: (prefix:Prefix) => ResolvedEAVN; constructor(public e:ID|Register, public a:ID|Register, public v:ID|Register, public n:ID|Register) { let parts = ["var resolved = this.resolved;"]; this.setupRegister("e", parts); this.setupRegister("a", parts); this.setupRegister("v", parts); this.setupRegister("n", parts); parts.push("return resolved"); this.resolve = new Function("prefix", parts.join("\n")) as (prefix:Prefix) => ResolvedEAVN; } toString() { return `InsertNode(${printField(this.e)}, ${printField(this.a)}, ${printField(this.v)}, ${printField(this.n)})`; } setupRegister(field:EAVNField, parts:string[]) { let value = this[field]; if(isRegister(value)) { parts.push(`resolved.${field} = prefix[this.${field}.offset];`); } else { this.resolved[field] = value; } } // We precompute the registers we're interested in for fast accepts. protected resolved:ResolvedEAVN = {e: undefined, a: undefined, v:undefined, n: undefined}; output(change:Change, binds:Iterator<Change>, commits:Iterator<Change>) { binds.push(change); } exec(context:EvaluationContext, input:Change, prefix:Prefix, transactionId:number, round:number, binds:Iterator<Change>, commits:Iterator<Change>):boolean { let resolved = this.resolve(prefix); let {e,a,v,n} = resolved; if(e === undefined || a === undefined || v === undefined || n === undefined) { throw new Error(`Unable to produce an output with an undefined EAVN field [${e}, ${a}, ${v}, ${n}]`); } let prefixRound = prefix[prefix.length - 2]; let prefixCount = prefix[prefix.length - 1]; let change = new Change(e!, a!, v!, n!, transactionId, prefixRound + 1, prefixCount * this.multiplier); this.output(change, binds, commits); return true; } } export class CommitInsertNode extends InsertNode { toString() { return `CommitInsertNode(${printField(this.e)}, ${printField(this.a)}, ${printField(this.v)}, ${printField(this.n)})`; } output(change:Change, binds:Iterator<Change>, commits:Iterator<Change>) { commits.push(change); } } export class RemoveNode extends InsertNode { multiplier:number = -1; toString() { return `RemoveNode(${printField(this.e)}, ${printField(this.a)}, ${printField(this.v)}, ${printField(this.n)})`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transactionId:number, round:number, binds:Iterator<Change>, commits:Iterator<Change>):boolean { let resolved = this.resolve(prefix); let {e,a,v,n} = resolved; if(e === undefined || a === undefined || (v === undefined && this.v !== IGNORE_REG) || n === undefined) { return false; } let prefixRound = prefix[prefix.length - 2]; let prefixCount = prefix[prefix.length - 1]; if(this.v !== IGNORE_REG) { let change = new RemoveChange(e!, a!, v!, n!, transactionId, prefixRound + 1, prefixCount * this.multiplier); this.output(change, binds, commits); } else if(this.a !== IGNORE_REG) { let change = new RemoveVsChange(e!, a!, v!, n!, transactionId, prefixRound + 1, prefixCount * this.multiplier); this.output(change, binds, commits); } else { let change = new RemoveAVsChange(e!, a!, v!, n!, transactionId, prefixRound + 1, prefixCount * this.multiplier); this.output(change, binds, commits); } return true; } } export class CommitRemoveNode extends CommitInsertNode { toString() { return `CommitRemoveNode(${printField(this.e)}, ${printField(this.a)}, ${printField(this.v)}, ${printField(this.n)})`; } multiplier = -1; protected _exec = RemoveNode.prototype.exec; exec(context:EvaluationContext, input:Change, prefix:Prefix, transactionId:number, round:number, binds:Iterator<Change>, commits:Iterator<Change>):boolean { return this._exec(context, input, prefix, transactionId, round, binds, commits); } } //------------------------------------------------------------------------------ // LinearFlow //------------------------------------------------------------------------------ export class LinearFlow extends Node { traceType = TraceNode.LinearFlow; results = new Iterator<Prefix>(); initialResults = new Iterator<Prefix>(); constructor(public nodes:Node[]) { super(); } toString() { let content = this.nodes.map(toString).join(",\n"); return `LinearFlow([\n ${indent(content, 2)}\n])`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { this.initialResults.clear(); this.initialResults.push(prefix); // We populate the prefix with values from the input change so we only derive the // results affected by it. let curPrefix; let iter = this.initialResults; for(let node of this.nodes) { if(iter.length === 0) return false; node.results.clear(); while(curPrefix = iter.next()) { context.tracer.node(node, curPrefix); let valid = node.exec(context, input, curPrefix, transaction, round, node.results, changes); context.tracer.pop(TraceFrameType.Node); } iter = node.results.iter(); } while(curPrefix = iter.next()) { results.push(curPrefix); } return true; } } //------------------------------------------------------------------------------ // BinaryFlow //------------------------------------------------------------------------------ export type KeyFunction = (prefix:Prefix) => string; export class IntermediateIndexIterator { values:{[value:string]: any[]}; valueKeys:string[]; currentCounts: any[]; valueIx = 0; countIx = 0; round = 0; count = 0; minRound = 0; reset(values:{[value:string]: any[]}, minRound = 0) { this.values = values; this.valueIx = 0; this.countIx = 0; this.round = 0; this.count = 0; this.minRound = minRound + 1; this.valueKeys = Object.keys(values); this.currentCounts = values[this.valueKeys[0]]; return this; } next():Prefix|undefined { let {currentCounts, countIx, minRound} = this; if(!currentCounts) return; countIx++; if(countIx >= currentCounts.length) { this.valueIx++; let nextValue = this.valueKeys[this.valueIx]; currentCounts = this.currentCounts = this.values[nextValue]; if(!currentCounts) return; countIx = 1; } let count = 0; if(countIx < minRound) { let total = 0; for(; countIx <= minRound; countIx++) { let cur = currentCounts[countIx]; if(!cur) continue; total += cur; } count = total; countIx = minRound; } else { for(; countIx < currentCounts.length; countIx++) { let cur = currentCounts[countIx]; if(cur) { count = cur; break; } } } this.round = countIx - 1; this.count = count; this.countIx = countIx; if(count == 0) return this.next(); return currentCounts[0]; } } export class IntermediateIndex { static CreateKeyFunction(registers:Register[]):KeyFunction { let items = registers.map((reg) => { return `prefix[${reg.offset}]`; }) let code = ` return "" ${items.length ? "+" : ""} ${items.join(' + "|" + ')}; `; return new Function("prefix", code) as KeyFunction; } index:{[key:string]: {[value:string]: any[]}} = {}; iterator = new IntermediateIndexIterator(); insert(key:string, prefix:Prefix) { let values = this.index[key]; if(!values) values = this.index[key] = createHash("intermediateIndexValues"); let valueKey = this.hashPrefix(prefix); let counts = values[valueKey]; if(!counts) { counts = values[valueKey] = createArray("intermediateIndexCounts"); counts[0] = prefix; } let round = prefix[prefix.length - 2] + 1; let count = prefix[prefix.length - 1]; counts[round] = count + (counts[round] || 0); if(!counts[round]) { let shouldRemove = true; for(let ix = 1, len = counts.length; ix < len; ix++) { if(counts[ix]) { shouldRemove = false; break; } } if(shouldRemove) { delete values[valueKey]; } } } iter(key:string, round:number):IntermediateIndexIterator|undefined { let values = this.index[key]; if(values) return this.iterator.reset(values, round); } hashPrefix(prefix:Prefix) { let round = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; prefix[prefix.length - 2] = undefined as any; prefix[prefix.length - 1] = undefined as any; let key = prefix.join("|"); prefix[prefix.length - 2] = round; prefix[prefix.length - 1] = count; return key; } } export class ZeroingIterator { counts:Multiplicity[]; roundIx = -1; countSum = 0; minRound = 0; count = 1; reset(counts:Multiplicity[], minRound:number = 0) { this.counts = counts; this.minRound = minRound; this.roundIx = -1; this.countSum = 0; this.count = 1; return this; } next():number|undefined { let {roundIx, counts, countSum, minRound} = this; let countsLength = counts.length; roundIx++; if(roundIx >= countsLength) return; let final; if(roundIx <= minRound) { if(minRound >= countsLength) countsLength = minRound + 1; for(; roundIx < countsLength; roundIx++) { let cur = counts[roundIx]; if(cur) { countSum += cur; } if(roundIx >= minRound && countSum === 0) { final = roundIx; break; } } } else { for(; roundIx <= countsLength; roundIx++) { let cur = counts[roundIx]; if(!cur) continue; countSum += cur; if((this.countSum === 0 && countSum > 0) || (this.countSum > 0 && countSum === 0)) { final = roundIx; break; } } } this.roundIx = roundIx; this.countSum = countSum; this.count = 1; if(countSum !== 0) { this.count = -1; } return final; } } export class KeyOnlyIntermediateIndex { index:{[key:string]: Multiplicity[]} = {}; iterator = new ZeroingIterator(); insert(key:string, prefix:Prefix) { let counts = this.index[key]; if(!counts) counts = this.index[key] = createArray("KeyOnlyIntermediateIndex"); let round = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; let prev = counts[round] || 0; counts[round] = count + prev; if(!counts[round]) { let shouldRemove = true; for(let ix = 0, len = counts.length; ix < len; ix++) { if(counts[ix]) { shouldRemove = false; break; } } if(shouldRemove) { delete this.index[key]; } } } has(key:string) { return this.index[key] ? true : false; } iter(key:string, round:number):ZeroingIterator|undefined { let values = this.index[key]; if(values) return this.iterator.reset(values, round); } } export abstract class BinaryFlow extends Node { traceType = TraceNode.BinaryJoin; constructor(public left:Node, public right:Node) { super(); } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let {left, right} = this; left.results.clear(); context.tracer.node(left, prefix); left.exec(context, input, prefix, transaction, round, left.results, changes); context.tracer.pop(TraceFrameType.Node); right.results.clear(); context.tracer.node(right, prefix); right.exec(context, input, prefix, transaction, round, right.results, changes); context.tracer.pop(TraceFrameType.Node); let result; let leftResults = left.results.iter(); let rightResults = right.results.iter(); while((result = leftResults.next()) !== undefined) { this.onLeft(context, result, transaction, round, results); } while((result = rightResults.next()) !== undefined) { this.onRight(context, result, transaction, round, results); } return true; } abstract onLeft(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void; abstract onRight(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void; } export class BinaryJoinRight extends BinaryFlow { leftIndex = new IntermediateIndex(); rightIndex = new IntermediateIndex(); keyFunc:KeyFunction; constructor(public left:Node, public right:Node, public keyRegisters:Register[], public registersToMerge:Register[]) { super(left, right); this.keyFunc = IntermediateIndex.CreateKeyFunction(keyRegisters); } _nodeName:string = "BinaryJoinRight"; toString() { let keys = "[" + this.keyRegisters.map((r) => `[${r.offset}]`).join(", ") + "]"; let merge = "[" + this.registersToMerge.map((r) => `[${r.offset}]`).join(", ") + "]"; return `${this._nodeName}({ keys: ${keys}, merge: ${merge}, left: ${indent(toString(this.left), 2)}, right: ${indent(toString(this.right), 2)} })`; } toBranchString() { let keys = "[" + this.keyRegisters.map((r) => `[${r.offset}]`).join(", ") + "]"; let merge = "[" + this.registersToMerge.map((r) => `[${r.offset}]`).join(", ") + "]"; return `${this._nodeName}({ keys: ${keys}, merge: ${merge}, right: ${indent(toString(this.right), 2)} })`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { // debug(" Binary Join Right:") let {left, right} = this; right.results.clear(); context.tracer.node(right, prefix); right.exec(context, input, prefix, transaction, round, right.results, changes); context.tracer.pop(TraceFrameType.Node); let leftResults = left.results.iter(); let rightResults = right.results.iter(); let result; while((result = leftResults.next()) !== undefined) { this.onLeft(context, result, transaction, round, results); } while((result = rightResults.next()) !== undefined) { this.onRight(context, result, transaction, round, results); } // debug(" results:", results.array.slice()); return true; } merge(left:Prefix, right:Prefix) { for(let register of this.registersToMerge) { let leftValue = left[register.offset]; let rightValue = right[register.offset]; if(leftValue === undefined || leftValue === rightValue) { left[register.offset] = rightValue } else { return false; } } return true; } onLeft(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void { let key = this.keyFunc(prefix); let prefixRound = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; this.leftIndex.insert(key, prefix); let diffs = this.rightIndex.iter(key, round) // debug(" join left", key, printPrefix(prefix), diffs); if(!diffs) return; let rightPrefix; while(rightPrefix = diffs.next()) { let result = copyArray(prefix, "BinaryJoinResult"); if(this.merge(result, rightPrefix)) { result[result.length - 2] = Math.max(prefixRound, diffs.round); result[result.length - 1] = count * diffs.count; context.tracer.capturePrefix(result); results.push(result); // debug(" join left -> ", printPrefix(result), diffs.round, count, diffs.count); } } } onRight(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void { let key = this.keyFunc(prefix); let prefixRound = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; this.rightIndex.insert(key, prefix); let diffs = this.leftIndex.iter(key, round) // debug(" join right", key, this.rightIndex.index[key]); if(!diffs) return; let leftPrefix; while(leftPrefix = diffs.next()) { let result = copyArray(leftPrefix, "BinaryJoinResult"); if(this.merge(result, prefix)) { result[result.length - 2] = Math.max(prefixRound, diffs.round); result[result.length - 1] = count * diffs.count; context.tracer.capturePrefix(result); results.push(result); // debug(" join right -> ", printPrefix(result.slice()), diffs.round, count, diffs.count); } } } } export class AntiJoin extends BinaryFlow { traceType = TraceNode.AntiJoin; leftIndex = new IntermediateIndex(); rightIndex = new KeyOnlyIntermediateIndex(); distinct = new DistinctIndex(); keyFunc:KeyFunction; constructor(public left:Node, public right:Node, public keyRegisters:Register[]) { super(left, right); this.keyFunc = IntermediateIndex.CreateKeyFunction(keyRegisters); } toString() { let left = indent(toString(this.left), 2); let right = indent(toString(this.right), 2); return `Antijoin({\n left: ${left},\n right: ${right}\n})`; } toBranchString() { let right = indent(toString(this.right), 2); return `Antijoin({\n right: ${right}\n})`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { // debug(" antijoin:") return super.exec(context,input,prefix,transaction,round,results,changes); } onLeft(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void { let key = this.keyFunc(prefix); let prefixRound = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; this.leftIndex.insert(key, prefix); let diffs = this.rightIndex.iter(key, prefixRound); // debug(" left:", key, count, this.rightIndex.index[key] && copyArray(this.rightIndex.index[key]), prefix); if(!diffs) { // debug(" left ->", key, count, diffs) return results.push(prefix); } else { let currentRound; while((currentRound = diffs.next()) !== undefined) { let result = copyArray(prefix, "AntiJoinResult"); result[result.length - 2] = currentRound; result[result.length - 1] = diffs.count * count; context.tracer.capturePrefix(result); results.push(result); // debug(" left ->", key, count, currentRound, result[result.length - 1]) } } } onRight(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void { let key = this.keyFunc(prefix); let prefixRound = prefix[prefix.length - 2]; let count = prefix[prefix.length - 1]; this.rightIndex.insert(key, prefix); let neue = new Iterator<[number, number]>(); this.distinct.distinctKey(key, prefixRound, count, neue) let diffs = this.leftIndex.iter(key, prefixRound) let copy = (thing:any) => { let neue = copyHash(thing); for(let key in thing) { neue[key] = thing[key].slice(); } return neue; } // debug(" right:", key, count, this.leftIndex.index[key] && copy(this.leftIndex.index[key])); // debug(" right distinct: ", this.distinct.index[key], neue); if(!diffs || !neue.length) return; let leftPrefix; let rightDelta; while(rightDelta = neue.next()) { let [rightRound, rightCount] = rightDelta; diffs = this.leftIndex.iter(key, prefixRound)!; // We already checked for this above. while(leftPrefix = diffs.next()) { let result = copyArray(leftPrefix, "AntiJoinResult"); let maxRound = Math.max(diffs.round, rightRound); result[result.length - 2] = maxRound; result[result.length - 1] = rightCount * diffs.count * -1; context.tracer.capturePrefix(result); results.push(result); // debug(" right ->", key, maxRound, rightCount, diffs.count, result[result.length - 1]) } } } } export class AntiJoinPresolvedRight extends AntiJoin { toString() { return `AntiJoinPresolvedRight(${toString(this.left)})`; } toBranchString() { return `AntiJoinPresolvedRight(${this.left.toBranchString()})`; } traceType = TraceNode.AntiJoinPresolvedRight; exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let {left, right} = this; left.results.clear(); context.tracer.node(left, prefix); left.exec(context, input, prefix, transaction, round, left.results, changes); context.tracer.pop(TraceFrameType.Node); let leftResults = left.results.iter(); let rightResults = right.results.iter(); let result; while((result = leftResults.next()) !== undefined) { this.onLeft(context, result, transaction, round, results); } while((result = rightResults.next()) !== undefined) { this.onRight(context, result, transaction, round, results); } return true; } } export class UnionFlow extends Node { traceType = TraceNode.Union; branches:BinaryJoinRight[] = []; emptyResults = new Iterator<Prefix>(); constructor(public left:Node, branches:Node[], public keyRegisters:Register[][], public registersToMerge:Register[], public extraOuterJoins:Register[]) { super(); let ix = 0; for(let branch of branches) { this.branches.push(new BinaryJoinRight(left, branch, keyRegisters[ix].concat(extraOuterJoins), registersToMerge)); ix++; } } toString() { let name; let branchText = (this.branches as Node[]).map((branch) => indent(branch.toBranchString(), 4)).join(",\n "); return `UnionFlow({ left: ${indent(toString(this.left), 2)}, branches: [\n ${branchText}\n)}] })`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let {left} = this; let {tracer} = context; let tempLeftResults = left.results; left.results.clear(); tracer.node(left, prefix); left.exec(context, input, prefix, transaction, round, left.results, changes); tracer.pop(TraceFrameType.Node); let leftPrefix; let leftResults = left.results.iter(); for(let node of this.branches) { node.results.clear(); tracer.node(node, prefix); node.exec(context, input, prefix, transaction, round, node.results, changes); tracer.pop(TraceFrameType.Node); // Because we've already run this node once, we don't want it to potentially see the left's // results multiple times. As such, we temporarily set the results to an empty iterator // so that downstream nodes see nothing and we set it back once we've gone through // all the left prefixes. left.results = this.emptyResults; leftResults.reset(); if(node.keyRegisters.length && input !== BLOCK_ADD && input !== BLOCK_REMOVE) { while((leftPrefix = leftResults.next()) !== undefined) { tracer.node(node, leftPrefix); node.exec(context, input, copyArray(leftPrefix, "UnionLeftPrefixCopy"), transaction, round, node.results, changes); tracer.pop(TraceFrameType.Node); } } // set the left results back to the real results left.results = tempLeftResults; let branchResults = node.results.iter(); let result; while((result = branchResults.next())) { results.push(result); } } return true; } } export class ChooseFlow extends Node { traceType = TraceNode.Choose; leftResults = new Iterator<Prefix>(); emptyResults = new Iterator<Prefix>(); branches:(BinaryJoinRight|AntiJoinPresolvedRight)[] = []; constructor(public left:Node, initialBranches:Node[], public keyRegisters:Register[][], public registersToMerge:Register[], public extraOuterJoins:Register[]) { super(); let allKeys:Register[] = [] for(let keySet of keyRegisters) { for(let key of keySet) { if(!allKeys.some((r) => r.offset === key.offset)) { allKeys.push(key); } } } let {branches} = this; let prev:Node|undefined; let ix = 0; for(let branch of initialBranches) { let myKeys = keyRegisters[ix].concat(extraOuterJoins); let join; if(prev) { join = new BinaryJoinRight(left, branch, myKeys, registersToMerge); let antijoin = new AntiJoinPresolvedRight(join, this, allKeys); branches.push(antijoin); } else { join = new BinaryJoinRight(left, branch, myKeys, registersToMerge); branches.push(join); } prev = join; ix++; } } toString() { let name; let branchText = (this.branches as Node[]).map((branch) => indent(branch.toBranchString(), 4)).join(",\n "); return `ChooseFlow({ left: ${indent(toString(this.left), 2)}, branches: [\n ${branchText}\n)}] })`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let {tracer} = context; let {branches, left} = this; let prev:Iterator<Prefix>|undefined; let ix = 0; let tempResults = this.results; let tempLeftResults = left.results; left.results.clear(); tracer.node(left, prefix); left.exec(context, input, prefix, transaction, round, left.results, changes); tracer.pop(TraceFrameType.Node); let leftResults = left.results.iter(); let leftPrefix; for(let node of branches) { node.results.clear(); tracer.node(node, prefix); node.exec(context, input, prefix, transaction, round, node.results, changes); tracer.pop(TraceFrameType.Node); // Because we've already run this node once, we don't want it to potentially see our // results multiple times. As such, we temporarily set our results to an empty iterator // so that downstream nodes see nothing and we set it back once we've gone through // all the left prefixes. This ensures that AntiJoinPresolvedRight only sees the previous // branches' results once. We also need to do this for our left's results, since we'll have // seen those as well and would otherwise double count them. this.results = this.emptyResults; left.results = this.emptyResults; leftResults.reset(); if(node.keyRegisters.length && input !== BLOCK_ADD && input !== BLOCK_REMOVE) { while((leftPrefix = leftResults.next()) !== undefined) { tracer.node(node, leftPrefix); node.exec(context, input, copyArray(leftPrefix, "ChooseLeftPrefixCopy"), transaction, round, node.results, changes); tracer.pop(TraceFrameType.Node); } } // per above, make sure we set our results back to the real iterator this.results = tempResults; left.results = tempLeftResults; let branchResult = node.results.iter(); let result; while((result = branchResult.next()) !== undefined) { tracer.capturePrefix(result); results.push(result); } } return true; } } export class MergeAggregateFlow extends BinaryJoinRight { _nodeName:string = "MergeAggregateFlow"; exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { // debug(" AGG MERGE"); let result; let {left, right} = this; left.results.clear(); left.exec(context, input, prefix, transaction, round, left.results, changes); // debug(" left results: ", leftResults); let leftResults = left.results.iter(); // we run the left's results through the aggregate to capture all the aggregate updates right.results.clear(); while((result = leftResults.next()) !== undefined) { // debug(" left result: ", result.slice()); right.exec(context, input, result, transaction, round, right.results, changes); } // now we go through all the lefts and rights like normal leftResults.reset(); while((result = leftResults.next()) !== undefined) { this.onLeft(context, result, transaction, round, results); } let rightResults = right.results.iter(); while((result = rightResults.next()) !== undefined) { this.onRight(context, result, transaction, round, results); } return true; } } // This node is a bit strange, but is required to make sure that aggregates // that are inside of a choose don't end up seeing results that wouldn't actually // join with the outer scope of the choose. For example if we have the following rule: // // prog.block("count the names of people", ({find, gather, record, choose}) => { // let person = find("person"); // let [sort] = choose(() => { // return gather(person.name).count(); // }, () => "yo yo yo"); // return [person.add("next", sort)]; // }); // // If we join the choose branch to the outer *after* we've aggregated, then we're // going to count everything with a name whether they're a person or not. Instead // we need to make sure there is a join with the outer scope before it makes it to // the choose. To do that, the AggregateOuterLookup node just keeps track of every // value it has seen from the outer and makes sure that each right has a join with // it. export class AggregateOuterLookup extends BinaryFlow { _nodeName:string = "AggregateOuterLookup"; traceType = TraceNode.AggregateOuterLookup; keyFunc:KeyFunction; leftIndex:KeyOnlyIntermediateIndex = new KeyOnlyIntermediateIndex(); rightIndex:IntermediateIndex = new IntermediateIndex(); constructor(public left:Node, public right:Node, public keyRegisters:Register[]) { super(left, right); this.keyFunc = IntermediateIndex.CreateKeyFunction(keyRegisters); } toString() { let keys = "[" + this.keyRegisters.map((r) => `[${r.offset}]`).join(", ") + "]"; //${indent(this.left.toString(), 2)}, return `AggregateOuterLookup({ keys: ${keys}, left: '*snip*', right: ${indent(this.right.toString(), 2)} })`; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let {left, right} = this; right.results.clear(); context.tracer.node(right, prefix); right.exec(context, input, prefix, transaction, round, right.results, changes); context.tracer.pop(TraceFrameType.Node); let result; let leftResults = left.results.iter(); while((result = leftResults.next()) !== undefined) { this.onLeft(context, result, transaction, round, results); } let rightResults = right.results.iter(); while((result = rightResults.next()) !== undefined) { this.onRight(context, result, transaction, round, results); } return true; } onLeft(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void { let key = this.keyFunc(prefix); let exists = this.leftIndex.has(key); this.leftIndex.insert(key, prefix); let afterExists = this.leftIndex.has(key); let diffs = this.rightIndex.iter(key, 0); if(exists && afterExists || !diffs) return; let multiplier = 1; if(exists && !afterExists) { // remove multiplier = -1; } let rightPrefix; while(rightPrefix = diffs.next()) { let result = copyArray(rightPrefix, "aggregateLookupResult"); result[result.length - 2] = diffs.round; result[result.length - 1] = diffs.count * multiplier; context.tracer.capturePrefix(result); results.push(result); } } onRight(context:EvaluationContext, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>):void { let key = this.keyFunc(prefix); this.rightIndex.insert(key, prefix); if(this.leftIndex.has(key)) { results.push(prefix); } } } export abstract class AggregateNode extends Node { abstract name:string; traceType = TraceNode.Aggregate; groupKey:Function; projectKey:Function; groups:{[group:string]: {result:any[], [projection:string]: Multiplicity[]}} = {}; resolved:RawValue[] = []; registerLookup:boolean[] = []; // @TODO: allow for multiple returns constructor(public groupRegisters:Register[], public projectRegisters:Register[], public inputs:(ID|Register)[], public resultRegisters:Register[]) { super(); this.groupKey = IntermediateIndex.CreateKeyFunction(groupRegisters); this.projectKey = IntermediateIndex.CreateKeyFunction(projectRegisters); for(let reg of groupRegisters) { this.registerLookup[reg.offset] = true; } for(let reg of resultRegisters) { this.registerLookup[reg.offset] = true; } } toString() { let groups = printFieldArray(this.groupRegisters); let projects = printFieldArray(this.projectRegisters); let inputs = printFieldArray(this.inputs); let results = printFieldArray(this.resultRegisters); return `AggregateNode(${this.name}, ${groups}, ${projects}, ${inputs}, ${results})`; } groupPrefix(group:string, prefix:Prefix) { let projection = this.projectKey(prefix); let prefixRound = prefix[prefix.length - 2]; let prefixCount = prefix[prefix.length - 1]; let delta = 0; let found = this.groups[group]; if(!found) { found = this.groups[group] = {result: []}; } let counts = found[projection] || []; let totalCount = 0; let countIx = 0; for(let count of counts) { // we need the total up to our current round if(countIx > prefixRound) break; countIx++; if(!count) continue; totalCount += count; } if(totalCount && totalCount + prefixCount <= 0) { // subtract delta = -1; } else if(totalCount === 0 && totalCount + prefixCount > 0) { // add delta = 1; } else if(totalCount + prefixCount < 0) { // we have removed more values than exist? throw new Error("Negative total count for an aggregate projection"); } else { // otherwise this change doesn't impact the projected count, we've just added // or removed a support. } counts[prefixRound] = (counts[prefixRound] || 0) + prefixCount; found[projection] = counts; return delta; } getResultPrefix(prefix:Prefix, result:ID, count:Multiplicity):Prefix { let neue = copyArray(prefix, "aggregateResult"); neue[this.resultRegisters[0].offset] = result; neue[neue.length - 1] = count; let ix = 0; while(ix < neue.length - 2) { if(!this.registerLookup[ix]) { neue[ix] = undefined; } ix++; } return neue; } resolve(prefix:Prefix):RawValue[] { let resolved = this.resolved; let ix = 0; for(let field of this.inputs) { if(isRegister(field)) { resolved[ix] = GlobalInterner.reverse(prefix[field.offset]); } else { resolved[ix] = GlobalInterner.reverse(field); } ix++; } return resolved; } stateToResult(state:any):ID { let current = this.getResult(state); return GlobalInterner.intern(current); } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let group = this.groupKey(prefix); let prefixRound = prefix[prefix.length - 2]; let delta = this.groupPrefix(group, prefix); let op = this.add; if(!delta) return false; if(delta < 0) op = this.remove; let groupStates = this.groups[group].result; let currentState = groupStates[prefixRound]; if(!currentState) { // otherwise we have to find the most recent result that we've seen for(let ix = 0, len = Math.min(groupStates.length, prefixRound); ix < len; ix++) { let current = groupStates[ix]; if(current === undefined) continue; currentState = copyHash(current, "AggregateState"); } } let resolved = this.resolve(prefix); let start = prefixRound; groupStates[prefixRound] = currentState; if(!currentState) { currentState = groupStates[prefixRound] = op(this.newResultState(), resolved); let cur = this.getResultPrefix(prefix, this.stateToResult(currentState), 1); results.push(cur); start = prefixRound + 1; } for(let ix = start, len = Math.max(groupStates.length, prefixRound + 1); ix < len; ix++) { let current = groupStates[ix]; if(current === undefined) continue; let prevResult = this.getResultPrefix(prefix, this.stateToResult(current), -1); current = groupStates[prefixRound] = op(current, resolved); let neueResult = this.getResultPrefix(prefix, this.stateToResult(current), 1); results.push(prevResult); results.push(neueResult); } return true; } abstract add(state:any, resolved:RawValue[]):any; abstract remove(state:any, resolved:RawValue[]):any; abstract getResult(state:any):RawValue; abstract newResultState():any; } //------------------------------------------------------------------------------ // SortNode //------------------------------------------------------------------------------ export abstract class SortNode extends Node { name = "Sort"; traceType = TraceNode.Aggregate; groupKey:Function; projectKey:Function; groups:{[group:string]: {result:any[], [projection:string]: Multiplicity[]}} = {}; resolved:ID[] = []; resolvedDirections:RawValue[] = []; sortRegisters:Register[]; // @TODO: allow for multiple returns constructor(public groupRegisters:Register[], public projectRegisters:Register[], public directions:(ID|Register)[], public resultRegisters:Register[]) { super(); this.groupKey = IntermediateIndex.CreateKeyFunction(groupRegisters); this.projectKey = IntermediateIndex.CreateKeyFunction(projectRegisters); this.sortRegisters = groupRegisters.concat(projectRegisters).filter(isRegister); } groupPrefix(group:string, prefix:Prefix) { let projection = this.projectKey(prefix); let prefixRound = prefix[prefix.length - 2]; let prefixCount = prefix[prefix.length - 1]; let delta = 0; let found = this.groups[group]; if(!found) { found = this.groups[group] = {result: []}; } let counts = found[projection] || []; let totalCount = 0; let countIx = 0; for(let count of counts) { // we need the total up to our current round if(countIx > prefixRound) break; countIx++; if(!count) continue; totalCount += count; } if(totalCount && totalCount + prefixCount <= 0) { // subtract delta = -1; } else if(totalCount === 0 && totalCount + prefixCount > 0) { // add delta = 1; } else if(totalCount + prefixCount < 0) { // we have removed more values than exist? throw new Error("Negative total count for an aggregate projection"); } else { // otherwise this change doesn't impact the projected count, we've just added // or removed a support. } counts[prefixRound] = (counts[prefixRound] || 0) + prefixCount; found[projection] = counts; return delta; } resolve(prefix:Prefix):ID[] { let {resolved, resolvedDirections} = this; if(resolved.length < prefix.length) resolved.length = prefix.length; for(let field of this.sortRegisters) { if(isRegister(field)) { resolved[field.offset] = prefix[field.offset]; } } let ix = 0; for(let field of this.directions) { if(isRegister(field)) { resolvedDirections[ix] = GlobalInterner.reverse(prefix[field.offset]); } else { resolvedDirections[ix] = GlobalInterner.reverse(field); } ix++; } return resolved; } isGreater(a:Prefix, b:Prefix):string|false { let {resolvedDirections} = this; let dirIx = 0; let dir = resolvedDirections[dirIx] || "up"; for(let register of this.projectRegisters) { let {offset} = register; let aV = GlobalInterner.reverse(a[offset]); let bV = GlobalInterner.reverse(b[offset]); if((dir === "up" && aV > bV) || (dir === "down" && aV < bV)) { return dir; } else if(aV !== bV) { return false; } dirIx++; dir = resolvedDirections[dirIx] || dir; } return false; } prefixEqual(a:Prefix, b:Prefix) { let ix = -1; for(let field of a) { ix++; if(field !== b[ix]) { return false; } } return true; } exec(context:EvaluationContext, input:Change, prefix:Prefix, transaction:number, round:number, results:Iterator<Prefix>, changes:Transaction):boolean { let group = this.groupKey(prefix); let prefixRound = prefix[prefix.length - 2]; let delta = this.groupPrefix(group, prefix); let op = this.add; if(!delta) return false; if(delta < 0) op = this.remove; let groupStates = this.groups[group].result; let currentState = groupStates[prefixRound]; if(!currentState) { // otherwise we have to find the most recent result that we've seen for(let ix = 0, len = Math.min(groupStates.length, prefixRound); ix < len; ix++) { let current = groupStates[ix]; if(current === undefined) continue; currentState = copyHash(current, "SortState"); } } let resolved = this.resolve(prefix); let start = prefixRound; groupStates[prefixRound] = currentState; if(!currentState) { currentState = groupStates[prefixRound] = op(this.newResultState(), resolved, prefixRound, results); start = prefixRound + 1; } for(let ix = start, len = Math.max(groupStates.length, prefixRound + 1); ix < len; ix++) { let current = groupStates[ix]; if(current === undefined) continue; current = groupStates[prefixRound] = op(current, resolved, ix, results); } return true; } resultPrefix(prefix:Prefix, outOffset:number, pos:number, round:number, count:Multiplicity) { let item = copyArray(prefix, "SortResult"); // add one here because we're one indexed item[outOffset] = GlobalInterner.intern(pos + 1); item[item.length - 2] = round; item[item.length - 1] = count; return item; } add = (state:any, resolved:ID[], round:number, results:Iterator<Prefix>):any => { let {resultPrefix} = this; let neue = copyArray(resolved, "SortIntermediate"); let ix = 0; for(let item of state.sorted) { if(this.isGreater(item, resolved)) { break; } ix++; } let outOffset = this.resultRegisters[0].offset; state.sorted.splice(ix, 0, neue); results.push(resultPrefix(neue, outOffset, ix, round, 1)); ix++; for(; ix < state.sorted.length; ix++) { let cur = state.sorted[ix]; results.push(resultPrefix(cur, outOffset, ix - 1, round, -1)); results.push(resultPrefix(cur, outOffset, ix, round, 1)); } return state; } remove = (state:any, resolved:ID[], round:number, results:Iterator<Prefix>):any => { let {resultPrefix} = this; let ix = 0; let found = false; for(let item of state.sorted) { if(this.prefixEqual(item, resolved)) { break; } ix++; } state.sorted.splice(ix, 1); let outOffset = this.resultRegisters[0].offset; results.push(resultPrefix(resolved, outOffset, ix, round, -1)); for(; ix < state.sorted.length; ix++) { let cur = state.sorted[ix]; results.push(resultPrefix(cur, outOffset, ix + 1, round, -1)); results.push(resultPrefix(cur, outOffset, ix, round, 1)); } return state; } newResultState():any { return {sorted: [], sortLookup: {}}; } } //------------------------------------------------------------------------------ // Block //------------------------------------------------------------------------------ export class Block { constructor(public name:string, public nodes:Node[], public totalRegisters:number) { for(let ix = 0; ix < this.totalRegisters + 2; ix++) { this.initial[ix] = undefined as any; } } results = new Iterator<Prefix>(); initial:Prefix = createArray(); toString() { let content = this.nodes.map(toString).join(",\n"); return `Block("${this.name}", [\n ${indent(content, 2)}\n])`; } exec(context:EvaluationContext, input:Change, transaction:Transaction):boolean { this.results.clear(); this.results.push(this.initial.slice()); let prefix; let iter = this.results; for(let node of this.nodes) { node.results.clear(); if(iter.length === 0) { if(node instanceof AntiJoin) { node.exec(context, input, this.initial.slice(), transaction.transaction, transaction.round, node.results, transaction); iter = node.results.iter(); } } else { while((prefix = iter.next()) !== undefined) { context.tracer.node(node, prefix); node.exec(context, input, prefix, transaction.transaction, transaction.round, node.results, transaction); context.tracer.pop(TraceFrameType.Node); } iter = node.results.iter(); } } return true; } } //------------------------------------------------------------------------------ // EvaluationContext //------------------------------------------------------------------------------ export class EvaluationContext { distinctIndex = new DistinctIndex(); intermediates:{[key:string]: IntermediateIndex} = {}; exportIndex:{[beav:string]: number} = {}; tracer:Tracer; constructor(public index:Index) { this.tracer = TRACE ? new Tracer(this) : new NoopTracer(this); } } //------------------------------------------------------------------------------ // Transaction //------------------------------------------------------------------------------ export type ExportHandler = (blockChanges:{[id:number]: Change[]|undefined}) => void; export class Transaction { round = -1; changes:Change[] = [] lastFrame = 0; protected outputs = new Iterator<Change>(); protected roundChanges:Change[][] = []; protected frameCommits:Change[] = []; protected framePartialCommits:RemoveVsChange[] = []; protected exportedChanges:{[blockId:number]: Change[]} = {}; constructor(public context:EvaluationContext, public transaction:number, public blocks:Block[], protected exportHandler?:ExportHandler) { context.tracer.transaction(transaction); } output(context:EvaluationContext, change:Change) { // debug(" E~", change.toString(), context.tracker.activeBlock); let {outputs} = this; let {distinctIndex, tracer} = context; tracer.maybeOutput(change); outputs.clear(); distinctIndex.distinct(change, outputs); tracer.postDistinct(); outputs.reset(); let output; while(output = outputs.next()) { tracer.output(output); // debug(" <-", output.toString()) let cur = this.roundChanges[output.round] || createArray("roundChangesArray"); cur.push(output); this.roundChanges[output.round] = cur; } tracer.pop(TraceFrameType.MaybeOutput); } commit(context:EvaluationContext, change:Change) { context.tracer.commit(change); let {outputs} = this; if(change instanceof RemoveVsChange) { this.framePartialCommits.push(change); } else { this.frameCommits.push(change); } // debug(" <-!", change.toString()) } export(context:EvaluationContext, blockId:number, change:Change) { if(!this.exportedChanges[blockId]) this.exportedChanges[blockId] = [change]; else this.exportedChanges[blockId].push(change); } protected prepareRound(context:EvaluationContext, changeIx:number) { let {roundChanges, changes} = this; let next = changes[changeIx]; let maxRound = roundChanges.length; let oldLength = changes.length; if(!next && this.round < maxRound) { for(let ix = this.round + 1; ix < maxRound; ix++) { let nextRoundChanges = roundChanges[ix]; if(nextRoundChanges) { this.collapseMultiplicity(nextRoundChanges, changes); // If we've got new changes to go through, we're done if(oldLength < changes.length) return; } } } let {frameCommits, framePartialCommits} = this; if(!next && (frameCommits.length || framePartialCommits.length)) { for(let commit of framePartialCommits) { commit.toRemoveChanges(context, frameCommits); } let collapsedCommits:Change[] = []; this.collapseCommits(this.frameCommits, collapsedCommits); let collapsedChanges:Change[] = []; this.collapseMultiplicity(collapsedCommits, collapsedChanges); if(collapsedChanges.length) { context.tracer.frame(collapsedChanges); this.lastFrame = this.changes.length; this.round = -1; this.roundChanges = []; this.frameCommits = []; this.framePartialCommits = []; for(let commit of collapsedChanges) { if(commit.count > 0) commit.count = Infinity; else if(commit.count < 0) commit.count = -Infinity; // debug(" ->! ", commit.toString()) this.output(context, commit); } this.prepareRound(context, changeIx); // debug(" ---------------- NEW FRAME -------------------") } } } protected collapseCommits(changes:Change[], results:Change[] /* output */) { // We sort the changes to group all the same EAVs together. changes.sort((a,b) => { let nodeDiff = a.n - b.n; if(!nodeDiff) { let eDiff = a.e - b.e; if(!eDiff) { let aDiff = a.a - b.a; if(!aDiff) { let vDiff = a.v - b.v; return vDiff; } return aDiff; } return eDiff; } return nodeDiff; }); let changeIx = 0; for(let changeIx = 0; changeIx < changes.length; changeIx++) { let current = changes[changeIx]; let currentType = current instanceof RemoveChange ? true : false; if(currentType) { current = new RemoveChange(current.e, current.a, current.v, current.n, current.transaction, current.round, current.count); } else { current = new Change(current.e, current.a, current.v, current.n, current.transaction, current.round, current.count); } // Collapse each subsequent matching EAV's multiplicity into the current one's. while(changeIx + 1 < changes.length) { let next = changes[changeIx + 1]; if(current.n === next.n && next.e == current.e && next.a == current.a && next.v == current.v) { current.count += next.count; changeIx++; } else { break; } } current.round = 0; if(currentType && current.count < 0) { results.push(current); } else if(!currentType && current.count > 0) { results.push(current); } } return results; } protected collapseMultiplicity(changes:Change[], results:Change[] /* output */, createNew = false) { // We sort the changes to group all the same EAVs together. changes.sort((a,b) => { let eDiff = a.e - b.e; if(!eDiff) { let aDiff = a.a - b.a; if(!aDiff) { return a.v - b.v; } return aDiff; } return eDiff; }); let changeIx = 0; for(let changeIx = 0; changeIx < changes.length; changeIx++) { let current = changes[changeIx]; if(createNew) { current = new Change(current.e, current.a, current.v, current.n, current.transaction, current.round, current.count); } // Collapse each subsequent matching EAV's multiplicity into the current one's. while(changeIx + 1 < changes.length) { let next = changes[changeIx + 1]; if(next.e == current.e && next.a == current.a && next.v == current.v) { current.count += next.count; changeIx++; } else { break; } } if(current.count !== 0) results.push(current); } return results; } exec(context:EvaluationContext) { let {changes, roundChanges} = this; let {index, tracer} = context; tracer.frame([]); let total = 0; let frames = 0; let changeIx = 0; let iterationLimit = 10000; this.prepareRound(context, changeIx); while(changeIx < changes.length) { let change = changes[changeIx]; tracer.input(change); total++; if(total > iterationLimit) { console.error(`Error: Program failed to fixpoint after ${iterationLimit} iterations. This is likely due to an unbounded cycle in the program.`); break; } if(this.round !== 0 && change.round === 0) { frames++; if(frames > 10) { console.error("Failed to terminate"); break; } } this.round = change.round; // debug("Round:", this.round); // debug(" <- ", change.toString()) for(let block of this.blocks) { tracer.block(block.name); //debug(" ", block.name); block.exec(context, change, this); tracer.pop(TraceFrameType.Block); } // debug(""); index.insert(change); tracer.pop(TraceFrameType.Input); changeIx++; this.prepareRound(context, changeIx); } let exportingBlocks = Object.keys(this.exportedChanges); if(exportingBlocks.length) { if(!this.exportHandler) throw new Error("Unable to export changes without export handler."); for(let blockId of exportingBlocks) { let rawExports:Change[] = createArray("rawExportsArray"); this.collapseMultiplicity(this.exportedChanges[+blockId], rawExports); let exports:Change[] = createArray("exportsArray"); for(let change of rawExports) { let {e, a, v, count} = change; let beav = `${blockId}|${e}|${a}|${v}`; let old = context.exportIndex[beav] || 0; let neue = old + count; let delta = 0; context.exportIndex[beav] = neue; // Once you go negative you don't go back. if(old === 0 && neue > 0) delta = 1; else if(old > 0 && neue === 0) delta = -1; if(delta) { let exportedChange = new Change(e, a, v, change.n, this.transaction, 0, delta); exports.push(exportedChange); } } this.exportedChanges[+blockId] = exports; } try { this.exportHandler(this.exportedChanges); } catch(e) { tracer.pop(TraceFrameType.Transaction); throw e; } } // Once the transaction is effectively done, we need to clean up after ourselves. We // arena allocated a bunch of IDs related to function call outputs, which we can now // safely release. GlobalInterner.releaseArena("functionOutput"); tracer.pop(TraceFrameType.Transaction); } } export class BlockChangeTransaction extends Transaction { constructor(public context:EvaluationContext, public transaction:number, public added:Block[], public removed:Block[], public blocks:Block[], protected exportHandler?:ExportHandler) { super(context, transaction, blocks, exportHandler); } exec(context:EvaluationContext) { // To remove a block, we run a change with negative count through the system that // is meant to compute all the results the block has generated and remove them. for(let remove of this.removed) { remove.exec(context, BLOCK_REMOVE, this); } // To add a block, we do the same as remove, but with a positive change that causes // the block to compute all results based on the state of the indexes for(let add of this.added) { add.exec(context, BLOCK_ADD, this); } super.exec(context); } } // window["counts"] = {};
the_stack
import { lookupProfile, NAME_LOOKUP_PATH, UserSession } from '@stacks/auth'; import { BLOCKSTACK_DEFAULT_GAIA_HUB_URL, DoesNotExist, GaiaHubError, getGlobalObject, InvalidStateError, megabytesToBytes, PayloadTooLargeError, SignatureVerificationError, } from '@stacks/common'; import { eciesGetJsonStringLength, EncryptionOptions, getPublicKeyFromPrivate, publicKeyToAddress, signECDSA, verifyECDSA, } from '@stacks/encryption'; import { createFetchFn, FetchFn } from '@stacks/network'; import { FileContentLoader } from './fileContentLoader'; import { connectToGaiaHub, deleteFromGaiaHub, GaiaHubConfig, getBlockstackErrorFromResponse, getBucketUrl, getFullReadUrl, uploadToGaiaHub, } from './hub'; /** * Specify a valid MIME type, encryption options, and whether to sign the [[UserSession.putFile]]. */ export interface PutFileOptions extends EncryptionOptions { /** * Specifies the Content-Type header for unencrypted data. * If the `encrypt` is enabled, this option is ignored, and the * Content-Type header is set to `application/json` for the ciphertext * JSON envelope. */ contentType?: string; /** * Encrypt the data with the app public key. * If a string is specified, it is used as the public key. * If the boolean `true` is specified then the current user's app public key is used. * @default true */ encrypt?: boolean | string; /** * Ignore etag for concurrency control and force file to be written. */ dangerouslyIgnoreEtag?: boolean; } const SIGNATURE_FILE_SUFFIX = '.sig'; /** * Used to pass options to [[UserSession.getFile]] */ export interface GetFileOptions extends GetFileUrlOptions { /** * Try to decrypt the data with the app private key. * If a string is specified, it is used as the private key. * @default true */ decrypt?: boolean | string; /** * Whether the content should be verified, only to be used * when [[UserSession.putFile]] was set to `sign = true`. * @default false */ verify?: boolean; } export interface GetFileUrlOptions { /** * The Blockstack ID to lookup for multi-player storage. * If not specified, the currently signed in username is used. */ username?: string; /** * The app to lookup for multi-player storage - defaults to current origin. * @default `window.location.origin` * Only if available in the executing environment, otherwise `undefined`. */ app?: string; /** * The URL to use for zonefile lookup. If falsey, this will use * the blockstack.js's [[getNameInfo]] function instead. */ zoneFileLookupURL?: string; } /** * Options for constructing a Storage instance */ export interface StorageOptions { /** * The userSession object to construct the Storage instance with. * The session object contains the credentials and keys for * Gaia hub access and encryption. */ userSession?: UserSession; } export class Storage { userSession: UserSession; constructor(options: StorageOptions) { this.userSession = options.userSession!; } /** * Retrieves the specified file from the app's data store. * * @param {String} path - the path to the file to read * @param {Object} options a [[GetFileOptions]] object * * @returns {Promise} that resolves to the raw data in the file * or rejects with an error */ async getFile(path: string, options?: GetFileOptions) { const defaults: GetFileOptions = { decrypt: true, verify: false, app: getGlobalObject('location', { returnEmptyObject: true })!.origin, }; const opt = Object.assign({}, defaults, options); // in the case of signature verification, but no // encryption expected, need to fetch _two_ files. if (opt.verify && !opt.decrypt) { return this.getFileSignedUnencrypted(path, opt); } const storedContents = await this.getFileContents( path, opt.app!, opt.username, opt.zoneFileLookupURL, !!opt.decrypt ); if (storedContents === null) { return storedContents; } else if (opt.decrypt && !opt.verify) { if (typeof storedContents !== 'string') { throw new Error('Expected to get back a string for the cipherText'); } if (typeof opt.decrypt === 'string') { const decryptOpt = { privateKey: opt.decrypt }; return this.userSession.decryptContent(storedContents, decryptOpt); } else { return this.userSession.decryptContent(storedContents); } } else if (opt.decrypt && opt.verify) { if (typeof storedContents !== 'string') { throw new Error('Expected to get back a string for the cipherText'); } let decryptionKey; if (typeof opt.decrypt === 'string') { decryptionKey = opt.decrypt; } return this.handleSignedEncryptedContents( path, storedContents, opt.app!, decryptionKey, opt.username, opt.zoneFileLookupURL ); } else if (!opt.verify && !opt.decrypt) { return storedContents; } else { throw new Error('Should be unreachable.'); } } /** * Fetch the public read URL of a user file for the specified app. * @param {String} path - the path to the file to read * @param {String} username - The Blockstack ID of the user to look up * @param {String} appOrigin - The app origin * @param {String} [zoneFileLookupURL=null] - The URL * to use for zonefile lookup. If falsey, this will use the * blockstack.js's [[getNameInfo]] function instead. * @return {Promise<string>} that resolves to the public read URL of the file * or rejects with an error */ async getUserAppFileUrl( path: string, username: string, appOrigin: string, zoneFileLookupURL?: string ): Promise<string | undefined> { const profile = await lookupProfile({ username, zoneFileLookupURL }); let bucketUrl: string | undefined; if (profile.hasOwnProperty('apps')) { if (profile.apps.hasOwnProperty(appOrigin)) { const url = profile.apps[appOrigin]; const bucket = url.replace(/\/?(\?|#|$)/, '/$1'); bucketUrl = `${bucket}${path}`; } } return bucketUrl; } /* Get the gaia address used for servicing multiplayer reads for the given * (username, app) pair. * @private * @ignore */ async getGaiaAddress( app: string, username?: string, zoneFileLookupURL?: string ): Promise<string> { const opts = normalizeOptions(this.userSession, { app, username, zoneFileLookupURL }); let fileUrl: string | undefined; if (username) { fileUrl = await this.getUserAppFileUrl('/', opts.username!, opts.app, opts.zoneFileLookupURL); } else { const gaiaHubConfig = await this.getOrSetLocalGaiaHubConnection(); fileUrl = await getFullReadUrl('/', gaiaHubConfig); } const matches = fileUrl!.match(/([13][a-km-zA-HJ-NP-Z0-9]{26,35})/); if (!matches) { throw new Error('Failed to parse gaia address'); } return matches[matches.length - 1]; } /** * Get the URL for reading a file from an app's data store. * * @param {String} path - the path to the file to read * * @returns {Promise<string>} that resolves to the URL or rejects with an error */ async getFileUrl(path: string, options?: GetFileUrlOptions): Promise<string> { const opts = normalizeOptions(this.userSession, options); let readUrl: string | undefined; if (opts.username) { readUrl = await this.getUserAppFileUrl( path, opts.username, opts.app!, opts.zoneFileLookupURL ); } else { const gaiaHubConfig = await this.getOrSetLocalGaiaHubConnection(); readUrl = await getFullReadUrl(path, gaiaHubConfig); } if (!readUrl) { throw new Error('Missing readURL'); } else { return readUrl; } } /* Handle fetching the contents from a given path. Handles both * multi-player reads and reads from own storage. * @private * @ignore */ async getFileContents( path: string, app: string, username: string | undefined, zoneFileLookupURL: string | undefined, forceText: boolean, fetchFn: FetchFn = createFetchFn() ): Promise<string | ArrayBuffer | null> { const opts = { app, username, zoneFileLookupURL }; const readUrl = await this.getFileUrl(path, opts); const response = await fetchFn(readUrl); if (!response.ok) { throw await getBlockstackErrorFromResponse(response, `getFile ${path} failed.`, null); } let contentType = response.headers.get('Content-Type'); if (typeof contentType === 'string') { contentType = contentType.toLowerCase(); } const etag = response.headers.get('ETag'); if (etag) { const sessionData = this.userSession.store.getSessionData(); sessionData.etags![path] = etag; this.userSession.store.setSessionData(sessionData); } if ( forceText || contentType === null || contentType.startsWith('text') || contentType.startsWith('application/json') ) { return response.text(); } else { return response.arrayBuffer(); } } /* Handle fetching an unencrypted file, its associated signature * and then validate it. Handles both multi-player reads and reads * from own storage. * @private * @ignore */ async getFileSignedUnencrypted(path: string, opt: GetFileOptions) { // future optimization note: // in the case of _multi-player_ reads, this does a lot of excess // profile lookups to figure out where to read files // do browsers cache all these requests if Content-Cache is set? const sigPath = `${path}${SIGNATURE_FILE_SUFFIX}`; try { const [fileContents, signatureContents, gaiaAddress] = await Promise.all([ this.getFileContents(path, opt.app!, opt.username, opt.zoneFileLookupURL, false), this.getFileContents(sigPath, opt.app!, opt.username, opt.zoneFileLookupURL, true), this.getGaiaAddress(opt.app!, opt.username, opt.zoneFileLookupURL), ]); if (!fileContents) { return fileContents; } if (!gaiaAddress) { throw new SignatureVerificationError( `Failed to get gaia address for verification of: ${path}` ); } if (!signatureContents || typeof signatureContents !== 'string') { throw new SignatureVerificationError( 'Failed to obtain signature for file: ' + `${path} -- looked in ${path}${SIGNATURE_FILE_SUFFIX}` ); } let signature; let publicKey; try { const sigObject = JSON.parse(signatureContents); signature = sigObject.signature; publicKey = sigObject.publicKey; } catch (err) { if (err instanceof SyntaxError) { throw new Error( 'Failed to parse signature content JSON ' + `(path: ${path}${SIGNATURE_FILE_SUFFIX})` + ' The content may be corrupted.' ); } else { throw err; } } const signerAddress = publicKeyToAddress(publicKey); if (gaiaAddress !== signerAddress) { throw new SignatureVerificationError( `Signer pubkey address (${signerAddress}) doesn't` + ` match gaia address (${gaiaAddress})` ); } else if (!verifyECDSA(fileContents, publicKey, signature)) { throw new SignatureVerificationError( 'Contents do not match ECDSA signature: ' + `path: ${path}, signature: ${path}${SIGNATURE_FILE_SUFFIX}` ); } else { return fileContents; } } catch (err) { // For missing .sig files, throw `SignatureVerificationError` instead of `DoesNotExist` error. if (err instanceof DoesNotExist && err.message.indexOf(sigPath) >= 0) { throw new SignatureVerificationError( 'Failed to obtain signature for file: ' + `${path} -- looked in ${path}${SIGNATURE_FILE_SUFFIX}` ); } else { throw err; } } } /* Handle signature verification and decryption for contents which are * expected to be signed and encrypted. This works for single and * multiplayer reads. In the case of multiplayer reads, it uses the * gaia address for verification of the claimed public key. * @private * @ignore */ async handleSignedEncryptedContents( path: string, storedContents: string, app: string, privateKey?: string, username?: string, zoneFileLookupURL?: string // eslint-disable-next-line node/prefer-global/buffer ): Promise<string | Buffer> { const appPrivateKey = privateKey || this.userSession.loadUserData().appPrivateKey; const appPublicKey = getPublicKeyFromPrivate(appPrivateKey); let address: string; if (username) { address = await this.getGaiaAddress(app, username, zoneFileLookupURL); } else { address = publicKeyToAddress(appPublicKey); } if (!address) { throw new SignatureVerificationError( `Failed to get gaia address for verification of: ${path}` ); } let sigObject; try { sigObject = JSON.parse(storedContents); } catch (err) { if (err instanceof SyntaxError) { throw new Error( 'Failed to parse encrypted, signed content JSON. The content may not ' + 'be encrypted. If using getFile, try passing' + ' { verify: false, decrypt: false }.' ); } else { throw err; } } const signature = sigObject.signature; const signerPublicKey = sigObject.publicKey; const cipherText = sigObject.cipherText; const signerAddress = publicKeyToAddress(signerPublicKey); if (!signerPublicKey || !cipherText || !signature) { throw new SignatureVerificationError( 'Failed to get signature verification data from file:' + ` ${path}` ); } else if (signerAddress !== address) { throw new SignatureVerificationError( `Signer pubkey address (${signerAddress}) doesn't` + ` match gaia address (${address})` ); } else if (!verifyECDSA(cipherText, signerPublicKey, signature)) { throw new SignatureVerificationError( 'Contents do not match ECDSA signature in file:' + ` ${path}` ); } else if (typeof privateKey === 'string') { const decryptOpt = { privateKey }; return this.userSession.decryptContent(cipherText, decryptOpt); } else { return this.userSession.decryptContent(cipherText); } } /** * Stores the data provided in the app's data store to to the file specified. * @param {String} path - the path to store the data in * @param {String|Buffer} content - the data to store in the file * @param options a [[PutFileOptions]] object * * @returns {Promise} that resolves if the operation succeed and rejects * if it failed */ async putFile( path: string, // eslint-disable-next-line node/prefer-global/buffer content: string | Buffer | ArrayBufferView | Blob, options?: PutFileOptions ): Promise<string> { const defaults: PutFileOptions = { encrypt: true, sign: false, cipherTextEncoding: 'hex', dangerouslyIgnoreEtag: false, }; const opt = Object.assign({}, defaults, options); const gaiaHubConfig = await this.getOrSetLocalGaiaHubConnection(); const maxUploadBytes = megabytesToBytes(gaiaHubConfig.max_file_upload_size_megabytes!); const hasMaxUpload = maxUploadBytes > 0; const contentLoader = new FileContentLoader(content, opt.contentType!); let contentType = contentLoader.contentType; // When not encrypting the content length can be checked immediately. if (!opt.encrypt && hasMaxUpload && contentLoader.contentByteLength > maxUploadBytes) { const sizeErrMsg = `The max file upload size for this hub is ${maxUploadBytes} bytes, the given content is ${contentLoader.contentByteLength} bytes`; const sizeErr = new PayloadTooLargeError(sizeErrMsg, null, maxUploadBytes); console.error(sizeErr); throw sizeErr; } // When encrypting, the content length must be calculated. Certain types like `Blob`s must // be loaded into memory. if (opt.encrypt && hasMaxUpload) { const encryptedSize = eciesGetJsonStringLength({ contentLength: contentLoader.contentByteLength, wasString: contentLoader.wasString, sign: !!opt.sign, cipherTextEncoding: opt.cipherTextEncoding!, }); if (encryptedSize > maxUploadBytes) { const sizeErrMsg = `The max file upload size for this hub is ${maxUploadBytes} bytes, the given content is ${encryptedSize} bytes after encryption`; const sizeErr = new PayloadTooLargeError(sizeErrMsg, null, maxUploadBytes); console.error(sizeErr); throw sizeErr; } } let etag: string; let newFile = true; const sessionData = this.userSession.store.getSessionData(); if (!opt.dangerouslyIgnoreEtag) { if (sessionData.etags?.[path]) { newFile = false; etag = sessionData.etags?.[path]; } } let uploadFn: (hubConfig: GaiaHubConfig) => Promise<string>; // In the case of signing, but *not* encrypting, we perform two uploads. if (!opt.encrypt && opt.sign) { const contentData = await contentLoader.load(); let privateKey: string; if (typeof opt.sign === 'string') { privateKey = opt.sign; } else { privateKey = this.userSession.loadUserData().appPrivateKey; } const signatureObject = signECDSA(privateKey, contentData); const signatureContent = JSON.stringify(signatureObject); uploadFn = async (hubConfig: GaiaHubConfig) => { const writeResponse = ( await Promise.all([ uploadToGaiaHub( path, contentData, hubConfig, contentType, newFile, etag, opt.dangerouslyIgnoreEtag ), uploadToGaiaHub( `${path}${SIGNATURE_FILE_SUFFIX}`, signatureContent, hubConfig, 'application/json' ), ]) )[0]; if (!opt.dangerouslyIgnoreEtag && writeResponse.etag) { sessionData.etags![path] = writeResponse.etag; this.userSession.store.setSessionData(sessionData); } return writeResponse.publicURL; }; } else { // In all other cases, we only need one upload. // eslint-disable-next-line node/prefer-global/buffer let contentForUpload: string | Buffer | Blob; if (!opt.encrypt && !opt.sign) { // If content does not need encrypted or signed, it can be passed directly // to the fetch request without loading into memory. contentForUpload = contentLoader.content; } else { // Use the `encrypt` key, otherwise the `sign` key, if neither are specified // then use the current user's app public key. let publicKey: string; if (typeof opt.encrypt === 'string') { publicKey = opt.encrypt; } else if (typeof opt.sign === 'string') { publicKey = getPublicKeyFromPrivate(opt.sign); } else { publicKey = getPublicKeyFromPrivate(this.userSession.loadUserData().appPrivateKey); } const contentData = await contentLoader.load(); contentForUpload = await this.userSession.encryptContent(contentData, { publicKey, wasString: contentLoader.wasString, cipherTextEncoding: opt.cipherTextEncoding, sign: opt.sign, }); contentType = 'application/json'; } uploadFn = async (hubConfig: GaiaHubConfig) => { const writeResponse = await uploadToGaiaHub( path, contentForUpload, hubConfig, contentType, newFile, etag, opt.dangerouslyIgnoreEtag ); if (writeResponse.etag) { sessionData.etags![path] = writeResponse.etag; this.userSession.store.setSessionData(sessionData); } return writeResponse.publicURL; }; } try { return await uploadFn(gaiaHubConfig); } catch (error: any) { // If the upload fails on first attempt, it could be due to a recoverable // error which may succeed by refreshing the config and retrying. if (isRecoverableGaiaError(error)) { console.error(error); console.error('Possible recoverable error during Gaia upload, retrying...'); const freshHubConfig = await this.setLocalGaiaHubConnection(); return await uploadFn(freshHubConfig); } else { throw error; } } } /** * Deletes the specified file from the app's data store. * @param path - The path to the file to delete. * @param options - Optional options object. * @param options.wasSigned - Set to true if the file was originally signed * in order for the corresponding signature file to also be deleted. * @returns Resolves when the file has been removed or rejects with an error. */ async deleteFile( path: string, options?: { wasSigned?: boolean; } ) { const gaiaHubConfig = await this.getOrSetLocalGaiaHubConnection(); const opts = Object.assign({}, options); if (opts.wasSigned) { // If signed, delete both the content file and the .sig file try { await deleteFromGaiaHub(path, gaiaHubConfig); await deleteFromGaiaHub(`${path}${SIGNATURE_FILE_SUFFIX}`, gaiaHubConfig); const sessionData = this.userSession.store.getSessionData(); delete sessionData.etags![path]; this.userSession.store.setSessionData(sessionData); } catch (error) { const freshHubConfig = await this.setLocalGaiaHubConnection(); await deleteFromGaiaHub(path, freshHubConfig); await deleteFromGaiaHub(`${path}${SIGNATURE_FILE_SUFFIX}`, gaiaHubConfig); const sessionData = this.userSession.store.getSessionData(); delete sessionData.etags![path]; this.userSession.store.setSessionData(sessionData); } } else { try { await deleteFromGaiaHub(path, gaiaHubConfig); const sessionData = this.userSession.store.getSessionData(); delete sessionData.etags![path]; this.userSession.store.setSessionData(sessionData); } catch (error) { const freshHubConfig = await this.setLocalGaiaHubConnection(); await deleteFromGaiaHub(path, freshHubConfig); const sessionData = this.userSession.store.getSessionData(); delete sessionData.etags![path]; this.userSession.store.setSessionData(sessionData); } } } /** * Get the app storage bucket URL * @param {String} gaiaHubUrl - the gaia hub URL * @param {String} appPrivateKey - the app private key used to generate the app address * @returns {Promise} That resolves to the URL of the app index file * or rejects if it fails */ getAppBucketUrl(gaiaHubUrl: string, appPrivateKey: string) { return getBucketUrl(gaiaHubUrl, appPrivateKey); } /** * Loop over the list of files in a Gaia hub, and run a callback on each entry. * Not meant to be called by external clients. * @param {GaiaHubConfig} hubConfig - the Gaia hub config * @param {String | null} page - the page ID * @param {number} callCount - the loop count * @param {number} fileCount - the number of files listed so far * @param {function} callback - the callback to invoke on each file. If it returns a falsey * value, then the loop stops. If it returns a truthy value, the loop continues. * @returns {Promise} that resolves to the number of files listed. * @private * @ignore */ async listFilesLoop( hubConfig: GaiaHubConfig | null, page: string | null, callCount: number, fileCount: number, callback: (name: string) => boolean, fetchFn: FetchFn = createFetchFn() ): Promise<number> { if (callCount > 65536) { // this is ridiculously huge, and probably indicates // a faulty Gaia hub anyway (e.g. on that serves endless data) throw new Error('Too many entries to list'); } hubConfig = hubConfig || (await this.getOrSetLocalGaiaHubConnection()); let response: Response; try { const pageRequest = JSON.stringify({ page }); const fetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': `${pageRequest.length}`, Authorization: `bearer ${hubConfig.token}`, }, body: pageRequest, }; response = await fetchFn(`${hubConfig.server}/list-files/${hubConfig.address}`, fetchOptions); if (!response.ok) { throw await getBlockstackErrorFromResponse(response, 'ListFiles failed.', hubConfig); } } catch (error) { // If error occurs on the first call, perform a gaia re-connection and retry. // Same logic as other gaia requests (putFile, getFile, etc). if (callCount === 0) { const freshHubConfig = await this.setLocalGaiaHubConnection(); return this.listFilesLoop(freshHubConfig, page, callCount + 1, 0, callback); } throw error; } const responseText = await response.text(); const responseJSON = JSON.parse(responseText); const entries = responseJSON.entries; const nextPage = responseJSON.page; if (entries === null || entries === undefined) { // indicates a misbehaving Gaia hub or a misbehaving driver // (i.e. the data is malformed) throw new Error('Bad listFiles response: no entries'); } let entriesLength = 0; for (let i = 0; i < entries.length; i++) { // An entry array can have null entries, signifying a filtered entry and that there may be // additional pages if (entries[i] !== null) { entriesLength++; const rc = callback(entries[i]); if (!rc) { // callback indicates that we're done return fileCount + i; } } } if (nextPage && entries.length > 0) { // keep going -- have more entries return this.listFilesLoop( hubConfig, nextPage, callCount + 1, fileCount + entriesLength, callback ); } else { // no more entries -- end of data return fileCount + entriesLength; } } /** * List the set of files in this application's Gaia storage bucket. * * @param {function} callback - a callback to invoke on each named file that * returns `true` to continue the listing operation or `false` to end it. * If the call is ended early by the callback, the last file is excluded. * If an error occurs the entire call is rejected. * * @returns {Promise} that resolves to the number of files listed */ listFiles(callback: (name: string) => boolean): Promise<number> { return this.listFilesLoop(null, null, 0, 0, callback); } /** * @ignore */ async getOrSetLocalGaiaHubConnection(): Promise<GaiaHubConfig> { const sessionData = this.userSession.store.getSessionData(); const userData = sessionData.userData; if (!userData) { throw new InvalidStateError('Missing userData'); } const hubConfig = userData.gaiaHubConfig; if (hubConfig) { return Promise.resolve(hubConfig); } return this.setLocalGaiaHubConnection(); } /** * These two functions are app-specific connections to gaia hub, * they read the user data object for information on setting up * a hub connection, and store the hub config to localstorage * @private * @returns {Promise} that resolves to the new gaia hub connection */ async setLocalGaiaHubConnection(): Promise<GaiaHubConfig> { const userData = this.userSession.loadUserData(); if (!userData) { throw new InvalidStateError('Missing userData'); } if (!userData.hubUrl) { userData.hubUrl = BLOCKSTACK_DEFAULT_GAIA_HUB_URL; } const gaiaConfig = await connectToGaiaHub( userData.hubUrl, userData.appPrivateKey, userData.gaiaAssociationToken ); userData.gaiaHubConfig = gaiaConfig; const sessionData = this.userSession.store.getSessionData(); sessionData.userData!.gaiaHubConfig = gaiaConfig; this.userSession.store.setSessionData(sessionData); return gaiaConfig; } } type FileUrlOptions = { path: string; username: string; appOrigin: string; zoneFileLookupURL: string; }; export function getUserAppFileUrl(options: FileUrlOptions): Promise<string | undefined> { return new Storage({}).getUserAppFileUrl( options.path, options.username, options.appOrigin, options.zoneFileLookupURL ); } /** * @param {Object} [options=null] - options object * @param {String} options.username - the Blockstack ID to lookup for multi-player storage * @param {String} options.app - the app to lookup for multi-player storage - * defaults to current origin * * @ignore */ function normalizeOptions<T>( userSession: UserSession, options?: { app?: string; username?: string; zoneFileLookupURL?: string; } & T ) { const opts = Object.assign({}, options); if (opts.username) { if (!opts.app) { if (!userSession.appConfig) { throw new InvalidStateError('Missing AppConfig'); } opts.app = userSession.appConfig.appDomain; } if (!opts.zoneFileLookupURL) { if (!userSession.appConfig) { throw new InvalidStateError('Missing AppConfig'); } if (!userSession.store) { throw new InvalidStateError('Missing store UserSession'); } const sessionData = userSession.store.getSessionData(); // Use the user specified coreNode if available, otherwise use the app specified coreNode. const configuredCoreNode = sessionData.userData?.coreNode || userSession.appConfig.coreNode; if (configuredCoreNode) { opts.zoneFileLookupURL = `${configuredCoreNode}${NAME_LOOKUP_PATH}`; } } } return opts; } /** * Determines if a gaia error response is possible to recover from * by refreshing the gaiaHubConfig, and retrying the request. */ function isRecoverableGaiaError(error: GaiaHubError): boolean { if (!error || !error.hubError || !error.hubError.statusCode) { return false; } const statusCode = error.hubError.statusCode; // 401 Unauthorized: possible expired, but renewable auth token. if (statusCode === 401) { return true; } // 409 Conflict: possible concurrent writes to a file. if (statusCode === 409) { return true; } // 500s: possible server-side transient error if (statusCode >= 500 && statusCode <= 599) { return true; } return false; }
the_stack
module es { type PredicateType<T> = (value?: T, index?: number, list?: T[]) => boolean export class List<T> { protected _elements: T[]; /** * 默认为列表的元素 */ constructor(elements: T[] = []) { this._elements = elements } /** * 在列表的末尾添加一个对象。 */ public add(element: T): void { this._elements.push(element) } /** * 将一个对象追加到列表的末尾。 */ public append(element: T): void { this.add(element) } /** * 在列表的开头添加一个对象。 */ public prepend(element: T): void { this._elements.unshift(element) } /** * 将指定集合的元素添加到列表的末尾。 */ public addRange(elements: T[]): void { this._elements.push(...elements) } /** * 对序列应用累加器函数。 */ public aggregate<U>( accumulator: (accum: U, value?: T, index?: number, list?: T[]) => any, initialValue?: U ): any { return this._elements.reduce(accumulator, initialValue) } /** * 确定序列的所有元素是否满足一个条件。 */ public all(predicate: PredicateType<T>): boolean { return this._elements.every(predicate) } /** * 确定序列是否包含任何元素。 */ public any(): boolean public any(predicate: PredicateType<T>): boolean public any(predicate?: PredicateType<T>): boolean { return predicate ? this._elements.some(predicate) : this._elements.length > 0 } /** * 计算通过对输入序列的每个元素调用转换函数获得的一系列数值的平均值。 */ public average(): number public average( transform: (value?: T, index?: number, list?: T[]) => any ): number public average( transform?: (value?: T, index?: number, list?: T[]) => any ): number { return this.sum(transform) / this.count(transform) } /** * 将序列的元素转换为指定的类型。 */ public cast<U>(): List<U> { return new List<U>(this._elements as any) } /** * 从列表中删除所有元素。 */ public clear(): void { this._elements.length = 0 } /** * 连接两个序列。 */ public concat(list: List<T>): List<T> { return new List<T>(this._elements.concat(list.toArray())) } /** * 确定一个元素是否在列表中。 */ public contains(element: T): boolean { return this.any(x => x === element) } /** * 返回序列中元素的数量。 */ public count(): number public count(predicate: PredicateType<T>): number public count(predicate?: PredicateType<T>): number { return predicate ? this.where(predicate).count() : this._elements.length } /** * 返回指定序列的元素,或者如果序列为空,则返回单例集合中类型参数的默认值。 */ public defaultIfEmpty(defaultValue?: T): List<T> { return this.count() ? this : new List<T>([defaultValue]) } /** * 根据指定的键选择器从序列中返回不同的元素。 */ public distinctBy(keySelector: (key: T) => string | number): List<T> { const groups = this.groupBy(keySelector); return Object.keys(groups).reduce((res, key) => { res.add(groups[key][0] as T); return res }, new List<T>()) } /** * 返回序列中指定索引处的元素。 */ public elementAt(index: number): T { if (index < this.count() && index >= 0) { return this._elements[index] } else { throw new Error( 'ArgumentOutOfRangeException: index is less than 0 or greater than or equal to the number of elements in source.' ) } } /** * 返回序列中指定索引处的元素,如果索引超出范围,则返回默认值。 */ public elementAtOrDefault(index: number): T | null { return index < this.count() && index >= 0 ? this._elements[index] : undefined } /** * 通过使用默认的相等比较器来比较值,生成两个序列的差值集。 */ public except(source: List<T>): List<T> { return this.where(x => !source.contains(x)) } /** * 返回序列的第一个元素。 */ public first(): T public first(predicate: PredicateType<T>): T public first(predicate?: PredicateType<T>): T { if (this.count()) { return predicate ? this.where(predicate).first() : this._elements[0] } else { throw new Error( 'InvalidOperationException: The source sequence is empty.' ) } } /** * 返回序列的第一个元素,如果序列不包含元素,则返回默认值。 */ public firstOrDefault(): T public firstOrDefault(predicate: PredicateType<T>): T public firstOrDefault(predicate?: PredicateType<T>): T { return this.count(predicate) ? this.first(predicate) : undefined } /** * 对列表中的每个元素执行指定的操作。 */ public forEach(action: (value?: T, index?: number, list?: T[]) => any): void { return this._elements.forEach(action) } /** * 根据指定的键选择器函数对序列中的元素进行分组。 */ public groupBy<TResult>( grouper: (key: T) => string | number, mapper: (element: T) => TResult = val => (val as any) as TResult ): { [key: string]: TResult[] } { const initialValue: { [key: string]: TResult[] } = {}; return this.aggregate((ac, v: any) => { const key = grouper(v); const existingGroup = ac[key]; const mappedValue = mapper(v); existingGroup ? existingGroup.push(mappedValue) : (ac[key] = [mappedValue]); return ac }, initialValue) } /** * 根据键的相等将两个序列的元素关联起来,并将结果分组。默认的相等比较器用于比较键。 */ public groupJoin<U, R>( list: List<U>, key1: (k: T) => any, key2: (k: U) => any, result: (first: T, second: List<U>) => R ): List<R> { return this.select(x => result( x, list.where(z => key1(x) === key2(z)) ) ) } /** * 返回列表中某个元素第一次出现的索引。 */ public indexOf(element: T): number { return this._elements.indexOf(element) } /** * 向列表中插入一个元素在指定索引处。 */ public insert(index: number, element: T): void | Error { if (index < 0 || index > this._elements.length) { throw new Error('Index is out of range.') } this._elements.splice(index, 0, element) } /** * 通过使用默认的相等比较器来比较值,生成两个序列的交集集。 */ public intersect(source: List<T>): List<T> { return this.where(x => source.contains(x)) } /** * 基于匹配的键将两个序列的元素关联起来。默认的相等比较器用于比较键。 */ public join<U, R>( list: List<U>, key1: (key: T) => any, key2: (key: U) => any, result: (first: T, second: U) => R ): List<R> { return this.selectMany(x => list.where(y => key2(y) === key1(x)).select(z => result(x, z)) ) } /** * 返回序列的最后一个元素。 */ public last(): T public last(predicate: PredicateType<T>): T public last(predicate?: PredicateType<T>): T { if (this.count()) { return predicate ? this.where(predicate).last() : this._elements[this.count() - 1] } else { throw Error('InvalidOperationException: The source sequence is empty.') } } /** * 返回序列的最后一个元素,如果序列不包含元素,则返回默认值。 */ public lastOrDefault(): T public lastOrDefault(predicate: PredicateType<T>): T public lastOrDefault(predicate?: PredicateType<T>): T { return this.count(predicate) ? this.last(predicate) : undefined } /** * 返回泛型序列中的最大值。 */ public max(): number public max(selector: (value: T, index: number, array: T[]) => number): number public max( selector?: (value: T, index: number, array: T[]) => number ): number { const id = x => x; return Math.max(...this._elements.map(selector || id)) } /** * 返回泛型序列中的最小值。 */ public min(): number public min(selector: (value: T, index: number, array: T[]) => number): number public min( selector?: (value: T, index: number, array: T[]) => number ): number { const id = x => x; return Math.min(...this._elements.map(selector || id)) } /** * 根据指定的类型筛选序列中的元素。 */ public ofType<U>(type: any): List<U> { let typeName; switch (type) { case Number: typeName = typeof 0; break; case String: typeName = typeof ''; break; case Boolean: typeName = typeof true; break; case Function: typeName = typeof function () { }; // tslint:disable-line no-empty break; default: typeName = null; break } return typeName === null ? this.where(x => x instanceof type).cast<U>() : this.where(x => typeof x === typeName).cast<U>() } /** * 根据键按升序对序列中的元素进行排序。 */ public orderBy( keySelector: (key: T) => any, comparer = keyComparer(keySelector, false) ): List<T> { // tslint:disable-next-line: no-use-before-declare return new OrderedList<T>(this._elements, comparer) } /** * 根据键值降序对序列中的元素进行排序。 */ public orderByDescending( keySelector: (key: T) => any, comparer = keyComparer(keySelector, true) ): List<T> { // tslint:disable-next-line: no-use-before-declare return new OrderedList<T>(this._elements, comparer) } /** * 按键按升序对序列中的元素执行后续排序。 */ public thenBy(keySelector: (key: T) => any): List<T> { return this.orderBy(keySelector) } /** * 根据键值按降序对序列中的元素执行后续排序。 */ public thenByDescending(keySelector: (key: T) => any): List<T> { return this.orderByDescending(keySelector) } /** * 从列表中删除第一个出现的特定对象。 */ public remove(element: T): boolean { return this.indexOf(element) !== -1 ? (this.removeAt(this.indexOf(element)), true) : false } /** * 删除与指定谓词定义的条件匹配的所有元素。 */ public removeAll(predicate: PredicateType<T>): List<T> { return this.where(negate(predicate as any)) } /** * 删除列表指定索引处的元素。 */ public removeAt(index: number): void { this._elements.splice(index, 1) } /** * 颠倒整个列表中元素的顺序。 */ public reverse(): List<T> { return new List<T>(this._elements.reverse()) } /** * 将序列中的每个元素投射到一个新形式中。 */ public select<TOut>( selector: (element: T, index: number) => TOut ): List<TOut> { return new List<TOut>(this._elements.map(selector)) } /** * 将序列的每个元素投影到一个列表中。并将得到的序列扁平化为一个序列。 */ public selectMany<TOut extends List<any>>( selector: (element: T, index: number) => TOut ): TOut { return this.aggregate( (ac, _, i) => ( ac.addRange( this.select(selector) .elementAt(i) .toArray() ), ac ), new List<TOut>() ) } /** * 通过使用默认的相等比较器对元素的类型进行比较,确定两个序列是否相等。 */ public sequenceEqual(list: List<T>): boolean { return this.all(e => list.contains(e)) } /** * 返回序列中唯一的元素,如果序列中没有恰好一个元素,则抛出异常。 */ public single(predicate?: PredicateType<T>): T { if (this.count(predicate) !== 1) { throw new Error('The collection does not contain exactly one element.') } else { return this.first(predicate) } } /** * 返回序列中唯一的元素,如果序列为空,则返回默认值;如果序列中有多个元素,此方法将抛出异常。 */ public singleOrDefault(predicate?: PredicateType<T>): T { return this.count(predicate) ? this.single(predicate) : undefined } /** * 绕过序列中指定数量的元素,然后返回剩余的元素。 */ public skip(amount: number): List<T> { return new List<T>(this._elements.slice(Math.max(0, amount))) } /** * 省略序列中最后指定数量的元素,然后返回剩余的元素。 */ public skipLast(amount: number): List<T> { return new List<T>(this._elements.slice(0, -Math.max(0, amount))) } /** * 只要指定条件为真,就绕过序列中的元素,然后返回剩余的元素。 */ public skipWhile(predicate: PredicateType<T>): List<T> { return this.skip( this.aggregate(ac => (predicate(this.elementAt(ac)) ? ++ac : ac), 0) ) } /** * 计算通过对输入序列的每个元素调用转换函数获得的数值序列的和。 */ public sum(): number public sum( transform: (value?: T, index?: number, list?: T[]) => number ): number public sum( transform?: (value?: T, index?: number, list?: T[]) => number ): number { return transform ? this.select(transform).sum() : this.aggregate((ac, v) => (ac += +v), 0) } /** * 从序列的开始返回指定数量的连续元素。 */ public take(amount: number): List<T> { return new List<T>(this._elements.slice(0, Math.max(0, amount))) } /** * 从序列的末尾返回指定数目的连续元素。 */ public takeLast(amount: number): List<T> { return new List<T>(this._elements.slice(-Math.max(0, amount))) } /** * 返回序列中的元素,只要指定的条件为真。 */ public takeWhile(predicate: PredicateType<T>): List<T> { return this.take( this.aggregate(ac => (predicate(this.elementAt(ac)) ? ++ac : ac), 0) ) } /** * 复制列表中的元素到一个新数组。 */ public toArray(): T[] { return this._elements } /** * 创建一个<dictionary>从List< T>根据指定的键选择器函数。 */ public toDictionary<TKey>( key: (key: T) => TKey ): List<{ Key: TKey; Value: T }> public toDictionary<TKey, TValue>( key: (key: T) => TKey, value: (value: T) => TValue ): List<{ Key: TKey; Value: T | TValue }> public toDictionary<TKey, TValue>( key: (key: T) => TKey, value?: (value: T) => TValue ): List<{ Key: TKey; Value: T | TValue }> { return this.aggregate((dicc, v, i) => { dicc[ this.select(key) .elementAt(i) .toString() ] = value ? this.select(value).elementAt(i) : v; dicc.add({ Key: this.select(key).elementAt(i), Value: value ? this.select(value).elementAt(i) : v }); return dicc }, new List<{ Key: TKey; Value: T | TValue }>()) } /** * 创建一个Set从一个Enumerable.List< T>。 */ public toSet() { let result = new Set(); for (let x of this._elements) result.add(x); return result; } /** * 创建一个List< T>从一个Enumerable.List< T>。 */ public toList(): List<T> { return this } /** * 创建一个查找,TElement>从一个IEnumerable< T>根据指定的键选择器和元素选择器函数。 */ public toLookup<TResult>( keySelector: (key: T) => string | number, elementSelector: (element: T) => TResult ): { [key: string]: TResult[] } { return this.groupBy(keySelector, elementSelector) } /** * 基于谓词过滤一系列值。 */ public where(predicate: PredicateType<T>): List<T> { return new List<T>(this._elements.filter(predicate)) } /** * 将指定的函数应用于两个序列的对应元素,生成结果序列。 */ public zip<U, TOut>( list: List<U>, result: (first: T, second: U) => TOut ): List<TOut> { return list.count() < this.count() ? list.select((x, y) => result(this.elementAt(y), x)) : this.select((x, y) => result(x, list.elementAt(y))) } } /** * 表示已排序的序列。该类的方法是通过使用延迟执行来实现的。 * 即时返回值是一个存储执行操作所需的所有信息的对象。 * 在通过调用对象的ToDictionary、ToLookup、ToList或ToArray方法枚举对象之前,不会执行由该方法表示的查询 */ export class OrderedList<T> extends List<T> { constructor(elements: T[], private _comparer: (a: T, b: T) => number) { super(elements); this._elements.sort(this._comparer) } /** * 按键按升序对序列中的元素执行后续排序。 * @override */ public thenBy(keySelector: (key: T) => any): List<T> { return new OrderedList( this._elements, composeComparers(this._comparer, keyComparer(keySelector, false)) ) } /** * 根据键值按降序对序列中的元素执行后续排序。 * @override */ public thenByDescending(keySelector: (key: T) => any): List<T> { return new OrderedList( this._elements, composeComparers(this._comparer, keyComparer(keySelector, true)) ) } } }
the_stack
import type { capDataStorageOptions, JsonStore, JsonTable, } from '../../../src/definitions'; import { Data } from './Data'; import { UtilsSQLite } from './UtilsSQLite'; const COL_ID = 'id'; const COL_NAME = 'name'; const COL_VALUE = 'value'; export class StorageDatabaseHelper { Path: any = null; NodeFs: any = null; public db: any; public isOpen = false; public dbName: string; public tableName: string; // private _secret: string = ""; private _utils: UtilsSQLite; constructor() { this.Path = require('path'); this.NodeFs = require('fs'); this._utils = new UtilsSQLite(); } public async openStore(dbName: string, tableName: string): Promise<void> { try { this.db = await this._utils.connection( dbName, false, /*,this._secret*/ ); if (this.db !== null) { await this._createTable(tableName); this.dbName = dbName; this.tableName = tableName; this.isOpen = true; return Promise.resolve(); } else { this.dbName = ''; this.tableName = ''; this.isOpen = false; return Promise.reject(`connection to store ${dbName}`); } } catch (err) { this.dbName = ''; this.tableName = ''; this.isOpen = false; return Promise.reject(err); } } public async closeStore(dbName: string): Promise<void> { if (dbName === this.dbName && this.isOpen && this.db != null) { try { await this.db.close(); this.dbName = ''; this.tableName = ''; this.isOpen = false; return Promise.resolve(); } catch (err) { return Promise.reject(err); } } else { return Promise.reject(`Store ${dbName} not opened`); } } public async isStoreExists(dbName: string): Promise<boolean> { let ret = false; try { ret = await this._utils.isFileExists(dbName); return Promise.resolve(ret); } catch (err) { return Promise.reject(err); } } private async _createTable(tableName: string): Promise<void> { const CREATE_STORAGE_TABLE = 'CREATE TABLE IF NOT EXISTS ' + tableName + '(' + COL_ID + ' INTEGER PRIMARY KEY AUTOINCREMENT,' + // Define a primary key COL_NAME + ' TEXT NOT NULL UNIQUE,' + COL_VALUE + ' TEXT' + ')'; try { if (this.db != null) { return this.db.run(CREATE_STORAGE_TABLE, async (err: Error) => { if (err) { return Promise.reject(`Error: in createTable ${err.message}`); } else { try { await this._createIndex(tableName); return Promise.resolve(); } catch (err) { return Promise.reject(err); } } }); } else { return Promise.reject(`connection to store ${this.dbName}`); } } catch (err) { return Promise.reject(err); } } private async _createIndex(tableName: string): Promise<void> { const idx = `index_${tableName}_on_${COL_NAME}`; const CREATE_INDEX_NAME = 'CREATE INDEX IF NOT EXISTS ' + idx + ' ON ' + tableName + ' (' + COL_NAME + ')'; try { if (this.db != null) { return this.db.run(CREATE_INDEX_NAME, async (err: Error) => { if (err) { return Promise.reject(`Error: in createIndex ${err.message}`); } else { return Promise.resolve(); } }); } else { return Promise.reject(`connection to store ${this.dbName}`); } } catch (err) { return Promise.reject(err); } } public async setTable(tableName: string): Promise<void> { try { await this._createTable(tableName); this.tableName = tableName; return Promise.resolve(); } catch (err) { this.tableName = ''; return Promise.reject(err); } } // Insert a data into the database public async set(data: Data): Promise<void> { if (this.db == null) { return Promise.reject(`this.db is null in set`); } try { // Check if data.name does not exist otherwise update it const res: Data = await this.get(data.name); if (res.id != null) { // exists so update it await this.update(data); return Promise.resolve(); } else { // does not exist add it const DATA_INSERT = `INSERT INTO "${this.tableName}" ("${COL_NAME}", "${COL_VALUE}") VALUES (?, ?)`; return this.db.run( DATA_INSERT, [data.name, data.value], (err: Error) => { if (err) { return Promise.reject(`Data INSERT: ${err.message}`); } else { return Promise.resolve(); } }, ); } } catch (err) { return Promise.reject(err); } } // get a Data public async get(name: string): Promise<Data> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in get`); } const DATA_SELECT_QUERY = `SELECT * FROM ${this.tableName} WHERE ${COL_NAME} = '${name}'`; this.db.all(DATA_SELECT_QUERY, (err: Error, rows: any) => { if (err) { const data = new Data(); data.id = null; resolve(data); } else { let data = new Data(); if (rows.length >= 1) { data = rows[0]; } else { data.id = null; } resolve(data); } }); }); } // update a Data public async update(data: Data): Promise<void> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in update`); } const DATA_UPDATE = `UPDATE "${this.tableName}" SET "${COL_VALUE}" = ? WHERE "${COL_NAME}" = ?`; this.db.run(DATA_UPDATE, [data.value, data.name], (err: Error) => { if (err) { reject(`Data UPDATE: ${err.message}`); } else { resolve(); } }); }); } // isKey exists public async iskey(name: string): Promise<boolean> { if (this.db == null) { return Promise.reject(`this.db is null in clear`); } try { const res: Data = await this.get(name); if (res.id != null) { return Promise.resolve(true); } else { return Promise.resolve(false); } } catch (err) { return Promise.reject(err); } } // remove a key public async remove(name: string): Promise<void> { if (this.db == null) { return Promise.reject(`this.db is null in clear`); } try { const res: Data = await this.get(name); if (res.id != null) { const DATA_DELETE = `DELETE FROM "${this.tableName}" WHERE "${COL_NAME}" = ?`; return this.db.run(DATA_DELETE, name, (err: Error) => { if (err) { return Promise.reject(`Data DELETE: ${err.message}`); } else { return Promise.resolve(); } }); } else { return Promise.reject(`REMOVE key does not exist`); } } catch (err) { return Promise.reject(err); } } // remove all keys public async clear(): Promise<void> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in clear`); } const DATA_DELETE = `DELETE FROM "${this.tableName}"`; this.db.exec(DATA_DELETE, (err: Error) => { if (err) { reject(`Data CLEAR: ${err.message}`); } else { // set back the key primary index to 0 const DATA_UPDATE = `UPDATE SQLITE_SEQUENCE SET SEQ = ? `; this.db.run(DATA_UPDATE, 0, (err: Error) => { if (err) { reject(`Data UPDATE SQLITE_SEQUENCE: ${err.message}`); } else { resolve(); } }); } }); }); } public async keys(): Promise<string[]> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in clear`); } try { let SELECT_KEYS = `SELECT "${COL_NAME}" FROM `; SELECT_KEYS += `"${this.tableName}" ORDER BY ${COL_NAME};`; this.db.all(SELECT_KEYS, (err: Error, rows: any) => { if (err) { reject(`Keys: ${err.message}`); } else { let arKeys: string[] = []; for (let i = 0; i < rows.length; i++) { arKeys = [...arKeys, rows[i].name]; if (i === rows.length - 1) { resolve(arKeys); } } } }); } catch (err) { return Promise.reject(err); } }); } public async values(): Promise<string[]> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in clear`); } try { let SELECT_VALUES = `SELECT "${COL_VALUE}" FROM `; SELECT_VALUES += `"${this.tableName}" ORDER BY ${COL_NAME};`; this.db.all(SELECT_VALUES, (err: Error, rows: any) => { if (err) { reject(`Values: ${err.message}`); } else { let arValues: string[] = []; for (let i = 0; i < rows.length; i++) { arValues = [...arValues, rows[i].value]; if (i === rows.length - 1) { resolve(arValues); } } } }); } catch (err) { reject(err); } }); } public async filtervalues(filter: string): Promise<string[]> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in clear`); } try { if (!filter.startsWith('%') && !filter.endsWith('%')) { filter = '%' + filter + '%'; } let SELECT_VALUES = `SELECT "${COL_VALUE}" FROM `; SELECT_VALUES += `"${this.tableName}" WHERE name `; SELECT_VALUES += `LIKE "${filter}" ORDER BY ${COL_NAME}`; this.db.all(SELECT_VALUES, (err: Error, rows: any) => { if (err) { reject(`FilterValues: ${err.message}`); } else { let arValues: string[] = []; for (let i = 0; i < rows.length; i++) { arValues = [...arValues, rows[i].value]; if (i === rows.length - 1) { resolve(arValues); } } } }); } catch (err) { reject(err); } }); } public async keysvalues(): Promise<Data[]> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`this.db is null in clear`); } try { let SELECT_KEYSVALUES = `SELECT "${COL_NAME}" , "${COL_VALUE}"`; SELECT_KEYSVALUES += ` FROM "${this.tableName}" ORDER BY ${COL_NAME};`; this.db.all(SELECT_KEYSVALUES, (err: Error, rows: any) => { if (err) { reject(`KeysValues: ${err.message}`); } else { resolve(rows); } }); } catch (err) { reject(err); } }); } public async deleteStore(dbName: string): Promise<void> { const dbPath = this.Path.join(this._utils.pathDB, dbName); try { this.NodeFs.unlinkSync(dbPath); //file removed return Promise.resolve(); } catch (err) { return Promise.reject(err); } } public async isTable(table: string): Promise<boolean> { return new Promise((resolve, reject) => { if (this.db == null) { reject(`isTable: this.db is null`); } try { let ret = false; const SELECT_TABLES = 'SELECT name FROM sqlite_master ' + "WHERE TYPE='table';"; this.db.all(SELECT_TABLES, (err: Error, rows: any) => { if (err) { reject(`isTable: ${err.message}`); } else { let arTables: string[] = []; for (let i = 0; i < rows.length; i++) { arTables = [...arTables, rows[i].name]; if (i === rows.length - 1) { if (arTables.includes(table)) ret = true; resolve(ret); } } } }); } catch (err) { return Promise.reject(err); } }); } public async tables(): Promise<string[]> { return new Promise((resolve, reject) => { try { const SELECT_TABLES = 'SELECT name FROM sqlite_master ' + "WHERE TYPE='table' ORDER BY name;"; this.db.all(SELECT_TABLES, (err: Error, rows: any) => { if (err) { reject(`tables: ${err.message}`); } else { let arTables: string[] = []; for (let i = 0; i < rows.length; i++) { if (rows[i].name != 'sqlite_sequence') { arTables = [...arTables, rows[i].name]; } if (i === rows.length - 1) { resolve(arTables); } } } }); } catch (err) { return Promise.reject(err); } }); } public async deleteTable(table: string): Promise<void> { if (this.db == null) { return Promise.reject(`this.db is null in deleteTable`); } try { const ret = await this.isTable(table); if (ret) { const DROP_STMT = `DROP TABLE IF EXISTS ${table};`; return this.db.exec(DROP_STMT, (err: Error) => { if (err) { return Promise.reject(`deleteTable: ${err.message}`); } else { return Promise.resolve(); } }); } else { return Promise.resolve(); } } catch (err) { return Promise.reject(err); } } public async importJson(values: capDataStorageOptions[]): Promise<number> { let changes = 0; for (const val of values) { try { const data: Data = new Data(); data.name = val.key; data.value = val.value; await this.set(data); changes += 1; } catch (err) { return Promise.reject(err); } } return Promise.resolve(changes); } public async exportJson(): Promise<JsonStore> { const retJson: JsonStore = {} as JsonStore; try { const prevTableName: string = this.tableName; retJson.database = this.dbName.slice(0, -9); retJson.encrypted = false; retJson.tables = []; // get the table list const tables: string[] = await this.tables(); for (const table of tables) { this.tableName = table; const retTable: JsonTable = {} as JsonTable; retTable.name = table; retTable.values = []; const dataTable: Data[] = await this.keysvalues(); for (const tdata of dataTable) { const retData: capDataStorageOptions = {} as capDataStorageOptions; retData.key = tdata.name; retData.value = tdata.value; retTable.values = [...retTable.values, retData]; } retJson.tables = [...retJson.tables, retTable]; } this.tableName = prevTableName; return Promise.resolve(retJson); } catch (err) { return Promise.reject(err); } } }
the_stack
import { List, Map } from 'immutable' import { addNestKey, DndIntents, moveDraggedValue, onIntentFactory, onMovedType } from '@ui-schema/kit-dnd' import React from 'react' import { onChangeHandler, StoreKeys } from '@ui-schema/ui-schema' import { DragDropSpec } from '@ui-schema/material-dnd/DragDropSpec' export const useOnDirectedMove = <C extends HTMLElement = HTMLElement, S extends DragDropSpec = DragDropSpec>( onIntent: onIntentFactory<C, S>, onChange: onChangeHandler, debug?: boolean, ): { onMove: onMovedType<C, S> } => { const lastMergeTag = React.useRef<{ time: number timer: number | undefined merge: undefined | string id: string | undefined }>({time: 0, timer: undefined, merge: undefined, id: undefined}) const onMove: onMovedType<C, S> = React.useMemo(() => { return onIntent(( { fromItem, toItem, }, intent, rawIntentKeys, done, ) => { if (!intent || !rawIntentKeys) { return } if (lastMergeTag.current.timer) { window.clearTimeout(lastMergeTag.current.timer) } const { type: fromType, dataKeys: fromDataKeys, index: fromIndex, isDroppable: fromIsDroppable, listKey: fromListKey, id: fromId, } = fromItem const { type: toType, index: toIndex, dataKeys: toDataKeys, id: toId, isDroppable: toIsDroppable, listKey: toListKey, } = toItem // todo: refine intentKeys with listKey const intentKeys = { ...rawIntentKeys, isParent: Boolean(rawIntentKeys.isParent || (rawIntentKeys.willBeParent && toListKey && ((fromDataKeys.size - toDataKeys.size) <= 2))), ...(toListKey ? { level: fromDataKeys.size === toDataKeys.size ? !fromDataKeys.equals(toDataKeys) ? DndIntents.switch : rawIntentKeys.level : rawIntentKeys.level, container: fromDataKeys.size === toDataKeys.size && !fromDataKeys.equals(toDataKeys) ? undefined : rawIntentKeys.container, } : {}), } if ( // todo: add support for `listKey` at e.g. `isParent`/`willBeParent`, // as e.g. a block inside an listKey-area doesn't recognize the area as it's parent and will move wrongly // an area can not be dragged deeper into itself: (fromIsDroppable && intentKeys.willBeParent && intentKeys.level === 'down') ) { if (debug) { console.log(' IGNO from ' + fromType + ' to ' + toType, intent, intentKeys) } return } if (debug) { console.log(' from ' + fromType + ' to ' + toType, fromId, fromIsDroppable, toIsDroppable, intent, intentKeys) console.log(' from ' + fromType + ' to ' + toType, toId, fromDataKeys?.toJS(), fromIndex, fromListKey, toDataKeys.toJS(), toIndex, toListKey) } if (!toIsDroppable) { // - BLOCK > BLOCK // - AREA > BLOCK if ( ( intentKeys.level === 'up' || intentKeys.level === 'same' || intentKeys.level === 'switch' ) && (intent.edgeX || intent.edgeY)) { return } let dk = toDataKeys if ( intentKeys.level === 'down' && (toDataKeys.size - fromDataKeys.size) >= 1 ) { if (intentKeys.isParent || intentKeys.willBeParent) { return } // ONLY when moving `down`, from outside the same list if (intentKeys.wasBeforeRelative) { // was before this block in the relative store order // thus the last relative key needs to be decreased dk = dk.update(fromDataKeys.size, (toIndexRelativeFirst) => typeof toIndexRelativeFirst === 'number' ? toIndexRelativeFirst - 1 : toIndexRelativeFirst ) } } // - switching within one array or between different relative roots onChange({ storeKeys: List() as StoreKeys, scopes: ['value', 'internal'], // todo: move `schema`/`required` to action like `type: update` type: 'update', updater: ({value, internal = Map()}) => { value = moveDraggedValue( value, fromDataKeys, fromIndex, dk, toIndex, ) internal = moveDraggedValue( internal, addNestKey<string | number>('internals', fromDataKeys).splice(0, 0, 'internals'), fromIndex, addNestKey<string | number>('internals', dk).splice(0, 0, 'internals'), toIndex, ) return {value, internal} }, }) done(dk, toIndex) return } if ( toIsDroppable && ( intentKeys.level === 'down' || intentKeys.level === 'up' || intentKeys.level === 'same' || intentKeys.level === 'switch' ) ) { // - any > AREA if ( ( // ignoring dragging to own area, when it's not dragging up and on any edge (intentKeys.isParent && intentKeys.level !== 'up') ) || ( // ignoring on y-edges when not dragging up, // to allow adding blocks at the end of an area from within another area in that area intentKeys.level !== 'up' && intent.edgeY ) || ( // ignoring x-edges for every action to make it possible to drag in-between nested blocks !fromIsDroppable && intent.edgeX && intentKeys.level !== 'up' ) ) { return } const setter = (doMerge: string | undefined) => { onChange({ storeKeys: List() as StoreKeys, scopes: ['value', 'internal'], type: 'update', // todo: move `schema`/`required` to action like `type: update` updater: ({value, internal = Map()}) => { let dk = toDataKeys const orgTks = addNestKey<string | number>('list', toDataKeys.push(toIndex)) let ti = intent.posQuarter === 'top-left' || intent.posQuarter === 'top-right' ? 0 : ((value.getIn(orgTks) as List<any>)?.size || 0) // when level up, adjust the dataKeys parent according to the new nested index // and either add to `0` or last index if (intentKeys.level === 'same' && intentKeys.container === 'down' && intentKeys.wasBeforeRelative) { dk = dk.push(toIndex - 1 || 0) } else if ((intentKeys.level === 'down' || intentKeys.level === 'switch') && intentKeys.wasBeforeRelative) { // was before this block in the relative store order // thus the last relative key needs to be decreased dk = dk.update(fromDataKeys.size, (toIndexRelativeFirst) => (toIndexRelativeFirst as number) - 1) dk = dk.push(toIndex) } else if (doMerge) { if (doMerge === 'next') { ti = toIndex + 1 } else if (doMerge === 'prev') { ti = toIndex } else { throw new Error('merge not implemented: ' + JSON.stringify(doMerge)) } } else { dk = dk.push(toIndex) } if (!doMerge) { if (toListKey) { // add the optional `listKey` of the target, // only needed for movement which target the actual list, not the draggable root-block, // e.g. would create invalid target for merges: the list instead of the block dk = dk.push(toListKey as unknown as number) } } if (debug) { console.log('doMerge,dk,ti,toIndex', doMerge, dk.toJS(), ti, toIndex) } value = moveDraggedValue( value, fromDataKeys, fromIndex, dk, ti, ) internal = moveDraggedValue( internal, addNestKey<string | number>('internals', fromDataKeys).splice(0, 0, 'internals'), fromIndex, addNestKey<string | number>('internals', dk).splice(0, 0, 'internals'), ti, ) done(dk, ti) return {value, internal} }, }) } let doMerge: string | undefined = undefined if (intentKeys.level === 'up' && intentKeys.isParent) { // handling AREA > AREA that are not siblings to get siblings if (!intent.edgeY && !intent.edgeX) { // no edges active return } // todo: only respects X-axis or Y-axis flow for blocks, in XY-axis flow it would need to find the related area below it's own area if (intent.edgeX) { if (intent.edgeX === 'right') { // move to right of parent doMerge = 'next' } else if (intent.edgeX === 'left') { // move to left of parent doMerge = 'prev' } } else if (intent.edgeY) { if (intent.edgeY === 'bottom') { // move to bottom of parent doMerge = 'next' } else if (intent.edgeY === 'top') { // move to top of parent doMerge = 'prev' } } if (!doMerge) { return } if (doMerge) { const ts = new Date().getTime() if ( lastMergeTag.current.merge !== doMerge || lastMergeTag.current.id !== toId ) { window.clearTimeout(lastMergeTag.current.timer) lastMergeTag.current.time = ts lastMergeTag.current.merge = doMerge lastMergeTag.current.id = toId return } const sinceLastMerge = (ts - lastMergeTag.current.time) if (sinceLastMerge > 450) { window.clearTimeout(lastMergeTag.current.timer) lastMergeTag.current.time = 0 setter(doMerge) return } else if (!lastMergeTag.current.timer) { lastMergeTag.current.timer = window.setTimeout(() => { setter(doMerge) }, 450) return } else { return } } else { return } } setter(undefined) return } }) }, [onChange, onIntent, lastMergeTag, debug]) return {onMove} }
the_stack
import WebSocket from 'ws'; import ReconnectingWebSocket, {ErrorEvent} from '../reconnecting-websocket'; import {spawn} from 'child_process'; const WebSocketServer = WebSocket.Server; const PORT = 50123; const PORT_UNRESPONSIVE = '50124'; const URL = `ws://localhost:${PORT}`; beforeEach(() => { (global as any).WebSocket = WebSocket; }); afterEach(() => { delete (global as any).WebSocket; jest.restoreAllMocks(); }); test('throws with invalid constructor', () => { delete (global as any).WebSocket; expect(() => { new ReconnectingWebSocket(URL, undefined, {WebSocket: 123, maxRetries: 0}); }).toThrow(); }); test('throws with missing constructor', () => { delete (global as any).WebSocket; expect(() => { new ReconnectingWebSocket(URL, undefined, {maxRetries: 0}); }).toThrow(); }); test('throws with non-constructor object', () => { (global as any).WebSocket = {}; expect(() => { new ReconnectingWebSocket(URL, undefined, {maxRetries: 0}); }).toThrow(); }); test('throws if not created with `new`', () => { expect(() => { // @ts-ignore ReconnectingWebSocket(URL, undefined); }).toThrow(TypeError); }); test('global WebSocket is used if available', done => { // @ts-ignore const ws = new ReconnectingWebSocket(URL, undefined, {maxRetries: 0}); ws.onerror = () => { // @ts-ignore expect(ws._ws instanceof WebSocket).toBe(true); done(); }; }); test('getters when not ready', done => { const ws = new ReconnectingWebSocket(URL, undefined, { maxRetries: 0, }); expect(ws.bufferedAmount).toBe(0); expect(ws.protocol).toBe(''); expect(ws.url).toBe(''); expect(ws.extensions).toBe(''); expect(ws.binaryType).toBe('blob'); ws.onerror = () => { done(); }; }); test('debug on', done => { const logSpy = jest.spyOn(console, 'log').mockReturnValue(); const ws = new ReconnectingWebSocket(URL, undefined, {maxRetries: 0, debug: true}); ws.onerror = () => { expect(logSpy).toHaveBeenCalledWith('RWS>', 'connect', 0); done(); }; }); test('debug off', done => { const logSpy = jest.spyOn(console, 'log').mockReturnValue(); const ws = new ReconnectingWebSocket(URL, undefined, {maxRetries: 0}); ws.onerror = () => { expect(logSpy).not.toHaveBeenCalled(); done(); }; }); test('pass WebSocket via options', done => { delete (global as any).WebSocket; const ws = new ReconnectingWebSocket(URL, undefined, { WebSocket, maxRetries: 0, }); ws.onerror = () => { // @ts-ignore - accessing private property expect(ws._ws instanceof WebSocket).toBe(true); done(); }; }); test('URL provider', async () => { const url = 'example.com'; const ws = new ReconnectingWebSocket(URL, undefined, {maxRetries: 0}); // @ts-ignore - accessing private property expect(await ws._getNextUrl(url)).toBe(url); // @ts-ignore - accessing private property expect(await ws._getNextUrl(() => url)).toBe(url); // @ts-ignore - accessing private property expect(await ws._getNextUrl(() => Promise.resolve(url))).toBe(url); // @ts-ignore - accessing private property expect(() => ws._getNextUrl(123)).toThrow(); // @ts-ignore - accessing private property expect(() => ws._getNextUrl(() => 123)).toThrow(); }); test('websocket protocol', done => { const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, anyProtocol); ws.addEventListener('open', () => { expect(ws.url).toBe(URL); expect(ws.protocol).toBe(anyProtocol); ws.close(); }); ws.addEventListener('close', () => { wss.close(() => { setTimeout(done, 500); }); }); }); test('undefined websocket protocol', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, {}); ws.addEventListener('open', () => { expect(ws.url).toBe(URL); expect(ws.protocol).toBe(''); ws.close(); }); ws.addEventListener('close', () => { wss.close(() => { setTimeout(done, 500); }); }); }); test('null websocket protocol', done => { const wss = new WebSocketServer({port: PORT}); // @ts-ignore - null is not allowed but could be passed in vanilla js const ws = new ReconnectingWebSocket(URL, null, {}); ws.addEventListener('open', () => { expect(ws.url).toBe(URL); expect(ws.protocol).toBe(''); ws.close(); }); ws.addEventListener('close', () => { wss.close(() => { setTimeout(done, 100); }); }); }); test('connection status constants', () => { const ws = new ReconnectingWebSocket(URL, undefined, {maxRetries: 0}); expect(ReconnectingWebSocket.CONNECTING).toBe(0); expect(ReconnectingWebSocket.OPEN).toBe(1); expect(ReconnectingWebSocket.CLOSING).toBe(2); expect(ReconnectingWebSocket.CLOSED).toBe(3); expect(ws.CONNECTING).toBe(0); expect(ws.OPEN).toBe(1); expect(ws.CLOSING).toBe(2); expect(ws.CLOSED).toBe(3); ws.close(); }); const maxRetriesTest = (count: number, done: () => void) => { const ws = new ReconnectingWebSocket(URL, undefined, { maxRetries: count, maxReconnectionDelay: 200, }); ws.addEventListener('error', () => { if (ws.retryCount === count) { setTimeout(done, 500); } if (ws.retryCount > count) { throw Error(`too many retries: ${ws.retryCount}`); } }); }; test('max retries: 0', done => maxRetriesTest(0, done)); test('max retries: 1', done => maxRetriesTest(1, done)); test('max retries: 5', done => maxRetriesTest(5, done)); test('level0 event listeners are kept after reconnect', done => { const ws = new ReconnectingWebSocket(URL, undefined, { maxRetries: 4, reconnectionDelayGrowFactor: 1.2, maxReconnectionDelay: 20, minReconnectionDelay: 10, }); const handleOpen = () => undefined; const handleClose = () => undefined; const handleMessage = () => undefined; const handleError = () => { expect(ws.onopen).toBe(handleOpen); expect(ws.onclose).toBe(handleClose); expect(ws.onmessage).toBe(handleMessage); expect(ws.onerror).toBe(handleError); if (ws.retryCount === 4) { done(); } }; ws.onopen = handleOpen; ws.onclose = handleClose; ws.onmessage = handleMessage; ws.onerror = handleError; }); test('level2 event listeners', done => { const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, anyProtocol, {}); ws.addEventListener('open', () => { expect(ws.protocol).toBe(anyProtocol); expect(ws.extensions).toBe(''); expect(ws.bufferedAmount).toBe(0); ws.close(); }); const fail = () => { throw Error('fail'); }; // @ts-ignore ws.addEventListener('unknown1', fail); ws.addEventListener('open', fail); ws.addEventListener('open', fail); ws.removeEventListener('open', fail); // @ts-ignore ws.removeEventListener('unknown2', fail); ws.addEventListener('close', () => { wss.close(() => { setTimeout(() => done(), 500); }); }); }); // https://developer.mozilla.org/en-US/docs/Web/API/EventListener/handleEvent test('level2 event listeners using object with handleEvent', done => { const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, anyProtocol, {}); ws.addEventListener('open', { // @ts-ignore handleEvent: () => { expect(ws.protocol).toBe(anyProtocol); expect(ws.extensions).toBe(''); expect(ws.bufferedAmount).toBe(0); ws.close(); }, }); const fail = { handleEvent: () => { throw Error('fail'); }, }; // @ts-ignore ws.addEventListener('unknown1', fail); // @ts-ignore ws.addEventListener('open', fail); // @ts-ignore ws.addEventListener('open', fail); // @ts-ignore ws.removeEventListener('open', fail); // @ts-ignore ws.removeEventListener('unknown2', fail); // @ts-ignore ws.addEventListener('close', { // @ts-ignore handleEvent: () => { wss.close(); setTimeout(() => done(), 500); }, }); }); test('connection timeout', done => { const proc = spawn('node', [`${__dirname}/unresponsive-server.js`, PORT_UNRESPONSIVE, '5000']); let lock = false; proc.stdout.on('data', () => { if (lock) return; lock = true; const ws = new ReconnectingWebSocket(`ws://localhost:${PORT_UNRESPONSIVE}`, undefined, { minReconnectionDelay: 50, connectionTimeout: 500, maxRetries: 1, }); ws.addEventListener('error', event => { expect(event.message).toBe('TIMEOUT'); if (ws.retryCount === 1) { setTimeout(() => done(), 1000); } }); }); }); test('getters', done => { const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, anyProtocol, {maxReconnectionDelay: 100}); ws.addEventListener('open', () => { expect(ws.protocol).toBe(anyProtocol); expect(ws.extensions).toBe(''); expect(ws.bufferedAmount).toBe(0); expect(ws.binaryType).toBe('nodebuffer'); ws.close(); }); ws.addEventListener('close', () => { wss.close(); setTimeout(() => done(), 500); }); }); test('binaryType', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, {minReconnectionDelay: 0}); expect(ws.binaryType).toBe('blob'); ws.binaryType = 'arraybuffer'; ws.addEventListener('open', () => { expect(ws.binaryType).toBe('arraybuffer'); // @ts-ignore ws.binaryType = 'nodebuffer'; expect(ws.binaryType).toBe('nodebuffer'); ws.close(); }); ws.addEventListener('close', () => { wss.close(); setTimeout(() => done(), 500); }); }); test('calling to close multiple times', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, {}); ws.addEventListener('open', () => { ws.close(); ws.close(); ws.close(); }); ws.addEventListener('close', () => { wss.close(); setTimeout(() => done(), 500); }); }); test('calling to reconnect when not ready', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, {}); ws.reconnect(); ws.reconnect(); ws.addEventListener('open', () => { ws.close(); }); ws.addEventListener('close', () => { wss.close(); setTimeout(() => done(), 500); }); }); test('start closed', done => { const anyMessageText = 'hello'; const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); wss.on('connection', (ws: WebSocket) => { ws.on('message', (msg: WebSocket.Data) => { ws.send(msg); }); }); wss.on('error', () => { throw Error('error'); }); expect.assertions(8); const ws = new ReconnectingWebSocket(URL, anyProtocol, { minReconnectionDelay: 100, maxReconnectionDelay: 200, startClosed: true, }); expect(ws.readyState).toBe(ws.CLOSED); setTimeout(() => { expect(ws.readyState).toBe(ws.CLOSED); ws.reconnect(); ws.addEventListener('open', () => { expect(ws.protocol).toBe(anyProtocol); expect(ws.readyState).toBe(ws.OPEN); ws.send(anyMessageText); }); ws.addEventListener('message', msg => { expect(msg.data).toBe(anyMessageText); ws.close(1000, ''); expect(ws.readyState).toBe(ws.CLOSING); }); ws.addEventListener('close', () => { expect(ws.readyState).toBe(ws.CLOSED); expect(ws.url).toBe(URL); wss.close(); setTimeout(() => done(), 1000); }); }, 300); }); test('connect, send, receive, close', done => { const anyMessageText = 'hello'; const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); wss.on('connection', (ws: WebSocket) => { ws.on('message', (msg: WebSocket.Data) => { ws.send(msg); }); }); wss.on('error', () => { throw Error('error'); }); expect.assertions(7); const ws = new ReconnectingWebSocket(URL, anyProtocol, { minReconnectionDelay: 100, maxReconnectionDelay: 200, }); expect(ws.readyState).toBe(ws.CONNECTING); ws.addEventListener('open', () => { expect(ws.protocol).toBe(anyProtocol); expect(ws.readyState).toBe(ws.OPEN); ws.send(anyMessageText); }); ws.addEventListener('message', msg => { expect(msg.data).toBe(anyMessageText); ws.close(1000, ''); expect(ws.readyState).toBe(ws.CLOSING); }); ws.addEventListener('close', () => { expect(ws.readyState).toBe(ws.CLOSED); expect(ws.url).toBe(URL); wss.close(); setTimeout(() => done(), 1000); }); }); test('connect, send, receive, reconnect', done => { const anyMessageText = 'hello'; const anyProtocol = 'foobar'; const wss = new WebSocketServer({port: PORT}); wss.on('connection', (ws: WebSocket) => { ws.on('message', (msg: WebSocket.Data) => { ws.send(msg); }); }); const totalRounds = 3; let currentRound = 0; // 6 = 3 * 2 open // 8 = 2 * 3 message + 2 reconnect // 7 = 2 * 3 close + 1 closed expect.assertions(21); const ws = new ReconnectingWebSocket(URL, anyProtocol, { minReconnectionDelay: 100, maxReconnectionDelay: 200, }); ws.onopen = () => { currentRound++; expect(ws.protocol).toBe(anyProtocol); expect(ws.readyState).toBe(ws.OPEN); ws.send(anyMessageText); }; ws.onmessage = msg => { expect(msg.data).toBe(anyMessageText); if (currentRound < totalRounds) { ws.reconnect(1000, 'reconnect'); expect(ws.retryCount).toBe(0); } else { ws.close(1000, 'close'); } expect(ws.readyState).toBe(ws.CLOSING); }; ws.addEventListener('close', event => { expect(ws.url).toBe(URL); if (currentRound >= totalRounds) { expect(ws.readyState).toBe(ws.CLOSED); wss.close(); setTimeout(() => done(), 1000); expect(event.reason).toBe('close'); } else { expect(event.reason).toBe('reconnect'); } }); }); test('immediately-failed connection should not timeout', done => { const ws = new ReconnectingWebSocket('ws://255.255.255.255', undefined, { maxRetries: 2, connectionTimeout: 500, }); ws.addEventListener('error', (err: ErrorEvent) => { if (err.message === 'TIMEOUT') { throw Error('error'); } if (ws.retryCount === 2) { setTimeout(() => done(), 500); } if (ws.retryCount > 2) { throw Error('error'); } }); }); test('immediately-failed connection with 0 maxRetries must not retry', done => { const ws = new ReconnectingWebSocket('ws://255.255.255.255', [], { maxRetries: 0, connectionTimeout: 2000, minReconnectionDelay: 100, maxReconnectionDelay: 200, }); let i = 0; ws.addEventListener('error', err => { i++; if (err.message === 'TIMEOUT') { throw Error('error'); } if (i > 1) { throw Error('error'); } setTimeout(() => { done(); }, 2100); }); }); test('connect and close before establishing connection', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, { minReconnectionDelay: 100, maxReconnectionDelay: 200, }); ws.close(); // closing before establishing connection ws.addEventListener('open', () => { throw Error('open called'); }); let closeCount = 0; ws.addEventListener('close', () => { closeCount++; if (closeCount > 1) { throw Error('close should be called once'); } }); setTimeout(() => { // wait a little to be sure no unexpected open or close events happen wss.close(); done(); }, 1000); }); test('enqueue messages', done => { const ws = new ReconnectingWebSocket(URL, undefined, { maxRetries: 0, }); const count = 10; const message = 'message'; for (let i = 0; i < count; i++) ws.send(message); ws.onerror = () => { expect(ws.bufferedAmount).toBe(message.length * count); done(); }; }); test('respect maximum enqueued messages', done => { const queueSize = 2; const ws = new ReconnectingWebSocket(URL, undefined, { maxRetries: 0, maxEnqueuedMessages: queueSize, }); const count = 10; const message = 'message'; for (let i = 0; i < count; i++) ws.send(message); ws.onerror = () => { expect(ws.bufferedAmount).toBe(message.length * queueSize); done(); }; }); test('enqueue messages before websocket initialization with expected order', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL); const messages = ['message1', 'message2', 'message3']; messages.forEach(m => ws.send(m)); // @ts-ignore - accessing private field expect(ws._messageQueue.length).toBe(messages.length); expect(ws.bufferedAmount).toBe(messages.reduce((a, m) => a + m.length, 0)); let i = 0; wss.on('connection', (client: WebSocket) => { client.on('message', (data: WebSocket.Data) => { if (data === 'ok') { expect(i).toBe(messages.length); ws.close(); } else { expect(data).toBe(messages[i]); i++; } }); }); ws.addEventListener('open', () => { ws.send('ok'); }); ws.addEventListener('close', () => { wss.close(() => { done(); }); }); }); test('closing from the other side should reconnect', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, { minReconnectionDelay: 100, maxReconnectionDelay: 200, }); const max = 3; let i = 0; wss.on('connection', (client: WebSocket) => { i++; if (i < max) { // closing client from server side should trigger a reconnection setTimeout(() => client.close(), 100); } if (i === max) { // will close from client side } if (i > max) { throw Error('unexpected connection'); } }); let j = 0; ws.addEventListener('open', () => { j++; if (j === max) { ws.close(); // wait a little to ensure no new connections are opened setTimeout(() => { wss.close(() => { done(); }); }, 500); } if (j > max) { throw Error('unexpected open'); } }); }); test('closing from the other side should allow to keep closed', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, { minReconnectionDelay: 100, maxReconnectionDelay: 200, }); const codes = [4000, 4001]; let i = 0; wss.on('connection', (client: WebSocket) => { if (i > codes.length) { throw Error('error'); } client.close(codes[i], String(codes[i])); i++; }); ws.addEventListener('close', e => { if (e.code === codes[0]) { // do nothing, will reconnect } if (e.code === codes[1] && e.reason === String(codes[1])) { // close connection (and keep closed) ws.close(); setTimeout(() => { wss.close(() => done()); }, 1000); } }); }); test('reconnection delay grow factor', done => { const ws = new ReconnectingWebSocket('wss://255.255.255.255', [], { minReconnectionDelay: 100, maxReconnectionDelay: 1000, reconnectionDelayGrowFactor: 2, }); // @ts-ignore - accessing private field expect(ws._getNextDelay()).toBe(0); const expected = [100, 200, 400, 800, 1000, 1000]; let retry = 0; ws.addEventListener('error', () => { // @ts-ignore - accessing private field expect(ws._getNextDelay()).toBe(expected[retry]); retry++; if (retry >= expected.length) { ws.close(); setTimeout(() => { done(); }, 2000); } }); }); test('minUptime', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, [], { minReconnectionDelay: 100, maxReconnectionDelay: 2000, reconnectionDelayGrowFactor: 2, minUptime: 500, }); const expectedDelays = [100, 200, 400, 800, 100, 100]; const expectedRetryCount = [1, 2, 3, 4, 1, 1]; let connectionCount = 0; wss.on('connection', (client: WebSocket) => { connectionCount++; if (connectionCount <= expectedDelays.length) { setTimeout(() => { client.close(); }, connectionCount * 100); } }); let openCount = 0; ws.addEventListener('open', () => { openCount++; if (openCount > expectedDelays.length) { ws.close(); wss.close(() => { setTimeout(() => { done(); }, 1000); }); } }); let closeCount = 0; ws.addEventListener('close', () => { if (closeCount < expectedDelays.length) { // @ts-ignore - accessing private field expect(ws._getNextDelay()).toBe(expectedDelays[closeCount]); // @ts-ignore - accessing private field expect(ws._retryCount).toBe(expectedRetryCount[closeCount]); closeCount++; } }); }); test('reconnect after closing', done => { const wss = new WebSocketServer({port: PORT}); const ws = new ReconnectingWebSocket(URL, undefined, { minReconnectionDelay: 100, maxReconnectionDelay: 200, }); let i = 0; ws.addEventListener('open', () => { i++; if (i === 1) { ws.close(); } if (i === 2) { ws.close(); } if (i > 2) { throw Error('no more expected reconnections'); } }); ws.addEventListener('close', () => { if (i === 1) setTimeout(() => { ws.reconnect(); }, 1000); if (i === 2) { wss.close(() => { setTimeout(() => { done(); }, 1000); }); } if (i > 2) { throw Error('no more expected reconnections'); } }); });
the_stack
import googleDrive from '@iconify-icons/logos/google-drive'; import { Icon } from '@iconify/react'; import { useMount, useUnmount } from 'ahooks'; import { Button, InlineLoading, InlineNotification, TextInput } from 'carbon-components-react'; import { Stack } from 'office-ui-fabric-react'; import React, { useRef, useState } from 'react'; import { useDispatch } from 'react-redux'; import { getConfig } from '../config'; import { updateFile } from '../reduxSlices/files'; import { reloadPage } from '../reduxSlices/pageReload'; import { DriveFile, MimeTypes, ModalBody, ModalFooter, parseDriveLink, showConfirm, showFormModal, showModal, store, } from '../utils'; import { promptError } from './FileAction.utils'; interface IMoveFileModalBodyProps { files: any[]; targetFolderId: string; closeFn: () => void; } function MoveFileModalBody({ files, targetFolderId, closeFn }: IMoveFileModalBodyProps) { const [finished, setFinished] = useState(0); const isCancelled = useRef(false); const dispatch = useDispatch(); useMount(async () => { let succeeded = 0; const errors: Error[] = []; for (const file of files) { try { let fileResponse: gapi.client.Response<DriveFile>; try { if (isCancelled.current) { return; } fileResponse = await gapi.client.drive.files.update({ supportsAllDrives: true, fileId: file[google.picker.Document.ID], fields: '*', removeParents: file[google.picker.Document.PARENT_ID], addParents: targetFolderId, resource: {}, }); console.log('MoveFileModalBody files.update', fileResponse); } catch (firstError) { // If move is not possible, create shortcut instead. try { if (isCancelled.current) { return; } fileResponse = await gapi.client.drive.files.create({ supportsAllDrives: true, fields: '*', resource: { name: file[google.picker.Document.NAME], mimeType: MimeTypes.GoogleShortcut, shortcutDetails: { targetId: file[google.picker.Document.ID], }, parents: [targetFolderId], }, }); console.log('MoveFileModalBody files.create', fileResponse); } catch (secondError) { // If shortcut creation failed, throw original error. throw firstError; } } succeeded++; dispatch(updateFile(fileResponse.result)); } catch (e) { errors.push(e); } finally { setFinished((f) => f + 1); } } // When everything is finished, reload current content to update the file list. if (succeeded > 0) { dispatch(reloadPage()); } if (errors.length > 0) { // If there are errors during moving, display first error. closeFn(); promptError(errors[0]); return; } // If there is no error, hold a while to display finished message. setTimeout(() => closeFn(), 1000); }); useUnmount(() => { isCancelled.current = true; }); let progress; if (finished < files.length) { progress = ( <InlineLoading description={`Moving ${finished + 1} of ${files.length}: ${ files[finished][google.picker.Document.NAME] }`} status="active" /> ); } else { progress = <InlineLoading description={`Move completed!`} status="finished" />; } return ( <> <ModalBody>{progress}</ModalBody> <ModalFooter> <Button kind="secondary" onClick={() => closeFn()} disabled={finished >= files.length}> Stop & Cancel </Button> </ModalFooter> </> ); } export function showMoveFile(parentFolder: DriveFile) { function showPickFile() { gapi.load('picker', () => { const myDocsView = new google.picker.DocsView() .setParent('root') .setIncludeFolders(true) .setSelectFolderEnabled(true); myDocsView['setLabel']('My drive'); // Undocumented const sharedDocsView = new google.picker.DocsView() .setParent('sharedWithMe') .setIncludeFolders(true) .setSelectFolderEnabled(true); sharedDocsView['setLabel']('Shared with me'); // Undocumented const teamDocsView = new google.picker.DocsView() .setIncludeFolders(true) .setEnableTeamDrives(true) .setSelectFolderEnabled(true); const picker = new google.picker.PickerBuilder() .addView(myDocsView) .addView(sharedDocsView) .addView(teamDocsView) .enableFeature(google.picker.Feature.MULTISELECT_ENABLED) .enableFeature(google.picker.Feature.SUPPORT_TEAM_DRIVES) .setOAuthToken( gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().access_token ) .setDeveloperKey(getConfig().REACT_APP_GAPI_KEY) .setCallback(async (data) => { if (data.action === google.picker.Action.PICKED && (data?.docs?.length ?? 0) > 0) { showModal({ modalHeading: 'Moving Files In Progress', preventCloseOnClickOutside: true, danger: true, RenderBodyFooter: ({ close }) => ( <MoveFileModalBody files={data.docs} targetFolderId={parentFolder.id!} closeFn={close} /> ), }); } if ( data.action === google.picker.Action.CANCEL || data.action === google.picker.Action.PICKED ) { picker.dispose(); } }) .build(); picker.setVisible(true); }); } showFormModal({ size: 'sm', modalHeading: 'Import by Move', selectorPrimaryFocus: `#url`, initialValues: { url: '', }, submitButtonText: 'Move', submittingText: 'Moving...', submittedText: `Move completed!`, submitFn: async ({ url }, helpers) => { if (!url) { helpers.setErrors({ url: 'Required', }); return false; } const id = parseDriveLink(url); if (!id) { // Unreachable? return false; } try { const respFile = await gapi.client.drive.files.get({ supportsAllDrives: true, fileId: id, fields: '*', }); console.log('MoveFileModalBody files.get', respFile); const file = respFile.result; const fileKind = file.mimeType === MimeTypes.GoogleFolder ? 'Folder' : 'File'; const confirm = await showConfirm({ modalHeading: `Confirm Move ${fileKind}`, content: ( <> <span> Are you sure want to move "<strong>{file.name}</strong>" into folder " <strong>{parentFolder.name}</strong>"? <br /> <br /> If you don't have the permission to move, a shortcut will be created. </span> </> ), submittedResult: true, }); if (!confirm) { return false; } try { const movedFile = await gapi.client.drive.files.update({ supportsAllDrives: true, fileId: file.id!, fields: '*', removeParents: file.parents?.[0], addParents: parentFolder.id, resource: {}, }); console.log('MoveFileModalBody files.update', movedFile); store.dispatch(updateFile(movedFile.result)); } catch (eFirst) { // If move failed, create shortcut. try { const newShortcut = await gapi.client.drive.files.create({ supportsAllDrives: true, fields: '*', resource: { name: file.name!, mimeType: MimeTypes.GoogleShortcut, shortcutDetails: { targetId: file.id, }, parents: [parentFolder.id!], }, }); console.log('MoveFileModalBody files.create', newShortcut); store.dispatch(updateFile(newShortcut.result)); } catch (eSecond) { // If shortcut creation failed, display error for move file. throw eFirst; } } store.dispatch(reloadPage()); } catch (e) { promptError(e); return false; } }, RenderForm: ({ formProps, hasSubmitted, close }) => ( <> {!parentFolder.capabilities?.canMoveChildrenOutOfTeamDrive && ( <div style={{ marginBottom: '2rem' }}> <InlineNotification kind="warning" subtitle={ <span> Files moved into this folder cannot be moved out later due to administrator settings. </span> } title="Note" /> </div> )} <div style={{ marginBottom: '2rem' }}> <TextInput id="url" name="url" labelText="Paste Google Doc / Drive URL" placeholder="Example: https://docs.google.com/document/d/xxxxxxx/edit" value={formProps.values.url} invalidText={formProps.errors.url} invalid={Boolean(formProps.touched.url && formProps.errors.url)} disabled={hasSubmitted} /> </div> <div> <Button kind="tertiary" onClick={() => { close(); showPickFile(); }} disabled={hasSubmitted} > <Stack verticalAlign="center" horizontal tokens={{ childrenGap: 8 }}> <Icon icon={googleDrive} /> <span>Pick a File</span> </Stack> </Button> </div> </> ), validateFn: ({ url }) => { let errors = {}; if (url && !parseDriveLink(url)) { errors['url'] = 'Not a valid Google Drive or Google Doc URL'; } return errors; }, }); }
the_stack
import { context, Span, trace, diag } from '@opentelemetry/api'; import { suppressTracing } from '@opentelemetry/core'; import type mongoose from 'mongoose'; import { MongooseInstrumentationConfig, SerializerPayload } from './types'; import { startSpan, handleCallbackResponse, handlePromiseResponse } from './utils'; import { InstrumentationBase, InstrumentationModuleDefinition, InstrumentationNodeModuleDefinition, } from '@opentelemetry/instrumentation'; import { VERSION } from './version'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; const contextCaptureFunctions = [ 'remove', 'deleteOne', 'deleteMany', 'find', 'findOne', 'estimatedDocumentCount', 'countDocuments', 'count', 'distinct', 'where', '$where', 'findOneAndUpdate', 'findOneAndDelete', 'findOneAndReplace', 'findOneAndRemove', ]; // when mongoose functions are called, we store the original call context // and then set it as the parent for the spans created by Query/Aggregate exec() // calls. this bypass the unlinked spans issue on thenables await operations. export const _STORED_PARENT_SPAN: unique symbol = Symbol('stored-parent-span'); export class MongooseInstrumentation extends InstrumentationBase<typeof mongoose> { static readonly component = 'mongoose'; protected override _config: MongooseInstrumentationConfig; private moduleVersion: string; constructor(config: MongooseInstrumentationConfig = {}) { super('opentelemetry-instrumentation-mongoose', VERSION, Object.assign({}, config)); // According to specification, statement is not set by default on mongodb spans. if (!config.dbStatementSerializer) this._config.dbStatementSerializer = () => undefined; } override setConfig(config: MongooseInstrumentationConfig = {}) { this._config = Object.assign({}, config); if (!config.dbStatementSerializer) this._config.dbStatementSerializer = () => undefined; } protected init(): InstrumentationModuleDefinition<typeof mongoose> { const module = new InstrumentationNodeModuleDefinition<typeof mongoose>( MongooseInstrumentation.component, ['*'], this.patch.bind(this), this.unpatch.bind(this) ); return module; } protected patch(moduleExports: typeof mongoose, moduleVersion: string) { diag.debug('mongoose instrumentation: patching'); this.moduleVersion = moduleVersion; this._wrap(moduleExports.Model.prototype, 'save', this.patchOnModelMethods('save')); this._wrap(moduleExports.Model.prototype, 'remove', this.patchOnModelMethods('remove')); this._wrap(moduleExports.Query.prototype, 'exec', this.patchQueryExec()); this._wrap(moduleExports.Aggregate.prototype, 'exec', this.patchAggregateExec()); contextCaptureFunctions.forEach((funcName: string) => { this._wrap(moduleExports.Query.prototype, funcName as any, this.patchAndCaptureSpanContext(funcName)); }); this._wrap(moduleExports.Model, 'aggregate', this.patchModelAggregate()); return moduleExports; } protected unpatch(moduleExports: typeof mongoose): void { diag.debug('mongoose instrumentation: unpatch mongoose'); this._unwrap(moduleExports.Model.prototype, 'save'); this._unwrap(moduleExports.Model.prototype, 'remove'); this._unwrap(moduleExports.Query.prototype, 'exec'); this._unwrap(moduleExports.Aggregate.prototype, 'exec'); contextCaptureFunctions.forEach((funcName: string) => { this._unwrap(moduleExports.Query.prototype, funcName as any); }); this._unwrap(moduleExports.Model, 'aggregate'); } private patchAggregateExec() { const self = this; diag.debug('mongoose instrumentation: patched mongoose Aggregate exec prototype'); return (originalAggregate: Function) => { return function exec(this: any, callback?: Function) { if (self._config.requireParentSpan && trace.getSpan(context.active()) === undefined) { return originalAggregate.apply(this, arguments); } const parentSpan = this[_STORED_PARENT_SPAN]; const attributes = { [SemanticAttributes.DB_STATEMENT]: self._config.dbStatementSerializer('aggregate', { options: this.options, aggregatePipeline: this._pipeline, }), }; const span = startSpan({ tracer: self.tracer, modelName: this._model?.modelName, operation: 'aggregate', attributes, collection: this._model.collection, parentSpan, }); self._addModuleVersionIfNeeded(span); return self._handleResponse(span, originalAggregate, this, arguments, callback); }; }; } private patchQueryExec() { const self = this; diag.debug('mongoose instrumentation: patched mongoose Query exec prototype'); return (originalExec: Function) => { return function exec(this: any, callback?: Function) { if (self._config.requireParentSpan && trace.getSpan(context.active()) === undefined) { return originalExec.apply(this, arguments); } const parentSpan = this[_STORED_PARENT_SPAN]; const attributes = { [SemanticAttributes.DB_STATEMENT]: self._config.dbStatementSerializer(this.op, { condition: this._conditions, updates: this._update, options: this.options, fields: this._fields, }), }; const span = startSpan({ tracer: self.tracer, modelName: this.model.modelName, operation: this.op, attributes, parentSpan, collection: this.mongooseCollection, }); self._addModuleVersionIfNeeded(span); return self._handleResponse(span, originalExec, this, arguments, callback); }; }; } private patchOnModelMethods(op: string) { const self = this; diag.debug(`mongoose instrumentation: patched mongoose Model ${op} prototype`); return (originalOnModelFunction: Function) => { return function method(this: any, options?: any, callback?: Function) { if (self._config.requireParentSpan && trace.getSpan(context.active()) === undefined) { return originalOnModelFunction.apply(this, arguments); } const serializePayload: SerializerPayload = { document: this }; if (options && !(options instanceof Function)) { serializePayload.options = options; } const attributes = { [SemanticAttributes.DB_STATEMENT]: self._config.dbStatementSerializer(op, serializePayload), }; const span = startSpan({ tracer: self.tracer, modelName: this.constructor.modelName, operation: op, attributes, collection: this.constructor.collection, }); self._addModuleVersionIfNeeded(span); if (options instanceof Function) { callback = options; options = undefined; } return self._handleResponse(span, originalOnModelFunction, this, arguments, callback); }; }; } // we want to capture the otel span on the object which is calling exec. // in the special case of aggregate, we need have no function to path // on the Aggregate object to capture the context on, so we patch // the aggregate of Model, and set the context on the Aggregate object private patchModelAggregate() { const self = this; diag.debug(`mongoose instrumentation: patched mongoose model aggregate`); return (original: Function) => { return function captureSpanContext(this: any) { const currentSpan = trace.getSpan(context.active()); const aggregate = self._callOriginalFunction(() => original.apply(this, arguments)); if (aggregate) aggregate[_STORED_PARENT_SPAN] = currentSpan; return aggregate; }; }; } private patchAndCaptureSpanContext(funcName: string) { const self = this; diag.debug(`mongoose instrumentation: patched mongoose query ${funcName} prototype`); return (original: Function) => { return function captureSpanContext(this: any) { this[_STORED_PARENT_SPAN] = trace.getSpan(context.active()); return self._callOriginalFunction(() => original.apply(this, arguments)); }; }; } private _handleResponse(span: Span, exec: Function, originalThis: any, args: IArguments, callback?: Function) { const self = this; if (callback instanceof Function) { return self._callOriginalFunction(() => handleCallbackResponse(callback, exec, originalThis, span, self._config.responseHook) ); } else { const response = self._callOriginalFunction(() => exec.apply(originalThis, args)); return handlePromiseResponse(response, span, self._config.responseHook); } } private _callOriginalFunction<T>(originalFunction: (...args: any[]) => T): T { if (this._config?.suppressInternalInstrumentation) { return context.with(suppressTracing(context.active()), originalFunction); } else { return originalFunction(); } } private _addModuleVersionIfNeeded(span: Span) { if (this._config.moduleVersionAttributeName) { span.setAttribute(this._config.moduleVersionAttributeName, this.moduleVersion); } } }
the_stack
import { Build, BuildDefinitionReference, } from 'azure-devops-node-api/interfaces/BuildInterfaces'; import { BuildResult, BuildRun, BuildStatus, DashboardPullRequest, GitTag, Policy, PullRequest, PullRequestOptions, RepoBuild, Team, TeamMember, } from '@backstage/plugin-azure-devops-common'; import { GitPullRequest, GitPullRequestSearchCriteria, GitRef, GitRepository, } from 'azure-devops-node-api/interfaces/GitInterfaces'; import { convertDashboardPullRequest, convertPolicy, getArtifactId, } from '../utils'; import { TeamMember as AdoTeamMember } from 'azure-devops-node-api/interfaces/common/VSSInterfaces'; import { Logger } from 'winston'; import { PolicyEvaluationRecord } from 'azure-devops-node-api/interfaces/PolicyInterfaces'; import { WebApi } from 'azure-devops-node-api'; import { WebApiTeam } from 'azure-devops-node-api/interfaces/CoreInterfaces'; export class AzureDevOpsApi { public constructor( private readonly logger: Logger, private readonly webApi: WebApi, ) {} public async getGitRepository( projectName: string, repoName: string, ): Promise<GitRepository> { this.logger?.debug( `Calling Azure DevOps REST API, getting Repository ${repoName} for Project ${projectName}`, ); const client = await this.webApi.getGitApi(); return client.getRepository(repoName, projectName); } public async getBuildList( projectName: string, repoId: string, top: number, ): Promise<Build[]> { this.logger?.debug( `Calling Azure DevOps REST API, getting up to ${top} Builds for Repository Id ${repoId} for Project ${projectName}`, ); const client = await this.webApi.getBuildApi(); return client.getBuilds( projectName, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, top, undefined, undefined, undefined, undefined, undefined, undefined, repoId, 'TfsGit', ); } public async getRepoBuilds( projectName: string, repoName: string, top: number, ) { this.logger?.debug( `Calling Azure DevOps REST API, getting up to ${top} Builds for Repository ${repoName} for Project ${projectName}`, ); const gitRepository = await this.getGitRepository(projectName, repoName); const buildList = await this.getBuildList( projectName, gitRepository.id as string, top, ); const repoBuilds: RepoBuild[] = buildList.map(build => { return mappedRepoBuild(build); }); return repoBuilds; } public async getGitTags( projectName: string, repoName: string, ): Promise<GitTag[]> { this.logger?.debug( `Calling Azure DevOps REST API, getting Git Tags for Repository ${repoName} for Project ${projectName}`, ); const gitRepository = await this.getGitRepository(projectName, repoName); const client = await this.webApi.getGitApi(); const tagRefs: GitRef[] = await client.getRefs( gitRepository.id as string, projectName, 'tags', false, false, false, false, true, ); const linkBaseUrl = `${this.webApi.serverUrl}/${encodeURIComponent( projectName, )}/_git/${encodeURIComponent(repoName)}?version=GT`; const commitBaseUrl = `${this.webApi.serverUrl}/${encodeURIComponent( projectName, )}/_git/${encodeURIComponent(repoName)}/commit`; const gitTags: GitTag[] = tagRefs.map(tagRef => { return mappedGitTag(tagRef, linkBaseUrl, commitBaseUrl); }); return gitTags; } public async getPullRequests( projectName: string, repoName: string, options: PullRequestOptions, ): Promise<PullRequest[]> { this.logger?.debug( `Calling Azure DevOps REST API, getting up to ${options.top} Pull Requests for Repository ${repoName} for Project ${projectName}`, ); const gitRepository = await this.getGitRepository(projectName, repoName); const client = await this.webApi.getGitApi(); const searchCriteria: GitPullRequestSearchCriteria = { status: options.status, }; const gitPullRequests = await client.getPullRequests( gitRepository.id as string, searchCriteria, projectName, undefined, undefined, options.top, ); const linkBaseUrl = `${this.webApi.serverUrl}/${encodeURIComponent( projectName, )}/_git/${encodeURIComponent(repoName)}/pullrequest`; const pullRequests: PullRequest[] = gitPullRequests.map(gitPullRequest => { return mappedPullRequest(gitPullRequest, linkBaseUrl); }); return pullRequests; } public async getDashboardPullRequests( projectName: string, options: PullRequestOptions, ): Promise<DashboardPullRequest[]> { this.logger?.debug( `Getting dashboard pull requests for project '${projectName}'.`, ); const client = await this.webApi.getGitApi(); const searchCriteria: GitPullRequestSearchCriteria = { status: options.status, }; const gitPullRequests: GitPullRequest[] = await client.getPullRequestsByProject( projectName, searchCriteria, undefined, undefined, options.top, ); return Promise.all( gitPullRequests.map(async gitPullRequest => { const projectId = gitPullRequest.repository?.project?.id; const prId = gitPullRequest.pullRequestId; let policies: Policy[] | undefined; if (projectId && prId) { policies = await this.getPullRequestPolicies( projectName, projectId, prId, ); } return convertDashboardPullRequest( gitPullRequest, this.webApi.serverUrl, policies, ); }), ); } private async getPullRequestPolicies( projectName: string, projectId: string, pullRequestId: number, ): Promise<Policy[]> { this.logger?.debug( `Getting pull request policies for pull request id '${pullRequestId}'.`, ); const client = await this.webApi.getPolicyApi(); const artifactId = getArtifactId(projectId, pullRequestId); const policyEvaluationRecords: PolicyEvaluationRecord[] = await client.getPolicyEvaluations(projectName, artifactId); return policyEvaluationRecords .map(convertPolicy) .filter((policy): policy is Policy => Boolean(policy)); } public async getAllTeams(): Promise<Team[]> { this.logger?.debug('Getting all teams.'); const client = await this.webApi.getCoreApi(); const webApiTeams: WebApiTeam[] = await client.getAllTeams(); const teams: Team[] = webApiTeams.map(team => ({ id: team.id, name: team.name, projectId: team.projectId, projectName: team.projectName, })); return teams.sort((a, b) => a.name && b.name ? a.name.localeCompare(b.name) : 0, ); } public async getTeamMembers({ projectId, teamId, }: { projectId: string; teamId: string; }): Promise<TeamMember[] | undefined> { this.logger?.debug(`Getting team member ids for team '${teamId}'.`); const client = await this.webApi.getCoreApi(); const teamMembers: AdoTeamMember[] = await client.getTeamMembersWithExtendedProperties(projectId, teamId); return teamMembers.map(teamMember => ({ id: teamMember.identity?.id, displayName: teamMember.identity?.displayName, uniqueName: teamMember.identity?.uniqueName, })); } public async getBuildDefinitions( projectName: string, definitionName: string, ): Promise<BuildDefinitionReference[]> { this.logger?.debug( `Calling Azure DevOps REST API, getting Build Definitions for ${definitionName} in Project ${projectName}`, ); const client = await this.webApi.getBuildApi(); return client.getDefinitions(projectName, definitionName); } public async getBuilds( projectName: string, top: number, repoId?: string, definitions?: number[], ): Promise<Build[]> { this.logger?.debug( `Calling Azure DevOps REST API, getting up to ${top} Builds for Repository Id ${repoId} for Project ${projectName}`, ); const client = await this.webApi.getBuildApi(); return client.getBuilds( projectName, definitions, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, top, undefined, undefined, undefined, undefined, undefined, undefined, repoId, repoId ? 'TfsGit' : undefined, ); } public async getBuildRuns( projectName: string, top: number, repoName?: string, definitionName?: string, ) { let repoId: string | undefined; let definitions: number[] | undefined; if (repoName) { const gitRepository = await this.getGitRepository(projectName, repoName); repoId = gitRepository.id; } if (definitionName) { const buildDefinitions = await this.getBuildDefinitions( projectName, definitionName, ); definitions = buildDefinitions .map(bd => bd.id) .filter((bd): bd is number => Boolean(bd)); } const builds = await this.getBuilds(projectName, top, repoId, definitions); const buildRuns: BuildRun[] = builds.map(mappedBuildRun); return buildRuns; } } export function mappedRepoBuild(build: Build): RepoBuild { return { id: build.id, title: [build.definition?.name, build.buildNumber] .filter(Boolean) .join(' - '), link: build._links?.web.href ?? '', status: build.status ?? BuildStatus.None, result: build.result ?? BuildResult.None, queueTime: build.queueTime?.toISOString(), startTime: build.startTime?.toISOString(), finishTime: build.finishTime?.toISOString(), source: `${build.sourceBranch} (${build.sourceVersion?.substr(0, 8)})`, uniqueName: build.requestedFor?.uniqueName ?? 'N/A', }; } export function mappedGitTag( gitRef: GitRef, linkBaseUrl: string, commitBaseUrl: string, ): GitTag { return { objectId: gitRef.objectId, peeledObjectId: gitRef.peeledObjectId, name: gitRef.name?.replace('refs/tags/', ''), createdBy: gitRef.creator?.displayName ?? 'N/A', link: `${linkBaseUrl}${encodeURIComponent( gitRef.name?.replace('refs/tags/', '') ?? '', )}`, commitLink: `${commitBaseUrl}/${encodeURIComponent( gitRef.peeledObjectId ?? '', )}`, }; } export function mappedPullRequest( pullRequest: GitPullRequest, linkBaseUrl: string, ): PullRequest { return { pullRequestId: pullRequest.pullRequestId, repoName: pullRequest.repository?.name, title: pullRequest.title, uniqueName: pullRequest.createdBy?.uniqueName ?? 'N/A', createdBy: pullRequest.createdBy?.displayName ?? 'N/A', creationDate: pullRequest.creationDate?.toISOString(), sourceRefName: pullRequest.sourceRefName, targetRefName: pullRequest.targetRefName, status: pullRequest.status, isDraft: pullRequest.isDraft, link: `${linkBaseUrl}/${pullRequest.pullRequestId}`, }; } export function mappedBuildRun(build: Build): BuildRun { return { id: build.id, title: [build.definition?.name, build.buildNumber] .filter(Boolean) .join(' - '), link: build._links?.web.href ?? '', status: build.status ?? BuildStatus.None, result: build.result ?? BuildResult.None, queueTime: build.queueTime?.toISOString(), startTime: build.startTime?.toISOString(), finishTime: build.finishTime?.toISOString(), source: `${build.sourceBranch} (${build.sourceVersion?.substr(0, 8)})`, uniqueName: build.requestedFor?.uniqueName ?? 'N/A', }; }
the_stack
import * as coreClient from "@azure/core-client"; export const Solution: coreClient.CompositeMapper = { type: { name: "Composite", className: "Solution", modelProperties: { id: { serializedName: "id", readOnly: true, type: { name: "String" } }, name: { serializedName: "name", readOnly: true, type: { name: "String" } }, type: { serializedName: "type", readOnly: true, type: { name: "String" } }, location: { serializedName: "location", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, plan: { serializedName: "plan", type: { name: "Composite", className: "SolutionPlan" } }, properties: { serializedName: "properties", type: { name: "Composite", className: "SolutionProperties" } } } } }; export const SolutionPlan: coreClient.CompositeMapper = { type: { name: "Composite", className: "SolutionPlan", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, publisher: { serializedName: "publisher", type: { name: "String" } }, promotionCode: { serializedName: "promotionCode", type: { name: "String" } }, product: { serializedName: "product", type: { name: "String" } } } } }; export const SolutionProperties: coreClient.CompositeMapper = { type: { name: "Composite", className: "SolutionProperties", modelProperties: { workspaceResourceId: { serializedName: "workspaceResourceId", required: true, type: { name: "String" } }, provisioningState: { serializedName: "provisioningState", readOnly: true, type: { name: "String" } }, containedResources: { serializedName: "containedResources", type: { name: "Sequence", element: { type: { name: "String" } } } }, referencedResources: { serializedName: "referencedResources", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; export const CodeMessageError: coreClient.CompositeMapper = { type: { name: "Composite", className: "CodeMessageError", modelProperties: { error: { serializedName: "error", type: { name: "Composite", className: "CodeMessageErrorError" } } } } }; export const CodeMessageErrorError: coreClient.CompositeMapper = { type: { name: "Composite", className: "CodeMessageErrorError", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const SolutionPatch: coreClient.CompositeMapper = { type: { name: "Composite", className: "SolutionPatch", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const SolutionPropertiesList: coreClient.CompositeMapper = { type: { name: "Composite", className: "SolutionPropertiesList", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "Solution" } } } } } } }; export const ManagementAssociationPropertiesList: coreClient.CompositeMapper = { type: { name: "Composite", className: "ManagementAssociationPropertiesList", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "ManagementAssociation" } } } } } } }; export const ManagementAssociation: coreClient.CompositeMapper = { type: { name: "Composite", className: "ManagementAssociation", modelProperties: { id: { serializedName: "id", readOnly: true, type: { name: "String" } }, name: { serializedName: "name", readOnly: true, type: { name: "String" } }, type: { serializedName: "type", readOnly: true, type: { name: "String" } }, location: { serializedName: "location", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Composite", className: "ManagementAssociationProperties" } } } } }; export const ManagementAssociationProperties: coreClient.CompositeMapper = { type: { name: "Composite", className: "ManagementAssociationProperties", modelProperties: { applicationId: { serializedName: "applicationId", required: true, type: { name: "String" } } } } }; export const ManagementConfigurationPropertiesList: coreClient.CompositeMapper = { type: { name: "Composite", className: "ManagementConfigurationPropertiesList", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "ManagementConfiguration" } } } } } } }; export const ManagementConfiguration: coreClient.CompositeMapper = { type: { name: "Composite", className: "ManagementConfiguration", modelProperties: { id: { serializedName: "id", readOnly: true, type: { name: "String" } }, name: { serializedName: "name", readOnly: true, type: { name: "String" } }, type: { serializedName: "type", readOnly: true, type: { name: "String" } }, location: { serializedName: "location", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Composite", className: "ManagementConfigurationProperties" } } } } }; export const ManagementConfigurationProperties: coreClient.CompositeMapper = { type: { name: "Composite", className: "ManagementConfigurationProperties", modelProperties: { applicationId: { serializedName: "applicationId", type: { name: "String" } }, parentResourceType: { serializedName: "parentResourceType", required: true, type: { name: "String" } }, parameters: { serializedName: "parameters", required: true, type: { name: "Sequence", element: { type: { name: "Composite", className: "ArmTemplateParameter" } } } }, provisioningState: { serializedName: "provisioningState", readOnly: true, type: { name: "String" } }, template: { serializedName: "template", required: true, type: { name: "Dictionary", value: { type: { name: "any" } } } } } } }; export const ArmTemplateParameter: coreClient.CompositeMapper = { type: { name: "Composite", className: "ArmTemplateParameter", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, value: { serializedName: "value", type: { name: "String" } } } } }; export const OperationListResult: coreClient.CompositeMapper = { type: { name: "Composite", className: "OperationListResult", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } } } } }; export const Operation: coreClient.CompositeMapper = { type: { name: "Composite", className: "Operation", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } } } } }; export const OperationDisplay: coreClient.CompositeMapper = { type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { serializedName: "provider", type: { name: "String" } }, resource: { serializedName: "resource", type: { name: "String" } }, operation: { serializedName: "operation", type: { name: "String" } } } } };
the_stack
import { db } from "./data" import { EventEmitter } from "./event" import * as monaco from "../monaco/monaco" import * as guid from "./guid" import savedScripts from "./saved-scripts" import { SaveScriptMsg } from "../common/messages" import * as figma from "./figma-plugin-bridge" import { print, dlog } from "./util" // const defaultScriptBody = ` // for (let n of figma.currentPage.selection) { // if (isText(n)) { // n.characters = n.characters.trim() // } // } // function isText(n :BaseNode) :n is TextNode { // return n.type == "TEXT" // } // `.trim().replace(/\n /mg, "\n") + "\n" type EditorViewState = monaco.editor.ICodeEditorViewState export interface ScriptMeta { id :number // <=0 for memory-only, >0 when saved in database. guid :string name :string tags :string[] createdAt :Date modifiedAt :Date } function createScriptMeta(meta :Partial<ScriptMeta>) :ScriptMeta { let m :ScriptMeta = { // defaults id: 0, guid: "", name: "Untitled", tags: [], createdAt: new Date(), modifiedAt: new Date(), // custom ...meta } return m } async function saveScriptMeta(s :ScriptMeta) { return db.put("scripts", s) } enum DirtyState { Clean, Dirty, DirtyImplicit, } interface ScriptEventMap { "save": Script "delete": Script } export class Script extends EventEmitter<ScriptEventMap> { meta :ScriptMeta isROLib :boolean = false // if true, can't be edited _body :string _editorViewState :EditorViewState|null = null _saveTimer :any = null _savedModelVersion :number = 0 // transient editor version _currModelVersion :number = 0 _metaDirty :DirtyState = DirtyState.Clean _bodyDirty :DirtyState = DirtyState.Clean constructor( meta :ScriptMeta, body :string, editorViewState :EditorViewState|null, isROLib? :boolean, ) { super() this.meta = meta this._body = body this._editorViewState = editorViewState this.isROLib = !!isROLib } get id() :number { return this.meta.id } get guid() :string { return this.meta.guid } get createdAt() :Date { return this.meta.createdAt } get modifiedAt() :Date { return this.meta.modifiedAt } get modelVersion() :number { return this._currModelVersion } get isUserScript() :boolean { return !this.isROLib && this.id >= 0 } get isMutable() :boolean { return this.isUserScript } get isLoaded() :boolean { return this.meta && this.meta.name && this.body != "" } get body() :string { return this._body } set body(v :string) { this._body = v this._bodyDirty = DirtyState.Dirty this._currModelVersion = 0 this._onAfterLoadBody() this.scheduleSave() } updateBody(text :string, modelVersion :number) { this._body = text this._currModelVersion = modelVersion this._bodyDirty = ( this._currModelVersion != this._savedModelVersion ? DirtyState.Dirty : DirtyState.Clean ) this.scheduleSave() } updateBodyNoDirty(text :string, modelVersion :number) { this._body = text this._currModelVersion = modelVersion } get name() :string { return this.meta.name } set name(v :string) { v = v.trim() if (v == "") { v = "Untitled" } if (this.meta.name !== v) { this.meta.name = v this._metaDirty = DirtyState.Dirty this.scheduleSave() } } get editorViewState() :EditorViewState|null { return this._editorViewState } set editorViewState(v :EditorViewState|null) { this._editorViewState = v if (this.id > 0) { db.put("scriptViewState", v, this.id) } } async reloadEditorViewState() :Promise<EditorViewState|null> { return this._editorViewState = ( await db.get("scriptViewState", this.id) as EditorViewState|null ) } isSavedInFigma() :boolean { return this.guid && savedScripts.hasGUID(this.guid) } requireValidGUID() :string { if (!this.meta.guid) { this.meta.guid = guid.gen() this._metaDirty = DirtyState.Dirty this.scheduleSave() } return this.meta.guid } scheduleSave() { // (re)start save timer let e = new Error() clearTimeout(this._saveTimer) this._saveTimer = setTimeout(() => { // print(`autosave script ${this}`) this.save() }, this.meta.id <= 0 ? 0 : 500) // immediate for first save } save() :Promise<void> { let p :Promise<void> clearTimeout(this._saveTimer) this._saveTimer = null this._savedModelVersion = this._currModelVersion dlog(`Script.save ID=${this.meta.id} GUID=${this.meta.guid}`, this) if (this.meta.id <= 0) { // create if (this._body == "") { // avoid creating files that are empty dlog("Script.save canceled because _body is empty") return Promise.resolve() } // check GUID if (!this.meta.guid) { console.warn(`unsaved script missing GUID; generating & assigning one`) this.meta.guid = guid.gen() } print(`save/create script ${JSON.stringify(this.meta.name)}`) // if (this.meta.id < 0) { // // example // this.meta.name = "Copy of " + this.meta.name // } this.meta.modifiedAt = new Date() this.meta.createdAt = this.meta.modifiedAt p = db.modify(["scripts", "scriptBody"], async (scripts, scriptBody) => { delete this.meta.id // to allow key generator to generate us a new id let sp = scripts.add(this.meta) this.meta.id = 0 // assign zero id while save is in progress let id = await sp as number this.meta.id = id scriptBody.put(this._body, id) }) as any as Promise<void> } else if (this._bodyDirty == DirtyState.Clean && this._metaDirty == DirtyState.Clean) { // no changes return Promise.resolve() } else { // update // check GUID if (!this.meta.guid) { console.warn(`existing script#${this.meta.id} missing GUID; generating & assigning one`) this.meta.guid = guid.gen() this._metaDirty = DirtyState.DirtyImplicit } let metaDirty = this._metaDirty != DirtyState.Clean let bodyDirty = this._bodyDirty != DirtyState.Clean if (bodyDirty || metaDirty) { if (this._bodyDirty == DirtyState.Dirty || this._metaDirty == DirtyState.Dirty) { // update timestamp as dirty is from user action this.meta.modifiedAt = new Date() metaDirty = true } p = db.modify(["scripts", "scriptBody"], async (scripts, scriptBody) => { if (metaDirty) { scripts.put(this.meta) } if (bodyDirty) { scriptBody.put(this._body, this.id) } }) as any as Promise<void> } else { p = Promise.resolve() } // save to canvas if needed this.saveToFigma({ createIfMissing: false }) } // clear dirty flags this._bodyDirty = DirtyState.Clean this._metaDirty = DirtyState.Clean return p.then(() => { this.triggerEvent("save", this) }).catch(err => { console.error(`failed to save ${this} in indexeddb: ${err.stack||err}`) }) } saveToFigma(options :{ createIfMissing :boolean }) { this.requireValidGUID() if (this.id == 0) { if (this._body.length == 0) { this._body = " " // force save } this.save() this._body = "" } figma.sendMsg<SaveScriptMsg>({ type: "save-script", create: options.createIfMissing, script: { guid: this.guid, name: this.name, body: this.body, }, }) } _onAfterLoadBody() :void { if (this.isROLib) { return } // dlog("Script patch body", this.name, {isROLib: this.isROLib}, this) const header = `(/*SCRIPTER*/async function __scripter_script_main(){\n` const footer = `\n})()/*SCRIPTER*/` // no ending newline if (!this._body.startsWith(header)) { this._body = header + this._body } if (!this._body.endsWith(footer)) { this._body = this._body + footer } } async load() :Promise<boolean> { let [meta, body, viewState] = await db.read(["scripts", "scriptBody", "scriptViewState"], (scripts, _1, _2) => scripts.get(this.id), (_1, scriptBody, _2) => scriptBody.get(this.id), (_1, _2, scriptViewState) => scriptViewState.get(this.id), ) if (!meta) { return false } this.meta = meta as ScriptMeta this._body = body this._editorViewState = (viewState as EditorViewState|undefined) || null this._onAfterLoadBody() return true } async loadIfEmpty() :Promise<boolean> { if (!this.meta || !this.meta.name) { return this.load() // full load } if (this.body != "") { return true // no load } let [body, viewState] = await db.read(["scriptBody", "scriptViewState"], (scriptBody, _) => scriptBody.get(this.id), (_, scriptViewState) => scriptViewState.get(this.id), ) this._body = body this._editorViewState = (viewState as EditorViewState|undefined) || null this._onAfterLoadBody() return true } // alternative to loadIfEmpty that calls cb immediately if script is loaded, // instead of in a future runloop frame as is always the case with promises. whenLoaded(cb :()=>void) :void { if (this.isLoaded) { return cb() } this.loadIfEmpty().then(cb) } async delete() { await db.modify(["scripts", "scriptBody", "scriptViewState"], async (scripts, scriptBody, scriptViewState) => { scripts.delete(this.id) scriptBody.delete(this.id) scriptViewState.delete(this.id) } ) this.triggerEvent("delete", this) this.meta = createScriptMeta({}) this._body = "" this._editorViewState = null } // returns an exact copy, with same id and guid mutableCopy() :Script { return new Script( {...this.meta, tags: [].concat(this.meta.tags)}, this._body, this._editorViewState, // intentionally a ref. (immutable) this.isROLib, ) } // returns a copy that has a zero id and a new guid duplicate(meta :Partial<ScriptMeta> = {}) :Script { return new Script( { ...this.meta, tags: [].concat(this.meta.tags), // deep copy id: 0, guid: guid.gen(), // default override ...meta, // caller override }, this._body, this._editorViewState, // intentionally a ref. (immutable) this.isROLib, ) } mergeApply(b :Script) { let a = this if (a.meta.modifiedAt > b.meta.modifiedAt) { return } // apply data of B a.body = b.body a.name = b.name if (a.meta.id == 0) { a.meta.id = b.meta.id } } toString() :string { return `script#${this.meta.id}` + (this.meta.guid ? `/${this.meta.guid}` : "") } // static createDefault() :Script { // return this.create({}, defaultScriptBody) // } static create(meta :Partial<ScriptMeta> = {}, body :string = "", isROLib? :boolean) :Script { if (!meta.guid) { // since July 2020 all scripts must have a GUID meta = { ...meta, guid: guid.gen() } } const s = new Script(createScriptMeta(meta), body, null, isROLib) s._onAfterLoadBody() return s } static async load(id :number) :Promise<Script|null> { let s = new Script({ id } as ScriptMeta, "", null) return (await s.load()) ? s : null } }
the_stack
namespace PE.Battle.UI { export let actionsInx = 0; export let movesInx = 0; export class Window_BattleMessage extends Window_Message { constructor() { super(); } frameskin: any; loadFrameSkin() { this.frameskin = ImageManager.loadSystem("battle_message_skin"); } normalColor() { return "#ffffff"; } } export class AbilityIndicator extends Sprite { ticks: number; constructor(public ability: string) { super(new Bitmap(224, 32)); this.bitmap.outlineWidth = 3; this.bitmap.fontSize = 20; this.bitmap.fillAll("rgba(0,0,0,0.7)"); this.bitmap.drawText(Abilities.getName(ability), 0, 0, 224, 32, "center"); this.ticks = 0; } update() { super.update(); this.ticks++; if (this.ticks > 60) { $Battle.waitMode = WaitMode.None; this.destroy(); } } } export class HPBar extends Sprite { animate: boolean; currentHP: any; __damage: any; indicator: Sprite; expbar: Sprite; expbox: Sprite; text: Sprite; bar: Sprite; box: Sprite; constructor(public pokemon: Battler, public _x: number, public _y: number, public foe: boolean) { super(); this.currentHP = this.pokemon.hp; this.pokemon.hpbar = this; this.__damage = 0; // this.__heal = 0; this.create(); this.animate = false; this.setWidth(); // this.completeCallbacks = []; } create() { this.box = new Sprite(); this.box.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "hp_box"); this.box.x = this._x; this.box.y = this._y; this.addChild(this.box); this.bar = new Sprite(); this.bar.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "hp_bar"); this.bar.x = this._x; this.bar.y = this._y; this.addChild(this.bar); this.text = new Sprite(new Bitmap(Graphics.width, Graphics.height)); this.text.x = 0; this.text.y = 0; this.text.bitmap.fontSize = 28; // this.text.bitmap.outlineWidth = 4; this.text.bitmap.textColor = "#fff"; this.text.bitmap.drawText(this.pokemon.nickname, this._x, this._y - 30, Graphics.width, 24, "left"); this.text.bitmap.fontSize = 18; this.text.bitmap.textColor = "#ff0"; this.text.bitmap.shadowColor = "#cccc00"; var w1 = this.text.bitmap.measureTextWidth("Lv. " + this.pokemon.level); this.text.bitmap.drawText("Lv. ", this._x + (192 - w1), this._y - 24, Graphics.width, 24, "left"); this.text.bitmap.textColor = "#fff"; this.text.bitmap.shadowColor = DEFAULT_SHADOW_COLOR; var w2 = this.text.bitmap.measureTextWidth("" + this.pokemon.level); this.text.bitmap.drawText("" + this.pokemon.level, this._x + (192 - w2), this._y - 24, Graphics.width, 24, "left"); if (this.pokemon.gender !== "N") { if (this.pokemon.gender === "M") { var w3 = this.text.bitmap.measureTextWidth("♂ "); this.text.bitmap.textColor = "#00bdf7"; this.text.bitmap.shadowColor = "#0097c5"; this.text.bitmap.drawText("♂", this._x + (192 - w1 - w3), this._y - 24, Graphics.width, 24, "left"); } else { var w3 = this.text.bitmap.measureTextWidth("♀ "); this.text.bitmap.textColor = "#ff3142"; this.text.bitmap.shadowColor = "#f30014"; this.text.bitmap.drawText("♀", this._x + (192 - w1 - w3), this._y - 24, Graphics.width, 24, "left"); } } if (!this.foe) { this.expbox = new Sprite(); this.expbox.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "exp_box"); this.expbox.x = this._x; this.expbox.y = this.box.y + 26; this.addChild(this.expbox); this.expbar = new Sprite(); this.expbar.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "exp_bar"); this.expbar.x = this._x; this.expbar.y = this.box.y + 26; this.expbar.setFrame(0, 0, 62, 8); this.addChild(this.expbar); this.indicator = new Sprite(new Bitmap(Graphics.height, Graphics.width)); this.indicator.bitmap.textColor = "#fff"; this.indicator.bitmap.fontSize = 20; this.indicator.bitmap.drawText(this.pokemon.hp + "/" + this.pokemon.hp, this._x + 32, this.box.y + 8, 200, 24, "left"); this.addChild(this.indicator); } this.addChild(this.text); } update() { super.update(); // if (this.animate && this.__damage > 0) this.updateDamage(); } damage(hp) { // this.__damage = hp; this.currentHP -= hp; if (this.currentHP <= 0) this.currentHP = 0; this.updateDamage(); } updateDamage() { if (this.indicator) { this.indicator.bitmap.clear(); this.indicator.bitmap.drawText(`${this.currentHP}/${this.pokemon.totalhp}`, this._x + 32, this.box.y + 8, 200, 24, "left"); } // 192 is original the bar width let width = Math.max(0, (192 * this.currentHP) / this.pokemon.totalhp); this.bar.setFrame(0, 0, width, 24); } start() { this.animate = true; } onComplete(callback) { // this.completeCallbacks.push(callback); } complete() { $Battle.waitMode = WaitMode.None; $Battle.changePhase(Phase.None); // for (const callback of this.completeCallbacks) { // callback(); // } this.animate = false; } setWidth() { let width = Math.max(0, (192 * this.currentHP) / this.pokemon.totalhp); this.bar.setFrame(0, 0, width, 24); } } export class CommandButton extends Sprites.Button { private _active: boolean; private _text: Sprite; constructor(public name: string, public frame: number, public x: number, public y: number) { super(96, 48); this._active = false; this.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "battle_buttons"); this.changeFrame(0, this.frame); this._text = new Sprite(new Bitmap(96, 48)); this._text.bitmap.fontSize = 24; this._text.bitmap.outlineWidth = 4; this._text.bitmap.outlineColor = "rgba(0,0,0, 0.3)"; this._text.bitmap.drawText(this.name, 0, 0, 96, 48, "center"); this._text.x = 0; this._text.y = 0; this.addChild(this._text); this.deactivate(); } activate() { this.setBlendColor([0, 0, 0, 0]); this._text.setBlendColor([0, 0, 0, 0]); this.changeFrame(1, this.frame); } deactivate() { this.setBlendColor([0, 0, 0, 100]); this._text.setBlendColor([0, 0, 0, 100]); this.changeFrame(0, this.frame); } } export class MoveButton extends Sprites.Button { private _text: Sprite; row: number; _active: boolean; constructor(move: any, public x: number, public y: number) { super(202, 74); this._active = false; this.row = parseInt(PE.Types[move.type]); this.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "moves_buttons"); this.changeFrame(0, this.row); this._text = new Sprite(new Bitmap(192, 64)); this._text.x = 0; this._text.y = 0; this._text.bitmap.outlineWidth = 4; this._text.bitmap.outlineColor = PE.Types.color(move.type); this._text.bitmap.fontSize = 20; this._text.bitmap.drawText(move.name, 4, 4, 194, 32, "center"); this._text.bitmap.fontSize = 20; this._text.bitmap.drawText("PP " + move.pp + "/" + move.pp, 112, 38, 192, 32, "left"); this.addChild(this._text); // this.setBlendColor([0, 0, 0, 100]); // this._text.setBlendColor([0, 0, 0, 100]); this.deactivate(); } activate() { this.setBlendColor([0, 0, 0, 0]); this._text.setBlendColor([0, 0, 0, 0]); this.changeFrame(1, this.row); } deactivate() { this.setBlendColor([0, 0, 0, 100]); this._text.setBlendColor([0, 0, 0, 100]); this.changeFrame(0, this.row); } } export class _MovesSelection extends Sprite { _moves: any; _backButton: Sprite; _bg: Sprite; _pos: { x: number; y: number }[]; constructor(public _pokemon: Battler) { super(); var x = Graphics.width - 412; var y = Graphics.height - 156; this._pos = [{ x: x, y: y }, { x: x + 206, y: y }, { x: x, y: y + 78 }, { x: x + 206, y: y + 78 }]; this._moves = []; this.createBackground(); this.createButtons(); this.visible = false; } createBackground() { // this._bg = new Sprite(); // this._bg.bitmap = ImageManager.loadBitmap('img/pictures/Battle/', 'moves_overlay', undefined, undefined); // this._bg.x = Graphics.width; // this._bg.y = Graphics.height - 152; // this._bg.anchor.x = 1; // this.addChild(this._bg); this._backButton = new Sprite(); this._backButton.bitmap = ImageManager.loadBitmap("img/pictures/Battle/", "back_button", undefined, undefined); this._backButton.x = 0; this._backButton.y = Graphics.height - 4; this._backButton.anchor.y = 1; this.addChild(this._backButton); let backtext = new Sprite(new Bitmap(64, 40)); backtext.bitmap.fontSize = 20; backtext.bitmap.outlineWidth = 4; backtext.bitmap.drawText(i18n._("BACK"), 8, 10, 64, 20, "left"); backtext.x = 0; backtext.y = Graphics.height - 4; backtext.anchor.y = 1; this.addChild(backtext); } createButtons() { let i = 0; for (let move of this._pokemon.moveset) { let button = new MoveButton(move, this._pos[i].x, this._pos[i].y); this._moves.push(button); this.addChild(button); i++; } this._moves[movesInx].activate(); } updateInput() { if (!this.visible) this.visible = true; if (Input.isTriggered("cancel")) { $Battle.changePhase(Battle.Phase.ActionSelection); this.visible = false; } if (Input.isTriggered("right")) { if (this._moves.length <= 1) return; this._moves[movesInx].deactivate(); movesInx++; if (movesInx >= this._moves.length) movesInx = 0; this._moves[movesInx].activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("left")) { if (this._moves.length <= 1) return; this._moves[movesInx].deactivate(); movesInx--; if (movesInx < 0) movesInx = this._moves.length - 1; this._moves[movesInx].activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("down")) { if (this._moves.length < 2) return; this._moves[movesInx].deactivate(); movesInx += 2; if (movesInx >= this._moves.length) movesInx = Math.abs(this._moves.length - movesInx); this._moves[movesInx].activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("up")) { if (this._moves.length <= 2) return; this._moves[movesInx].deactivate(); movesInx -= 2; if (movesInx < 0) movesInx = this._moves.length - Math.abs(movesInx); this._moves[movesInx].activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("ok")) { this.visible = false; let move = this._pokemon.moveset[movesInx]; $Battle.choose(move, $Battle.sides.foe.actives[0]); $Battle.changePhase(Battle.Phase.None); $Battle.runActions(); } } } export class BattleCommands extends Sprite { _bg: Sprite; options: { name: string; frame: number; x: number; y: number; sprite?: CommandButton; action: any }[]; constructor(public x: number, public y: number) { super(); this.x = Graphics.width - 200; this.y = Graphics.height - 136; var startX = 0; var startY = 0; this.options = [ { name: "FIGTH", frame: 0, x: startX, y: startY, action: this.openMovesSelection }, { name: "PARTY", frame: 1, x: startX + 100, y: startY, action: this.openParty }, { name: "BAG", frame: 2, x: startX, y: startY + 54, action: this.openBag }, { name: "RUN", frame: 3, x: startX + 100, y: startY + 54, action: this.run } ]; this.createButtons(); } createButtons() { for (let option of this.options) { option.sprite = new CommandButton(option.name, option.frame, option.x, option.y); this.addChild(option.sprite); } this.options[actionsInx].sprite.activate(); } updateInput() { if (!this.visible) this.visible = true; // if (this.isBusy()) return; if (Input.isTriggered("right")) { this.options[actionsInx].sprite.deactivate(); actionsInx++; if (actionsInx >= this.options.length) actionsInx = 0; this.options[actionsInx].sprite.activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("left")) { this.options[actionsInx].sprite.deactivate(); actionsInx--; if (actionsInx < 0) actionsInx = this.options.length - 1; this.options[actionsInx].sprite.activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("down")) { this.options[actionsInx].sprite.deactivate(); actionsInx += 2; if (actionsInx >= this.options.length) actionsInx -= 4; this.options[actionsInx].sprite.activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("up")) { this.options[actionsInx].sprite.deactivate(); actionsInx -= 2; if (actionsInx < 0) actionsInx += 4; this.options[actionsInx].sprite.activate(); SoundManager.playCursor(); return; } if (Input.isTriggered("ok")) { this.options[actionsInx].action(); this.visible = false; } } openMovesSelection() { $Battle.changePhase(Phase.MoveSelection); } openParty() { SceneManager.push(PE.Party.Scene_Party); } openBag() {} run() { $Battle.terminate(); SceneManager.goto(PE.TitleScenes.CustomScene); } } }
the_stack
import { sp } from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/lists/web"; import "@pnp/sp/folders/web"; import "@pnp/sp/files/folder"; import "@pnp/sp/items/list"; import "@pnp/sp/fields/list"; import "@pnp/sp/views/list"; import "@pnp/sp/site-users/web"; import { IList } from "@pnp/sp/lists"; import * as _ from "lodash"; export default class SPHelper { private lst_pageComments: string = ''; private lst_pageDocuments: string = ''; private lst_docListName: string = ''; private _list: IList = null; private _doclist: IList = null; private cqPostDocs: string = `<View> <Query> <Where> <And> <Eq> <FieldRef Name='FSObjType' /> <Value Type='Text'>1</Value> </Eq> <Eq> <FieldRef Name='FileRef' /> <Value Type='Text'>{{FilePath}}</Value> </Eq> </And> </Where> <ViewFields><FieldRef Name="ID" /></ViewFields> </Query> </View>`; public constructor(lstDocLib?: string) { this.lst_pageComments = "Page Comments"; this._list = sp.web.lists.getByTitle(this.lst_pageComments); if (lstDocLib) { this.lst_pageDocuments = lstDocLib; } } public getDocLibInfo = async () => { this._doclist = sp.web.lists.getById(this.lst_pageDocuments); let listInfo: any = await this._doclist.select('Title').get(); this.lst_docListName = listInfo.Title; } public queryList = async (query, $list: IList) => { return await $list.getItemsByCAMLQuery(query); } public getCurrentUserInfo = async () => { let currentUserInfo = await sp.web.currentUser.get(); return ({ ID: currentUserInfo.Id, Email: currentUserInfo.Email, LoginName: currentUserInfo.LoginName, DisplayName: currentUserInfo.Title, Picture: '/_layouts/15/userphoto.aspx?size=S&username=' + currentUserInfo.UserPrincipalName, }); } public getSiteUsers = async (currentUserId: number) => { let resusers = await sp.web.siteUsers.filter('IsHiddenInUI eq false and PrincipalType eq 1').get(); _.remove(resusers, (o) => { return o.Id == currentUserId || o.Email == ""; }); let userResults = []; resusers.map((user) => { userResults.push({ id: user.Id, fullname: user.Title, email: user.Email, profile_picture_url: '/_layouts/15/userphoto.aspx?size=S&username=' + user.UserPrincipalName }); }); return userResults; } public getPostAttachmentFilePath = async (pageUrl) => { let pageName = pageUrl.split('/')[pageUrl.split('/').length - 1].split('.').slice(0, -1).join('.'); let res = await sp.web.select('ServerRelativeUrl').get(); let doclistName = (this.lst_docListName.toLowerCase() === 'documents') ? "Shared Documents" : this.lst_docListName; return res.ServerRelativeUrl + "/" + doclistName + "/" + pageName; } public checkForPageFolder = async (postAttachmentPath) => { let xml = this.cqPostDocs.replace('{{FilePath}}', postAttachmentPath); let q = { ViewXml: xml }; let res = await this.queryList(q, this._doclist); if (res.length > 0) return true; else return false; } public getPostComments = async (pageurl, currentUserInfo) => { let pagecomments = await this._list.items.select('Comments', 'Likes', 'FieldValuesAsText/Comments', 'FieldValuesAsText/Likes') .filter(`PageURL eq '${pageurl}'`).expand('FieldValuesAsText').get(); if (pagecomments.length > 0) { var tempComments = pagecomments[0].FieldValuesAsText.Comments; var tempLikes = pagecomments[0].FieldValuesAsText.Likes; if (tempLikes != undefined && tempLikes != null && tempLikes !== "") tempLikes = JSON.parse(tempLikes); else tempLikes = []; if (tempComments != undefined && tempComments != null && tempComments !== "") { var jsonComments = JSON.parse(tempComments); if (tempLikes.length > 0) { tempLikes.map((liked) => { var fil = _.find(jsonComments, (o) => { return o.id == liked.commentID; }); if (fil !== undefined && fil !== null) { fil.upvote_count = liked.userVote.length; var cufil = _.find(liked.userVote, (o) => { return o.userid == currentUserInfo.ID; }); if (cufil !== undefined && cufil !== null) fil.user_has_upvoted = true; } }); } return jsonComments; } else return []; } else return []; } public getComment = async (pageurl) => { let pagecomments = await this._list.items.select('Comments', 'FieldValuesAsText/Comments') .filter(`PageURL eq '${pageurl}'`).expand('FieldValuesAsText').get(); if (pagecomments.length > 0) return pagecomments[0].FieldValuesAsText.Comments; else return null; } public addComment = async (pageUrl, comments) => { let pageName = pageUrl.split('/')[pageUrl.split('/').length - 1]; let commentsToAdd = await sp.web.lists.getByTitle(this.lst_pageComments).items.add({ Title: pageName, PageURL: pageUrl, Comments: JSON.stringify(comments) }); return commentsToAdd; } public updateComment = async (pageurl, comments) => { let pageComment = await this._list.items.select('ID', 'PageURL').filter(`PageURL eq '${pageurl}'`).get(); if (comments.length > 0) { if (pageComment.length > 0) { let pageCommentsToUpdate = await this._list.items.getById(pageComment[0].ID).update({ Comments: JSON.stringify(comments) }); return pageCommentsToUpdate; } } else { return await this._list.items.getById(pageComment[0].ID).delete(); } } public postComment = async (pageurl, commentJson, currentUserInfo) => { commentJson.created_by_current_user = false; let comments = await this.getPostComments(pageurl, currentUserInfo); if (comments.length > 0) { comments.push(commentJson); let updateComments = await this.updateComment(pageurl, comments); return updateComments; } else { comments.push(commentJson); let addComments = await this.addComment(pageurl, comments); return addComments; } } public addVoteForComment = async (pageurl, commentJson, currentUserInfo) => { var tempLikes = []; tempLikes.push({ commentID: commentJson.id, userVote: [{ userid: currentUserInfo.ID, name: currentUserInfo.DisplayName }] }); let pageComment = await this._list.items.select('ID').filter(`PageURL eq '${pageurl}'`).get(); if (pageComment.length > 0) { return await this._list.items.getById(pageComment[0].ID).update({ Likes: JSON.stringify(tempLikes) }); } } public updateVoteForComment = async (pageurl, jsonLikes) => { let pageComment = await this._list.items.select('ID').filter(`PageURL eq '${pageurl}'`).get(); if (pageComment.length > 0) { return await this._list.items.getById(pageComment[0].ID).update({ Likes: JSON.stringify(jsonLikes) }); } } public voteComment = async (pageurl, commentJson, currentUserInfo) => { let res = await this._list.items.select('Likes', 'FieldValuesAsText/Likes').filter(`PageURL eq '${pageurl}'`).expand('FieldValuesAsText').get(); if (res.length > 0) { var tempLikes = res[0].FieldValuesAsText.Likes; if (tempLikes != undefined && tempLikes != null && tempLikes !== "") { // Likes already exits so update the item var jsonLikes = JSON.parse(tempLikes); var userAlreadyVoted = _.find(jsonLikes, (o) => { return o.commentID == commentJson.id && _.find(o.userVote, (oo) => { return oo.userid == currentUserInfo.ID; }); }); var userPresent = (userAlreadyVoted === undefined || userAlreadyVoted == null) ? false : true; var fil = _.find(jsonLikes, (o) => { return o.commentID == commentJson.id; }); if (fil !== undefined && fil !== null) { // Found likes for the comment id if (commentJson.user_has_upvoted) { if (!userPresent) fil.userVote = _.concat(fil.userVote, { userid: currentUserInfo.ID, name: currentUserInfo.DisplayName }); } else { if (userPresent) { if (fil !== undefined && fil !== null) _.remove(fil.userVote, (o) => { return o['userid'] == currentUserInfo.ID; }); } } } else { // No likes found for the comment id jsonLikes.push({ commentID: commentJson.id, userVote: [{ userid: currentUserInfo.ID, name: currentUserInfo.DisplayName }] }); } return await this.updateVoteForComment(pageurl, jsonLikes); } else { // Likes doesn't exists so add new if (commentJson.user_has_upvoted) return await this.addVoteForComment(pageurl, commentJson, currentUserInfo); } } else { return commentJson; } } public deleteComment = async (pageurl, commentJson) => { let comments = await this.getComment(pageurl); if (comments !== undefined && comments !== null) { var jsonComments = JSON.parse(comments); _.remove(jsonComments, (o) => { return o['id'] == commentJson.id; }); return await this.updateComment(pageurl, jsonComments); } } public editComments = async (pageurl, commentJson) => { let comment = await this.getComment(pageurl); if (comment !== undefined && comment !== null) { var jsonComments = JSON.parse(comment); var match = _.find(jsonComments, (o) => { return o.id == commentJson.id; }); if (match) _.merge(match, { pings: commentJson.pings, content: commentJson.content, modified: commentJson.modified }); return await this.updateComment(pageurl, jsonComments); } } public createFolder = async (folderPath) => { return await sp.web.folders.add(folderPath); } public uploadFileToFolder = async (folderpath, fileinfo) => { return await sp.web.getFolderByServerRelativeUrl(folderpath).files.add(fileinfo.name, fileinfo.content, true); } public postAttachments = async (commentArray: any[], pageFolderExists, postAttachmentPath): Promise<any> => { var self = this; return new Promise(async (resolve, reject) => { if (!pageFolderExists) await this.createFolder(postAttachmentPath); var reader = new FileReader(); reader.onload = async () => { var contentBuffer = reader.result; let uploadedFile = await self.uploadFileToFolder(postAttachmentPath, { name: commentArray[0].file.name, content: contentBuffer }); _.set(commentArray[0], 'file_id', uploadedFile.data.UniqueId); _.set(commentArray[0], 'file_url', postAttachmentPath + "/" + commentArray[0].file.name); resolve(commentArray); }; await reader.readAsArrayBuffer(commentArray[0].file); }); } public checkListExists = async (): Promise<boolean> => { return new Promise<boolean>(async (res, rej) => { sp.web.lists.getByTitle(this.lst_pageComments).get().then((listExists) => { res(true); }).catch(async err => { let listExists = await (await sp.web.lists.ensure(this.lst_pageComments)).list; await listExists.fields.addText('PageURL', 255, { Required: true, Description: '' }); await listExists.fields.addMultilineText('Comments', 6, false, false, false, false, { Required: true, Description: '' }); await listExists.fields.addMultilineText('Likes', 6, false, false, false, false, { Required: false, Description: '' }); let allItemsView = await listExists.views.getByTitle('All Items'); await allItemsView.fields.add('PageURL'); await allItemsView.fields.add('Comments'); await allItemsView.fields.add('Likes'); res(true); }); }); } }
the_stack
import { holdLoop } from '../../tests/utils' import { wait } from './async' import { loadSource, loadSources, Source } from './entropy_source' describe('Entropy source utilities', () => { describe('loadSource', () => { it('passes source options', async () => { const sourceGetter = jasmine.createSpy() const sourceLoader = jasmine.createSpy().and.returnValue(sourceGetter) const loadedSource = loadSource(sourceLoader, '12345') await loadedSource() expect(sourceLoader).toHaveBeenCalledWith('12345') expect(sourceGetter).toHaveBeenCalledWith() }) describe('result handling', () => { async function checkSource(source: Source<undefined, 'unpredictable value'>) { const loadedSource = loadSource(source, undefined) const component = await loadedSource() expect(component).toEqual({ value: 'unpredictable value', duration: jasmine.anything() }) } describe('synchronous "load" phase', () => { it('with no "get" phase', async () => { const source = () => 'unpredictable value' as const await checkSource(source) }) it('with synchronous "get" phase', async () => { const source = () => () => 'unpredictable value' as const await checkSource(source) }) it('with asynchronous "get" phase', async () => { const source = () => () => wait(5, 'unpredictable value' as const) await checkSource(source) }) }) describe('asynchronous "load" phase', () => { it('with no "get" phase', async () => { const source = () => wait(5, 'unpredictable value' as const) await checkSource(source) }) it('with synchronous "get" phase', async () => { const source = () => wait(5, () => 'unpredictable value' as const) await checkSource(source) }) it('with asynchronous "get" phase', async () => { const source = () => wait(5, () => wait(5, 'unpredictable value' as const)) await checkSource(source) }) }) }) describe('error handling', () => { async function checkSource(source: Source<undefined, never>) { const loadedSource = loadSource(source, undefined) const component = await loadedSource() expect(component).toEqual({ error: jasmine.objectContaining({ message: 'Fail' }), duration: jasmine.anything(), }) } describe('synchronous "load" phase', () => { it('with no "get" phase', async () => { await checkSource(() => { throw 'Fail' }) }) it('with synchronous "get" phase', async () => { await checkSource(() => () => { throw 'Fail' }) }) it('with asynchronous "get" phase', async () => { await checkSource(() => async () => { await wait(5) throw new Error('Fail') }) }) }) describe('asynchronous "load" phase', () => { it('with no "get" phase', async () => { await checkSource(async () => { await wait(5) throw new Error('Fail') }) }) it('with synchronous "get" phase', async () => { await checkSource(async () => { await wait(5) return () => { throw new Error('Fail') } }) }) it('with asynchronous "get" phase', async () => { await checkSource(async () => { await wait(5) return async () => { await wait(5) throw new Error('Fail') } }) }) }) }) it('runs source\'s "load" phase once in total and "get" phase once per each getter call', async () => { const sourceGetter = jasmine.createSpy().and.returnValues('one', 'two', 'three') const sourceLoader = jasmine.createSpy().and.returnValue(sourceGetter) const loadedSource = loadSource(sourceLoader, undefined) await wait(5) expect(sourceLoader).toHaveBeenCalledTimes(1) expect(sourceGetter).not.toHaveBeenCalled() expect(await loadedSource()).toEqual({ value: 'one', duration: jasmine.anything() }) expect(await loadedSource()).toEqual({ value: 'two', duration: jasmine.anything() }) expect(await loadedSource()).toEqual({ value: 'three', duration: jasmine.anything() }) expect(sourceLoader).toHaveBeenCalledTimes(1) expect(sourceGetter).toHaveBeenCalledTimes(3) }) it('allows getting the component before source is loaded', async () => { let isSourceReallyLoaded = false const source = async () => { await wait(10) isSourceReallyLoaded = true return 'unpredictable value' } const loadedSource = loadSource(source, undefined) expect(isSourceReallyLoaded).toBeFalse() expect(await loadedSource()).toEqual({ value: 'unpredictable value', duration: jasmine.anything() }) expect(isSourceReallyLoaded).toBeTrue() }) it('measures duration in case of success', async () => { const source = () => { holdLoop(7) // setTimeout is too inaccurate return () => holdLoop(5) } const loadedSource = loadSource(source, undefined) await wait(50) // To make a pause between the loading completes and the getting starts const component = await loadedSource() expect(component.duration).toBeGreaterThanOrEqual(7 + 5) expect(component.duration).toBeLessThan(50 + 5) }) it('measures duration in case of error in "load" phase', async () => { const source = () => { holdLoop(5) // setTimeout is too inaccurate throw new Error('Failed to load') } const loadedSource = loadSource(source, undefined) await wait(50) // To make a pause between the loading completes and the getting starts const component = await loadedSource() expect(component.duration).toBeGreaterThanOrEqual(5) expect(component.duration).toBeLessThan(50) }) it('measures duration in case of error in "get" phase', async () => { const source = () => { holdLoop(7) // setTimeout is too inaccurate return () => { holdLoop(5) throw new Error('Failed to get') } } const loadedSource = loadSource(source, undefined) await wait(50) // To make a pause between the loading completes and the getting starts const component = await loadedSource() expect(component.duration).toBeGreaterThanOrEqual(7 + 5) expect(component.duration).toBeLessThan(50 + 5) }) }) describe('loadSources', () => { it('passes source options', async () => { const sources = { foo: jasmine.createSpy(), bar: jasmine.createSpy(), baz: jasmine.createSpy(), } const loadedSources = loadSources(sources, '12345', []) await loadedSources() expect(sources.foo).toHaveBeenCalledWith('12345') expect(sources.bar).toHaveBeenCalledWith('12345') expect(sources.baz).toHaveBeenCalledWith('12345') }) it("returns sources' values and errors", async () => { const sources = { success: () => wait(10, 'qwerty'), loadFail: async () => { await wait(5) throw new Error('Failed to load') }, getFail: () => async () => { await wait(15) throw 'Failed to get' }, } const loadedSources = loadSources(sources, undefined, []) const components = await loadedSources() expect(components).toEqual({ success: { value: 'qwerty', duration: jasmine.anything() }, loadFail: { error: new Error('Failed to load'), duration: jasmine.anything() }, getFail: { error: { message: 'Failed to get' }, duration: jasmine.anything() }, }) }) it("keeps the sources' order", async () => { const sources = { one: () => wait(15, () => wait(10, '')), two: () => wait(5, () => wait(15, '')), three: () => wait(10, () => wait(5, '')), four: () => wait(5, () => wait(5, '')), } const loadedSources = loadSources(sources, undefined, []) const components = await loadedSources() expect(Object.keys(components)).toEqual(['one', 'two', 'three', 'four']) }) it('excludes', async () => { const sources = { one: jasmine.createSpy().and.returnValue(1), two: jasmine.createSpy().and.returnValue(2), three: jasmine.createSpy().and.returnValue(3), four: jasmine.createSpy().and.returnValue(4), five: jasmine.createSpy().and.returnValue(5), } const loadedSources = loadSources(sources, undefined, ['four', 'two']) const components = await loadedSources() expect(components).toEqual({ one: { value: 1, duration: jasmine.anything() }, three: { value: 3, duration: jasmine.anything() }, five: { value: 5, duration: jasmine.anything() }, }) expect(sources.one).toHaveBeenCalledTimes(1) expect(sources.two).not.toHaveBeenCalled() expect(sources.three).toHaveBeenCalledTimes(1) expect(sources.four).not.toHaveBeenCalled() expect(sources.five).toHaveBeenCalledTimes(1) }) it('runs sources\' "load" phase once in total and "get" phase once per each getter call', async () => { const sourceGetters = { foo: jasmine.createSpy().and.returnValues('one', 'two', 'three'), bar: jasmine.createSpy().and.returnValues(1, 2, 3), } const sourceLoaders = { foo: jasmine.createSpy().and.returnValue(sourceGetters.foo), bar: jasmine.createSpy().and.returnValue(sourceGetters.bar), } const loadedSources = loadSources(sourceLoaders, undefined, []) await wait(5) expect(sourceLoaders.foo).toHaveBeenCalledTimes(1) expect(sourceLoaders.bar).toHaveBeenCalledTimes(1) expect(sourceGetters.foo).not.toHaveBeenCalled() expect(sourceGetters.bar).not.toHaveBeenCalled() expect(await loadedSources()).toEqual({ foo: { value: 'one', duration: jasmine.anything() }, bar: { value: 1, duration: jasmine.anything() }, }) expect(await loadedSources()).toEqual({ foo: { value: 'two', duration: jasmine.anything() }, bar: { value: 2, duration: jasmine.anything() }, }) expect(await loadedSources()).toEqual({ foo: { value: 'three', duration: jasmine.anything() }, bar: { value: 3, duration: jasmine.anything() }, }) expect(sourceLoaders.foo).toHaveBeenCalledTimes(1) expect(sourceLoaders.bar).toHaveBeenCalledTimes(1) expect(sourceGetters.foo).toHaveBeenCalledTimes(3) expect(sourceGetters.bar).toHaveBeenCalledTimes(3) }) it('releases the JS event loop for asynchronous events', async () => { const makeSource = () => () => { holdLoop(10) return () => { holdLoop(10) } } const sources = { 0: makeSource(), 1: makeSource(), 2: makeSource(), 3: makeSource(), 4: makeSource(), 5: makeSource(), 6: makeSource(), 7: makeSource(), } let intervalFireCounter = 0 const intervalId = setInterval(() => ++intervalFireCounter, 1) try { const loadedSources = loadSources(sources, undefined, []) await loadedSources() } finally { clearInterval(intervalId) } expect(intervalFireCounter).toBeGreaterThan(1) }) it('runs source\'s "load" phase once even when a signal isn\'t loaded when getter is called', async () => { const sources = { one: () => { // This pause will cause `loadSources` to release the JS event loop // which will let the getter run before the next source starts loading holdLoop(20) return '' }, two: jasmine.createSpy(), } const loadedSources = loadSources(sources, undefined, []) expect(sources.two).not.toHaveBeenCalled() await Promise.all([loadedSources(), loadedSources(), loadedSources()]) expect(sources.two).toHaveBeenCalledTimes(1) }) }) })
the_stack
import { DataViewFieldType } from 'app/constants'; import ReactChart from 'app/models/ReactChart'; import { PageInfo } from 'app/pages/MainPage/pages/ViewPage/slice/types'; import { ChartConfig, ChartContext, ChartDataSectionField, ChartOptions, ChartStyleConfig, ChartStyleSectionGroup, } from 'app/types/ChartConfig'; import ChartDataSetDTO, { IChartDataSet } from 'app/types/ChartDataSet'; import { getColumnRenderName, getStyles, getUnusedHeaderRows, getValue, toFormattedValue, transformToDataSet, } from 'app/utils/chartHelper'; import { DATARTSEPERATOR } from 'globalConstants'; import { Debugger } from 'utils/debugger'; import { CloneValueDeep, isEmptyArray, Omit } from 'utils/object'; import { ConditionalStyleFormValues } from '../../FormGenerator/Customize/ConditionalStyle'; import AntdTableWrapper from './AntdTableWrapper'; import { getCustomBodyCellStyle, getCustomBodyRowStyle, } from './conditionalStyle'; import Config from './config'; import { ResizableTitle, TableColumnTitle, TableComponentsTd, } from './TableComponents'; import { PageOptions, TableCellEvents, TableColumnsList, TableComponentConfig, TableHeaderConfig, TableStyle, TableStyleOptions, } from './types'; class BasicTableChart extends ReactChart { useIFrame = false; isISOContainer = 'react-table'; config = Config; utilCanvas; dataColumnWidths = {}; tablePadding = 16; tableCellBorder = 1; cachedAntTableOptions: any = {}; cachedDatartConfig: ChartConfig = {}; cacheContext: any = null; showSummaryRow = false; rowNumberUniqKey = `@datart@rowNumberKey`; totalWidth = 0; exceedMaxContent = false; pageInfo: Partial<PageInfo> | undefined = { pageNo: 0, pageSize: 0, total: 0, }; constructor(props?) { super(AntdTableWrapper, { id: props?.id || 'react-table', name: props?.name || 'Table', icon: props?.icon || 'table', }); this.meta.requirements = props?.requirements || [ { group: [0, 999], aggregate: [0, 999], }, ]; } onUpdated(options: ChartOptions, context: ChartContext): void { if (!this.isMatchRequirement(options.config)) { this.adapter?.unmount(); return; } Debugger.instance.measure( 'Table OnUpdate cost ---> ', () => { const tableOptions = this.getOptions( context, options.dataset, options.config, options.widgetSpecialConfig, ); // this.cachedAntTableOptions = Omit(tableOptions, ['dataSource']); this.cachedAntTableOptions = Omit(tableOptions, []); this.cachedDatartConfig = options.config; this.cacheContext = context; this.adapter?.updated(tableOptions, context); }, false, ); } public onUnMount(options, context?): void { this.cachedAntTableOptions = {}; this.cachedDatartConfig = {}; this.cacheContext = null; } public onResize(options, context?): void { const columns = this.getDataColumnWidths( options.config, options.dataset, context, ); const tableOptions = Object.assign( this.cachedAntTableOptions, { ...this.getAntdTableStyleOptions( this.cachedDatartConfig?.styles, this.cachedDatartConfig?.settings!, context, ), }, { columns }, ); this.adapter?.updated(tableOptions, context); } protected getOptions( context: ChartContext, dataset?: ChartDataSetDTO, config?: ChartConfig, widgetSpecialConfig?: any, ) { if (!dataset || !config) { return { locale: { emptyText: ' ' } }; } const dataConfigs = config.datas || []; const styleConfigs = config.styles || []; const settingConfigs = config.settings || []; const chartDataSet = transformToDataSet( dataset.rows, dataset.columns, dataConfigs, ); const mixedSectionConfigRows = dataConfigs .filter(c => c.key === 'mixed') .flatMap(config => config.rows || []); const aggregateConfigs = mixedSectionConfigRows.filter( r => r.type === DataViewFieldType.NUMERIC, ); this.dataColumnWidths = this.calculateFieldsMaxWidth( mixedSectionConfigRows, chartDataSet, styleConfigs, context, settingConfigs, ); this.totalWidth = Object.values<any>(this.dataColumnWidths).reduce( (a, b) => a + (b.columnWidthValue || 0), 0, ); this.exceedMaxContent = this.totalWidth >= context.width; const tablePagination = this.getPagingOptions( settingConfigs, dataset?.pageInfo, ); const tableColumns = this.getColumns( mixedSectionConfigRows, styleConfigs, settingConfigs, chartDataSet, context, ); return { rowKey: 'id', pagination: tablePagination, dataSource: chartDataSet, columns: tableColumns, summaryFn: this.getTableSummaryFn( settingConfigs, chartDataSet, tableColumns, aggregateConfigs, context, ), onRow: (_, index) => { const row = chartDataSet?.[index]; const rowData = row?.convertToCaseSensitiveObject(); return { index, rowData }; }, components: this.getTableComponents( styleConfigs, widgetSpecialConfig, mixedSectionConfigRows, ), ...this.getAntdTableStyleOptions(styleConfigs, settingConfigs, context), onChange: (pagination, filters, sorter, extra) => { if (extra?.action === 'sort' || extra?.action === 'paginate') { this.invokePagingRelatedEvents( sorter?.column?.colName, sorter?.order, pagination?.current, sorter?.column?.aggregate, ); } }, rowClassName: (_, index) => { return index % 2 === 0 ? 'datart-basic-table-odd' : 'datart-basic-table-even'; }, tableStyleConfig: this.getTableStyle(styleConfigs, settingConfigs), }; } private getDataColumnWidths( config: ChartConfig, dataset: ChartDataSetDTO, context, ): TableColumnsList[] { const dataConfigs = config.datas || []; const styleConfigs = config.styles || []; const settingConfigs = config.settings || []; const chartDataSet = transformToDataSet( dataset.rows, dataset.columns, dataConfigs, ); const mixedSectionConfigRows = dataConfigs .filter(c => c.key === 'mixed') .flatMap(config => config.rows || []); this.dataColumnWidths = this.calculateFieldsMaxWidth( mixedSectionConfigRows, chartDataSet, styleConfigs, context, settingConfigs, ); this.totalWidth = Object.values<any>(this.dataColumnWidths).reduce( (a, b) => a + (b.columnWidthValue || 0), 0, ); this.exceedMaxContent = this.totalWidth >= context.width; return this.getColumns( mixedSectionConfigRows, styleConfigs, settingConfigs, chartDataSet, context, ); } private getTableStyle( styles: ChartStyleConfig[], settingConfigs: ChartStyleConfig[], ): TableStyle { const [oddBgColor, oddFontColor, evenBgColor, evenFontColor] = getStyles( styles, ['tableBodyStyle'], ['oddBgColor', 'oddFontColor', 'evenBgColor', 'evenFontColor'], ); const [rightFixedColumns] = getStyles( styles, ['style'], ['rightFixedColumns'], ); const [backgroundColor, summaryFont] = getStyles( settingConfigs, ['summary'], ['summaryBcColor', 'summaryFont'], ); return { odd: { backgroundColor: oddBgColor, color: oddFontColor, }, even: { backgroundColor: evenBgColor, color: evenFontColor, }, isFixedColumns: rightFixedColumns ? true : false, summaryStyle: Object.assign({ backgroundColor }, summaryFont), }; } private getTableSummaryFn( settingConfigs: ChartStyleConfig[], chartDataSet: IChartDataSet<string>, tableColumns: TableColumnsList[], aggregateConfigs: ChartDataSectionField[], context: ChartContext, ): ((value) => { summarys: Array<string | null> }) | undefined { const [aggregateFields] = getStyles( settingConfigs, ['summary'], ['aggregateFields'], ); this.showSummaryRow = aggregateFields && aggregateFields.length > 0; if (!this.showSummaryRow) { return; } const aggregateFieldConfigs = aggregateConfigs.filter(c => aggregateFields.includes(c.uid), ); if (!aggregateFieldConfigs.length) { return; } const _flatChildren = node => { if (Array.isArray(node?.children)) { return (node.children || []).reduce((acc, cur) => { return acc.concat(..._flatChildren(cur)); }, []); } return [node]; }; const flatHeaderColumns: TableColumnsList[] = (tableColumns || []).reduce( (acc, cur) => { return acc.concat(..._flatChildren(cur)); }, [], ); return (_): { summarys: Array<string | null> } => { return { summarys: flatHeaderColumns .map(c => c.key) .map((k, index) => { const currentSummaryField = aggregateFieldConfigs.find( c => chartDataSet.getFieldKey(c) === k, ); if (currentSummaryField) { const total = chartDataSet?.map((dc: any) => dc.getCell(currentSummaryField), ); return ( (!index ? context?.translator?.('viz.palette.graph.summary') + ': ' : '') + toFormattedValue( total.reduce((acc, cur) => acc + cur, 0), currentSummaryField.format, ) ); } if (k === `${DATARTSEPERATOR}id` || !index) { return context?.translator?.('viz.palette.graph.summary'); } return null; }), }; }; } private calculateFieldsMaxWidth( mixedSectionConfigRows: ChartDataSectionField[], chartDataSet: IChartDataSet<string>, styleConfigs: ChartStyleConfig[], context: ChartContext, settingConfigs: ChartStyleConfig[], ): { [x: string]: { columnWidthValue?: number | undefined; getUseColumnWidth?: boolean | undefined; }; } { const [fontFamily, fontSize, fontWeight] = getStyles( styleConfigs, ['tableBodyStyle'], ['fontFamily', 'fontSize', 'fontWeight'], ); const [headerFont] = getStyles( styleConfigs, ['tableHeaderStyle'], ['font'], ); const [tableHeaders] = getStyles( styleConfigs, ['header', 'modal'], ['tableHeaders'], ); const [enableRowNumber] = getStyles( styleConfigs, ['style'], ['enableRowNumber'], ); const getAllColumnListInfo: ChartStyleSectionGroup[] = getValue( styleConfigs, ['column', 'modal', 'list'], 'rows', ); const [summaryFont] = getStyles( settingConfigs, ['summary'], ['summaryFont'], ); const getRowNumberWidth = maxContent => { if (!enableRowNumber) { return 0; } return this.getTextWidth( context, maxContent, fontWeight, fontSize, fontFamily, ); }; const rowNumberUniqKeyWidth = getRowNumberWidth(chartDataSet?.length) + this.tablePadding * 2 + this.tableCellBorder * 2; const rowNumberUniqKeyHeaderWidth = this.getTextWidth( context, context?.translator?.('viz.palette.graph.number'), headerFont?.fontWeight, headerFont?.fontSize, headerFont?.fontFamily, ); const rowSummaryWidth = this.getTextWidth( context, context?.translator?.('viz.palette.graph.summary'), summaryFont?.fontWeight, summaryFont?.fontSize, summaryFont?.fontFamily, ); const aggregateConfigs = mixedSectionConfigRows.filter( r => r.type === DataViewFieldType.NUMERIC, ); const maxContentByFields: { [p: string]: { columnWidthValue?: number | undefined; getUseColumnWidth?: undefined | boolean; }; }[] = mixedSectionConfigRows.map(c => { const header = this.findHeader(c.uid, tableHeaders); const rowUniqKey = chartDataSet.getFieldKey(c); const [columnWidth, getUseColumnWidth] = getStyles( getAllColumnListInfo, [c.uid!, 'columnStyle'], ['columnWidth', 'useColumnWidth'], ); const datas = chartDataSet?.map(dc => { const text = dc.getCell(c); const width = this.getTextWidth( context, toFormattedValue(text, c.format), fontWeight, fontSize, fontFamily, ); const headerWidth = this.getTextWidth( context, header?.label || chartDataSet.getFieldKey(c), headerFont?.fontWeight, headerFont?.fontSize, headerFont?.fontFamily, ); const currentSummaryField = aggregateConfigs.find( ac => ac.uid === c.uid, ); const total = chartDataSet?.map((dc: any) => dc.getCell(currentSummaryField), ); const summaryText = total.reduce((acc, cur) => acc + cur, 0); const summaryWidth = this.getTextWidth( context, toFormattedValue(summaryText, c.format), summaryFont?.fontWeight, summaryFont?.fontSize, summaryFont?.fontFamily, ); const sorterIconWidth = 12; return Math.max( width, headerWidth + sorterIconWidth + (c?.alias?.desc ? headerFont?.fontSize || 12 : 0), summaryWidth + sorterIconWidth, ); }); return { [rowUniqKey]: { columnWidthValue: getUseColumnWidth ? columnWidth || 100 : (datas.length ? Math.max(...datas) : 0) + this.tablePadding * 2 + this.tableCellBorder * 2, getUseColumnWidth, }, }; }); maxContentByFields.push({ [this.rowNumberUniqKey]: { columnWidthValue: enableRowNumber ? Math.max( rowNumberUniqKeyWidth, rowNumberUniqKeyHeaderWidth + this.tablePadding * 2 + this.tableCellBorder * 2, rowSummaryWidth + this.tablePadding * 2 + this.tableCellBorder * 2, ) : 0, }, }); return maxContentByFields.reduce((acc, cur: any) => { return Object.assign({}, acc, { ...cur }); }, {}); } protected getTableComponents( styleConfigs: ChartStyleConfig[], widgetSpecialConfig: { env: string | undefined; [x: string]: any }, mixedSectionConfigRows: ChartDataSectionField[], ): TableComponentConfig { const linkFields = widgetSpecialConfig?.linkFields; const jumpField = widgetSpecialConfig?.jumpField; const [tableHeaders] = getStyles( styleConfigs, ['header', 'modal'], ['tableHeaders'], ); const [headerBgColor, headerFont, headerTextAlign] = getStyles( styleConfigs, ['tableHeaderStyle'], ['bgColor', 'font', 'align'], ); const [fontFamily, fontSize, fontWeight, fontStyle, bodyTextAlign] = getStyles( styleConfigs, ['tableBodyStyle'], ['fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'align'], ); const getAllColumnListInfo: ChartStyleSectionGroup[] = getValue( styleConfigs, ['column', 'modal', 'list'], 'rows', ); let allConditionalStyle: ConditionalStyleFormValues[] = []; getAllColumnListInfo?.forEach(info => { const [getConditionalStyleValue]: Array< ConditionalStyleFormValues[] | undefined > = getStyles( info.rows!, ['conditionalStyle'], ['conditionalStylePanel'], ); if (Array.isArray(getConditionalStyleValue)) { allConditionalStyle = [ ...allConditionalStyle, ...getConditionalStyleValue, ]; } }); return { header: { cell: props => { const uid = props.uid; const { style, title, ...rest } = props; const header = this.findHeader(uid, tableHeaders || []); const cellCssStyle = { textAlign: headerTextAlign, backgroundColor: headerBgColor, ...headerFont, fontSize: +headerFont?.fontSize, }; if (header && header.style) { const fontStyle = header.style?.font?.value; Object.assign( cellCssStyle, { textAlign: header.style.align, backgroundColor: header.style.backgroundColor, }, { ...fontStyle }, ); } return ( <ResizableTitle {...rest} style={Object.assign(cellCssStyle, style)} /> ); }, }, body: { cell: props => { const { style, key, rowData, ...rest } = props; const uid = props.uid; const [conditionalStyle] = getStyles( getAllColumnListInfo, [uid, 'conditionalStyle'], ['conditionalStylePanel'], ); const [align] = getStyles( getAllColumnListInfo, [uid, 'columnStyle'], ['align'], ); const conditionalCellStyle = getCustomBodyCellStyle( props?.cellValue, conditionalStyle, ); const sensitiveFieldName = Object.keys(rowData || {})?.[0]; const useColumnWidth = this.dataColumnWidths?.[props.dataIndex]?.getUseColumnWidth; const _getBodyTextAlignStyle = alignValue => { if (alignValue && alignValue !== 'default') { return alignValue; } if (bodyTextAlign === 'default') { const type = mixedSectionConfigRows.find( v => v.uid === uid, )?.type; if (type === 'NUMERIC') { return 'right'; } return 'left'; } return bodyTextAlign; }; return ( <TableComponentsTd {...rest} style={Object.assign(style || {}, conditionalCellStyle, { textAlign: _getBodyTextAlignStyle(align), })} isLinkCell={linkFields?.includes(sensitiveFieldName)} isJumpCell={jumpField === sensitiveFieldName} useColumnWidth={useColumnWidth} /> ); }, row: props => { const { style, rowData, ...rest } = props; // NOTE: rowData is case sensitive row keys object const rowStyle = getCustomBodyRowStyle(rowData, allConditionalStyle); return <tr {...rest} style={Object.assign(style || {}, rowStyle)} />; }, wrapper: props => { const { style, ...rest } = props; const bodyStyle = { textAlign: bodyTextAlign === 'default' ? 'left' : bodyTextAlign, fontFamily, fontWeight, fontStyle, fontSize: +fontSize, }; return ( <tbody {...rest} style={Object.assign(style || {}, bodyStyle)} /> ); }, }, }; } private updateTableColumns(e, { size }, index) { const { columns } = this.cachedAntTableOptions; const nextColumns = [...columns]; nextColumns[index] = { ...nextColumns[index], width: size.width, }; const tableOptions = Object.assign(this.cachedAntTableOptions, { columns: nextColumns, }); this.adapter?.updated(tableOptions, this.cacheContext); } protected getColumns( mixedSectionConfigRows: ChartDataSectionField[], styleConfigs: ChartStyleConfig[], settingConfigs: ChartStyleConfig[], chartDataSet: IChartDataSet<string>, context: ChartContext, ): TableColumnsList[] { const [enableRowNumber, leftFixedColumns, rightFixedColumns] = getStyles( styleConfigs, ['style'], ['enableRowNumber', 'leftFixedColumns', 'rightFixedColumns'], ); const [tableHeaderStyles] = getStyles( styleConfigs, ['header', 'modal'], ['tableHeaders'], ); const [pageSize] = getStyles(settingConfigs, ['paging'], ['pageSize']); const columnsList = !tableHeaderStyles || tableHeaderStyles.length === 0 ? this.getFlatColumns( mixedSectionConfigRows, chartDataSet, styleConfigs, ) : this.getGroupColumns( mixedSectionConfigRows, tableHeaderStyles, chartDataSet, styleConfigs, ); const rowNumbers: TableColumnsList[] = enableRowNumber ? [ { key: `${DATARTSEPERATOR}id`, title: context?.translator?.('viz.palette.graph.number'), width: this.dataColumnWidths?.[this.rowNumberUniqKey] ?.columnWidthValue || 0, fixed: leftFixedColumns || rightFixedColumns ? 'left' : null, render: (value, row, rowIndex) => { const pageNo = this.pageInfo?.pageNo || 1; return (pageNo - 1) * (pageSize || 100) + rowIndex + 1; }, }, ] : []; return rowNumbers.concat(columnsList); } getFlatColumns( dataConfigs: TableHeaderConfig[], chartDataSet: IChartDataSet<string>, styleConfigs: ChartStyleConfig[], ): TableColumnsList[] { const [autoMergeFields] = getStyles( styleConfigs, ['style'], ['autoMergeFields'], ); const columnList: TableColumnsList[] = dataConfigs.map((c, cIndex) => { const colName = c.colName; const columnRowSpans = (autoMergeFields || []).includes(c.uid) ? chartDataSet ?.map(dc => dc.getCell(c)) .reverse() .reduce((acc, cur, index, array) => { if (array[index + 1] === cur) { let prevRowSpan = 0; if (acc.length === index && index > 0) { prevRowSpan = acc[index - 1].nextRowSpan; } return acc.concat([ { rowSpan: 0, nextRowSpan: prevRowSpan + 1 }, ]); } else { let prevRowSpan = 0; if (acc.length === index && index > 0) { prevRowSpan = acc[index - 1].nextRowSpan; } return acc.concat([ { rowSpan: prevRowSpan + 1, nextRowSpan: 0 }, ]); } }, [] as any[]) .map(x => x.rowSpan) .reverse() : []; const columnConfig = this.dataColumnWidths?.[chartDataSet.getFieldKey(c)]; const colMaxWidth = !this.exceedMaxContent && Object.values<{ getUseColumnWidth: undefined | boolean }>( this.dataColumnWidths, ).some(item => item.getUseColumnWidth) ? columnConfig?.getUseColumnWidth ? columnConfig?.columnWidthValue : '' : columnConfig?.columnWidthValue; return { sorter: true, showSorterTooltip: false, title: TableColumnTitle({ title: getColumnRenderName(c), desc: c?.alias?.desc, uid: chartDataSet.getFieldKey(c), }), dataIndex: chartDataSet.getFieldIndex(c), key: chartDataSet.getFieldKey(c), aggregate: c?.aggregate, colName, width: colMaxWidth, fixed: null, ellipsis: { showTitle: false, }, onHeaderCell: record => { return { ...Omit(record, [ 'dataIndex', 'onHeaderCell', 'onCell', 'colName', 'render', 'sorter', 'showSorterTooltip', ]), uid: c.uid, onResize: (e, node) => { this.updateTableColumns(e, node, cIndex); }, }; }, onCell: (record, rowIndex) => { const row = chartDataSet[rowIndex]; const cellValue = row.getCell(c); const rowData = { [chartDataSet.getFieldOriginKey(c)]: cellValue }; return { uid: c.uid, cellValue, dataIndex: row.getFieldKey(c), rowData, ...this.registerTableCellEvents( colName, cellValue, rowIndex, rowData, c.aggregate, ), }; }, render: (value, row, rowIndex) => { const formattedValue = toFormattedValue(value, c.format); if (!(autoMergeFields || []).includes(c.uid)) { return formattedValue; } return { children: formattedValue, props: { rowSpan: columnRowSpans[rowIndex], cellValue: value }, }; }, }; }); return this.getFixedColumns(columnList, styleConfigs); } getFixedColumns( list: TableColumnsList[], styleConfigs: ChartStyleConfig[], ): TableColumnsList[] { const [leftFixedColumns, rightFixedColumns] = getStyles( styleConfigs, ['style'], ['leftFixedColumns', 'rightFixedColumns'], ); let columnsList = CloneValueDeep(list); leftFixedColumns && (columnsList = columnsList.map((item, index) => { if (index < Math.min(leftFixedColumns, columnsList.length - 1)) { item.fixed = 'left'; } return item; })); rightFixedColumns && (columnsList = columnsList .reverse() .map((item, index) => { if (index < rightFixedColumns && !item.fixed) { item.fixed = 'right'; } return item; }) .reverse()); return columnsList; } getGroupColumnsOfFlattenedColumns = ( tableHeader: TableHeaderConfig[], mixedSectionConfigRows: ChartDataSectionField[], chartDataSet: IChartDataSet<string>, ): TableHeaderConfig[] => { const newMixedConfig = mixedSectionConfigRows?.concat(); let list: TableHeaderConfig[] = []; const _getFlattenedChildren = tableHeaderStylesConfig => { if (tableHeaderStylesConfig.children?.length) { tableHeaderStylesConfig.children.map(item => _getFlattenedChildren(item), ); } else { const currentConfigIndex = newMixedConfig?.findIndex( c => chartDataSet.getFieldKey(c) === chartDataSet.getFieldKey(tableHeaderStylesConfig), ); if (currentConfigIndex >= 0) { list.push( Object.assign( {}, tableHeaderStylesConfig, newMixedConfig?.[currentConfigIndex], ), ); newMixedConfig?.splice(currentConfigIndex, 1); } } }; tableHeader.forEach(item => { if (item.children?.length) { item.children.map(items => _getFlattenedChildren(items)); } else { const currentConfigIndex = newMixedConfig?.findIndex( c => chartDataSet.getFieldKey(c) === chartDataSet.getFieldKey(item), ); if (currentConfigIndex >= 0) { list.push( Object.assign({}, item, newMixedConfig?.[currentConfigIndex]), ); newMixedConfig?.splice(currentConfigIndex, 1); } } }); if (newMixedConfig?.length) { list = list.concat(newMixedConfig); } return list; }; getGroupColumns( mixedSectionConfigRows: ChartDataSectionField[], tableHeader: TableHeaderConfig[], chartDataSet: IChartDataSet<string>, styleConfigs: ChartStyleConfig[], ): TableColumnsList[] { const dataConfigs = this.getGroupColumnsOfFlattenedColumns( tableHeader, mixedSectionConfigRows, chartDataSet, ); const flattenedColumns = this.getFlatColumns( dataConfigs, chartDataSet, styleConfigs, ); const groupedHeaderColumns: TableColumnsList[] = tableHeader ?.map( style => this.getHeaderColumnGroup(chartDataSet, style, flattenedColumns) || [], ) ?.filter(Boolean) || []; const unusedHeaderRows: TableColumnsList[] = getUnusedHeaderRows( flattenedColumns, groupedHeaderColumns, ); return groupedHeaderColumns.concat(unusedHeaderRows); } private getHeaderColumnGroup( chartDataSet: IChartDataSet<string>, tableHeader: TableHeaderConfig, columns: TableColumnsList[], ): TableColumnsList { if (!tableHeader.isGroup) { const column = columns.find( c => c.key === chartDataSet.getFieldKey(tableHeader), ); return column!; } return { uid: tableHeader.uid, colName: tableHeader?.colName, title: tableHeader.label, onHeaderCell: record => { return { ...Omit(record, ['dataIndex', 'onHeaderCell', 'onCell', 'colName']), }; }, children: (tableHeader.children || []) .map(th => { return this.getHeaderColumnGroup(chartDataSet, th, columns); }) .filter(Boolean), }; } protected getAntdTableStyleOptions( styleConfigs?: ChartStyleConfig[], settingConfigs?: ChartStyleConfig[], context?: ChartContext, ): TableStyleOptions { const [enablePaging] = getStyles( settingConfigs || [], ['paging'], ['enablePaging'], ); const [showTableBorder, enableFixedHeader] = getStyles( styleConfigs || [], ['style'], ['enableBorder', 'enableFixedHeader'], ); const [tableHeaderStyles] = getStyles( styleConfigs || [], ['header', 'modal'], ['tableHeaders'], ); const [font] = getStyles( styleConfigs || [], ['tableHeaderStyle'], ['font'], ); const [summaryFont] = getStyles( settingConfigs || [], ['summary'], ['summaryFont'], ); const [tableSize] = getStyles(styleConfigs || [], ['style'], ['tableSize']); const HEADER_PADDING = { default: 32, middle: 24, small: 16 }; const TABLE_LINE_HEIGHT = 1.5715; const PAGINATION_HEIGHT = { default: 64, middle: 56, small: 56 }; const SUMMRAY_ROW_HEIGHT = { default: 34, middle: 26, small: 18 }; const _getMaxHeaderHierarchy = (headerStyles: Array<{ children: [] }>) => { const _maxDeeps = (arr: Array<{ children: [] }> = [], deeps: number) => { if (!isEmptyArray(arr) && arr?.length > 0) { return Math.max(...arr.map(a => _maxDeeps(a.children, deeps + 1))); } return deeps; }; return _maxDeeps(headerStyles, 0) || 1; }; const headerHeight = ((font?.fontSize || 0) * TABLE_LINE_HEIGHT + HEADER_PADDING[tableSize || 'default'] + (showTableBorder ? this.tableCellBorder : 0)) * _getMaxHeaderHierarchy(tableHeaderStyles) + this.tableCellBorder; return { scroll: Object.assign({ scrollToFirstRowOnChange: true, x: !enableFixedHeader ? '100%' : this.exceedMaxContent ? this.totalWidth : '100%', y: !enableFixedHeader ? '100%' : context?.height ? context?.height - (this.showSummaryRow ? SUMMRAY_ROW_HEIGHT[tableSize || 'default'] + (summaryFont?.fontSize || 0) * TABLE_LINE_HEIGHT : 0) - headerHeight - (enablePaging ? PAGINATION_HEIGHT[tableSize || 'default'] : 0) : 0, }), bordered: !!showTableBorder, size: tableSize || 'default', }; } protected getPagingOptions( settingConfigs: ChartStyleConfig[], pageInfo?: Partial<PageInfo>, ): PageOptions { const [enablePaging] = getStyles( settingConfigs, ['paging'], ['enablePaging'], ); this.pageInfo = pageInfo; return enablePaging ? Object.assign({ showSizeChanger: false, current: pageInfo?.pageNo, pageSize: pageInfo?.pageSize, total: pageInfo?.total, }) : false; } private createEventParams = params => ({ type: 'click', componentType: 'table', seriesType: undefined, data: undefined, dataIndex: undefined, event: undefined, name: undefined, seriesName: undefined, value: undefined, ...params, }); private invokePagingRelatedEvents( seriesName: string, value: any, pageNo: number, aggOperator?: string, ) { const eventParams = this.createEventParams({ seriesType: 'paging-sort-filter', seriesName, value: { aggOperator: aggOperator, direction: value === undefined ? undefined : value === 'ascend' ? 'ASC' : 'DESC', pageNo, }, }); this.mouseEvents?.forEach(cur => { if (cur.name === 'click') { cur.callback?.(eventParams); } }); } private registerTableCellEvents( seriesName: string, value: any, dataIndex: number, rowData: any, aggOperator?: string, ): TableCellEvents { const eventParams = this.createEventParams({ seriesType: 'body', name: seriesName, data: { format: undefined, name: seriesName, aggOperator, rowData, value: value, }, seriesName, // column name/index dataIndex, // row index value, // cell value }); return this.mouseEvents?.reduce((acc, cur) => { cur.name && (eventParams.type = cur.name); if (cur.name === 'click') { Object.assign(acc, { onClick: event => cur.callback?.({ ...eventParams, event }), }); } if (cur.name === 'dblclick') { Object.assign(acc, { onDoubleClick: event => cur.callback?.({ ...eventParams, event }), }); } if (cur.name === 'contextmenu') { Object.assign(acc, { onContextMenu: event => cur.callback?.({ ...eventParams, event }), }); } if (cur.name === 'mouseover') { Object.assign(acc, { onMouseEnter: event => cur.callback?.({ ...eventParams, event }), }); } if (cur.name === 'mouseout') { Object.assign(acc, { onMouseLeave: event => cur.callback?.({ ...eventParams, event }), }); } return acc; }, {}); } private getTextWidth = ( context: ChartContext, text: string, fontWeight: string, fontSize: string, fontFamily: string, ): number => { const canvas = this.utilCanvas || (this.utilCanvas = context.document.createElement('canvas')); const measureLayer = canvas.getContext('2d'); measureLayer.font = `${fontWeight} ${fontSize}px ${fontFamily}`; const metrics = measureLayer.measureText(text); return Math.ceil(metrics.width); }; private findHeader = ( uid: string | undefined, headers: TableHeaderConfig[], ): TableHeaderConfig | undefined => { let header = (headers || []) .filter(h => !h.isGroup) .find(h => h.uid === uid); if (!!header) { return header; } for (let i = 0; i < (headers || []).length; i++) { header = this.findHeader(uid, headers[i].children || []); if (!!header) { break; } } return header; }; } export default BasicTableChart;
the_stack
module TDev.RT { //? Math goodness, abs, max, ... //@ robust export module Math_ { //? Maps an integer value from one range to another. Does not contrain the value. //@ [result].writesMutable //@ [in_max].defl(1023) [out_max].defl(4) export function map_range(x: number, in_min: number, in_max: number, out_min: number, out_max: number): number { return Bits.add_int32(out_min, Bits.multiply_int32( Bits.subtract_int32(x, in_min), Bits.divide_int32( Bits.subtract_int32(out_max, out_min), Bits.subtract_int32(in_max, in_min) ) ) ); } //? Creates a matrix of zeros of a given size //@ [result].writesMutable //@ [rows].defl(3) [columns].defl(3) export function create_matrix(rows: number, columns: number): Matrix { return Matrix.mk(rows, columns); } //? Returns the smallest integral value greater than or equal to the specified number export function ceiling(x:number) : number { return Math.ceil(x); } //? Returns the largest integer less than or equal to the specified number export function floor(x:number) : number { return Math.floor(x); } //? Returns a specified number raised to the specified power export function pow(x:number, y:number) : number { return Math.pow(x, y); } //? Returns a random integral number between `min` and `max` included. //@ tandre //@ [min].defl(-100) [max].defl(100) export function random_range(min: number, max: number): number { var r = Math_.random(max - min + 1); if (r == undefined) return undefined; return min + r; } //? Returns a random integral number bounded between limit and 0, not including limit unless it is 0 //@ tandre //@ [limit].defl(2) oldName("rand") export function random(limit: number): number { var max = Math.round(limit); if (max == 0) return 0; if (is_inf(max) || is_nan(max)) return undefined; // TODO: we could support infinity var r = max; while (r == max) r = Random.normalized() * (max); // supposedly can happen because of floating-point behavior return Math.floor(r); } //? Returns a random floating-point number x: 0 ≤ x < 1 //@ tandre export function random_normalized() : number { return Random.normalized(); } //? Renamed to 'random normalized' //@ hidden //@ tandre export function rand_norm() : number { return random_normalized(); } //? Returns the result of integer division of one number by another number export function div(x:number, y:number) : number { return (x / y)|0; } //? Returns the modulus resulting from the division of one number by another number export function mod(x:number, y:number) : number { return x % y; } //? Returns the absolute value of a number export function abs(x:number) : number { return Math.abs(x); } //? Returns the angle whose cosine is the specified number export function acos(x:number) : number { return Math.acos(x); } //? Returns the angle whose sine is the specified number export function asin(x:number) : number { return Math.asin(x); } //? Returns the angle whose tangent is the specified number export function atan(x:number) : number { return Math.atan(x); } //? Returns the angle whose tangent is the quotient of two specified numbers export function atan2(y:number, x:number) : number { return Math.atan2(y,x); } //? Returns the cosine of the specified angle (in radians) export function cos(angle:number) : number { return Math.cos(angle); } //? Returns the natural logarithmic base, specified by the constant, e export function e() : number { return Math.E; } //? Returns e raised to the specified power export function exp(x:number) : number { return Math.exp(x); } //? Returns the logarithm of a specified number in a specified base export function log(x:number, base:number) : number { return base == 0 || base == 1 ? NaN : Math.log(x) / Math.log(base); } //? Returns the natural (base e) logarithm of a specified number export function loge(x:number) : number { return Math.log(x); } //? Returns the base 10 logarithm of a specified number export function log10(x:number) : number { return log(x, 10); } //? Returns the larger of two numbers export function max(x:number, y:number) : number { return Math.max(x,y); } //? Returns the smaller of two numbers export function min(x:number, y:number) : number { return Math.min(x,y); } //? Returns the Pi constant //@ name("\u03C0") export function pi() : number { return Math.PI; } //? Returns the gravity constant (9.80665) export function gravity() : number { return 9.80665; } //? Rounds a number to the nearest integral value export function round(x:number) : number { return x < 0 ? Math.ceil(x - 0.5) : Math.floor(x + 0.5); } //? Returns a value indicating the sign of a number export function sign(x:number) : number { if (x < 0) return -1; else if (x > 0) return 1; else return 0; } //? Returns the sine of the specified angle (in radians) export function sin(angle:number) : number { return Math.sin(angle); } //? Returns the square root of a specified number export function sqrt(x:number) : number { return Math.sqrt(x); } //? Returns the tangent of the specified angle (in radians) export function tan(angle:number) : number { return Math.tan(angle); } //? Converts degrees into radians export function deg_to_rad(degrees:number) : number { return degrees / 180.0 * Math.PI; } //? Converts rad into degrees export function rad_to_deg(radians:number) : number { return radians / Math.PI * 180.0; } //? Returns the positive infinity //@ name("\u221E\u208A") export function pos_inf() : number { return Number.POSITIVE_INFINITY; } //? Returns the negative infinity //@ name("\u221E\u208B") export function neg_inf() : number { return Number.NEGATIVE_INFINITY; } //? Indicates whether number evaluates to negative or positive infinity //@ name("is \u221E") export function is_inf(x:number) : boolean { return is_pos_inf(x) || is_neg_inf(x); } //? Indicates whether number evaluates to positive infinity //@ name("is \u221E\u208A") export function is_pos_inf(x:number) : boolean { return x == Number.POSITIVE_INFINITY; } //? Indicates whether number evaluates to negative infinity //@ name("is \u221E\u208B") export function is_neg_inf(x:number) : boolean { return x == Number.NEGATIVE_INFINITY; } //? Indicates that value cannot be represented as a number, i.e. Not-a-Number. This usually happens when the number is the result of a division by zero. export function is_nan(x:number) : boolean { return isNaN(x); } //? Rounds a number to a specified number of fractional digits. //@ [digits].defl(2) export function round_with_precision(x: number, digits: number): number { if (digits <= 0) return Math.round(x); var d = Math.pow(10, digits); return Math.round(x * d) / d; } //? Returns the hyperbolic cosine of the specified angle (in radians) export function cosh(angle: number): number { return (Math.pow(Math_.e(), 2* angle) + 1) / (2 * Math.pow(Math_.e(), angle)); } //? Returns the hyperbolic sine of the specified angle (in radians) export function sinh(angle: number): number { return (Math.pow(Math_.e(), 2* angle) - 1) / (2 * Math.pow(Math_.e(), angle)); } //? Returns the hyperbolic tangent of the specified angle (in radians) export function tanh(angle: number): number { return (Math.pow(Math_.e(), 2* angle) - 1) / (Math.pow(Math_.e(), 2* angle) + 1); } //? Use Collections->create number map instead. //@ hidden [result].writesMutable export function create_number_map() : NumberMap { return Collections.create_number_map(); } //? Creates a 3D vector export function create_vector3(x:number, y:number, z:number) : Vector3 { return Vector3.mk(x, y, z); } // Returns the smallest positive number greater than zero. var _epsilon: number = -1; //? Returns the machine epsilon, the smallest positive number greater than zero. //@ name("\u03B5") export function epsilon(): number { if (_epsilon < 0) { _epsilon = 1; while(1 + _epsilon != 1) _epsilon /= 2; } return _epsilon; } //? Clamps `value` between `min` and `max` export function clamp(min : number, max : number, value : number) : number { return value < min ? min : value > max ? max : value; } //? Clamps `value` between 0 and 1. export function normalize(value : number) : number { return clamp(0, 1, value); } //? Returns the remainder resulting from the division of a specified number by another specified number export function ieee_remainder(x: number, y: number):number { return x - (y * Math.round(x / y)); } //? Return numbers between `start` and `start + length - 1` inclusively export function range(start:number, length:number) : Collection<number> { var r = [] for (var i = 0; i < length; ++i) r.push(start + i) return Collection.fromArray(r, "number") } } }
the_stack
import fs from 'fs' import assert from 'assert' import net from 'net' import sinon from 'sinon' import config from '../../src/config' import Peer from '../../src/service/peer' import { NetworkCreatePeerOrgType } from '../../src/model/type/network.type' import MinimumNetwork from '../util/minimumNetwork' describe('Peer service:', function () { this.timeout(60000) let minimumNetwork: MinimumNetwork let orgPeerCreateJson: NetworkCreatePeerOrgType[] let peerService: Peer let peerServiceOrg0Peer: Peer let peerServiceOrg0Orderer: Peer before(() => { minimumNetwork = new MinimumNetwork() peerService = new Peer(config) peerServiceOrg0Peer = new Peer(minimumNetwork.org0PeerConfig) peerServiceOrg0Orderer = new Peer(minimumNetwork.org0OrdererConfig) orgPeerCreateJson = JSON.parse(fs.readFileSync('./cicd/test_script/org-peer-create.json').toString()) }) describe('up & down', () => { before(async () => { await minimumNetwork.createNetwork() }) after(async () => { await minimumNetwork.deleteNetwork() }) it('should start and shutdown docker container', (done) => { const peerHostname = `${minimumNetwork.getPeer().hostname}.${minimumNetwork.getPeer().orgDomain}` const port = minimumNetwork.getPeer().port peerService.up({ peerHostname }).then(() => { const socket = net.connect(port, '127.0.0.1', () => { peerService.down({ peerHostname }) .then(() => { // TODO check container done() }) .catch((err) => { assert.fail(`peer down error: ${err.message}`) }) }) socket.on('error', (err) => { assert.fail(`peer connect test error: ${err.message}`) }) }).catch((err) => { assert.fail(`peer up error: ${err.message}`) }) }) }) describe('cryptogen', () => { before(() => { minimumNetwork.createNetworkFolder() }) after(async () => { await minimumNetwork.deleteNetwork() }) it('should generate peer ca file when function cryptogen done', async () => { await peerService.cryptogen({ peerOrgs: orgPeerCreateJson }) /** * config-yaml */ assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/config-yaml/crypto-config.yaml`), true) /** * peerOrganizations */ orgPeerCreateJson.forEach((peerOrg) => { const peerOrgPath = `${config.infraConfig.bdkPath}/${config.networkName}/peerOrganizations/${peerOrg.domain}` // folder assert.strictEqual(fs.existsSync(`${peerOrgPath}`), true) // ca assert.strictEqual(fs.existsSync(`${peerOrgPath}/ca/ca.${peerOrg.domain}-cert.pem`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/ca/priv_sk`), true) // tlsca assert.strictEqual(fs.existsSync(`${peerOrgPath}/tlsca/tlsca.${peerOrg.domain}-cert.pem`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/tlsca/priv_sk`), true) // yaml assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/msp/config.yaml`), true) // tls assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/tls/ca.crt`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/tls/client.crt`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/tls/client.key`), true) // peers peerCount for (let index = 0; index < peerOrg.peerCount; index++) { const hostname = `peer${index}` const hostPath = `${peerOrgPath}/peers/${hostname}.${peerOrg.domain}` // folder assert.strictEqual(fs.existsSync(hostPath), true) // msp assert.strictEqual(fs.existsSync(`${hostPath}/msp/config.yaml`), true) assert.strictEqual(fs.existsSync(`${hostPath}/msp/signcerts/${hostname}.${peerOrg.domain}-cert.pem`), true) // tls assert.strictEqual(fs.existsSync(`${hostPath}/tls/ca.crt`), true) assert.strictEqual(fs.existsSync(`${hostPath}/tls/server.crt`), true) assert.strictEqual(fs.existsSync(`${hostPath}/tls/server.key`), true) } }) }) }) describe('copyTLSCa', () => { before(async () => { minimumNetwork.createNetworkFolder() await peerService.cryptogen({ peerOrgs: orgPeerCreateJson }) }) after(async () => { await minimumNetwork.deleteNetwork() }) it('should copy the peer TLS CA to the specified folder under the blockchain network', () => { peerService.copyTLSCa({ peerOrgs: orgPeerCreateJson }) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/tlsca`), true) orgPeerCreateJson.forEach((peerOrg) => { for (let index = 0; index < peerOrg.peerCount; index++) { assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/tlsca/peer${index}.${peerOrg.domain}`), true) } }) }) }) describe('createConnectionProfileYaml', () => { before(async () => { minimumNetwork.createNetworkFolder() await peerService.cryptogen({ peerOrgs: orgPeerCreateJson }) peerService.copyTLSCa({ peerOrgs: orgPeerCreateJson }) }) after(async () => { await minimumNetwork.deleteNetwork() }) it('should generate peer connection profile file', () => { peerService.createConnectionProfileYaml({ peerOrgs: orgPeerCreateJson }) orgPeerCreateJson.forEach((peerOrg) => { const filePath = `${config.infraConfig.bdkPath}/${config.networkName}/peerOrganizations/${peerOrg.domain}` assert.strictEqual(fs.existsSync(`${filePath}/connection-${peerOrg.name}.json`), true) assert.strictEqual(fs.existsSync(`${filePath}/connection-${peerOrg.name}.yaml`), true) }) }) it.skip('should throw error when peerOrgs is undefined', () => { // TODO }) }) // TODO createPeerOrgConfigtxJSON describe('createDockerCompose', () => { before(async () => { minimumNetwork.createNetworkFolder() await peerService.cryptogen({ peerOrgs: orgPeerCreateJson }) peerService.copyTLSCa({ peerOrgs: orgPeerCreateJson }) peerService.createConnectionProfileYaml({ peerOrgs: orgPeerCreateJson }) }) after(async () => { await minimumNetwork.deleteNetwork() }) it('should generate orderer/peer docker-compose file', () => { peerService.createDockerCompose({ peerOrgs: orgPeerCreateJson }) const dockerCompsoePath = `${config.infraConfig.bdkPath}/${config.networkName}/docker-compose` const dockerEnvPath = `${config.infraConfig.bdkPath}/${config.networkName}/env` assert.strictEqual(fs.existsSync(`${dockerCompsoePath}`), true) assert.strictEqual(fs.existsSync(`${dockerEnvPath}`), true) orgPeerCreateJson.forEach((peerOrg) => { for (let index = 0; index < peerOrg.peerCount; index++) { assert.strictEqual(fs.existsSync(`${dockerCompsoePath}/docker-compose-peer-peer${index}.${peerOrg.domain}.yaml`), true) assert.strictEqual(fs.existsSync(`${dockerEnvPath}/peer-peer${index}.${peerOrg.domain}.env`), true) } }) }) }) describe('addOrgToChannel', () => { it('should use addOrgToChannelSteps', async () => { const addOrgToChannelStepsFetchChannelConfigStub = sinon.stub().resolves() const addOrgToChannelStepsComputeUpdateConfigTxStub = sinon.stub().resolves() const addOrgToChannelStepsStub = sinon.stub(Peer.prototype, 'addOrgToChannelSteps').callsFake(() => ({ fetchChannelConfig: addOrgToChannelStepsFetchChannelConfigStub, computeUpdateConfigTx: addOrgToChannelStepsComputeUpdateConfigTxStub, })) await peerService.addOrgToChannel({ channelName: minimumNetwork.channelName, orgName: orgPeerCreateJson[0].name, }) assert.strictEqual(addOrgToChannelStepsFetchChannelConfigStub.called, true) assert.strictEqual(addOrgToChannelStepsComputeUpdateConfigTxStub.called, true) addOrgToChannelStepsStub.restore() }) }) describe('addOrgToChannelSteps', () => { let channelName: string let channelPath: string before(async () => { channelName = minimumNetwork.channelName channelPath = `${config.infraConfig.bdkPath}/${config.networkName}/channel-artifacts/${channelName}` await minimumNetwork.createNetwork() await minimumNetwork.peerAndOrdererUp() await minimumNetwork.createChannelAndJoin() }) after(async () => { await minimumNetwork.deleteNetwork() }) describe('fetchChannelConfig', () => { it('should fetch channel config from blockchain', async () => { await peerServiceOrg0Peer.addOrgToChannelSteps().fetchChannelConfig({ channelName, orgName: orgPeerCreateJson[0].name, }) assert.strictEqual(fs.existsSync(`${channelPath}/${channelName}_fetch.pb`), true) }) }) describe('computeUpdateConfigTx', () => { before(async () => { await peerService.cryptogen({ peerOrgs: orgPeerCreateJson }) await peerService.createPeerOrgConfigtxJSON({ peerOrgs: orgPeerCreateJson }) await peerServiceOrg0Peer.addOrgToChannelSteps().fetchChannelConfig({ channelName, orgName: orgPeerCreateJson[0].name, }) }) it('should compute config diff', async () => { await peerServiceOrg0Peer.addOrgToChannelSteps().computeUpdateConfigTx({ channelName, orgName: orgPeerCreateJson[0].name, }) assert.strictEqual(fs.existsSync(`${channelPath}/${channelName}_update_envelope.pb`), true) }) }) }) describe('addOrgToSystemChannel', () => { it('should use addOrgToSystemChannelSteps', async () => { const addOrgToSystemChannelStepsFetchChannelConfigStub = sinon.stub().resolves() const addOrgToSystemChannelStepsComputeUpdateConfigTxStub = sinon.stub().resolves() const addOrgToSystemChannelStepsStub = sinon.stub(Peer.prototype, 'addOrgToSystemChannelSteps').callsFake(() => ({ fetchChannelConfig: addOrgToSystemChannelStepsFetchChannelConfigStub, computeUpdateConfigTx: addOrgToSystemChannelStepsComputeUpdateConfigTxStub, })) await peerService.addOrgToSystemChannel({ channelName: minimumNetwork.channelName, orgName: orgPeerCreateJson[0].name, orderer: minimumNetwork.getOrderer().fullUrl, }) assert.strictEqual(addOrgToSystemChannelStepsFetchChannelConfigStub.called, true) assert.strictEqual(addOrgToSystemChannelStepsComputeUpdateConfigTxStub.called, true) addOrgToSystemChannelStepsStub.restore() }) }) describe('addOrgToSystemChannelSteps', () => { let channelName: string let channelPath: string before(async () => { channelName = 'system-channel' channelPath = `${config.infraConfig.bdkPath}/${config.networkName}/channel-artifacts/${channelName}` await minimumNetwork.createNetwork() await minimumNetwork.peerAndOrdererUp() }) after(async () => { await minimumNetwork.deleteNetwork() }) describe('fetchChannelConfig', () => { it('should fetch channel config from blockchain', async () => { await peerServiceOrg0Orderer.addOrgToSystemChannelSteps().fetchChannelConfig({ channelName, orgName: orgPeerCreateJson[0].name, orderer: minimumNetwork.getOrderer().fullUrl, }) assert.strictEqual(fs.existsSync(`${channelPath}/${channelName}_fetch.pb`), true) }) }) describe('computeUpdateConfigTx', () => { before(async () => { await peerService.cryptogen({ peerOrgs: orgPeerCreateJson }) await peerService.createPeerOrgConfigtxJSON({ peerOrgs: orgPeerCreateJson }) await peerServiceOrg0Orderer.addOrgToSystemChannelSteps().fetchChannelConfig({ channelName, orgName: orgPeerCreateJson[0].name, orderer: minimumNetwork.getOrderer().fullUrl, }) }) it('should compute config diff', async () => { await peerServiceOrg0Orderer.addOrgToSystemChannelSteps().computeUpdateConfigTx({ channelName, orgName: orgPeerCreateJson[0].name, orderer: minimumNetwork.getOrderer().fullUrl, }) assert.strictEqual(fs.existsSync(`${channelPath}/${channelName}_update_envelope.pb`), true) }) }) }) })
the_stack
import { stylePropsView, validStyles } from '@tamagui/helpers' import { useForceUpdate } from '@tamagui/use-force-update' import React, { Children, Fragment, createElement, forwardRef, memo, useCallback, useContext, useRef, useState, } from 'react' import { StyleSheet, Text, TouchableWithoutFeedback, View, ViewStyle } from 'react-native' import { onConfiguredOnce } from './conf' import { stackDefaultStyles } from './constants/constants' import { isWeb, useIsomorphicLayoutEffect } from './constants/platform' import { rnw } from './constants/rnw' import { createShallowUpdate } from './helpers/createShallowUpdate' import { extendStaticConfig, parseStaticConfig } from './helpers/extendStaticConfig' import { SplitStyleResult, insertSplitStyles, useSplitStyles } from './helpers/getSplitStyles' import { getAllSelectors } from './helpers/insertStyleRule' import { proxyThemeVariables } from './helpers/proxyThemeVariables' import { wrapThemeManagerContext } from './helpers/wrapThemeManagerContext' import { useFeatures } from './hooks/useFeatures' import { useIsTouchDevice } from './hooks/useIsTouchDevice' import { mediaState } from './hooks/useMedia' import { usePressable } from './hooks/usePressable' import { getThemeManagerIfChanged, useTheme } from './hooks/useTheme' import { SpaceFlexDirection, SpaceTokens, StackProps, StaticConfig, StaticConfigParsed, StylableComponent, TamaguiComponent, TamaguiComponentState, TamaguiConfig, TamaguiElement, TamaguiInternalConfig, UseAnimationHook, } from './types' import { Slot, mergeEvent } from './views/Slot' import { TextAncestorContext } from './views/TextAncestorContext' React['keep'] const defaultComponentState: TamaguiComponentState = { hover: false, press: false, pressIn: false, focus: false, // only used by enterStyle mounted: false, animation: null, } export const mouseUps = new Set<Function>() if (typeof document !== 'undefined') { document.addEventListener('mouseup', () => { mouseUps.forEach((x) => x()) mouseUps.clear() }) document.addEventListener('touchend', () => { mouseUps.forEach((x) => x()) mouseUps.clear() }) document.addEventListener('touchcancel', () => { mouseUps.forEach((x) => x()) mouseUps.clear() }) } // mutates function mergeShorthands({ defaultProps }: StaticConfigParsed, { shorthands }: TamaguiConfig) { // they are defined in correct order already { ...parent, ...child } for (const key in defaultProps) { defaultProps[shorthands[key] || key] = defaultProps[key] } } let initialTheme: any export function createComponent< ComponentPropTypes extends Object = {}, Ref = TamaguiElement, BaseProps = never >(configIn: Partial<StaticConfig> | StaticConfigParsed, ParentComponent?: StylableComponent) { const staticConfig = (() => { const config = extendStaticConfig(configIn, ParentComponent) if ('parsed' in config) { return config } else { return parseStaticConfig(config) } })() const defaultComponentClassName = `is_${staticConfig.componentName}` let tamaguiConfig: TamaguiInternalConfig let AnimatedText: any let AnimatedView: any let avoidClasses = true let defaultNativeStyle: any let defaultNativeStyleSheet: StyleSheet.NamedStyles<{ base: {} }> let tamaguiDefaultProps: any let initialSplitStyles: SplitStyleResult function addPseudoToStyles(styles: any[], name: string, pseudos: any) { // on web use pseudo object { hoverStyle } to keep specificity with concatClassName const pseudoStyle = pseudos[name] const shouldNestObject = isWeb && name !== 'enterStyle' && name !== 'exitStyle' const defaultPseudoStyle = initialSplitStyles.pseudos[name] if (defaultPseudoStyle) { styles.push(shouldNestObject ? { [name]: defaultPseudoStyle } : defaultPseudoStyle) } if (pseudoStyle) { styles.push(shouldNestObject ? { [name]: pseudoStyle } : pseudoStyle) } } // see onConfiguredOnce below which attaches a name then to this component const component = forwardRef<Ref, ComponentPropTypes>((propsIn: any, forwardedRef) => { // React inserts default props after your props for some reason... order important const props = tamaguiDefaultProps && !propsIn.asChild ? { ...tamaguiDefaultProps, ...propsIn } : propsIn const { Component, isText, isZStack } = staticConfig const componentName = props.componentName || staticConfig.componentName const componentClassName = props.asChild ? '' : props.componentName ? `is_${props.componentName}` : defaultComponentClassName if (process.env.NODE_ENV === 'development') { if (props['debug']) { // prettier-ignore console.log('⚠️', componentName || Component?.displayName || Component?.name || '[Unnamed Component]', 'debug on') // keep separate react native warn touches every value on prop causing weird behavior console.log('props in:', { propsIn, props, ordered: Object.keys(props) }) if (props['debug'] === 'break') debugger } } const forceUpdate = useForceUpdate() const theme = useTheme(props.theme, componentName, props, forceUpdate) const [state, set_] = useState<TamaguiComponentState>(defaultComponentState) const setStateShallow = createShallowUpdate(set_) const shouldAvoidClasses = !!(props.animation && avoidClasses) const splitStyles = useSplitStyles( props, staticConfig, theme, !shouldAvoidClasses ? { ...state, dynamicStylesInline: true, } : { ...state, noClassNames: true, dynamicStylesInline: true, resolveVariablesAs: 'value', }, shouldAvoidClasses || props.asChild ? null : initialSplitStyles.classNames ) const { viewProps: viewPropsIn, pseudos, medias, style, classNames } = splitStyles const useAnimations = tamaguiConfig.animations?.useAnimations as UseAnimationHook | undefined const isAnimated = !!(useAnimations && props.animation) const hasEnterStyle = !!props.enterStyle const hostRef = useRef<HTMLElement | View>(null) const animationFeatureStylesIn = props.animation ? { ...defaultNativeStyle, ...style } : null const features = useFeatures(props, { forceUpdate, setStateShallow, useAnimations, state, style: animationFeatureStylesIn, pseudos, staticConfig, theme, hostRef, onDidAnimate: props.onDidAnimate, }) const { tag, hitSlop, asChild, children, onPress, onPressIn, onPressOut, onHoverIn, onHoverOut, space: spaceProp, spaceDirection: _spaceDirection, disabled: disabledProp, onMouseDown, onMouseEnter, onMouseLeave, hrefAttrs, separator, // ignore from here on out // for next/link compat etc // @ts-ignore onClick, theme: _themeProp, // @ts-ignore defaultVariants, ...nonTamaguiProps } = viewPropsIn // get the right component const isTaggable = !Component || typeof Component === 'string' const hasTextAncestor = isWeb ? useContext(TextAncestorContext) : false // default to tag, fallback to component (when both strings) const element = isWeb ? (isTaggable ? tag || Component : Component) : Component const BaseTextComponent = !isWeb ? Text : element || 'span' const BaseViewComponent = !isWeb ? View : element || (hasTextAncestor ? 'span' : 'div') let elementType = isText ? (isAnimated ? AnimatedText || Text : null) || BaseTextComponent : (isAnimated ? AnimatedView || View : null) || BaseViewComponent elementType = Component || elementType const isStringElement = typeof elementType === 'string' const disabled = (props.accessibilityState != null && props.accessibilityState.disabled === true) || props.accessibilityDisabled // these can ultimately be for DOM, react-native-web views, or animated views // so the type is pretty loose let viewProps: Record<string, any> // if react-native-web view just pass all props down if (isWeb && !staticConfig.isReactNativeWeb) { // otherwise replicate react-native-web functionality const { // event props onMoveShouldSetResponder, onMoveShouldSetResponderCapture, onResponderEnd, onResponderGrant, onResponderMove, onResponderReject, onResponderRelease, onResponderStart, onResponderTerminate, onResponderTerminationRequest, onScrollShouldSetResponder, onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder, onStartShouldSetResponderCapture, // react-native props nativeID, // react-native-web accessibility props // @ts-ignore accessibilityActiveDescendant, // @ts-ignore accessibilityAtomic, // @ts-ignore accessibilityAutoComplete, // @ts-ignore accessibilityBusy, // @ts-ignore accessibilityChecked, // @ts-ignore accessibilityColumnCount, // @ts-ignore accessibilityColumnIndex, // @ts-ignore accessibilityColumnSpan, // @ts-ignore accessibilityControls, // @ts-ignore accessibilityCurrent, // @ts-ignore accessibilityDescribedBy, // @ts-ignore accessibilityDetails, // @ts-ignore accessibilityDisabled, // @ts-ignore accessibilityErrorMessage, // @ts-ignore accessibilityExpanded, // @ts-ignore accessibilityFlowTo, // @ts-ignore accessibilityHasPopup, // @ts-ignore accessibilityHidden, // @ts-ignore accessibilityInvalid, // @ts-ignore accessibilityKeyShortcuts, // @ts-ignore accessibilityLabel, // @ts-ignore accessibilityLabelledBy, // @ts-ignore accessibilityLevel, // @ts-ignore accessibilityLiveRegion, // @ts-ignore accessibilityModal, // @ts-ignore accessibilityMultiline, // @ts-ignore accessibilityMultiSelectable, // @ts-ignore accessibilityOrientation, // @ts-ignore accessibilityOwns, // @ts-ignore accessibilityPlaceholder, // @ts-ignore accessibilityPosInSet, // @ts-ignore accessibilityPressed, // @ts-ignore accessibilityReadOnly, // @ts-ignore accessibilityRequired, // @ts-ignore accessibilityRole, // @ts-ignore accessibilityRoleDescription, // @ts-ignore accessibilityRowCount, // @ts-ignore accessibilityRowIndex, // @ts-ignore accessibilityRowSpan, // @ts-ignore accessibilitySelected, // @ts-ignore accessibilitySetSize, // @ts-ignore accessibilitySort, // @ts-ignore accessibilityValueMax, // @ts-ignore accessibilityValueMin, // @ts-ignore accessibilityValueNow, // @ts-ignore accessibilityValueText, // deprecated accessible, accessibilityState, accessibilityValue, // android collapsable, focusable, onLayout, ...webProps } = nonTamaguiProps viewProps = webProps assignNativePropsToWeb(elementType, viewProps, nonTamaguiProps) if (!asChild) { rnw.useElementLayout(hostRef, onLayout) // from react-native-web rnw.useResponderEvents(hostRef, { onMoveShouldSetResponder, onMoveShouldSetResponderCapture, onResponderEnd, onResponderGrant, onResponderMove, onResponderReject, onResponderRelease, onResponderStart, onResponderTerminate, onResponderTerminationRequest, onScrollShouldSetResponder, onScrollShouldSetResponderCapture, onSelectionChangeShouldSetResponder, onSelectionChangeShouldSetResponderCapture, onStartShouldSetResponder, onStartShouldSetResponderCapture, }) } // from react-native-web const platformMethodsRef = rnw.usePlatformMethods(viewProps) const setRef = rnw.useMergeRefs(hostRef, platformMethodsRef, forwardedRef) if (!isAnimated) { // @ts-ignore viewProps.ref = setRef } else { if (forwardedRef) { // @ts-ignore viewProps.ref = forwardedRef } } if (props.href != null && hrefAttrs != null) { const { download, rel, target } = hrefAttrs if (download != null) { viewProps.download = download } if (rel != null) { viewProps.rel = rel } if (typeof target === 'string') { viewProps.target = target.charAt(0) !== '_' ? '_' + target : target } } const role = viewProps.role // FOCUS // "focusable" indicates that an element may be a keyboard tab-stop. const _focusable = focusable != null ? focusable : accessible if (_focusable === false) { viewProps.tabIndex = '-1' } if ( // These native elements are focusable by default elementType === 'a' || elementType === 'button' || elementType === 'input' || elementType === 'select' || elementType === 'textarea' ) { if (_focusable === false || accessibilityDisabled === true) { viewProps.tabIndex = '-1' } } else if ( // These roles are made focusable by default role === 'button' || role === 'checkbox' || role === 'link' || role === 'radio' || role === 'textbox' || role === 'switch' ) { if (_focusable !== false) { viewProps.tabIndex = '0' } } else { // Everything else must explicitly set the prop if (_focusable === true) { viewProps.tabIndex = '0' } } } else { viewProps = nonTamaguiProps if (forwardedRef) { // @ts-ignore viewProps.ref = forwardedRef } } // from react-native-web if (process.env.NODE_ENV === 'development' && !isText && isWeb) { Children.toArray(props.children).forEach((item) => { if (typeof item === 'string') { console.error(`Unexpected text node: ${item}. A text node cannot be a child of a <View>.`) } }) } // isMounted const internal = useRef<{ isMounted: boolean }>() if (!internal.current) { internal.current = { isMounted: true, } } useIsomorphicLayoutEffect(() => { // we need to use state to properly have mounted go from false => true if (typeof window !== 'undefined' && (hasEnterStyle || props.animation)) { // for SSR we never set mounted, ensuring enterStyle={{}} is set by default setStateShallow({ mounted: true, }) } internal.current!.isMounted = true return () => { mouseUps.delete(unPress) internal.current!.isMounted = false } }, [hasEnterStyle, props.animation]) let styles: any[] const animationStyles = state.animation ? state.animation.style : null if (isStringElement && shouldAvoidClasses) { styles = { ...defaultNativeStyle, ...(animationStyles ?? style), ...medias, } } else { styles = [ isWeb ? null : defaultNativeStyleSheet ? (defaultNativeStyleSheet.base as ViewStyle) : null, // parity w react-native-web, only for text in text // TODO this should be able to be done w css to replicate after extraction: // (.text .text { display: inline-flex; }) (but if they set display we'd need stronger precendence) // isText && hasTextAncestor && isWeb ? { display: 'inline-flex' } : null, animationStyles ?? style, medias, ] if (!animationStyles) { !state.mounted && addPseudoToStyles(styles, 'enterStyle', pseudos) state.hover && addPseudoToStyles(styles, 'hoverStyle', pseudos) state.focus && addPseudoToStyles(styles, 'focusStyle', pseudos) state.press && addPseudoToStyles(styles, 'pressStyle', pseudos) } } if (isWeb) { const fontFamilyName = isText ? props.fontFamily || staticConfig.defaultProps.fontFamily : null const fontFamily = fontFamilyName && fontFamilyName[0] === '$' ? fontFamilyName.slice(1) : null const classList = [ componentName ? componentClassName : '', fontFamily ? `font_${fontFamily}` : '', theme.className, classNames ? Object.values(classNames).join(' ') : '', ] if (!shouldAvoidClasses) { if (classNames) { classList.push(Object.values(classNames).join(' ')) } // TODO restore this to isText classList // hasTextAncestor === true && cssText.textHasAncestor, // TODO MOVE TO VARIANTS [number] [any] // numberOfLines != null && numberOfLines > 1 && cssText.textMultiLine, } const className = classList.join(' ') const style = animationStyles ?? splitStyles.style if (process.env.NODE_ENV === 'development' && props['debug']) { // prettier-ignore console.log(' » className', { splitStyles, style, isStringElement, pseudos, state, classNames, propsClassName: props.className, classList, className: className.trim().split(' '), themeClassName: theme.className, values: Object.fromEntries(Object.entries(classNames).map(([k, v]) => [v, getAllSelectors()[v]])) }) } if (staticConfig.isReactNativeWeb) { viewProps.dataSet = { ...viewProps.dataSet, className: className, } } else { viewProps.className = className } viewProps.style = style } else { viewProps.style = styles } // TODO need to loop active variants and see if they have matchin pseudos and apply as well const initialPseudos = initialSplitStyles.pseudos const attachPress = !!( (pseudos && pseudos.pressStyle) || (initialPseudos && initialPseudos.pressStyle) || onPress || onPressOut || onPressIn || onClick ) const isTouch = useIsTouchDevice() const isHoverable = isWeb && !isTouch const attachHover = isHoverable && !!((pseudos && pseudos.hoverStyle) || onHoverIn || onHoverOut || onMouseEnter || onMouseLeave) const handlesPressEvents = !isStringElement && !asChild const pressKey = handlesPressEvents ? 'onPress' : 'onClick' const pressInKey = handlesPressEvents ? 'onPressIn' : 'onMouseDown' const pressOutKey = handlesPressEvents ? 'onPressOut' : 'onMouseUp' // check presence to prevent reparenting bugs, allows for onPress={x ? function : undefined} usage // while avoiding reparenting... // once proper reparenting is supported, we can remove this and use that... const shouldAttach = !asChild && (attachPress || attachHover || 'pressStyle' in props || 'onPress' in props || 'onPressIn' in props || 'onPressOut' in props || (isWeb && ('hoverStyle' in props || 'onHoverIn' in props || 'onHoverOut' in props || 'onMouseEnter' in props || 'onMouseLeave' in props))) const unPress = useCallback(() => { if (!internal.current!.isMounted) return setStateShallow({ press: false, pressIn: false, }) }, []) const events = shouldAttach ? { [pressOutKey]: attachPress ? (e) => { unPress() onPressOut?.(e) } : undefined, ...(isHoverable && { onMouseEnter: attachHover ? (e) => { let next: Partial<typeof state> = {} if (attachHover) { next.hover = true } if (state.pressIn) { next.press = true } if (Object.keys(next).length) { setStateShallow(next) } onHoverIn?.(e) onMouseEnter?.(e) } : undefined, onMouseLeave: attachHover ? (e) => { let next: Partial<typeof state> = {} mouseUps.add(unPress) if (attachHover) { next.hover = false } if (state.pressIn) { next.press = false next.pressIn = false } if (Object.keys(next).length) { setStateShallow(next) } onHoverOut?.(e) onMouseLeave?.(e) } : undefined, }), [pressInKey]: attachPress ? (e) => { setStateShallow({ press: true, pressIn: true, }) onPressIn?.(e) onMouseDown?.(e) if (isWeb) { mouseUps.add(unPress) } } : null, [pressKey]: attachPress ? (e) => { unPress() onClick?.(e) onPress?.(e) } : null, } : null let space = spaceProp // find space by media query if (features.enabled.mediaQuery) { for (const key in mediaState) { if (!mediaState[key]) continue if (props[key] && props[key].space !== undefined) { space = props[key].space } } } let childEls = !children || asChild ? children : wrapThemeManagerContext( spacedChildren({ separator, children, space, direction: props.spaceDirection || 'both', isZStack, }), getThemeManagerIfChanged(theme) ) let content: any if (asChild) { elementType = Slot viewProps = { ...viewProps, onPress, onPressIn, onPressOut, } } // EVENTS: web if (isWeb) { const [pressableProps] = usePressable( events ? { disabled, ...(hitSlop && { hitSlop, }), onPressOut: events[pressOutKey], onPressIn: events[pressInKey], onPress: events[pressKey], } : { disabled: true, } ) if (events) { if (handlesPressEvents) { Object.assign(viewProps, pressableProps) } else { Object.assign(viewProps, events) } } } // add focus events if (process.env.TAMAGUI_TARGET === 'native') { const attachFocus = !!( (pseudos && pseudos.focusStyle) || (initialPseudos && initialPseudos.focusStyle) ) if (attachFocus) { viewProps.onFocus = mergeEvent(viewProps.onFocus, () => { setStateShallow({ focus: true }) }) viewProps.onBlur = mergeEvent(viewProps.onBlur, () => { setStateShallow({ focus: false }) }) } } content = createElement(elementType, viewProps, childEls) // EVENTS native // native just wrap in <Pressable /> if (process.env.TAMAGUI_TARGET === 'native') { if (attachPress && events) { content = ( <TouchableWithoutFeedback onPressIn={events[pressInKey]} onPress={events[pressKey]} onPressOut={events[pressOutKey]} > {content} </TouchableWithoutFeedback> ) } } if (isWeb && events && attachHover) { content = ( <span className="tui_Hoverable" style={{ display: 'contents', }} onMouseEnter={events.onMouseEnter} onMouseLeave={events.onMouseLeave} > {content} </span> ) } if (process.env.NODE_ENV === 'development') { if (props['debug']) { // prettier-ignore console.log(' » ', { propsIn: { ...props }, propsOut: { ...viewProps }, state, splitStyles, animationStyles, isStringElement, classNamesIn: props.className?.split(' '), classNamesOut: viewProps.className?.split(' '), events, shouldAttach, ViewComponent: elementType, viewProps, styles, pseudos, content, childEls, shouldAvoidClasses, avoidClasses, animation: props.animation, style, defaultNativeStyle, initialSplitStyles, ...(typeof window !== 'undefined' ? { theme, themeClassName: theme.className, staticConfig, tamaguiConfig } : null) }) } } if (features.elements.length) { return ( <> {features.elements} {content} </> ) } return content }) component.displayName = staticConfig.componentName // Once configuration is run and all components are registered // get default props + className and analyze styles onConfiguredOnce((conf) => { if (process.env.IS_STATIC === 'is_static') { // in static mode we just use these to lookup configuration return } tamaguiConfig = conf // do this to make sure shorthands don't duplicate with.. longhands mergeShorthands(staticConfig, tamaguiConfig) avoidClasses = !!tamaguiConfig.animations?.avoidClasses AnimatedText = tamaguiConfig.animations?.Text AnimatedView = tamaguiConfig?.animations?.View initialTheme = initialTheme || proxyThemeVariables(conf.themes[conf.defaultTheme || Object.keys(conf.themes)[0]]) initialSplitStyles = insertSplitStyles(staticConfig.defaultProps, staticConfig, initialTheme, { mounted: true, hover: false, press: false, pressIn: false, focus: false, resolveVariablesAs: 'both', keepVariantsAsProps: true, }) // this ruins the prop order!!! // can't believe it but it puts default props after props? const defaults = { ...component.defaultProps, ...initialSplitStyles.viewProps, } defaultNativeStyle = {} const validStyles = staticConfig.validStyles || stylePropsView // split - keep variables on props to be processed using theme values at runtime (native) for (const key in staticConfig.defaultProps) { const val = staticConfig.defaultProps[key] if ((typeof val === 'string' && val[0] === '$') || !validStyles[key]) { defaults[key] = val } else { defaultNativeStyle[key] = val } } defaultNativeStyleSheet = StyleSheet.create({ base: defaultNativeStyle, }) if (Object.keys(defaults).length) { tamaguiDefaultProps = defaults } // add debug logs if (process.env.NODE_ENV === 'development' && staticConfig.defaultProps?.debug) { if (process.env.IS_STATIC !== 'is_static') { console.log(`🐛 [${staticConfig.componentName || 'Component'}]`, { staticConfig, initialSplitStyles, tamaguiDefaultProps, defaultNativeStyle, defaults, }) } } }) let res: TamaguiComponent<ComponentPropTypes, Ref, BaseProps> = component as any if (configIn.memo) { res = memo(res) as any } res.staticConfig = { validStyles: staticConfig.validStyles || stylePropsView, ...staticConfig, } // res.extractable HoC res.extractable = (Component: any, conf?: Partial<StaticConfig>) => { Component.staticConfig = extendStaticConfig( { Component, ...conf, neverFlatten: true, isExtractable: true, defaultProps: { ...Component.defaultProps, ...conf?.defaultProps, }, }, res ) return Component } return res } // for elements to avoid spacing export const Unspaced = (props: { children?: any }) => { return props.children } Unspaced['isUnspaced'] = true // dont used styled() here to avoid circular deps // keep inline to avoid circular deps type SpaceDirection = 'vertical' | 'horizontal' export type SpacerProps = Omit<StackProps, 'flex' | 'direction'> & { size?: number | SpaceTokens flex?: boolean | number direction?: SpaceDirection } export const Spacer = createComponent<SpacerProps>({ memo: true, componentName: 'Spacer', validStyles, defaultProps: { ...stackDefaultStyles, size: true, }, variants: { size: { '...size': (size, { tokens }) => { size = size == true ? '$true' : size const sizePx = tokens.space[size] ?? size return { width: sizePx, height: sizePx, minWidth: sizePx, minHeight: sizePx, } }, }, flex: { true: { flexGrow: 1, }, }, direction: { horizontal: { height: 0, minHeight: 0, }, vertical: { width: 0, minWidth: 0, }, }, }, defaultVariants: { direction: 'horizontal', }, }) export type SpacedChildrenProps = { isZStack?: boolean children?: any space?: any spaceFlex?: boolean | number direction?: SpaceFlexDirection separator?: React.ReactNode } export function spacedChildren({ isZStack, children, space, direction, spaceFlex, separator, }: SpacedChildrenProps) { const hasSpace = !!(space || spaceFlex) const hasSeparator = !(separator === undefined || separator === null) if (!hasSpace && !hasSeparator) { return children } const childrenList = Children.toArray(children) if (childrenList.length <= 1) { return childrenList } const final: any[] = [] for (const [index, child] of childrenList.entries()) { const isEmpty = child === null || child === undefined || child === false || (Array.isArray(child) && child.length === 0) // push them all, but wrap some in Fragment if (isEmpty || !child || (child['key'] && !isZStack)) { final.push(child) } else { final.push( <Fragment key={index}>{isZStack ? <AbsoluteFill>{child}</AbsoluteFill> : child}</Fragment> ) } const next = childrenList[index + 1] if (next && !isUnspaced(next)) { if (separator) { if (hasSpace) { final.push( createSpacer({ key: `_${index}_before_sep_spacer`, direction, space, spaceFlex, }) ) } final.push( React.isValidElement(separator) ? React.cloneElement(separator, { key: `sep_${index}` }) : separator ) if (hasSpace) { final.push( createSpacer({ key: `_${index}_after_sep_spacer`, direction, space, spaceFlex, }) ) } } else { final.push( createSpacer({ key: `_${index}_spacer`, direction, space, spaceFlex, }) ) } } } return final } type CreateSpacerProps = SpacedChildrenProps & { key: string } function createSpacer({ key, direction, space, spaceFlex }: CreateSpacerProps) { return ( <Spacer key={key} direction={ direction === 'both' ? undefined : direction === 'row' || direction === 'row-reverse' ? 'horizontal' : 'vertical' } size={space} {...(spaceFlex && { flex: spaceFlex, })} /> ) } function isUnspaced(child: any) { return child?.['type']?.['isVisuallyHidden'] || child?.['type']?.['isUnspaced'] } export function AbsoluteFill(props: any) { return isWeb ? ( <div style={ { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, } as any } > {props.children} </div> ) : ( <View style={StyleSheet.absoluteFill}>{props.child}</View> ) } // this can be done with CSS entirely right? // const shouldWrapTextAncestor = isWeb && isText && !hasTextAncestor // if (shouldWrapTextAncestor) { // // from react-native-web // content = createElement(TextAncestorContext.Provider, { value: true }, content) // } function processIDRefList(idRefList: string | Array<string>): string { return Array.isArray(idRefList) ? idRefList.join(' ') : idRefList } const accessibilityRoleToWebRole = { adjustable: 'slider', button: 'button', header: 'heading', image: 'img', imagebutton: null, keyboardkey: null, label: null, link: 'link', none: 'presentation', search: 'search', summary: 'region', text: null, } // adapted from react-native-web export function assignNativePropsToWeb(elementType: string, viewProps: any, nativeProps: any) { if (!viewProps.role && nativeProps.accessibilityRole) { if (nativeProps.accessibilityRole === 'none') { viewProps.role = 'presentation' } else { const webRole = accessibilityRoleToWebRole[nativeProps.accessibilityRole] if (webRole != null) { viewProps.role = webRole || nativeProps.accessibilityRole } } } if (nativeProps.accessibilityActiveDescendant != null) { viewProps['aria-activedescendant'] = nativeProps.accessibilityActiveDescendant } if (nativeProps.accessibilityAtomic != null) { viewProps['aria-atomic'] = nativeProps.accessibilityAtomic } if (nativeProps.accessibilityAutoComplete != null) { viewProps['aria-autocomplete'] = nativeProps.accessibilityAutoComplete } if (nativeProps.accessibilityBusy != null) { viewProps['aria-busy'] = nativeProps.accessibilityBusy } if (nativeProps.accessibilityChecked != null) { viewProps['aria-checked'] = nativeProps.accessibilityChecked } if (nativeProps.accessibilityColumnCount != null) { viewProps['aria-colcount'] = nativeProps.accessibilityColumnCount } if (nativeProps.accessibilityColumnIndex != null) { viewProps['aria-colindex'] = nativeProps.accessibilityColumnIndex } if (nativeProps.accessibilityColumnSpan != null) { viewProps['aria-colspan'] = nativeProps.accessibilityColumnSpan } if (nativeProps.accessibilityControls != null) { viewProps['aria-controls'] = processIDRefList(nativeProps.accessibilityControls) } if (nativeProps.accessibilityCurrent != null) { viewProps['aria-current'] = nativeProps.accessibilityCurrent } if (nativeProps.accessibilityDescribedBy != null) { viewProps['aria-describedby'] = processIDRefList(nativeProps.accessibilityDescribedBy) } if (nativeProps.accessibilityDetails != null) { viewProps['aria-details'] = nativeProps.accessibilityDetails } if (nativeProps.disabled === true) { viewProps['aria-disabled'] = true // Enhance with native semantics if ( elementType === 'button' || elementType === 'form' || elementType === 'input' || elementType === 'select' || elementType === 'textarea' ) { viewProps.disabled = true } } if (nativeProps.accessibilityErrorMessage != null) { viewProps['aria-errormessage'] = nativeProps.accessibilityErrorMessage } if (nativeProps.accessibilityExpanded != null) { viewProps['aria-expanded'] = nativeProps.accessibilityExpanded } if (nativeProps.accessibilityFlowTo != null) { viewProps['aria-flowto'] = processIDRefList(nativeProps.accessibilityFlowTo) } if (nativeProps.accessibilityHasPopup != null) { viewProps['aria-haspopup'] = nativeProps.accessibilityHasPopup } if (nativeProps.accessibilityHidden === true) { viewProps['aria-hidden'] = nativeProps.accessibilityHidden } if (nativeProps.accessibilityInvalid != null) { viewProps['aria-invalid'] = nativeProps.accessibilityInvalid } if ( nativeProps.accessibilityKeyShortcuts != null && Array.isArray(nativeProps.accessibilityKeyShortcuts) ) { viewProps['aria-keyshortcuts'] = nativeProps.accessibilityKeyShortcuts.join(' ') } if (nativeProps.accessibilityLabel != null) { viewProps['aria-label'] = nativeProps.accessibilityLabel } if (nativeProps.accessibilityLabelledBy != null) { viewProps['aria-labelledby'] = processIDRefList(nativeProps.accessibilityLabelledBy) } if (nativeProps.accessibilityLevel != null) { viewProps['aria-level'] = nativeProps.accessibilityLevel } if (nativeProps.accessibilityLiveRegion != null) { viewProps['aria-live'] = nativeProps.accessibilityLiveRegion === 'none' ? 'off' : nativeProps.accessibilityLiveRegion } if (nativeProps.accessibilityModal != null) { viewProps['aria-modal'] = nativeProps.accessibilityModal } if (nativeProps.accessibilityMultiline != null) { viewProps['aria-multiline'] = nativeProps.accessibilityMultiline } if (nativeProps.accessibilityMultiSelectable != null) { viewProps['aria-multiselectable'] = nativeProps.accessibilityMultiSelectable } if (nativeProps.accessibilityOrientation != null) { viewProps['aria-orientation'] = nativeProps.accessibilityOrientation } if (nativeProps.accessibilityOwns != null) { viewProps['aria-owns'] = processIDRefList(nativeProps.accessibilityOwns) } if (nativeProps.accessibilityPlaceholder != null) { viewProps['aria-placeholder'] = nativeProps.accessibilityPlaceholder } if (nativeProps.accessibilityPosInSet != null) { viewProps['aria-posinset'] = nativeProps.accessibilityPosInSet } if (nativeProps.accessibilityPressed != null) { viewProps['aria-pressed'] = nativeProps.accessibilityPressed } if (nativeProps.accessibilityReadOnly != null) { viewProps['aria-readonly'] = nativeProps.accessibilityReadOnly // Enhance with native semantics if (elementType === 'input' || elementType === 'select' || elementType === 'textarea') { viewProps.readOnly = true } } if (nativeProps.accessibilityRequired != null) { viewProps['aria-required'] = nativeProps.accessibilityRequired // Enhance with native semantics if (elementType === 'input' || elementType === 'select' || elementType === 'textarea') { viewProps.required = true } } if (nativeProps.accessibilityRoleDescription != null) { viewProps['aria-roledescription'] = nativeProps.accessibilityRoleDescription } if (nativeProps.accessibilityRowCount != null) { viewProps['aria-rowcount'] = nativeProps.accessibilityRowCount } if (nativeProps.accessibilityRowIndex != null) { viewProps['aria-rowindex'] = nativeProps.accessibilityRowIndex } if (nativeProps.accessibilityRowSpan != null) { viewProps['aria-rowspan'] = nativeProps.accessibilityRowSpan } if (nativeProps.accessibilitySelected != null) { viewProps['aria-selected'] = nativeProps.accessibilitySelected } if (nativeProps.accessibilitySetSize != null) { viewProps['aria-setsize'] = nativeProps.accessibilitySetSize } if (nativeProps.accessibilitySort != null) { viewProps['aria-sort'] = nativeProps.accessibilitySort } if (nativeProps.accessibilityValueMax != null) { viewProps['aria-valuemax'] = nativeProps.accessibilityValueMax } if (nativeProps.accessibilityValueMin != null) { viewProps['aria-valuemin'] = nativeProps.accessibilityValueMin } if (nativeProps.accessibilityValueNow != null) { viewProps['aria-valuenow'] = nativeProps.accessibilityValueNow } if (nativeProps.accessibilityValueText != null) { viewProps['aria-valuetext'] = nativeProps.accessibilityValueText } if (nativeProps.nativeID) { viewProps.id = nativeProps.nativeID } }
the_stack
declare module '~request~form-data/lib/form_data' { class FormData { static LINE_BREAK: string; static DEFAULT_CONTENT_TYPE: string; append (key: string, value: any, options?: string | FormData.Options): FormData; getHeaders <T> (userHeaders?: T): T & FormData.Headers; getCustomHeaders (contentType?: string): FormData.CustomHeaders; getBoundary (): string; getLengthSync (): number; getLength (cb: (error: Error, length?: number) => any): void; submit (params: string | Object, cb: (error: Error, response?: any) => any): any; pipe <T> (to: T): T; } module FormData { export interface Options { filename: string; } export interface Headers { 'content-type': string; } export interface CustomHeaders extends Headers { 'content-length': string; } } export = FormData; } // Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-tough-cookie/3e37dc2e6d448130d2fa4be1026e195ffda2b398/lib/cookie.d.ts declare module '~request~tough-cookie/lib/cookie' { /** * Parse a cookie date string into a Date. Parses according to RFC6265 * Section 5.1.1, not Date.parse(). */ export function parseDate (date: string): Date; /** * Format a Date into a RFC1123 string (the RFC6265-recommended format). */ export function formatDate (date: Date): string; /** * Transforms a domain-name into a canonical domain-name. The canonical domain-name * is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded * domain-name (Section 5.1.2 of RFC6265). For the most part, this function is * idempotent (can be run again on its output without ill effects). */ export function canonicalDomain (domain: string): string; /** * Answers "does this real domain match the domain in a cookie?". The str is the * "current" domain-name and the domStr is the "cookie" domain-name. Matches * according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". * * The canonicalize parameter will run the other two paramters through canonicalDomain or not. */ export function domainMatch (str: string, domStr: string, canonicalize?: boolean): boolean; /** * Given a current request/response path, gives the Path apropriate for storing in * a cookie. This is basically the "directory" of a "file" in the path, but is * specified by Section 5.1.4 of the RFC. * * The path parameter MUST be only the pathname part of a URI (i.e. excludes the hostname, * query, fragment, etc.). This is the .pathname property of node's uri.parse() output. */ export function defaultPath (path: string): string; /** * Answers "does the request-path path-match a given cookie-path?" as * per RFC6265 Section 5.1.4. Returns a boolean. * * This is essentially a prefix-match where cookiePath is a prefix of reqPath. */ export function pathMatch (reqPath: string, cookiePath: string): boolean; /** * alias for Cookie.parse(cookieString[, options]) */ export function parse (cookieString: string, options?: CookieParseOptions): Cookie; /** * alias for Cookie.fromJSON(string) */ export function fromJSON (json: string): Cookie; /** * Returns the public suffix of this hostname. The public suffix is the shortest * domain-name upon which a cookie can be set. Returns null if the hostname cannot * have cookies set for it. * * For example: www.example.com and www.subdomain.example.com both have public suffix example.com. * * For further information, see http://publicsuffix.org/. This module derives its list from that site. */ export function getPublicSuffix (hostname: string): string; /** * For use with .sort(), sorts a list of cookies into the recommended order * given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: * - Longest .path * - oldest .creation (which has a 1ms precision, same as Date) * - lowest .creationIndex (to get beyond the 1ms precision) * * ``` * var cookies = [ \/* unsorted array of Cookie objects *\/ ]; * cookies = cookies.sort(cookieCompare); * ``` * * Note: Since JavaScript's Date is limited to a 1ms precision, cookies within * the same milisecond are entirely possible. This is especially true when using * the now option to .setCookie(). The .creationIndex property is a per-process * global counter, assigned during construction with new Cookie(). This preserves * the spirit of the RFC sorting: older cookies go first. This works great for * MemoryCookieStore, since Set-Cookie headers are parsed in order, but may not * be so great for distributed systems. Sophisticated Stores may wish to set this * to some other logical clock such that if cookies A and B are created in the * same millisecond, but cookie A is created before cookie B, then * A.creationIndex < B.creationIndex. If you want to alter the global counter, * which you probably shouldn't do, it's stored in Cookie.cookiesCreated. */ export function cookieCompare (a: Cookie, b: Cookie): number; /** * Generates a list of all possible domains that domainMatch() the parameter. * May be handy for implementing cookie stores. */ export function permuteDomain (domain: string): string[]; /** * Generates a list of all possible paths that pathMatch() the parameter. * May be handy for implementing cookie stores. */ export function permutePath (path: string): string[]; /** * Base class for CookieJar stores. Available as tough.Store. */ export class Store { // TODO(blakeembrey): Finish this. // https://github.com/SalesforceEng/tough-cookie#store } /** * A just-in-memory CookieJar synchronous store implementation, used by default. * Despite being a synchronous implementation, it's usable with both the * synchronous and asynchronous forms of the CookieJar API. */ export class MemoryCookieStore extends Store {} /** * Exported via tough.Cookie. */ export class Cookie { /** * Parses a single Cookie or Set-Cookie HTTP header into a Cookie object. Returns * undefined if the string can't be parsed. * * The options parameter is not required and currently has only one property: * * - loose - boolean - if true enable parsing of key-less cookies like =abc and =, which are not RFC-compliant. * If options is not an object, it is ignored, which means you can use Array#map with it. * * Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: * * ``` * if (res.headers['set-cookie'] instanceof Array) * cookies = res.headers['set-cookie'].map(Cookie.parse); * else * cookies = [Cookie.parse(res.headers['set-cookie'])]; * ``` */ static parse (cookieString: string, options?: CookieParseOptions): Cookie; /** * the name or key of the cookie (default "") */ key: string; /** * the value of the cookie (default "") */ value: string; /** * if set, the Expires= attribute of the cookie (defaults to the string "Infinity"). * See setExpires() */ expires: Date; /** * (seconds) if set, the Max-Age= attribute in seconds of the cookie. May also * be set to strings "Infinity" and "-Infinity" for non-expiry and immediate-expiry, * respectively. See setMaxAge() */ maxAge: number; /** * the Domain= attribute of the cookie */ domain: string; /** * the Path= of the cookie */ path: string; /** * the Secure cookie flag */ secure: boolean; /** * the HttpOnly cookie flag */ httpOnly: boolean; /** * any unrecognized cookie attributes as strings (even if equal-signs inside) */ extensions: string[]; /** * when this cookie was constructed */ creation: Date; /** * set at construction, used to provide greater sort precision * (please see cookieCompare(a,b) for a full explanation) */ creationIndex: number; /** * is this a host-only cookie (i.e. no Domain field was set, but was instead implied) */ hostOnly: boolean; /** * if true, there was no Path field on the cookie and defaultPath() was used to derive one. */ pathIsDefault: boolean; /** * last time the cookie got accessed. Will affect cookie cleaning once * implemented. Using cookiejar.getCookies(...) will update this attribute. */ lastAccessed: Date; /** * encode to a Set-Cookie header value. The Expires cookie field is set * using formatDate(), but is omitted entirely if .expires is Infinity. */ toString (): string; /** * encode to a Cookie header value (i.e. the .key and .value properties joined with '='). */ cookieString (): string; /** * sets the expiry based on a date-string passed through parseDate(). If parseDate * returns null (i.e. can't parse this date string), .expires is set to "Infinity" (a string) is set. */ setExpires (expires: string): void; /** * sets the maxAge in seconds. Coerces -Infinity to "-Infinity" and * Infinity to "Infinity" so it JSON serializes correctly. */ setMaxAge (maxAge: number): void; /** * expiryTime() Computes the absolute unix-epoch milliseconds that this cookie * expires. expiryDate() works similarly, except it returns a Date object. Note * that in both cases the now parameter should be milliseconds. * * Max-Age takes precedence over Expires (as per the RFC). The .creation * attribute -- or, by default, the now paramter -- is used to offset the .maxAge attribute. * * If Expires (.expires) is set, that's returned. * * Otherwise, expiryTime() returns Infinity and expiryDate() returns a Date * object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be * expressed by a 32-bit time_t; the common limit for most user-agents). */ expiryTime (now?: number): number; expiryDate (now?: number): Date; /** * compute the TTL relative to now (milliseconds). The same precedence rules * as for expiryTime/expiryDate apply. * * The "number" Infinity is returned for cookies without an explicit * expiry and 0 is returned if the cookie is expired. Otherwise a time-to-live * in milliseconds is returned. */ TTL (now?: number): number; /** * return the canonicalized .domain field. This is lower-cased and punycode * (RFC3490) encoded if the domain has any non-ASCII characters. */ cdomain (): string; canonicalizedDomain (): string; /** * For convenience in using JSON.serialize(cookie). Returns a plain-old Object that can be JSON-serialized. * * Any Date properties (i.e., .expires, .creation, and .lastAccessed) are * exported in ISO format (.toISOString()). * * NOTE: Custom Cookie properties will be discarded. In tough-cookie 1.x, since * there was no .toJSON method explicitly defined, all enumerable properties were * captured. If you want a property to be serialized, add the property name to * the Cookie.serializableProperties Array. */ toJSON (): Object; /** * Does the reverse of cookie.toJSON(). If passed a string, will JSON.parse() that first. * * Any Date properties (i.e., .expires, .creation, and .lastAccessed) are parsed * via Date.parse(), not the tough-cookie parseDate, since it's JavaScript/JSON-y * timestamps being handled at this layer. * * Returns null upon JSON parsing error. */ static fromJSON (json: string): Cookie; /** * Does a deep clone of this cookie, exactly implemented as Cookie.fromJSON(cookie.toJSON()). */ clone (): Cookie; } export interface CookieParseOptions { loose: boolean; } export interface SetCookieOptions { /** * default true - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. */ http?: boolean; /** * autodetect from url - indicates if this is a "Secure" API. If the currentUrl * starts with https: or wss: then this is defaulted to true, otherwise false. */ secure?: boolean; /** * default new Date() - what to use for the creation/access time of cookies */ now?: Date; /** * default false - silently ignore things like parse errors and invalid * domains. Store errors aren't ignored by this option. */ ignoreError?: boolean; } export interface GetCookieOptions { /** * default true - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. */ http?: boolean; /** * autodetect from url - indicates if this is a "Secure" API. If the currentUrl * starts with https: or wss: then this is defaulted to true, otherwise false. */ secure?: boolean; /** * default new Date() - what to use for the creation/access time of cookies */ now?: Date; /** * default true - perform expiry-time checking of cookies and asynchronously * remove expired cookies from the store. Using false will return expired cookies * and not remove them from the store (which is useful for replaying Set-Cookie headers, potentially). */ expire?: boolean; /** * default false - if true, do not scope cookies by path. The default uses * RFC-compliant path scoping. Note: may not be supported by the underlying * store (the default MemoryCookieStore supports it). */ allPaths?: boolean; } export interface CookieJarOptions { /** * default true - reject cookies with domains like "com" and "co.uk" */ rejectPublicSuffixes: boolean; /** * default false - accept malformed cookies like bar and =bar, which have an * implied empty name. This is not in the standard, but is used sometimes * on the web and is accepted by (most) browsers. */ looseMode: boolean; } /** * Simply use new CookieJar(). If you'd like to use a custom store, pass that * to the constructor otherwise a MemoryCookieStore will be created and used. */ export class CookieJar { enableLooseMode: boolean; rejectPublicSuffixes: boolean; constructor (store?: Store, options?: boolean | CookieJarOptions); /** * Attempt to set the cookie in the cookie jar. If the operation fails, an * error will be given to the callback cb, otherwise the cookie is passed * through. The cookie will have updated .creation, .lastAccessed and .hostOnly properties. */ setCookie (cookieOrString: string | Cookie, currentUrl: string, cb: (err: Error, cookie?: Cookie) => any): void; setCookie (cookieOrString: string | Cookie, currentUrl: string, options: SetCookieOptions, cb: (err: Error, cookie?: Cookie) => any): void; /** * Synchronous version of setCookie; only works with synchronous stores * (e.g. the default MemoryCookieStore). */ setCookieSync (cookieOrString: string | Cookie, currentUrl: string, options?: SetCookieOptions): void; /** * Retrieve the list of cookies that can be sent in a Cookie header for the current url. * * If an error is encountered, that's passed as err to the callback, otherwise * an Array of Cookie objects is passed. The array is sorted with cookieCompare() * unless the {sort:false} option is given. */ getCookies (currentUrl: string, cb: (err: Error, cookies?: Cookie[]) => any): void; getCookies (currentUrl: string, options: GetCookieOptions, cb: (err: Error, cookies?: Cookie[]) => any): void; /** * Synchronous version of getCookies; only works with synchronous stores * (e.g. the default MemoryCookieStore). */ getCookiesSync (currentUrl: string, options?: GetCookieOptions): Cookie[]; /** * Accepts the same options as .getCookies() but passes a string suitable * for a Cookie header rather than an array to the callback. Simply maps the * Cookie array via .cookieString(). */ getCookieString (currentUrl: string, cb: (err: Error, cookies?: string) => any): void; getCookieString (currentUrl: string, options: GetCookieOptions, cb: (err: Error, cookies?: string) => any): void; /** * Synchronous version of getCookieString; only works with synchronous stores * (e.g. the default MemoryCookieStore). */ getCookieStringSync (currentUrl: string, options?: GetCookieOptions): string; /** * Serialize the Jar if the underlying store supports .getAllCookies. * * NOTE: Custom Cookie properties will be discarded. If you want a property * to be serialized, add the property name to the Cookie.serializableProperties Array. * * See [Serialization Format]. */ serialize (cb: (error: Error, serializedObject: Object) => any): void; /** * Sync version of .serialize */ serializeSync (): Object; /** * Alias of .serializeSync() for the convenience of JSON.stringify(cookiejar). */ toJSON (): Object; /** * A new Jar is created and the serialized Cookies are added to the * underlying store. Each Cookie is added via store.putCookie in the order * in which they appear in the serialization. * * The store argument is optional, but should be an instance of Store. By * default, a new instance of MemoryCookieStore is created. * * As a convenience, if serialized is a string, it is passed through * JSON.parse first. If that throws an error, this is passed to the callback. */ static deserialize (serialized: string | Object, cb: (error: Error, object: Object) =>any): CookieJar; static deserialize (serialized: string | Object, store: Store, cb: (error: Error, object: Object) => any): CookieJar; /** * Sync version of .deserialize. Note that the store must be synchronous * for this to work. */ static deserializeSync (serialized: string | Object, store: Store): Object; /** * Alias of .deserializeSync to provide consistency with Cookie.fromJSON(). */ static fromJSON (string: string): Object; /** * Produces a deep clone of this jar. Modifications to the original won't * affect the clone, and vice versa. * * The store argument is optional, but should be an instance of Store. By * default, a new instance of MemoryCookieStore is created. Transferring * between store types is supported so long as the source implements * .getAllCookies() and the destination implements .putCookie(). */ clone (cb: (error: Error, newJar: CookieJar) => any): void; clone (store: Store, cb: (error: Error, newJar: CookieJar) => any): void; /** * Synchronous version of .clone, returning a new CookieJar instance. * * The store argument is optional, but must be a synchronous Store instance * if specified. If not passed, a new instance of MemoryCookieStore is used. * * The source and destination must both be synchronous Stores. If one or both * stores are asynchronous, use .clone instead. Recall that MemoryCookieStore * supports both synchronous and asynchronous API calls. */ cloneSync (store?: Store): CookieJar; } } // Generated by typings // Source: https://raw.githubusercontent.com/louy/typed-request/8dbbc8c9c3aee44d1ca00ac82a88a00f37198e1d/index.d.ts declare module 'request' { import {Stream} from 'stream'; import {Agent, ClientRequest, IncomingMessage} from 'http'; import * as FormData from '~request~form-data/lib/form_data'; import * as toughCookie from '~request~tough-cookie/lib/cookie'; var request: request.RequestAPI<request.Request, request.CoreOptions, request.RequiredUriUrl>; namespace request { export interface RequestAPI<TRequest extends Request, TOptions extends CoreOptions, TUriUrlOptions> { defaults(options: TOptions): RequestAPI<TRequest, TOptions, RequiredUriUrl>; defaults(options: RequiredUriUrl & TOptions): DefaultUriUrlRequestApi<TRequest, TOptions, OptionalUriUrl>; (uri: string, options?: TOptions, callback?: RequestCallback): TRequest; (uri: string, callback?: RequestCallback): TRequest; (options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; get(uri: string, options?: TOptions, callback?: RequestCallback): TRequest; get(uri: string, callback?: RequestCallback): TRequest; get(options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; post(uri: string, options?: TOptions, callback?: RequestCallback): TRequest; post(uri: string, callback?: RequestCallback): TRequest; post(options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; put(uri: string, options?: TOptions, callback?: RequestCallback): TRequest; put(uri: string, callback?: RequestCallback): TRequest; put(options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; head(uri: string, options?: TOptions, callback?: RequestCallback): TRequest; head(uri: string, callback?: RequestCallback): TRequest; head(options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; patch(uri: string, options?: TOptions, callback?: RequestCallback): TRequest; patch(uri: string, callback?: RequestCallback): TRequest; patch(options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; del(uri: string, options?: TOptions, callback?: RequestCallback): TRequest; del(uri: string, callback?: RequestCallback): TRequest; del(options: TUriUrlOptions & TOptions, callback?: RequestCallback): TRequest; forever(agentOptions: any, optionsArg: any): TRequest; jar(): CookieJar; cookie(str: string): Cookie; initParams: any; debug: boolean; } interface DefaultUriUrlRequestApi<TRequest extends Request, TOptions extends CoreOptions, TUriUrlOptions> extends RequestAPI<TRequest, TOptions, TUriUrlOptions> { defaults(options: TOptions): DefaultUriUrlRequestApi<TRequest, TOptions, OptionalUriUrl>; defaults(options: RequiredUriUrl & TOptions): DefaultUriUrlRequestApi<TRequest, TOptions, OptionalUriUrl>; (): TRequest; get(): TRequest; post(): TRequest; put(): TRequest; head(): TRequest; patch(): TRequest; del(): TRequest; } interface CoreOptions { baseUrl?: string; callback?: (error: any, response: IncomingMessage, body: any) => void; jar?: boolean | CookieJar; formData?: any; // Object form?: any; // Object or string auth?: AuthOptions; oauth?: OAuthOptions; aws?: AWSOptions; hawk?: HawkOptions; qs?: any; json?: any; multipart?: RequestPart[] | Multipart; agentOptions?: any; agentClass?: any; forever?: any; host?: string; port?: number; method?: string; headers?: Headers; body?: any; followRedirect?: boolean | ((response: IncomingMessage) => boolean); followAllRedirects?: boolean; maxRedirects?: number; encoding?: string; pool?: any; timeout?: number; proxy?: any; strictSSL?: boolean; gzip?: boolean; preambleCRLF?: boolean; postambleCRLF?: boolean; key?: Buffer; cert?: Buffer; passphrase?: string; ca?: Buffer; har?: HttpArchiveRequest; useQuerystring?: boolean; } interface UriOptions { uri: string; } interface UrlOptions { url: string; } export type RequiredUriUrl = UriOptions | UrlOptions; interface OptionalUriUrl { uri?: string; url?: string; } export type OptionsWithUri = UriOptions & CoreOptions; export type OptionsWithUrl = UrlOptions & CoreOptions; export type Options = OptionsWithUri | OptionsWithUrl; export interface RequestCallback { (error: any, response: IncomingMessage, body: any): void; } export interface HttpArchiveRequest { url?: string; method?: string; headers?: NameValuePair[]; postData?: { mimeType?: string; params?: NameValuePair[]; }; } export interface NameValuePair { name: string; value: string; } export interface Multipart { chunked?: boolean; data?: { 'content-type'?: string, body: string }[]; } export interface RequestPart { headers?: Headers; body: any; } export interface Request extends Stream { readable: boolean; writable: boolean; getAgent(): Agent; // start(): void; // abort(): void; pipeDest(dest: any): void; setHeader(name: string, value: string, clobber?: boolean): Request; setHeaders(headers: Headers): Request; qs(q: Object, clobber?: boolean): Request; form(): FormData; form(form: any): Request; multipart(multipart: RequestPart[]): Request; json(val: any): Request; aws(opts: AWSOptions, now?: boolean): Request; auth(username: string, password: string, sendInmediately?: boolean, bearer?: string): Request; oauth(oauth: OAuthOptions): Request; jar(jar: CookieJar): Request; on(event: string, listener: Function): this; on(event: 'request', listener: (req: ClientRequest) => void): this; on(event: 'response', listener: (resp: IncomingMessage) => void): this; on(event: 'data', listener: (data: Buffer | string) => void): this; on(event: 'error', listener: (e: Error) => void): this; on(event: 'complete', listener: (resp: IncomingMessage, body?: string | Buffer) => void): this; write(buffer: Buffer, cb?: Function): boolean; write(str: string, cb?: Function): boolean; write(str: string, encoding: string, cb?: Function): boolean; write(str: string, encoding?: string, fd?: string): boolean; end(): void; end(chunk: Buffer, cb?: Function): void; end(chunk: string, cb?: Function): void; end(chunk: string, encoding: string, cb?: Function): void; pause(): void; resume(): void; abort(): void; destroy(): void; toJSON(): Object; } export interface Headers { [key: string]: any; } export interface AuthOptions { user?: string; username?: string; pass?: string; password?: string; sendImmediately?: boolean; bearer?: string; } export interface OAuthOptions { callback?: string; consumer_key?: string; consumer_secret?: string; token?: string; token_secret?: string; verifier?: string; } export interface HawkOptions { credentials: any; } export interface AWSOptions { secret: string; bucket?: string; } /** * Cookies */ // Request wraps the `tough-cookies`'s CookieJar in a synchronous RequestJar // https://github.com/request/request/blob/master/lib/cookies.js export type Cookie = toughCookie.Cookie; export type CookieStore = toughCookie.Store; export type SetCookieOptions = toughCookie.SetCookieOptions; export interface CookieJar { // RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) { // var self = this // return self._jar.setCookieSync(cookieOrStr, uri, options || {}) // } setCookie(cookieOrString: Cookie | string, uri: string, options?: SetCookieOptions): Cookie; // RequestJar.prototype.getCookieString = function(uri) { // var self = this // return self._jar.getCookieStringSync(uri) // } getCookieString(uri: string): string; // RequestJar.prototype.getCookies = function(uri) { // var self = this // return self._jar.getCookiesSync(uri) // } getCookies(uri: string): Cookie[]; } } export = request; }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type ArtworkSidebarCurrentBidInfo_Test_QueryVariables = {}; export type ArtworkSidebarCurrentBidInfo_Test_QueryResponse = { readonly artwork: { readonly " $fragmentRefs": FragmentRefs<"ArtworkSidebarCurrentBidInfo_artwork">; } | null; }; export type ArtworkSidebarCurrentBidInfo_Test_QueryRawResponse = { readonly artwork: ({ readonly sale: ({ readonly is_closed: boolean | null; readonly is_live_open: boolean | null; readonly internalID: string; readonly is_with_buyers_premium: boolean | null; readonly id: string | null; }) | null; readonly sale_artwork: ({ readonly is_with_reserve: boolean | null; readonly reserve_message: string | null; readonly reserve_status: string | null; readonly current_bid: ({ readonly display: string | null; }) | null; readonly counts: ({ readonly bidder_positions: number | null; }) | null; readonly id: string | null; }) | null; readonly myLotStanding: ReadonlyArray<{ readonly active_bid: ({ readonly is_winning: boolean | null; readonly id: string | null; }) | null; readonly most_recent_bid: ({ readonly max_bid: ({ readonly display: string | null; }) | null; readonly id: string | null; }) | null; }> | null; readonly id: string | null; }) | null; }; export type ArtworkSidebarCurrentBidInfo_Test_Query = { readonly response: ArtworkSidebarCurrentBidInfo_Test_QueryResponse; readonly variables: ArtworkSidebarCurrentBidInfo_Test_QueryVariables; readonly rawResponse: ArtworkSidebarCurrentBidInfo_Test_QueryRawResponse; }; /* query ArtworkSidebarCurrentBidInfo_Test_Query { artwork(id: "auction_artwork_estimate_premium") { ...ArtworkSidebarCurrentBidInfo_artwork id } } fragment ArtworkSidebarCurrentBidInfo_artwork on Artwork { sale { is_closed: isClosed is_live_open: isLiveOpen internalID is_with_buyers_premium: isWithBuyersPremium id } sale_artwork: saleArtwork { is_with_reserve: isWithReserve reserve_message: reserveMessage reserve_status: reserveStatus current_bid: currentBid { display } counts { bidder_positions: bidderPositions } id } myLotStanding(live: true) { active_bid: activeBid { is_winning: isWinning id } most_recent_bid: mostRecentBid { max_bid: maxBid { display } id } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "auction_artwork_estimate_premium" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v2 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ]; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "ArtworkSidebarCurrentBidInfo_Test_Query", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "ArtworkSidebarCurrentBidInfo_artwork" } ], "storageKey": "artwork(id:\"auction_artwork_estimate_premium\")" } ], "type": "Query" }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "ArtworkSidebarCurrentBidInfo_Test_Query", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ { "alias": "is_closed", "args": null, "kind": "ScalarField", "name": "isClosed", "storageKey": null }, { "alias": "is_live_open", "args": null, "kind": "ScalarField", "name": "isLiveOpen", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": "is_with_buyers_premium", "args": null, "kind": "ScalarField", "name": "isWithBuyersPremium", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": "sale_artwork", "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtwork", "plural": false, "selections": [ { "alias": "is_with_reserve", "args": null, "kind": "ScalarField", "name": "isWithReserve", "storageKey": null }, { "alias": "reserve_message", "args": null, "kind": "ScalarField", "name": "reserveMessage", "storageKey": null }, { "alias": "reserve_status", "args": null, "kind": "ScalarField", "name": "reserveStatus", "storageKey": null }, { "alias": "current_bid", "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": (v2/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCounts", "kind": "LinkedField", "name": "counts", "plural": false, "selections": [ { "alias": "bidder_positions", "args": null, "kind": "ScalarField", "name": "bidderPositions", "storageKey": null } ], "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": null, "args": [ { "kind": "Literal", "name": "live", "value": true } ], "concreteType": "LotStanding", "kind": "LinkedField", "name": "myLotStanding", "plural": true, "selections": [ { "alias": "active_bid", "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "activeBid", "plural": false, "selections": [ { "alias": "is_winning", "args": null, "kind": "ScalarField", "name": "isWinning", "storageKey": null }, (v1/*: any*/) ], "storageKey": null }, { "alias": "most_recent_bid", "args": null, "concreteType": "BidderPosition", "kind": "LinkedField", "name": "mostRecentBid", "plural": false, "selections": [ { "alias": "max_bid", "args": null, "concreteType": "BidderPositionMaxBid", "kind": "LinkedField", "name": "maxBid", "plural": false, "selections": (v2/*: any*/), "storageKey": null }, (v1/*: any*/) ], "storageKey": null } ], "storageKey": "myLotStanding(live:true)" }, (v1/*: any*/) ], "storageKey": "artwork(id:\"auction_artwork_estimate_premium\")" } ] }, "params": { "id": null, "metadata": {}, "name": "ArtworkSidebarCurrentBidInfo_Test_Query", "operationKind": "query", "text": "query ArtworkSidebarCurrentBidInfo_Test_Query {\n artwork(id: \"auction_artwork_estimate_premium\") {\n ...ArtworkSidebarCurrentBidInfo_artwork\n id\n }\n}\n\nfragment ArtworkSidebarCurrentBidInfo_artwork on Artwork {\n sale {\n is_closed: isClosed\n is_live_open: isLiveOpen\n internalID\n is_with_buyers_premium: isWithBuyersPremium\n id\n }\n sale_artwork: saleArtwork {\n is_with_reserve: isWithReserve\n reserve_message: reserveMessage\n reserve_status: reserveStatus\n current_bid: currentBid {\n display\n }\n counts {\n bidder_positions: bidderPositions\n }\n id\n }\n myLotStanding(live: true) {\n active_bid: activeBid {\n is_winning: isWinning\n id\n }\n most_recent_bid: mostRecentBid {\n max_bid: maxBid {\n display\n }\n id\n }\n }\n}\n" } }; })(); (node as any).hash = '8ddf50200304994b30c1daf0736d8180'; export default node;
the_stack
import * as S from "./main"; declare const InputDeviceCapabilities: any; const LocMap = Map; const LocWeakMap = WeakMap; const defineProperty = Object.defineProperty; export function nodeListIter<T>(nl: { length: number; [index: number]: T; }): Iterable<T> { return { [Symbol.iterator]() { let i = 0; return { next(): { value: T; done: boolean } { return i < nl.length ? { done: false, value: nl[i++] } : { done: true, value: <any>undefined }; } }; } }; } /** stores event handlers in EventTarget */ export const eventsSym = Symbol.for("@effectful/debugger/events"); export type EventsMap = Map< string, Map< EventListenerOrEventListenerObject, (AddEventListenerOptions[] | undefined)[] > >; declare global { interface EventTarget { [eventsSym]: EventsMap; } } export function getEventsMap(target: EventTarget) { return target[eventsSym]; } const overrideProps: any = { [S.descriptorSymbol]: false }; function restoreEvents(et: EventTarget, map: EventsMap) { cleanupEvents(et); for (const [type, byType] of map) for (const [listener, byListener] of byType) for (const byCapture of byListener) if (byCapture) for (const options of byCapture) et.addEventListener(type, listener, options); et[eventsSym] = map; } export function cleanupEvents(et: EventTarget) { const map = et[eventsSym]; if (!map) return; for (const [type, byType] of et[eventsSym]) for (const [listener, byListener] of byType) for (const byCapture of byListener) if (byCapture) for (const options of byCapture) et.removeEventListener(type, listener, options); } const ETp = typeof EventTarget !== "undefined" && EventTarget.prototype; const savedAddEventListener = ETp && ETp.addEventListener; const savedRemoveEventListener = ETp && ETp.removeEventListener; interface EventListenerOnceHandler extends EventListenerObject { inner: EventListenerOrEventListenerObject; type: string; capture: boolean; } declare global { interface EventListenerOptions { // extending options - removing only listeners with `once` set once?: boolean; } } function wrapOnceHandleEvent(this: EventListenerOnceHandler, event: Event) { if (event.currentTarget) removeEventListenerInfo( event.currentTarget, this.type, this.inner, this.capture ); } S.regOpaqueObject(wrapOnceHandleEvent, "S#wrapOnceHandleEvent"); const onceHandlers = new LocWeakMap< EventListenerOrEventListenerObject, EventListenerOnceHandler >(); /** `EventTarget#addEventListener` wrapper which keeps the listener's reference */ export function addEventListener( this: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions ) { const self = this || global; if (typeof options === "boolean") { options = { capture: options }; } else if (!options) options = {}; const once = options.once; if (savedAddEventListener) { savedAddEventListener.call(self, type, listener, options); if (once || type === "load") { let onceHandler = onceHandlers.get(listener); if (!onceHandler) { onceHandlers.set( listener, (onceHandler = { type, inner: listener, capture: options.capture || false, handleEvent: wrapOnceHandleEvent }) ); } savedAddEventListener.call(self, type, onceHandler, { once: true, capture: options.capture }); } } const byType = self[eventsSym] || (self[eventsSym] = new LocMap()); let byListener = byType.get(type); if (!byListener) byType.set(type, (byListener = new LocMap())); let byCapture = byListener.get(listener); if (!byCapture) { byCapture = [void 0, void 0]; byListener.set(listener, byCapture); } const captIndex = Number(options.capture || false); const list = byCapture[captIndex] || (byCapture[captIndex] = []); list.push(options); } function removeEventListenerInfo( self: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions ) { if (typeof options === "boolean") { options = { capture: options }; } else if (!options) options = {}; const byType = self[eventsSym]; if (!byType) return; const byListener = byType.get(type); if (!byListener) return; const byCapture = byListener.get(listener); if (!byCapture) return; const index = Number(options.capture || false); const list = byCapture[index]; if (!list) return; if (options.once && list.some(i => !i.once)) return; byCapture[index] = void 0; if (!byCapture.some(Boolean)) byListener.delete(listener); } /** `EventTarget#removeEventListener` wrapper which keeps the listener's reference */ export function removeEventListener( this: EventTarget, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions ) { const self = this || global; if (savedRemoveEventListener) savedRemoveEventListener.call(self, type, listener, options); removeEventListenerInfo(self, type, listener, options); } /** * monkey patching `addEventListener`/`removeEventListener` * to keep reference to event listeners */ export function trackEvents(ev: EventTarget) { ev.addEventListener = addEventListener; ev.removeEventListener = removeEventListener; } /** monkey patching global `document` to make it serializable */ export function trackGlobalDocument() { if (typeof document === "undefined") return; // ignoring jsdom props (not needed if jsdom is transpiled too) const el = document.createElement("div"); el.addEventListener("test-event", function () {}); el.innerHTML = `<div id="root"><p>hello, world!</p></div>`; const _children = el.children; const _attrs = el.attributes; for (const i of Object.getOwnPropertySymbols(el)) overrideProps[i] = false; for (const i of Object.getOwnPropertySymbols(document)) overrideProps[i] = false; S.getState().byObject.set( document, S.regDescriptor({ name: "global#document", write(ctx, value: Document) { const json: S.JSONObject = {}; json.el = ctx.step(document.documentElement, json, "el"); const events = value[eventsSym]; if (events) json.ev = ctx.step(events, json, "ev"); return json; }, create() { return document; }, readContent(ctx, json, value) { value.replaceChild(ctx.step((<any>json).el), value.documentElement); if ((<any>json).ev) restoreEvents(value, ctx.step((<any>json).ev)); }, overrideProps: { ...overrideProps, location: false, [eventsSym]: false } }) ); if (typeof NodeList !== "undefined") { S.regConstructor(NodeList, { name: "dom#NodeList", overrideProps }); } if (typeof EventTarget !== "undefined") { S.regConstructor(NodeList, { name: "dom#EventTarget", overrideProps }); } if (typeof Element !== "undefined") { S.regConstructor( Element, { name: "dom#Element", write(ctx, value: Element, par, key) { const json: S.JSONObject = { tag: value.tagName }; const nodes: S.JSONArray = (json.c = []); for (const i of nodeListIter(value.childNodes)) nodes.push(ctx.step(i, nodes, nodes.length)); const attrs: S.JSONObject = (json.a = {}); for (const i of nodeListIter(value.attributes)) attrs[i.name] = i.value; const events = value[eventsSym]; if (events) json.ev = ctx.step(events, json, "ev"); return json; }, create(_, json) { return document.createElement((<any>json).tag); }, readContent(ctx, json, value) { const obj = <any>json; for (const i of obj.c) value.appendChild(ctx.step(i)); for (const n in obj.a) value.setAttribute(n, obj.a[n]); if (obj.ev) restoreEvents(value, ctx.step(obj.ev)); }, overrideProps: { ...overrideProps, [eventsSym]: false } }, true ); } if (typeof Event !== "undefined") defineProperty(Event.prototype, S.descriptorSymbol, { value: S.regDescriptor({ name: "dom#Event", create(ctx: S.ReadContext, json: any): Event { const EventConstructor = ctx.step((<any>json).c); const jsonInit: any = (<any>json).init; const init: any = {}; for (const i of Object.keys(jsonInit)) { const prop = jsonInit[i]; if (prop && typeof prop === "object") init[i] = ctx.step(prop); else init[i] = prop; } return new EventConstructor(init.type, init); }, write(ctx: S.WriteContext, value: Event) { const res: S.JSONObject = {}; res.c = ctx.step(value.constructor, res, "c"); const descrs: any = {}; for ( let i = value; i && i !== Object.prototype; i = Object.getPrototypeOf(i) ) Object.assign(descrs, Object.getOwnPropertyDescriptors(i), descrs); const init: S.JSONObject = (res.init = {}); for (const name in descrs) { if (!descrs[name].get) continue; const prop = (<any>value)[name]; if (prop) init[name] = ctx.step(prop, init, name); } return res; }, readContent() {}, props: false }), configurable: true }); if (typeof Text !== "undefined") S.regConstructor(Text, { name: "dom#Text", write(_, value) { return { text: value.data }; }, create(_, json) { return document.createTextNode((<any>json).text); }, overrideProps }); if (typeof ProcessingInstruction !== "undefined") S.regConstructor(ProcessingInstruction, { name: "dom#PI", write(_, value) { return { target: value.target, data: value.data }; }, create(_, json) { return document.createProcessingInstruction( (<any>json).target, (<any>json).data ); }, overrideProps }); if (typeof Comment !== "undefined") S.regConstructor(Comment, { name: "dom#Comment", write(_, value) { return { text: value.data }; }, create(_, json) { return document.createTextNode((<any>json).text); }, overrideProps }); if (typeof CSSStyleDeclaration !== "undefined") S.regConstructor(CSSStyleDeclaration, { name: "dom#CSSStyleDeclaration", write(_, value) { return { text: value.cssText }; }, create(_, json) { const dummy = document.createElement("div"); dummy.style.cssText = (<any>json).text; return dummy.style; }, overrideProps }); if ((<any>global).CSS2Properties) S.regConstructor((<any>global).CSS2Properties, { name: "dom#CSS2Properties", write(_, value) { return { text: (<any>value).cssText }; }, create(_, json) { const dummy = document.createElement("div"); dummy.style.cssText = (<any>json).text; return dummy.style; }, overrideProps }); if (typeof Document !== "undefined") S.regConstructor( Document, { name: "dom#Document", write(_, value) { const s = new XMLSerializer(); return { text: s.serializeToString(value), type: value.contentType }; }, create(_, json: S.JSONValue): Document { return new DOMParser().parseFromString( (<any>json).text, (<any>json).type ); }, readContent(ctx, json, value) { value.replaceChild(ctx.step((<any>json).el), value.documentElement); }, overrideProps }, true ); if (typeof InputDeviceCapabilities !== "undefined") { S.regConstructor(InputDeviceCapabilities, { name: "dom#InputDeviceCapabilities", write(_ctx, value) { return { fireTouchEvents: (<any>value).fireTouchEvents }; }, create(_ctx, json) { // TODO: don't care about object model for now return new InputDeviceCapabilities({ fireTouchEvents: (<any>json).fireTouchEvents }); }, props: false }); } if (typeof MutationRecord !== "undefined") S.regConstructor(MutationRecord, { name: "dom#MutationRecord", write(ctx, value) { const res = <any>{}; res.ty = ctx.step(value.type, res, "ty"); res.el = ctx.step(value.target, res, "el"); if (value.addedNodes) res.an = ctx.step([...nodeListIter(value.addedNodes)], res, "an"); if (value.removedNodes) res.rn = ctx.step([...nodeListIter(value.removedNodes)], res, "rn"); if (value.previousSibling) res.ps = ctx.step(value.previousSibling, res, "ps"); if (value.nextSibling) res.ns = ctx.step(value.nextSibling, res, "ns"); if (value.attributeName) res.tn = ctx.step(value.attributeName, res, "tn"); if (value.attributeNamespace) res.ts = ctx.step(value.attributeNamespace, res, "ts"); if (value.oldValue) res.ov = ctx.step(value.oldValue, res, "ov"); return res; }, create() { // TODO: don't care about object model for now return <any>{}; }, readContent(ctx, json: S.JSONValue, value: MutationRecord) { const j = <any>json; const v = <any>value; v.type = ctx.step(j.ty); v.target = ctx.step(j.el); v.addedNodes = ctx.step(j.an); v.removedNodes = ctx.step(j.rn); v.previousSibling = ctx.step(j.ps); v.nextSibling = ctx.step(j.ns); v.attributeName = ctx.step(j.tn); v.attributeNamespace = ctx.step(j.ts); v.oldValue = ctx.step(j.ov); }, props: false }); if (typeof MutationObserver !== "undefined") S.regConstructor(MutationObserver, { name: "dom#MutationObserver", overrideProps }); } /** * Monkey patching platform objects to make them serializable, * run it as soon as possible if a global serialization is needed */ export function track(withEvents?: boolean) { if (typeof EventTarget !== "undefined") trackEvents(EventTarget.prototype); trackGlobalDocument(); S.regGlobal(); }
the_stack
import '../../../test/test_helper'; import querystring from 'querystring'; import {ShopifyHeader} from '../../../base_types'; import {DataType, GetRequestParams} from '../../http_client/types'; import {assertHttpRequest} from '../../http_client/test/test_helper'; import {RestClient} from '../rest_client'; import {RestRequestReturn, PageInfo} from '../types'; import {Context} from '../../../context'; import * as ShopifyErrors from '../../../error'; const domain = 'test-shop.myshopify.io'; const successResponse = { products: [ { title: 'Test title', amount: 10, }, ], }; describe('REST client', () => { it('can make GET request', async () => { const client = new RestClient(domain, 'dummy-token'); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); await expect(client.get({path: 'products'})).resolves.toEqual( buildExpectedResponse(successResponse), ); assertHttpRequest({ method: 'GET', domain, path: '/admin/api/unstable/products.json', }); }); it('can make GET request with path in query', async () => { const client = new RestClient(domain, 'dummy-token'); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); const getRequest = { path: 'products', query: { path: 'some_path', }, }; await expect(client.get(getRequest)).resolves.toEqual( buildExpectedResponse(successResponse), ); assertHttpRequest({ method: 'GET', domain, path: '/admin/api/unstable/products.json?path=some_path', }); }); it('can make POST request with JSON data', async () => { const client = new RestClient(domain, 'dummy-token'); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); const postData = { title: 'Test product', amount: 10, }; await expect( client.post({path: 'products', type: DataType.JSON, data: postData}), ).resolves.toEqual(buildExpectedResponse(successResponse)); assertHttpRequest({ method: 'POST', domain, path: '/admin/api/unstable/products.json', headers: {'Content-Type': DataType.JSON.toString()}, data: JSON.stringify(postData), }); }); it('can make POST request with form data', async () => { const client = new RestClient(domain, 'dummy-token'); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); const postData = { title: 'Test product', amount: 10, }; await expect( client.post({ path: 'products', type: DataType.URLEncoded, data: postData, }), ).resolves.toEqual(buildExpectedResponse(successResponse)); assertHttpRequest({ method: 'POST', domain, path: '/admin/api/unstable/products.json', headers: {'Content-Type': DataType.URLEncoded.toString()}, data: querystring.stringify(postData), }); }); it('can make PUT request with JSON data', async () => { const client = new RestClient(domain, 'dummy-token'); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); const putData = { title: 'Test product', amount: 10, }; await expect( client.put({path: 'products/123', type: DataType.JSON, data: putData}), ).resolves.toEqual(buildExpectedResponse(successResponse)); assertHttpRequest({ method: 'PUT', domain, path: '/admin/api/unstable/products/123.json', headers: {'Content-Type': DataType.JSON.toString()}, data: JSON.stringify(putData), }); }); it('can make DELETE request', async () => { const client = new RestClient(domain, 'dummy-token'); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); await expect(client.delete({path: 'products/123'})).resolves.toEqual( buildExpectedResponse(successResponse), ); assertHttpRequest({ method: 'DELETE', domain, path: '/admin/api/unstable/products/123.json', }); }); it('merges custom headers with the default ones', async () => { const client = new RestClient(domain, 'dummy-token'); const customHeaders: Record<string, string> = { 'X-Not-A-Real-Header': 'some_value', }; fetchMock.mockResponseOnce(JSON.stringify(successResponse)); await expect( client.get({path: 'products', extraHeaders: customHeaders}), ).resolves.toEqual(buildExpectedResponse(successResponse)); customHeaders[ShopifyHeader.AccessToken] = 'dummy-token'; assertHttpRequest({ method: 'GET', domain, path: '/admin/api/unstable/products.json', headers: customHeaders, }); }); it('includes pageInfo of type PageInfo in the returned object for calls with next or previous pages', async () => { const params = getDefaultPageInfo(); const client = new RestClient(domain, 'dummy-token'); const linkHeaders = [ `<${params.previousPageUrl}>; rel="previous"`, `<${params.nextPageUrl}>; rel="next"`, 'This invalid info header will be ignored', ]; fetchMock.mockResponses([ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ]); const response = (await client.get({ path: 'products', query: {limit: 10}, })) as RestRequestReturn; expect(response).toHaveProperty('pageInfo'); expect(response.pageInfo).toEqual(params); }); it('is able to make subsequent get requests to either pageInfo.nextPage or pageInfo.prevPage', async () => { const params = getDefaultPageInfo(); const client = new RestClient(domain, 'dummy-token'); const linkHeaders = [ `<${params.previousPageUrl}>; rel="previous"`, `<${params.nextPageUrl}>; rel="next"`, ]; fetchMock.mockResponses( [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], ); const initialResponse = (await client.get({ path: 'products', query: {limit: 10}, })) as RestRequestReturn; const pageInfo = initialResponse.pageInfo as PageInfo; const nextPageResponse = await client.get( pageInfo.nextPage as GetRequestParams, ); expect(nextPageResponse).toBeDefined(); expect(nextPageResponse).toHaveProperty('pageInfo'); const prevPageResponse = await client.get( pageInfo.prevPage as GetRequestParams, ); expect(prevPageResponse).toBeDefined(); expect(prevPageResponse).toHaveProperty('pageInfo'); }); it('can request next pages until they run out', async () => { const params = getDefaultPageInfo(); const client = new RestClient(domain, 'dummy-token'); const linkHeaders = [ `<${params.previousPageUrl}>; rel="previous"`, `<${params.nextPageUrl}>; rel="next"`, ]; fetchMock.mockResponses( [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], [ JSON.stringify(successResponse), {headers: {link: `<${params.previousPageUrl}>; rel="previous"`}}, ], ); const initialResponse = (await client.get({ path: 'products', query: {limit: 10}, })) as RestRequestReturn; expect(initialResponse.pageInfo!.nextPageUrl).toBe(params.nextPageUrl); const secondResponse = (await client.get( initialResponse.pageInfo!.nextPage!, )) as RestRequestReturn; expect(secondResponse.pageInfo!.nextPageUrl).toBe(params.nextPageUrl); const thirdResponse = (await client.get( secondResponse.pageInfo!.nextPage!, )) as RestRequestReturn; expect(thirdResponse.pageInfo!.nextPageUrl).toBeUndefined(); expect(thirdResponse.pageInfo!.nextPage).toBeUndefined(); }); it('can request previous pages until they run out', async () => { const params = getDefaultPageInfo(); const client = new RestClient(domain, 'dummy-token'); const linkHeaders = [ `<${params.previousPageUrl}>; rel="previous"`, `<${params.nextPageUrl}>; rel="next"`, ]; fetchMock.mockResponses( [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], [ JSON.stringify(successResponse), {headers: {link: linkHeaders.join(', ')}}, ], [ JSON.stringify(successResponse), {headers: {link: `<${params.previousPageUrl}>; rel="next"`}}, ], ); const initialResponse = (await client.get({ path: 'products', query: {limit: 10}, })) as RestRequestReturn; expect(initialResponse.pageInfo!.previousPageUrl).toBe( params.previousPageUrl, ); const secondResponse = (await client.get( initialResponse.pageInfo!.prevPage!, )) as RestRequestReturn; expect(secondResponse.pageInfo!.previousPageUrl).toBe( params.previousPageUrl, ); const thirdResponse = (await client.get( secondResponse.pageInfo!.prevPage!, )) as RestRequestReturn; expect(thirdResponse.pageInfo!.previousPageUrl).toBeUndefined(); expect(thirdResponse.pageInfo!.prevPage).toBeUndefined(); }); it('adapts to private app requests', async () => { Context.IS_PRIVATE_APP = true; Context.initialize(Context); const client = new RestClient(domain); fetchMock.mockResponseOnce(JSON.stringify(successResponse)); await expect(client.get({path: 'products'})).resolves.toEqual( buildExpectedResponse(successResponse), ); const customHeaders: Record<string, string> = {}; customHeaders[ShopifyHeader.AccessToken] = 'test_secret_key'; assertHttpRequest({ method: 'GET', domain, path: '/admin/api/unstable/products.json', headers: customHeaders, }); }); it('fails to instantiate without access token', () => { expect(() => new RestClient(domain)).toThrow( ShopifyErrors.MissingRequiredArgument, ); }); }); function getDefaultPageInfo(): PageInfo { const limit = '10'; const fields = ['test1', 'test2']; const previousUrl = `https://${domain}/admin/api/unstable/products.json?limit=${limit}&fields=${fields.join( ',', )}&page_info=previousToken`; const nextUrl = `https://${domain}/admin/api/unstable/products.json?limit=${limit}&fields=${fields.join( ',', )}&page_info=nextToken`; const prevPage = { path: 'products', query: { fields: fields.join(','), limit: `${limit}`, // eslint-disable-next-line @typescript-eslint/naming-convention page_info: 'previousToken', }, }; const nextPage = { path: 'products', query: { fields: fields.join(','), limit: `${limit}`, // eslint-disable-next-line @typescript-eslint/naming-convention page_info: 'nextToken', }, }; return { limit, fields, previousPageUrl: previousUrl, nextPageUrl: nextUrl, prevPage, nextPage, }; } function buildExpectedResponse( obj: unknown, pageInfo?: PageInfo, ): RestRequestReturn { const expectedResponse: RestRequestReturn = { body: obj, headers: expect.objectContaining({}), }; if (pageInfo) { expectedResponse.pageInfo = pageInfo; } return expect.objectContaining(expectedResponse); }
the_stack
import {expect} from 'chai'; import {Attribute} from '../../../../lib/attribute'; import {Backend, InferenceHandler, SessionHandler} from '../../../../lib/backend'; import {WebGLBackend} from '../../../../lib/backends/backend-webgl'; import {WebGLInferenceHandler} from '../../../../lib/backends/webgl/inference-handler'; import {WebGLConcat} from '../../../../lib/backends/webgl/ops/concat'; import {Profiler} from '../../../../lib/instrument'; import {Tensor} from '../../../../lib/tensor'; import {ShapeUtil} from '../../../../lib/util'; import {createAscendingArray} from './test_utils'; import {createTextureFromArray} from './test_utils'; let backend: Backend|undefined; let sessionhandler: SessionHandler|undefined; let inferenceHandler: InferenceHandler|undefined; describe('#UnitTest# - packed concat - Tensor concat', () => { before('Initialize Context', async () => { const profiler = Profiler.create(); backend = await Backend('webgl'); // Explicitly set to true to trigger packed version (backend as WebGLBackend).pack = true; sessionhandler = backend.createSessionHandler({profiler}); inferenceHandler = sessionhandler.createInferenceHandler(); }); // Set it back to false, apparently this state is sticky throughout all the tests running in same browser session.. after('Resetting Context', () => { (backend as WebGLBackend).pack = false; }); const testDataSet = getTestData(); for (let k = 0; k < testDataSet.length; ++k) { const testData = testDataSet[k]; describe(`Test concat ${JSON.stringify(testData)}`, () => {}); it(`Test packed concat kernel `, () => { const webglInferenceHandler = inferenceHandler as WebGLInferenceHandler; // webglInferenceHandler.session.pack = false; // TODO support WebGl 1.0 if (webglInferenceHandler.session.textureManager.glContext.version === 1) { console.log('Running packed concat with webgl1 is not supported. Skipping.'); return; } const op = new WebGLConcat(); const attributes = new Attribute(undefined); const axis = testData.axis; attributes.set('axis', 'int', axis); op.initialize(attributes); const elementCount = testData.elementCount; const inputTensorShape = testData.inputShape; const inputTextureShape = testData.inputTextureShape; // create input data and tensor. The input data will be used to verify if the output tensor contains the // same value but possibly different order depending on our packing algorithm. const inputData = createAscendingArray(elementCount); const inputTensorA = new Tensor(inputTensorShape, 'float32', undefined, undefined, inputData); const inputTensorB = new Tensor(inputTensorShape, 'float32', undefined, undefined, inputData); // manually creat packed texture from inputTensor, and insert in cache const gl = webglInferenceHandler.session.textureManager.glContext.gl; webglInferenceHandler.session.textureManager.glContext.checkError(); const webglTextureA = createTextureFromArray( webglInferenceHandler.session.textureManager.glContext, testData.rawInput ? testData.rawInput : inputData, gl.RGBA, inputTextureShape[0], inputTextureShape[1]); const webglTextureB = createTextureFromArray( webglInferenceHandler.session.textureManager.glContext, testData.rawInput ? testData.rawInput : inputData, gl.RGBA, inputTextureShape[0], inputTextureShape[1]); webglInferenceHandler.session.textureManager.glContext.checkError(); const packedShape = inputTextureShape; const textureDataA = { width: inputTextureShape[0], height: inputTextureShape[1], channels: 4 as const, isPacked: true, shape: packedShape, strides: ShapeUtil.computeStrides(packedShape), unpackedShape: inputTensorShape, tensor: inputTensorA, texture: webglTextureA! }; const textureDataB = { width: inputTextureShape[0], height: inputTextureShape[1], channels: 4 as const, isPacked: true, shape: packedShape, strides: ShapeUtil.computeStrides(packedShape), unpackedShape: inputTensorShape, tensor: inputTensorB, texture: webglTextureB! }; webglInferenceHandler.setTextureData(inputTensorA.dataId, textureDataA, true); webglInferenceHandler.setTextureData(inputTensorB.dataId, textureDataB, true); // compile shader code const programInfo = op.createProgramInfo(inferenceHandler! as WebGLInferenceHandler, [inputTensorA, inputTensorB]); const artifact = webglInferenceHandler.session.programManager.build(programInfo); webglInferenceHandler.session.programManager.setArtifact(op, artifact); // run kernal and get output const runData = op.createRunData(webglInferenceHandler, artifact.programInfo, [inputTensorA, inputTensorB]); webglInferenceHandler.session.programManager.run(artifact, runData); const result = runData.outputTextureData.tensor.data; webglInferenceHandler.session.textureManager.glContext.checkError(); // verify result. const expectedOutput = testData.expectedOutput; expect(result).to.not.equal(null); expect(result).to.have.lengthOf(elementCount * 2); expect(result).to.deep.equal(expectedOutput); }); } }); interface TestData { elementCount: number; axis: number; inputShape: number[]; outputShape: number[]; inputTextureShape: number[]; outputTextureShape: number[]; expectedOutput: Float32Array; // If empty, the test will use auto-generated data. rawInput?: Float32Array; } function getTestData(): TestData[] { return [ // test 2D tensor { elementCount: 16, axis: 0, inputShape: [4, 4], outputShape: [8, 4], inputTextureShape: [2, 2], outputTextureShape: [2, 4], expectedOutput: new Float32Array([ 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16 ]), }, { elementCount: 16, axis: 1, inputShape: [4, 4], outputShape: [4, 8], inputTextureShape: [2, 2], outputTextureShape: [4, 2], expectedOutput: new Float32Array([ 1, 2, 5, 6, 1, 2, 5, 6, 3, 4, 7, 8, 3, 4, 7, 8, 9, 10, 13, 14, 9, 10, 13, 14, 11, 12, 15, 16, 11, 12, 15, 16 ]), }, { elementCount: 8, axis: 0, inputShape: [2, 4], outputShape: [4, 4], inputTextureShape: [2, 1], outputTextureShape: [2, 2], expectedOutput: new Float32Array([1, 2, 5, 6, 3, 4, 7, 8, 1, 2, 5, 6, 3, 4, 7, 8]), }, { elementCount: 8, axis: 1, inputShape: [2, 4], outputShape: [2, 8], inputTextureShape: [2, 1], outputTextureShape: [4, 2], expectedOutput: new Float32Array([ 1, 2, 5, 6, 1, 2, 5, 6, 3, 4, 7, 8, 3, 4, 7, 8, ]), }, { elementCount: 6, axis: 0, inputShape: [2, 3], outputShape: [4, 3], inputTextureShape: [2, 1], outputTextureShape: [2, 2], expectedOutput: new Float32Array([1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]), rawInput: new Float32Array([1, 2, 4, 5, 3, 0, 6, 0]) }, { elementCount: 6, axis: 1, inputShape: [2, 3], outputShape: [2, 6], inputTextureShape: [2, 1], outputTextureShape: [2, 2], expectedOutput: new Float32Array([1, 2, 3, 1, 2, 3, 4, 5, 6, 4, 5, 6]), rawInput: new Float32Array([1, 2, 4, 5, 3, 0, 6, 0]) }, // test 3d tensor { elementCount: 16, axis: 0, inputShape: [2, 2, 4], outputShape: [4, 2, 4], inputTextureShape: [2, 2], outputTextureShape: [2, 4], expectedOutput: new Float32Array([ 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16 ]) }, { elementCount: 16, axis: 1, inputShape: [2, 2, 4], outputShape: [2, 4, 4], inputTextureShape: [2, 2], outputTextureShape: [4, 2], expectedOutput: new Float32Array([ 1, 2, 5, 6, 3, 4, 7, 8, 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 9, 10, 13, 14, 11, 12, 15, 16 ]) }, { elementCount: 16, axis: 2, inputShape: [2, 2, 4], outputShape: [2, 2, 8], inputTextureShape: [2, 2], outputTextureShape: [4, 4], expectedOutput: new Float32Array([ 1, 2, 5, 6, 1, 2, 5, 6, 3, 4, 7, 8, 3, 4, 7, 8, 9, 10, 13, 14, 9, 10, 13, 14, 11, 12, 15, 16, 11, 12, 15, 16 ]) }, // test 4d tensor { elementCount: 32, axis: 0, inputShape: [2, 2, 2, 4], outputShape: [4, 2, 2, 4], inputTextureShape: [2, 4], outputTextureShape: [2, 8], expectedOutput: new Float32Array([ 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 17, 18, 21, 22, 19, 20, 23, 24, 25, 26, 29, 30, 27, 28, 31, 32, 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 17, 18, 21, 22, 19, 20, 23, 24, 25, 26, 29, 30, 27, 28, 31, 32 ]) }, { elementCount: 32, axis: 1, inputShape: [2, 2, 2, 4], outputShape: [2, 4, 2, 4], inputTextureShape: [2, 4], outputTextureShape: [8, 4], expectedOutput: new Float32Array([ 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 17, 18, 21, 22, 19, 20, 23, 24, 25, 26, 29, 30, 27, 28, 31, 32, 17, 18, 21, 22, 19, 20, 23, 24, 25, 26, 29, 30, 27, 28, 31, 32 ]) }, { elementCount: 32, axis: 2, inputShape: [2, 2, 2, 4], outputShape: [2, 2, 4, 4], inputTextureShape: [2, 4], outputTextureShape: [8, 4], expectedOutput: new Float32Array([ 1, 2, 5, 6, 3, 4, 7, 8, 1, 2, 5, 6, 3, 4, 7, 8, 9, 10, 13, 14, 11, 12, 15, 16, 9, 10, 13, 14, 11, 12, 15, 16, 17, 18, 21, 22, 19, 20, 23, 24, 17, 18, 21, 22, 19, 20, 23, 24, 25, 26, 29, 30, 27, 28, 31, 32, 25, 26, 29, 30, 27, 28, 31, 32 ]) }, { elementCount: 32, axis: 3, inputShape: [2, 2, 2, 4], outputShape: [2, 2, 4, 4], inputTextureShape: [2, 4], outputTextureShape: [8, 4], expectedOutput: new Float32Array([ 1, 2, 5, 6, 1, 2, 5, 6, 3, 4, 7, 8, 3, 4, 7, 8, 9, 10, 13, 14, 9, 10, 13, 14, 11, 12, 15, 16, 11, 12, 15, 16, 17, 18, 21, 22, 17, 18, 21, 22, 19, 20, 23, 24, 19, 20, 23, 24, 25, 26, 29, 30, 25, 26, 29, 30, 27, 28, 31, 32, 27, 28, 31, 32 ]) }, ]; }
the_stack
import { Difference, Options, Result, Statistics, SymlinkStatistics } from "../src" import { compare as compareAsync, fileCompareHandlers } from "../src" import util = require('util') import path from 'path' import Streams from 'memory-streams' export interface DisplayOptions { showAll: boolean, wholeReport: boolean, csv: boolean, noDiffIndicator: boolean, reason: boolean } export interface Test { // Test name. This represents also the name of the file holding expected result unless overriden by 'expected' param. name: string path1: string path2: string // Short test description. description: string // Expected result. expected: string // Left/right dirs will be relative to current process. withRelativePath: boolean // Options sent to library test. options: Partial<Options> // Display parameters for print method. displayOptions: Partial<DisplayOptions> // Prints test result. If missing 'defaultPrint()' is used. print: (res: Result, writer: Streams.WritableStream, displayOptions: DisplayOptions) => void // Do not call checkStatistics() after each library test. skipStatisticsCheck: boolean // only apply for synchronous compare onlySync: boolean // only apply for synchronous compare onlyAsync: boolean // limit test to specific node versions; ie. '>=2.5.0' nodeVersionSupport: string // exclude platform from run test; by default all platforms are allowed excludePlatform: Platform[] // Execute hand-written async test runAsync: () => Promise<string> // Custom validation function customValidator: (result: Statistics) => boolean } type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd' export function getTests(testDirPath: string): Partial<Test>[] { const res: Partial<Test>[] = [ { name: 'test001_1', path1: 'd1', path2: 'd2', options: { compareSize: true, }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test001_2', path1: 'd1', path2: 'd2', options: { compareSize: true, }, displayOptions: { showAll: true, wholeReport: true, csv: true, }, }, { name: 'test001_3', path1: 'd3', path2: 'd4', options: { compareSize: true, }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test001_4', path1: 'd4', path2: 'd4', options: { compareSize: true, }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test001_5', path1: 'd8', path2: 'd9', options: { compareSize: true, }, displayOptions: { showAll: true, }, }, { name: 'test001_6', path1: 'd8', path2: 'd9', options: { compareSize: true, }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test001_8', path1: 'd1', path2: 'd2', options: { compareSize: true, }, displayOptions: {}, }, { name: 'test001_9', path1: 'd1/a1.txt', path2: 'd2/a1.txt', description: 'should compare two files', options: { compareSize: true, }, displayOptions: {}, }, { name: 'test001_10', description: 'should propagate async exception', onlyAsync: true, runAsync: () => { return compareAsync(testDirPath + '/d1', testDirPath + '/none', {}) .then(cmpres => { return 'res: ' + JSON.stringify(cmpres) }) .catch(() => { return `error occurred` }) } }, { name: 'test001_11', path1: 'd37', path2: 'd38', description: 'provides reason when entries are distinct', options: { compareSize: true, compareContent: true, compareDate: true }, displayOptions: { showAll: true, reason: true, wholeReport: true }, }, { name: 'test001_12', path1: 'd37', path2: 'd38', description: 'provides reason when entries are distinct (csv)', options: { compareSize: true, compareContent: true, compareDate: true }, displayOptions: { showAll: true, reason: true, wholeReport: true, csv: true }, }, //////////////////////////////////////////////////// // Filters // //////////////////////////////////////////////////// { description: 'include files by name', name: 'test002_0', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '*.e1' }, displayOptions: { showAll: true, }, }, { description: 'include files by name; show directories in report', name: 'test002_1', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '*.e1' }, displayOptions: { showAll: true, wholeReport: true, }, }, { description: 'exclude directories by name; show directories in report', name: 'test002_2', path1: 'd1', path2: 'd10', options: { compareSize: true, excludeFilter: '.x' }, displayOptions: { showAll: true, wholeReport: true, }, }, { description: 'exclude files by name', name: 'test002_3', path1: 'd1', path2: 'd2', options: { compareSize: true, excludeFilter: '*.txt' }, displayOptions: { showAll: true, }, }, { description: 'exclude files by name; show directories in report', name: 'test002_4', path1: 'd1', path2: 'd2', options: { compareSize: true, excludeFilter: '*.txt' }, displayOptions: { showAll: true, wholeReport: true, }, }, { description: 'exclude files and directories by name with multiple patterns; match names beginning with dot', name: 'test002_5', path1: 'd6', path2: 'd7', options: { compareSize: true, excludeFilter: '*.e1,*.e2' }, displayOptions: { showAll: true, }, }, { description: 'exclude files by name with multiple patterns; match names beginning with dot; show directories in report', name: 'test002_6', path1: 'd6', path2: 'd7', options: { compareSize: true, excludeFilter: '*.e1,*.e2' }, displayOptions: { showAll: true, wholeReport: true, }, }, { description: 'include files by path', name: 'test002_7', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '**/A2/**/*.e*' }, displayOptions: { showAll: true, }, }, { description: 'exclude directories by path', name: 'test002_8', path1: 'd6', path2: 'd7', options: { compareSize: true, excludeFilter: '**/A4/**' }, displayOptions: { showAll: true, }, }, { description: 'exclude files by path', name: 'test002_9', path1: 'd6', path2: 'd7', options: { compareSize: true, excludeFilter: '**/A2/**/*.e*' }, displayOptions: { showAll: true, }, }, { description: 'simultaneous use of include/exclude patterns', name: 'test002_10', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '*.txt', excludeFilter: 'A2' }, displayOptions: { showAll: true, }, }, { description: 'include directories by relative path ("/...")', name: 'test002_11', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '/A2/**' }, displayOptions: { showAll: true, }, }, { description: 'include files by relative path ("/...")', name: 'test002_12', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '/A2/**/*.txt' }, displayOptions: { showAll: true, }, }, { description: 'exclude files and directories by relative path ("/...")', name: 'test002_13', path1: 'd6', path2: 'd7', options: { compareSize: true, excludeFilter: '/A2/**/*.txt,/.A3/**,/A1.e1' }, displayOptions: { showAll: true, }, }, { description: 'include all files in root directory', name: 'test002_14', path1: 'd6', path2: 'd7', options: { compareSize: true, includeFilter: '/*' }, displayOptions: { showAll: true, }, }, //////////////////////////////////////////////////// // Compare by content // //////////////////////////////////////////////////// { name: 'test003_0', path1: 'd11', path2: 'd12', options: { compareSize: true, compareContent: true }, displayOptions: { showAll: true, }, }, { name: 'test003_1', path1: 'd1', path2: 'd2', options: { compareSize: true, compareContent: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test003_2', path1: 'd39/a', path2: 'd39/b', description: 'compare only by content', options: { compareSize: false, compareContent: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, { name: 'test003_3', path1: 'd39/a', path2: 'd39/b', description: 'compare only by size', options: { compareSize: true, compareContent: false }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, //////////////////////////////////////////////////// // Symlinks // //////////////////////////////////////////////////// { name: 'test005_0', path1: 'd13', path2: 'd14', options: { compareSize: true, skipSymlinks: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_1', path1: 'd17', path2: 'd17', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_1_1', path1: 'd17', path2: 'd17', withRelativePath: true, options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_2', path1: 'd17', path2: 'd17', options: { compareSize: true, ignoreCase: true, skipSymlinks: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_3', path1: 'd17', path2: 'd18', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_4', path1: 'd22', path2: 'd22', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_5', path1: 'd19', path2: 'd19', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_5_1', path1: 'd19', path2: 'd19', withRelativePath: true, options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_6', path1: 'd19', path2: 'd19', options: { compareSize: true, ignoreCase: true, skipSymlinks: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_7', path1: 'd20', path2: 'd20', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_8', path1: 'd21', path2: 'd21', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_9', path1: 'd20', path2: 'd21', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_10', path1: 'd21', path2: 'd20', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_11', path1: 'd20', path2: 'd22', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_12', path1: 'd22', path2: 'd20', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_13', path1: 'd23', path2: 'd23', description: 'be able to compare symlinks to files', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_14', path1: 'd24', path2: 'd24', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_15', path1: 'd25', path2: 'd25', description: 'do not fail when broken symlinks are encountered and skipSymlinks option is used', options: { compareSize: true, ignoreCase: true, skipSymlinks: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_16', path1: 'd26', path2: 'd27', description: 'detect symbolic link loops; loops span between left/right directories', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_17', path1: 'd28', path2: 'd28', description: 'detect symbolic link loops; loop back to root directory', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_18', path1: 'd29', path2: 'd30', description: 'compare two symlinks', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test005_19', path1: 'd34_symlink/d', path2: 'd34_symlink/d', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, //////////////////////////////////////////////////// // Broken symlinks // //////////////////////////////////////////////////// { name: 'test005_30', path1: '#16/02/b', path2: '#16/02/a', description: "evaluate single broken link on both sides as different", options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, { name: 'test005_31', path1: '#16/03/b', path2: '#16/03/a', description: "report broken links before files or directories", options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, { name: 'test005_32', path1: '#16/01/a', path2: '#16/01/b', description: "handle broken links (left)", options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, { name: 'test005_33', path1: '#16/01/b', path2: '#16/01/a', description: "handle broken links (right)", options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, { name: 'test005_34', path1: '#16/03/b', path2: '#16/03/a', description: "ignores broken links if skipSymlinks is used", options: { compareSize: true, ignoreCase: true, skipSymlinks: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, }, //////////////////////////////////////////////////// // Compare symlinks // //////////////////////////////////////////////////// { name: 'test005_50', path1: '#19/01/a', path2: '#19/01/b', description: "evaluate identical file symlinks pointing to identical files as equal when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 0, equalSymlinks: 1, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 0, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_51', path1: '#19/01/a', path2: '#19/01/b', description: "evaluate identical file symlinks pointing to identical files as equal when compare-symlink is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_52', path1: '#19/06/a', path2: '#19/06/b', description: "evaluate identical file symlinks pointing to different files as different when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 0, equalSymlinks: 1, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 0, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_53', path1: '#19/06/a', path2: '#19/06/b', description: "evaluate identical file symlinks pointing to different files as different when compare-symlink is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_54', path1: '#19/05/a', path2: '#19/05/b', description: "evaluate identical directory symlinks as equal when compare-symlink option is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 0, equalSymlinks: 1, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 0, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_55', path1: '#19/05/a', path2: '#19/05/b', description: "evaluate identical directory symlinks as equal when compare-symlink option is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_56', path1: '#19/02/a', path2: '#19/02/b', description: "evaluate different file symlinks pointing to identical files as distinct when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 1, equalSymlinks: 0, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 1, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_57', path1: '#19/02/a', path2: '#19/02/b', description: "evaluate different file symlinks pointing to identical files as equal if compare-symlink option is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_58', path1: '#19/07/a', path2: '#19/07/b', description: "evaluate different directory symlinks as distinct when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 1, equalSymlinks: 0, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 1, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_59', path1: '#19/07/a', path2: '#19/07/b', description: "evaluate different directory symlinks as equal if compare-symlink option is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_60', path1: '#19/03/a', path2: '#19/03/b', description: "evaluate mixed file/symlink as distinct when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 1, equalSymlinks: 0, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 1, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_61', path1: '#19/03/a', path2: '#19/03/b', description: "evaluate mixed file/symlink as equal when compare-symlink is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_62', path1: '#19/08/a', path2: '#19/08/b', description: "evaluate mixed directory/symlink as distinct when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 1, equalSymlinks: 0, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 1, totalSymlinks: 1 }), excludePlatform: ['win32'], }, { name: 'test005_63', path1: '#19/08/a', path2: '#19/08/b', description: "evaluate mixed directory/symlink as equal when compare-symlink is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_64', path1: '#19/04/a', path2: '#19/04/b', description: "evaluate mixed file symlink and directory symlink as different when compare-symlink is used", options: { compareSize: true, compareSymlink: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 0, equalSymlinks: 0, leftSymlinks: 1, rightSymlinks: 1, differencesSymlinks: 2, totalSymlinks: 2 }), excludePlatform: ['win32'], }, { name: 'test005_65', path1: '#19/04/a', path2: '#19/04/b', description: "evaluate mixed file symlink and directory symlink as different when compare-symlink is not used", options: { compareSize: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => !stats.symlinks, excludePlatform: ['win32'], }, { name: 'test005_66', path1: '#19/07/a', path2: '#19/07/b', description: "no symlink is compared if skipSymlink is used", options: { compareSize: true, compareSymlink: true, skipSymlinks: true }, displayOptions: { showAll: true, wholeReport: true, reason: true }, customValidator: stats => validateSymlinks(stats.symlinks, { distinctSymlinks: 0, equalSymlinks: 0, leftSymlinks: 0, rightSymlinks: 0, differencesSymlinks: 0, totalSymlinks: 0 }), excludePlatform: ['win32'], }, //////////////////////////////////////////////////// // Skip subdirs // //////////////////////////////////////////////////// { name: 'test006_0', path1: 'd1', path2: 'd2', options: { compareSize: true, skipSubdirs: true }, displayOptions: { showAll: true, }, }, { name: 'test006_1', path1: 'd1', path2: 'd2', options: { compareSize: true, skipSubdirs: true }, displayOptions: { showAll: true, wholeReport: true, }, }, //////////////////////////////////////////////////// // Skip empty directories // //////////////////////////////////////////////////// { name: 'test006_10', path1: '#43/a', path2: '#43/b', description: 'should ignore empty directories', options: { compareSize: true, skipEmptyDirs: true }, displayOptions: { showAll: true, wholeReport: true}, }, //////////////////////////////////////////////////// // Ignore case // //////////////////////////////////////////////////// { name: 'test007_0', path1: 'd15', path2: 'd16', options: { compareSize: true, ignoreCase: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test007_1', path1: 'd15', path2: 'd16', options: { compareSize: true, ignoreCase: false }, displayOptions: { showAll: true, wholeReport: true, }, }, //////////////////////////////////////////////////// // Options handling // //////////////////////////////////////////////////// { name: 'test008_1', path1: 'd1', path2: 'd2', expected: 'total: 17, equal: 3, distinct: 0, only left: 7, only right: 7', options: {}, displayOptions: { wholeReport: true, noDiffIndicator: true }, }, { name: 'test008_2', path1: 'd1', path2: 'd2', expected: 'total: 17, equal: 3, distinct: 0, only left: 7, only right: 7', options: undefined, displayOptions: { wholeReport: true, noDiffIndicator: true }, }, { name: 'test008_3', path1: 'd1', path2: 'd2', expected: 'total: 17, equal: 3, distinct: 0, only left: 7, only right: 7', options: {}, displayOptions: { wholeReport: true, noDiffIndicator: true }, }, //////////////////////////////////////////////////// // Result Builder Callback // //////////////////////////////////////////////////// { name: 'test009_1', path1: 'd1', path2: 'd2', expected: 'test: 17', options: { resultBuilder(entry1, entry2, state, level, relativePath, options, statistics) { if (!statistics.test) { statistics.test = 0 } statistics.test++ } }, displayOptions: {}, skipStatisticsCheck: true, print(cmpres, writer) { writer.write('test: ' + cmpres.test); } }, { name: 'test009_2', path1: 'd1', path2: 'd2', expected: 'diffset: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]', options: { resultBuilder(entry1, entry2, state, level, relativePath, options, statistics, diffSet) { if (!statistics.test) { statistics.test = 0 } statistics.test++ if (diffSet) { diffSet.push(statistics.test) } } }, displayOptions: {}, skipStatisticsCheck: true, print(cmpres, writer) { const comparator = (a: Difference, b: Difference): number => { return (a as unknown as number) - (b as unknown as number) } writer.write(' diffset: ' + JSON.stringify(cmpres.diffSet?.sort(comparator), null, 0)); } }, //////////////////////////////////////////////////// // Compare date // //////////////////////////////////////////////////// { name: 'test010_0', path1: 'd31', path2: 'd32', options: { compareSize: true, compareDate: false }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test010_1', path1: 'd31', path2: 'd32', options: { compareSize: true, compareDate: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test010_2', path1: 'd31', path2: 'd32', options: { compareSize: true, compareDate: false, compareContent: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test010_3', path1: 'd31', path2: 'd32', options: { compareSize: true, compareDate: true, compareContent: true }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test010_4', path1: 'd33/1', path2: 'd33/2', description: 'should correctly use tolerance in date comparison', options: { compareSize: true, compareDate: true, dateTolerance: 5000 }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test010_5', path1: 'd33/1', path2: 'd33/2', description: 'should correctly use tolerance in date comparison', options: { compareSize: true, compareDate: true, dateTolerance: 9000 }, displayOptions: { showAll: true, wholeReport: true, }, }, { name: 'test010_6', path1: 'd33/1', path2: 'd33/2', description: 'should default to 1000 ms for date tolerance', options: { compareSize: true, compareDate: true }, displayOptions: { showAll: true, wholeReport: true, }, }, //////////////////////////////////////////////////// // Line by line compare // //////////////////////////////////////////////////// { name: 'test011_1', path1: 'd35/lf-spaces', path2: 'd35/crlf-spaces', description: 'should ignore line endings', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, }, displayOptions: {}, }, { name: 'test011_1_1', path1: 'd35/crlf-spaces', path2: 'd35/lf-spaces', description: 'should ignore line endings (small buffer', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, lineBasedHandlerBufferSize: 2, }, displayOptions: {}, }, { name: 'test011_2', path1: 'd35/crlf-spaces', path2: 'd35/lf-spaces', description: 'should not ignore line endings', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: false, }, displayOptions: {}, }, { name: 'test011_3', path1: 'd35/lf-spaces', path2: 'd35/lf-tabs', description: 'should ignore white spaces', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_4', path1: 'd35/crlf-spaces', path2: 'd35/lf-tabs', description: 'should ignore white spaces and line endings', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_5', path1: 'd35/lf-spaces', path2: 'd35/lf-tabs', description: 'should not ignore white spaces', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_6', path1: 'd35/lf-spaces', path2: 'd35/lf-mix', description: 'should ignore mixed white spaces', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_7', path1: 'd35/lf-tabs', path2: 'd35/lf-mix', description: 'should ignore mixed white spaces', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_8', path1: 'd35/lf-spaces', path2: 'd35/lf-spaces-inside', description: 'should not ignore white spaces situated inside line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_20', path1: 'd35/single-line/single-line-lf', path2: 'd35/single-line/single-line-crlf', description: 'should ignore line endings for files with single line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_21', path1: 'd35/single-line/single-line-lf', path2: 'd35/single-line/single-line-crlf', description: 'should ignore line endings for files with single line if buffer size is smaller than line size', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_22', path1: 'd35/single-line/single-line-lf', path2: 'd35/single-line/single-line-crlf', description: 'should not ignore line endings for files with single line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: false, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_23', path1: 'd35/single-line/single-line-lf', path2: 'd35/single-line/single-line-no-line-ending', description: 'should ignore line endings when comparing file with single line (lf) and file with single line (no line ending)', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_24', path1: 'd35/single-line/single-line-crlf', path2: 'd35/single-line/single-line-no-line-ending', description: 'should ignore line endings when comparing file with single line (crlf) and file with single line (no line ending)', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_25', path1: 'd35/single-line/single-line-no-line-ending', path2: 'd35/single-line/single-line-no-line-ending', description: 'should ignore line endings when comparing two files with single line and no line endings', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_26', path1: 'd35/single-line/single-line-no-line-ending', path2: 'd35/single-line/single-line-no-line-ending', description: 'should ignore line endings when comparing two files with single line and no line endings, buffer size less than line size', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_27', path1: 'd35/single-line/single-line-lf', path2: 'd35/single-line/single-line-crlf-spaces', description: 'should ignore line endings amd spaces for files with single line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_28', path1: 'd35/single-line/single-line-crlf', path2: 'd35/single-line/single-line-crlf-spaces', description: 'should ignore line endings amd spaces for files with single line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_29', path1: 'd35/single-line/single-line-no-line-ending', path2: 'd35/single-line/single-line-crlf-spaces', description: 'should ignore line endings amd spaces for files with single line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_30', path1: 'd35/single-line/single-line-no-line-ending', path2: 'd35/single-line/single-line-no-line-ending-spaces', description: 'should ignore line endings amd spaces for files with single line', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_50', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-no-ending-lf', description: 'should ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_51', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-no-ending-lf', description: 'should not ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: false, ignoreWhiteSpaces: false }, displayOptions: {}, }, { name: 'test011_52', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-no-ending-spaces-crlf', description: 'should ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_53', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-no-ending-spaces-lf', description: 'should ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_54', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-with-ending-crlf', description: 'should ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_55', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-with-ending-lf', description: 'should ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true }, displayOptions: {}, }, { name: 'test011_56', path1: 'd35/last-line-no-ending/last-line-no-ending-crlf', path2: 'd35/last-line-no-ending/last-line-no-ending-spaces-crlf', description: 'should ignore line endings amd spaces for files where last line has no ending', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: true, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_70', path1: 'd35/#29-ignore-all-whitespaces/a/app.ts', path2: 'd35/#29-ignore-all-whitespaces/b/app.ts', description: 'should ignore all white spaces', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false, ignoreAllWhiteSpaces: true, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_71', path1: 'd35/#29-ignore-all-whitespaces/a/app.ts', path2: 'd35/#29-ignore-all-whitespaces/c/app.ts', description: 'should not ignore empty lines if `ignore all whitespaces` is active', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false, ignoreAllWhiteSpaces: true, ignoreEmptyLines: false, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_72', path1: 'd35/#29-ignore-all-whitespaces/a/app.ts', path2: 'd35/#29-ignore-all-whitespaces/c/app.ts', description: 'should ignore empty lines and all whitespaces', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false, ignoreAllWhiteSpaces: true, ignoreEmptyLines: true, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_80', path1: 'd35/#29-ignore-empty-lines/a-lf/app.ts', path2: 'd35/#29-ignore-empty-lines/b-lf/app.ts', description: 'should ignore empty lines', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: false, ignoreWhiteSpaces: false, ignoreAllWhiteSpaces: false, ignoreEmptyLines: true, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, { name: 'test011_81', path1: 'd35/#29-ignore-empty-lines/a-lf/app.ts', path2: 'd35/#29-ignore-empty-lines/b-crlf/app.ts', description: 'should ignore empty lines when line endings are different', options: { compareContent: true, compareFileSync: fileCompareHandlers.lineBasedFileCompare.compareSync, compareFileAsync: fileCompareHandlers.lineBasedFileCompare.compareAsync, ignoreLineEnding: true, ignoreWhiteSpaces: false, ignoreAllWhiteSpaces: false, ignoreEmptyLines: true, lineBasedHandlerBufferSize: 3 }, displayOptions: {}, }, //////////////////////////////////////////////////// // Relative paths // //////////////////////////////////////////////////// { name: 'test012_0', path1: 'd1', path2: 'd2', description: 'should report relative paths', options: {}, withRelativePath: true, print(cmpres, writer) { printRelativePathResult(cmpres, testDirPath, writer) } }, { name: 'test012_1', path1: 'd1/A6/../../d1', path2: 'd2', description: 'should report absolute paths', options: {}, withRelativePath: false, print(cmpres, writer) { printRelativePathResult(cmpres, testDirPath, writer) } }, { name: 'test012_2', path1: testDirPath + '/d1', path2: 'd2', description: 'should report absolute and relative paths', options: {}, withRelativePath: true, print(cmpres, writer) { printRelativePathResult(cmpres, testDirPath, writer) } }, //////////////////////////////////////////////////// // Custom name comparator // //////////////////////////////////////////////////// { name: 'test013_1', path1: 'd40/a', path2: 'd40/b', description: 'should use custom name comparator (node <11>)', // Older node versions do not have stable sort order. // See https://github.com/nodejs/node/pull/22754#issuecomment-419551068 // File order is not considered in this test. nodeVersionSupport: '<11', options: { compareContent: true, compareNameHandler: customNameCompare, ignoreExtension: true }, displayOptions: { wholeReport: true, }, }, { name: 'test013_2', path1: 'd40/a', path2: 'd40/b', description: 'should use custom name comparator (node >11', nodeVersionSupport: '>=11', options: { compareContent: true, compareNameHandler: customNameCompare, ignoreExtension: true }, displayOptions: { showAll: true, wholeReport: true, }, }, ] return res } function customNameCompare(name1: string, name2: string, options: Options) { if (options.ignoreCase) { name1 = name1.toLowerCase() name2 = name2.toLowerCase() } if (options.ignoreExtension) { name1 = path.basename(name1, path.extname(name1)) name2 = path.basename(name2, path.extname(name2)) } return ((name1 === name2) ? 0 : ((name1 > name2) ? 1 : -1)) } function printRelativePathResult(res, testDirPath, writer) { let result = res.diffSet.map(diff => util.format('path1: %s, path2: %s', diff.path1, diff.path2)) result = JSON.stringify(result) result = result.replace(/\\\\/g, "/") result = result.replace(new RegExp(testDirPath.replace(/\\/g, "/"), 'g'), 'absolute_path') writer.write(result) } function validateSymlinks(expected: SymlinkStatistics | undefined, actual: SymlinkStatistics) { return JSON.stringify(expected) === JSON.stringify(actual) }
the_stack
import earcut from "earcut"; import polylabel from "polylabel"; import * as martinez from "martinez-polygon-clipping"; import * as THREE from "three"; import { Geometry } from "./Geometry"; import { Transform } from "../../../geo/Transform"; /** * @class VertexGeometry * @abstract * @classdesc Represents a vertex geometry. */ export abstract class VertexGeometry extends Geometry { private _subsampleThreshold: number; /** * Create a vertex geometry. * * @constructor * @ignore */ constructor() { super(); this._subsampleThreshold = 0.005; } /** * Get the 3D coordinates for the vertices of the geometry with possibly * subsampled points along the lines. * * @param {Transform} transform - The transform of the image related to * the geometry. * @returns {Array<Array<number>>} Polygon array of 3D world coordinates * representing the geometry. * @ignore */ public abstract getPoints3d(transform: Transform): number[][]; /** * Get the polygon pole of inaccessibility, the most * distant internal point from the polygon outline. * * @returns {Array<number>} 2D basic coordinates for the pole of inaccessibility. * @ignore */ public abstract getPoleOfInaccessibility2d(): number[]; /** * Get the polygon pole of inaccessibility, the most * distant internal point from the polygon outline. * * @param transform - The transform of the image related to * the geometry. * @returns {Array<number>} 3D world coordinates for the pole of inaccessibility. * @ignore */ public abstract getPoleOfInaccessibility3d(transform: Transform): number[]; /** * 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 abstract getVertex2d(index: number): number[]; /** * Get a vertex from the polygon representation of the 3D coordinates for the * vertices of the geometry. * * @param {number} index - Vertex index. * @param {Transform} transform - The transform of the image related to the geometry. * @returns {Array<number>} Array representing the 3D world coordinates of the vertex. * @ignore */ public abstract getVertex3d(index: number, transform: Transform): number[]; /** * Get a polygon representation of the 2D basic coordinates for the vertices of the geometry. * * @returns {Array<Array<number>>} Polygon array of 2D basic coordinates representing * the vertices of the geometry. * @ignore */ public abstract getVertices2d(): number[][]; /** * Get a polygon representation of the 3D world coordinates for the vertices of the geometry. * * @param {Transform} transform - The transform of the image related to the geometry. * @returns {Array<Array<number>>} Polygon array of 3D world coordinates representing * the vertices of the geometry. * @ignore */ public abstract getVertices3d(transform: Transform): number[][]; /** * Get a flattend array of the 3D world coordinates for the * triangles filling the geometry. * * @param {Transform} transform - The transform of the image related to the geometry. * @returns {Array<number>} Flattened array of 3D world coordinates of the triangles. * @ignore */ public abstract getTriangles3d(transform: Transform): number[]; /** * Set the value of a vertex in the polygon representation of the geometry. * * @description The polygon is defined to have the first vertex at the * bottom-left corner with the rest of the vertices following in clockwise order. * * @param {number} index - The index of the vertex to be set. * @param {Array<number>} value - The new value of the vertex. * @param {Transform} transform - The transform of the image related to the geometry. * @ignore */ public abstract setVertex2d(index: number, value: number[], transform: Transform): void; /** * Finds the polygon pole of inaccessibility, the most distant internal * point from the polygon outline. * * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate. * @returns {Array<number>} Point of inaccessibility. * @ignore */ protected _getPoleOfInaccessibility2d(points2d: number[][]): number[] { let pole2d: number[] = polylabel([points2d], 3e-2); return pole2d; } protected _project(points2d: number[][], transform: Transform): number[][] { const camera: THREE.Camera = this._createCamera( transform.upVector().toArray(), transform.unprojectSfM([0, 0], 0), transform.unprojectSfM([0, 0], 10)); return this._deunproject( points2d, transform, camera); } protected _subsample(points2d: number[][], threshold: number = this._subsampleThreshold): number[][] { const subsampled: number[][] = []; const length: number = points2d.length; for (let index: number = 0; index < length; index++) { const p1: number[] = points2d[index]; const p2: number[] = points2d[(index + 1) % length]; subsampled.push(p1); const dist: number = Math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2); const subsamples: number = Math.floor(dist / threshold); const coeff: number = 1 / (subsamples + 1); for (let i: number = 1; i <= subsamples; i++) { const alpha: number = i * coeff; const subsample: number[] = [ (1 - alpha) * p1[0] + alpha * p2[0], (1 - alpha) * p1[1] + alpha * p2[1], ]; subsampled.push(subsample); } } return subsampled; } /** * Triangulates a 2d polygon and returns the triangle * representation as a flattened array of 3d points. * * @param {Array<Array<number>>} points2d - 2d points of outline to triangulate. * @param {Array<Array<number>>} points3d - 3d points of outline corresponding to the 2d points. * @param {Array<Array<Array<number>>>} [holes2d] - 2d points of holes to triangulate. * @param {Array<Array<Array<number>>>} [holes3d] - 3d points of holes corresponding to the 2d points. * @returns {Array<number>} Flattened array of 3d points ordered based on the triangles. * @ignore */ protected _triangulate( points2d: number[][], points3d: number[][], holes2d?: number[][][], holes3d?: number[][][]): number[] { let data: number[][][] = [points2d.slice(0, -1)]; for (let hole2d of holes2d != null ? holes2d : []) { data.push(hole2d.slice(0, -1)); } let points: number[][] = points3d.slice(0, -1); for (let hole3d of holes3d != null ? holes3d : []) { points = points.concat(hole3d.slice(0, -1)); } let flattened: { vertices: number[], holes: number[], dimensions: number } = earcut.flatten(data); let indices: number[] = earcut(flattened.vertices, flattened.holes, flattened.dimensions); let triangles: number[] = []; for (let i: number = 0; i < indices.length; ++i) { let point: number[] = points[indices[i]]; triangles.push(point[0]); triangles.push(point[1]); triangles.push(point[2]); } return triangles; } protected _triangulateSpherical( points2d: number[][], holes2d: number[][][], transform: Transform): number[] { const triangles: number[] = []; const epsilon: number = 1e-9; const subareasX: number = 3; const subareasY: number = 3; for (let x: number = 0; x < subareasX; x++) { for (let y: number = 0; y < subareasY; y++) { const epsilonX0: number = x === 0 ? -epsilon : epsilon; const epsilonY0: number = y === 0 ? -epsilon : epsilon; const x0: number = x / subareasX + epsilonX0; const y0: number = y / subareasY + epsilonY0; const x1: number = (x + 1) / subareasX + epsilon; const y1: number = (y + 1) / subareasY + epsilon; const bbox2d: number[][] = [ [x0, y0], [x0, y1], [x1, y1], [x1, y0], [x0, y0], ]; const lookat2d: number[] = [ (2 * x + 1) / (2 * subareasX), (2 * y + 1) / (2 * subareasY), ]; triangles.push(...this._triangulateSubarea(points2d, holes2d, bbox2d, lookat2d, transform)); } } return triangles; } protected _unproject(points2d: number[][], transform: Transform, distance: number = 200): number[][] { return points2d .map( (point: number[]) => { return transform.unprojectBasic(point, distance); }); } private _createCamera(upVector: number[], position: number[], lookAt: number[]): THREE.Camera { const camera: THREE.Camera = new THREE.Camera(); camera.up.copy(new THREE.Vector3().fromArray(upVector)); camera.position.copy(new THREE.Vector3().fromArray(position)); camera.lookAt(new THREE.Vector3().fromArray(lookAt)); camera.updateMatrix(); camera.updateMatrixWorld(true); return camera; } private _deunproject(points2d: number[][], transform: Transform, camera: THREE.Camera): number[][] { return points2d .map( (point2d: number[]): number[] => { const pointWorld: number[] = transform.unprojectBasic(point2d, 10000); const pointCamera: THREE.Vector3 = new THREE.Vector3(pointWorld[0], pointWorld[1], pointWorld[2]) .applyMatrix4(camera.matrixWorldInverse); return [pointCamera.x / pointCamera.z, pointCamera.y / pointCamera.z]; }); } private _triangulateSubarea( points2d: number[][], holes2d: number[][][], bbox2d: number[][], lookat2d: number[], transform: Transform): number[] { const intersections: martinez.MultiPolygon = martinez.intersection([points2d, ...holes2d], [bbox2d]) as martinez.MultiPolygon; if (!intersections) { return []; } const triangles: number[] = []; const threshold: number = this._subsampleThreshold; const camera: THREE.Camera = this._createCamera( transform.upVector().toArray(), transform.unprojectSfM([0, 0], 0), transform.unprojectBasic(lookat2d, 10)); for (const intersection of intersections) { const subsampledPolygon2d: number[][] = this._subsample(intersection[0], threshold); const polygon2d: number[][] = this._deunproject(subsampledPolygon2d, transform, camera); const polygon3d: number[][] = this._unproject(subsampledPolygon2d, transform); const polygonHoles2d: number[][][] = []; const polygonHoles3d: number[][][] = []; for (let i: number = 1; i < intersection.length; i++) { let subsampledHole2d: number[][] = this._subsample(intersection[i], threshold); const hole2d: number[][] = this._deunproject(subsampledHole2d, transform, camera); const hole3d: number[][] = this._unproject(subsampledHole2d, transform); polygonHoles2d.push(hole2d); polygonHoles3d.push(hole3d); } triangles.push(...this._triangulate(polygon2d, polygon3d, polygonHoles2d, polygonHoles3d)); } return triangles; } }
the_stack
import { IntMap, SortedArray, Iterator, Segmentation, Interval, OrderedSet } from '../../../mol-data/int'; import { UniqueArray } from '../../../mol-data/generic'; import { SymmetryOperator } from '../../../mol-math/geometry/symmetry-operator'; import { Model, ElementIndex } from '../model'; import { sort, arraySwap, hash1, sortArray, hashString, hashFnv32a } from '../../../mol-data/util'; import { StructureElement } from './element'; import { Unit } from './unit'; import { StructureLookup3D } from './util/lookup3d'; import { CoarseElements } from '../model/properties/coarse'; import { StructureSubsetBuilder } from './util/subset-builder'; import { InterUnitBonds, computeInterUnitBonds, Bond } from './unit/bonds'; import { StructureSymmetry } from './symmetry'; import { StructureProperties } from './properties'; import { ResidueIndex, ChainIndex, EntityIndex } from '../model/indexing'; import { Carbohydrates } from './carbohydrates/data'; import { computeCarbohydrates } from './carbohydrates/compute'; import { Vec3, Mat4 } from '../../../mol-math/linear-algebra'; import { idFactory } from '../../../mol-util/id-factory'; import { GridLookup3D } from '../../../mol-math/geometry'; import { UUID } from '../../../mol-util'; import { CustomProperties } from '../../custom-property'; import { AtomicHierarchy } from '../model/properties/atomic'; import { StructureSelection } from '../query/selection'; import { getBoundary, Boundary } from '../../../mol-math/geometry/boundary'; import { ElementSymbol } from '../model/types'; import { CustomStructureProperty } from '../../../mol-model-props/common/custom-structure-property'; import { Trajectory } from '../trajectory'; import { RuntimeContext, Task } from '../../../mol-task'; import { computeStructureBoundary } from './util/boundary'; import { PrincipalAxes } from '../../../mol-math/linear-algebra/matrix/principal-axes'; /** Internal structure state */ type State = { parent?: Structure, boundary?: Boundary, lookup3d?: StructureLookup3D, interUnitBonds?: InterUnitBonds, dynamicBonds: boolean, unitSymmetryGroups?: ReadonlyArray<Unit.SymmetryGroup>, unitSymmetryGroupsIndexMap?: IntMap<number>, unitsSortedByVolume?: ReadonlyArray<Unit>; carbohydrates?: Carbohydrates, models?: ReadonlyArray<Model>, model?: Model, masterModel?: Model, representativeModel?: Model, uniqueResidueNames?: Set<string>, uniqueElementSymbols?: Set<ElementSymbol>, entityIndices?: ReadonlyArray<EntityIndex>, uniqueAtomicResidueIndices?: ReadonlyMap<UUID, ReadonlyArray<ResidueIndex>>, serialMapping?: SerialMapping, hashCode: number, transformHash: number, elementCount: number, bondCount: number, uniqueElementCount: number, atomicResidueCount: number, polymerResidueCount: number, polymerGapCount: number, polymerUnitCount: number, coordinateSystem: SymmetryOperator, label: string, propertyData?: any, customProps?: CustomProperties } class Structure { subsetBuilder(isSorted: boolean) { return new StructureSubsetBuilder(this, isSorted); } /** Count of all elements in the structure, i.e. the sum of the elements in the units */ get elementCount() { return this.state.elementCount; } /** Count of all bonds (intra- and inter-unit) in the structure */ get bondCount() { if (this.state.bondCount === -1) { this.state.bondCount = this.interUnitBonds.edgeCount + Bond.getIntraUnitBondCount(this); } return this.state.bondCount; } get hasCustomProperties() { return !!this.state.customProps && this.state.customProps.all.length > 0; } get customPropertyDescriptors() { if (!this.state.customProps) this.state.customProps = new CustomProperties(); return this.state.customProps; } /** * Property data unique to this instance of the structure. */ get currentPropertyData() { if (!this.state.propertyData) this.state.propertyData = Object.create(null); return this.state.propertyData; } /** * Property data of the parent structure if it exists, currentPropertyData otherwise. */ get inheritedPropertyData() { return this.parent ? this.parent.currentPropertyData : this.currentPropertyData; } /** Count of all polymer residues in the structure */ get polymerResidueCount() { if (this.state.polymerResidueCount === -1) { this.state.polymerResidueCount = getPolymerResidueCount(this); } return this.state.polymerResidueCount; } /** Count of all polymer gaps in the structure */ get polymerGapCount() { if (this.state.polymerGapCount === -1) { this.state.polymerGapCount = getPolymerGapCount(this); } return this.state.polymerGapCount; } get polymerUnitCount() { if (this.state.polymerUnitCount === -1) { this.state.polymerUnitCount = getPolymerUnitCount(this); } return this.state.polymerUnitCount; } get uniqueElementCount() { if (this.state.uniqueElementCount === -1) { this.state.uniqueElementCount = getUniqueElementCount(this); } return this.state.uniqueElementCount; } get atomicResidueCount() { if (this.state.atomicResidueCount === -1) { this.state.atomicResidueCount = getAtomicResidueCount(this); } return this.state.atomicResidueCount; } /** * True if any model the structure is based on is coarse grained. * @see Model.isCoarseGrained */ get isCoarseGrained() { return this.models.some(m => Model.isCoarseGrained(m)); } get isEmpty() { return this.units.length === 0; } get hashCode() { if (this.state.hashCode !== -1) return this.state.hashCode; return this.computeHash(); } /** Hash based on all unit.id values in the structure, reflecting the units transformation */ get transformHash() { if (this.state.transformHash !== -1) return this.state.transformHash; this.state.transformHash = hashFnv32a(this.units.map(u => u.id)); return this.state.transformHash; } private computeHash() { let hash = 23; for (let i = 0, _i = this.units.length; i < _i; i++) { const u = this.units[i]; hash = (31 * hash + u.id) | 0; hash = (31 * hash + SortedArray.hashCode(u.elements)) | 0; } hash = (31 * hash + this.elementCount) | 0; hash = hash1(hash); if (hash === -1) hash = 0; this.state.hashCode = hash; return hash; } /** Returns a new element location iterator */ elementLocations(): Iterator<StructureElement.Location> { return new Structure.ElementLocationIterator(this); } /** The parent or itself in case this is the root */ get root(): Structure { return this.state.parent ?? this; } /** The root/top-most parent or `undefined` in case this is the root */ get parent() { return this.state.parent; } /** * Conformation transformation that was applied to every unit of this structure. * * Coordinate system applies to the *current* structure only. * A parent structure can have a different coordinate system and thefore it has to be composed "manualy" * by the consumer. */ get coordinateSystem(): SymmetryOperator { return this.state.coordinateSystem; } get label() { return this.state.label; } get boundary() { if (this.state.boundary) return this.state.boundary; this.state.boundary = computeStructureBoundary(this); return this.state.boundary; } get lookup3d() { if (this.state.lookup3d) return this.state.lookup3d; this.state.lookup3d = new StructureLookup3D(this); return this.state.lookup3d; } get interUnitBonds() { if (this.state.interUnitBonds) return this.state.interUnitBonds; this.state.interUnitBonds = computeInterUnitBonds(this, { ignoreWater: !this.dynamicBonds }); return this.state.interUnitBonds; } get dynamicBonds() { return this.state.dynamicBonds; } get unitSymmetryGroups(): ReadonlyArray<Unit.SymmetryGroup> { if (this.state.unitSymmetryGroups) return this.state.unitSymmetryGroups; this.state.unitSymmetryGroups = StructureSymmetry.computeTransformGroups(this); return this.state.unitSymmetryGroups; } /** Maps unit.id to index of SymmetryGroup in unitSymmetryGroups array */ get unitSymmetryGroupsIndexMap(): IntMap<number> { if (this.state.unitSymmetryGroupsIndexMap) return this.state.unitSymmetryGroupsIndexMap; this.state.unitSymmetryGroupsIndexMap = Unit.SymmetryGroup.getUnitSymmetryGroupsIndexMap(this.unitSymmetryGroups); return this.state.unitSymmetryGroupsIndexMap; } get carbohydrates(): Carbohydrates { if (this.state.carbohydrates) return this.state.carbohydrates; this.state.carbohydrates = computeCarbohydrates(this); return this.state.carbohydrates; } get models(): ReadonlyArray<Model> { if (this.state.models) return this.state.models; this.state.models = getModels(this); return this.state.models; } get uniqueResidueNames() { return this.state.uniqueResidueNames || (this.state.uniqueResidueNames = getUniqueResidueNames(this)); } get uniqueElementSymbols() { return this.state.uniqueElementSymbols || (this.state.uniqueElementSymbols = getUniqueElementSymbols(this)); } get entityIndices() { return this.state.entityIndices || (this.state.entityIndices = getEntityIndices(this)); } get uniqueAtomicResidueIndices() { return this.state.uniqueAtomicResidueIndices || (this.state.uniqueAtomicResidueIndices = getUniqueAtomicResidueIndices(this)); } /** Contains only atomic units */ get isAtomic() { for (const u of this.units) if (!Unit.isAtomic(u)) return false; return true; } /** Contains some atomic units */ get hasAtomic() { for (const u of this.units) if (Unit.isAtomic(u)) return true; return false; } /** Contains only coarse units */ get isCoarse() { for (const u of this.units) if (!Unit.isCoarse(u)) return false; return true; } /** Contains some coarse units */ get hasCoarse() { for (const u of this.units) if (Unit.isCoarse(u)) return true; return false; } /** * Provides mapping for serial element indices accross all units. * * Note that this is especially costly for structures with many units that are grouped * into few symmetry groups. Use only when needed and prefer `StructureElement` * to address elements in a structure. */ get serialMapping() { return this.state.serialMapping || (this.state.serialMapping = getSerialMapping(this)); } /** * If the structure is based on a single model or has a master-/representative-model, return it. * Otherwise throw an exception. */ get model(): Model { if (this.state.model) return this.state.model; if (this.state.representativeModel) return this.state.representativeModel; if (this.state.masterModel) return this.state.masterModel; const models = this.models; if (models.length > 1) { throw new Error('The structure is based on multiple models and has neither a master- nor a representative-model.'); } this.state.model = models[0]; return this.state.model; } /** The master-model, other models can have bonds to it */ get masterModel(): Model | undefined { return this.state.masterModel; } /** A representative model, e.g. the first model of a trajectory */ get representativeModel(): Model | undefined { return this.state.representativeModel; } hasElement(e: StructureElement.Location) { if (!this.unitMap.has(e.unit.id)) return false; return SortedArray.has(this.unitMap.get(e.unit.id).elements, e.element); } getModelIndex(m: Model) { return this.models.indexOf(m); } remapModel(m: Model) { const { dynamicBonds, interUnitBonds } = this.state; const units: Unit[] = []; for (const ug of this.unitSymmetryGroups) { const unit = ug.units[0].remapModel(m, dynamicBonds); units.push(unit); for (let i = 1, il = ug.units.length; i < il; ++i) { const u = ug.units[i]; units.push(u.remapModel(m, dynamicBonds, unit.props)); } } return Structure.create(units, { label: this.label, interUnitBonds: dynamicBonds ? undefined : interUnitBonds, dynamicBonds }); } private _child: Structure | undefined; private _target: Structure | undefined; private _proxy: Structure | undefined; /** * For `structure` with `parent` this returns a proxy that * targets `parent` and has `structure` attached as a child. */ asParent(): Structure { if (this._proxy) return this._proxy; if (this.parent) { const p = this.parent.coordinateSystem.isIdentity ? this.parent : Structure.transform(this.parent, this.parent.coordinateSystem.inverse); const s = this.coordinateSystem.isIdentity ? p : Structure.transform(p, this.coordinateSystem.matrix); this._proxy = new Structure(s.units, s.unitMap, s.unitIndexMap, { ...s.state, dynamicBonds: this.dynamicBonds }, { child: this, target: this.parent }); } else { this._proxy = this; } return this._proxy; } get child(): Structure | undefined { return this._child; } /** Get the proxy target. Usefull for equality checks. */ get target(): Structure { return this._target ?? this; } /** * @param units Array of all units in the structure, sorted by unit.id * @param unitMap Maps unit.id to index of unit in units array * @param unitIndexMap Array of all units in the structure, sorted by unit.id */ constructor(readonly units: ReadonlyArray<Unit>, readonly unitMap: IntMap<Unit>, readonly unitIndexMap: IntMap<number>, private readonly state: State, asParent?: { child: Structure, target: Structure }) { // always assign to ensure object shape this._child = asParent?.child; this._target = asParent?.target; this._proxy = undefined; } } function cmpUnits(units: ArrayLike<Unit>, i: number, j: number) { return units[i].id - units[j].id; } function getModels(s: Structure) { const { units } = s; const arr = UniqueArray.create<Model['id'], Model>(); for (const u of units) { UniqueArray.add(arr, u.model.id, u.model); } return arr.array; } function getUniqueResidueNames(s: Structure) { const { microheterogeneityCompIds } = StructureProperties.residue; const names = new Set<string>(); const loc = StructureElement.Location.create(s); for (const unitGroup of s.unitSymmetryGroups) { const unit = unitGroup.units[0]; // TODO: support coarse unit? if (!Unit.isAtomic(unit)) continue; const residues = Segmentation.transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements); loc.unit = unit; while (residues.hasNext) { const seg = residues.move(); loc.element = unit.elements[seg.start]; const compIds = microheterogeneityCompIds(loc); for (const compId of compIds) names.add(compId); } } return names; } function getUniqueElementSymbols(s: Structure) { const prop = StructureProperties.atom.type_symbol; const symbols = new Set<ElementSymbol>(); const loc = StructureElement.Location.create(s); for (const unitGroup of s.unitSymmetryGroups) { const unit = unitGroup.units[0]; if (!Unit.isAtomic(unit)) continue; loc.unit = unit; for (let i = 0, il = unit.elements.length; i < il; ++i) { loc.element = unit.elements[i]; symbols.add(prop(loc)); } } return symbols; } function getEntityIndices(structure: Structure): ReadonlyArray<EntityIndex> { const { units } = structure; const l = StructureElement.Location.create(structure); const keys = UniqueArray.create<number, EntityIndex>(); for (const unit of units) { const prop = unit.kind === Unit.Kind.Atomic ? StructureProperties.entity.key : StructureProperties.coarse.entityKey; l.unit = unit; const elements = unit.elements; const chainsIt = Segmentation.transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements); while (chainsIt.hasNext) { const chainSegment = chainsIt.move(); l.element = elements[chainSegment.start]; const key = prop(l); UniqueArray.add(keys, key, key); } } sortArray(keys.array); return keys.array; } function getUniqueAtomicResidueIndices(structure: Structure): ReadonlyMap<UUID, ReadonlyArray<ResidueIndex>> { const map = new Map<UUID, UniqueArray<ResidueIndex, ResidueIndex>>(); const modelIds: UUID[] = []; const unitGroups = structure.unitSymmetryGroups; for (const unitGroup of unitGroups) { const unit = unitGroup.units[0]; if (!Unit.isAtomic(unit)) continue; let uniqueResidues: UniqueArray<ResidueIndex, ResidueIndex>; if (map.has(unit.model.id)) uniqueResidues = map.get(unit.model.id)!; else { uniqueResidues = UniqueArray.create<ResidueIndex, ResidueIndex>(); modelIds.push(unit.model.id); map.set(unit.model.id, uniqueResidues); } const residues = Segmentation.transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements); while (residues.hasNext) { const seg = residues.move(); UniqueArray.add(uniqueResidues, seg.index, seg.index); } } const ret = new Map<UUID, ReadonlyArray<ResidueIndex>>(); for (const id of modelIds) { const array = map.get(id)!.array; sortArray(array); ret.set(id, array); } return ret; } function getUniqueElementCount(structure: Structure): number { const { unitSymmetryGroups } = structure; let uniqueElementCount = 0; for (let i = 0, _i = unitSymmetryGroups.length; i < _i; i++) { uniqueElementCount += unitSymmetryGroups[i].elements.length; } return uniqueElementCount; } function getPolymerResidueCount(structure: Structure): number { const { units } = structure; let polymerResidueCount = 0; for (let i = 0, _i = units.length; i < _i; i++) { polymerResidueCount += units[i].polymerElements.length; } return polymerResidueCount; } function getPolymerGapCount(structure: Structure): number { const { units } = structure; let polymerGapCount = 0; for (let i = 0, _i = units.length; i < _i; i++) { polymerGapCount += units[i].gapElements.length / 2; } return polymerGapCount; } function getPolymerUnitCount(structure: Structure): number { const { units } = structure; let polymerUnitCount = 0; for (let i = 0, _i = units.length; i < _i; i++) { if (units[i].polymerElements.length > 0) polymerUnitCount += 1; } return polymerUnitCount; } function getAtomicResidueCount(structure: Structure): number { const { units } = structure; let atomicResidueCount = 0; for (let i = 0, _i = units.length; i < _i; i++) { const unit = units[i]; if (!Unit.isAtomic(unit)) continue; const { elements, residueIndex } = unit; let idx = -1; let prevIdx = -1; for (let j = 0, jl = elements.length; j < jl; ++j) { idx = residueIndex[elements[j]]; if (idx !== prevIdx) { atomicResidueCount += 1; prevIdx = idx; } } } return atomicResidueCount; } interface SerialMapping { /** Cumulative count of preceding elements for each unit */ cumulativeUnitElementCount: ArrayLike<number> /** Unit index for each serial element in the structure */ unitIndices: ArrayLike<number> /** Element index for each serial element in the structure */ elementIndices: ArrayLike<ElementIndex> /** Get serial index of element in the structure */ getSerialIndex: (unit: Unit, element: ElementIndex) => Structure.SerialIndex } function getSerialMapping(structure: Structure): SerialMapping { const { units, elementCount, unitIndexMap } = structure; const cumulativeUnitElementCount = new Uint32Array(units.length); const unitIndices = new Uint32Array(elementCount); const elementIndices = new Uint32Array(elementCount) as unknown as ElementIndex[]; for (let i = 0, m = 0, il = units.length; i < il; ++i) { cumulativeUnitElementCount[i] = m; const { elements } = units[i]; for (let j = 0, jl = elements.length; j < jl; ++j) { const mj = m + j; unitIndices[mj] = i; elementIndices[mj] = elements[j]; } m += elements.length; } return { cumulativeUnitElementCount, unitIndices, elementIndices, getSerialIndex: (unit, element) => cumulativeUnitElementCount[unitIndexMap.get(unit.id)] + OrderedSet.indexOf(unit.elements, element) as Structure.SerialIndex }; } namespace Structure { export const Empty = create([]); export interface Props { parent?: Structure interUnitBonds?: InterUnitBonds /** * Ensure bonds are recalculated upon model changes. * Also enables calculation of inter-unit bonds in water molecules. */ dynamicBonds?: boolean, coordinateSystem?: SymmetryOperator label?: string /** Master model for structures of a protein model and multiple ligand models */ masterModel?: Model /** Representative model for structures of a model trajectory */ representativeModel?: Model } /** Serial index of an element in the structure across all units */ export type SerialIndex = { readonly '@type': 'serial-index' } & number /** Represents a single structure */ export interface Loci { readonly kind: 'structure-loci', readonly structure: Structure, } export function Loci(structure: Structure): Loci { return { kind: 'structure-loci', structure }; } export function toStructureElementLoci(structure: Structure): StructureElement.Loci { const elements: StructureElement.Loci['elements'][0][] = []; for (const unit of structure.units) { elements.push({ unit, indices: Interval.ofBounds(0, unit.elements.length) }); } return StructureElement.Loci(structure, elements); } export function toSubStructureElementLoci(parent: Structure, structure: Structure): StructureElement.Loci { return StructureSelection.toLociWithSourceUnits(StructureSelection.Singletons(parent, structure)); } export function isLoci(x: any): x is Loci { return !!x && x.kind === 'structure-loci'; } export function areLociEqual(a: Loci, b: Loci) { return a.structure === b.structure; } export function isLociEmpty(loci: Loci) { return loci.structure.isEmpty; } export function remapLoci(loci: Loci, structure: Structure) { if (structure === loci.structure) return loci; return Loci(structure); } export function create(units: ReadonlyArray<Unit>, props: Props = {}): Structure { // init units const unitMap = IntMap.Mutable<Unit>(); const unitIndexMap = IntMap.Mutable<number>(); let elementCount = 0; let isSorted = true; let lastId = units.length > 0 ? units[0].id : 0; for (let i = 0, _i = units.length; i < _i; i++) { const u = units[i]; unitMap.set(u.id, u); elementCount += u.elements.length; if (u.id < lastId) isSorted = false; lastId = u.id; } if (!isSorted) sort(units, 0, units.length, cmpUnits, arraySwap); for (let i = 0, _i = units.length; i < _i; i++) { unitIndexMap.set(units[i].id, i); } // initial state const state: State = { hashCode: -1, transformHash: -1, elementCount, bondCount: -1, uniqueElementCount: -1, atomicResidueCount: -1, polymerResidueCount: -1, polymerGapCount: -1, polymerUnitCount: -1, dynamicBonds: false, coordinateSystem: SymmetryOperator.Default, label: '' }; // handle props if (props.parent) state.parent = props.parent.parent || props.parent; if (props.interUnitBonds) state.interUnitBonds = props.interUnitBonds; if (props.dynamicBonds) state.dynamicBonds = props.dynamicBonds; else if (props.parent) state.dynamicBonds = props.parent.dynamicBonds; if (props.coordinateSystem) state.coordinateSystem = props.coordinateSystem; else if (props.parent) state.coordinateSystem = props.parent.coordinateSystem; if (props.label) state.label = props.label; else if (props.parent) state.label = props.parent.label; if (props.masterModel) state.masterModel = props.masterModel; else if (props.parent) state.masterModel = props.parent.masterModel; if (props.representativeModel) state.representativeModel = props.representativeModel; else if (props.parent) state.representativeModel = props.parent.representativeModel; return new Structure(units, unitMap, unitIndexMap, state); } export async function ofTrajectory(trajectory: Trajectory, ctx: RuntimeContext): Promise<Structure> { if (trajectory.frameCount === 0) return Empty; const units: Unit[] = []; let first: Model | undefined = void 0; let count = 0; for (let i = 0, il = trajectory.frameCount; i < il; ++i) { const frame = await Task.resolveInContext(trajectory.getFrameAtIndex(i), ctx); if (!first) first = frame; const structure = ofModel(frame); for (let j = 0, jl = structure.units.length; j < jl; ++j) { const u = structure.units[j]; const invariantId = u.invariantId + count; const chainGroupId = u.chainGroupId + count; const newUnit = Unit.create(units.length, invariantId, chainGroupId, u.traits, u.kind, u.model, u.conformation.operator, u.elements); units.push(newUnit); } count = units.length; } return create(units, { representativeModel: first!, label: first!.label }); } const PARTITION = false; /** * Construct a Structure from a model. * * Generally, a single unit corresponds to a single chain, with the exception * of consecutive "single atom chains" with same entity_id and same auth_asym_id. */ export function ofModel(model: Model, props: Props = {}): Structure { const chains = model.atomicHierarchy.chainAtomSegments; const { index } = model.atomicHierarchy; const { auth_asym_id } = model.atomicHierarchy.chains; const { atomicChainOperatorMappinng } = model; const builder = new StructureBuilder({ label: model.label, ...props }); for (let c = 0 as ChainIndex; c < chains.count; c++) { const operator = atomicChainOperatorMappinng.get(c) || SymmetryOperator.Default; const start = chains.offsets[c]; // set to true for chains that consist of "single atom residues", // note that it assumes there are no "zero atom residues" let singleAtomResidues = AtomicHierarchy.chainResidueCount(model.atomicHierarchy, c) === chains.offsets[c + 1] - chains.offsets[c]; let multiChain = false; if (isWaterChain(model, c)) { // merge consecutive water chains while (c + 1 < chains.count && isWaterChain(model, c + 1 as ChainIndex)) { const op1 = atomicChainOperatorMappinng.get(c); const op2 = atomicChainOperatorMappinng.get(c + 1 as ChainIndex); if (op1 !== op2) break; multiChain = true; c++; } } else { // merge consecutive "single atom chains" with same entity_id and auth_asym_id while (c + 1 < chains.count && chains.offsets[c + 1] - chains.offsets[c] === 1 && chains.offsets[c + 2] - chains.offsets[c + 1] === 1 ) { singleAtomResidues = true; const e1 = index.getEntityFromChain(c); const e2 = index.getEntityFromChain(c + 1 as ChainIndex); if (e1 !== e2) break; const a1 = auth_asym_id.value(c); const a2 = auth_asym_id.value(c + 1); if (a1 !== a2) break; const op1 = atomicChainOperatorMappinng.get(c); const op2 = atomicChainOperatorMappinng.get(c + 1 as ChainIndex); if (op1 !== op2) break; multiChain = true; c++; } } const elements = SortedArray.ofBounds(start as ElementIndex, chains.offsets[c + 1] as ElementIndex); if (PARTITION) { // check for polymer to exclude CA/P-only models if (singleAtomResidues && !isPolymerChain(model, c)) { partitionAtomicUnitByAtom(model, elements, builder, multiChain, operator); } else if (elements.length > 200000 || isWaterChain(model, c)) { // split up very large chains e.g. lipid bilayers, micelles or water with explicit H partitionAtomicUnitByResidue(model, elements, builder, multiChain, operator); } else { builder.addUnit(Unit.Kind.Atomic, model, operator, elements, multiChain ? Unit.Trait.MultiChain : Unit.Trait.None); } } else { builder.addUnit(Unit.Kind.Atomic, model, operator, elements, multiChain ? Unit.Trait.MultiChain : Unit.Trait.None); } } const cs = model.coarseHierarchy; if (cs.isDefined) { if (cs.spheres.count > 0) { addCoarseUnits(builder, model, model.coarseHierarchy.spheres, Unit.Kind.Spheres); } if (cs.gaussians.count > 0) { addCoarseUnits(builder, model, model.coarseHierarchy.gaussians, Unit.Kind.Gaussians); } } return builder.getStructure(); } function isWaterChain(model: Model, chainIndex: ChainIndex) { const e = model.atomicHierarchy.index.getEntityFromChain(chainIndex); return model.entities.data.type.value(e) === 'water'; } function isPolymerChain(model: Model, chainIndex: ChainIndex) { const e = model.atomicHierarchy.index.getEntityFromChain(chainIndex); return model.entities.data.type.value(e) === 'polymer'; } function partitionAtomicUnitByAtom(model: Model, indices: SortedArray, builder: StructureBuilder, multiChain: boolean, operator: SymmetryOperator) { const { x, y, z } = model.atomicConformation; const position = { x, y, z, indices }; const lookup = GridLookup3D(position, getBoundary(position), 8192); const { offset, count, array } = lookup.buckets; const traits = (multiChain ? Unit.Trait.MultiChain : Unit.Trait.None) | (offset.length > 1 ? Unit.Trait.Partitioned : Unit.Trait.None); builder.beginChainGroup(); for (let i = 0, _i = offset.length; i < _i; i++) { const start = offset[i]; const set = new Int32Array(count[i]); for (let j = 0, _j = count[i]; j < _j; j++) { set[j] = indices[array[start + j]]; } builder.addUnit(Unit.Kind.Atomic, model, operator, SortedArray.ofSortedArray(set), traits); } builder.endChainGroup(); } // keeps atoms of residues together function partitionAtomicUnitByResidue(model: Model, indices: SortedArray, builder: StructureBuilder, multiChain: boolean, operator: SymmetryOperator) { const { residueAtomSegments } = model.atomicHierarchy; const startIndices: number[] = []; const endIndices: number[] = []; const residueIt = Segmentation.transientSegments(residueAtomSegments, indices); while (residueIt.hasNext) { const residueSegment = residueIt.move(); startIndices[startIndices.length] = indices[residueSegment.start]; endIndices[endIndices.length] = indices[residueSegment.end]; } const firstResidueAtomCount = endIndices[0] - startIndices[0]; const gridCellCount = 512 * firstResidueAtomCount; const { x, y, z } = model.atomicConformation; const position = { x, y, z, indices: SortedArray.ofSortedArray(startIndices) }; const lookup = GridLookup3D(position, getBoundary(position), gridCellCount); const { offset, count, array } = lookup.buckets; const traits = (multiChain ? Unit.Trait.MultiChain : Unit.Trait.None) | (offset.length > 1 ? Unit.Trait.Partitioned : Unit.Trait.None); builder.beginChainGroup(); for (let i = 0, _i = offset.length; i < _i; i++) { const start = offset[i]; const set: number[] = []; for (let j = 0, _j = count[i]; j < _j; j++) { const k = array[start + j]; for (let l = startIndices[k], _l = endIndices[k]; l < _l; l++) { set[set.length] = l; } } builder.addUnit(Unit.Kind.Atomic, model, operator, SortedArray.ofSortedArray(new Int32Array(set)), traits); } builder.endChainGroup(); } function addCoarseUnits(builder: StructureBuilder, model: Model, elements: CoarseElements, kind: Unit.Kind) { const { chainElementSegments } = elements; for (let cI = 0; cI < chainElementSegments.count; cI++) { const elements = SortedArray.ofBounds<ElementIndex>(chainElementSegments.offsets[cI], chainElementSegments.offsets[cI + 1]); builder.addUnit(kind, model, SymmetryOperator.Default, elements, Unit.Trait.None); } } export function transform(s: Structure, transform: Mat4) { if (Mat4.isIdentity(transform)) return s; if (!Mat4.isRotationAndTranslation(transform, SymmetryOperator.RotationTranslationEpsilon)) throw new Error('Only rotation/translation combination can be applied.'); const units: Unit[] = []; for (const u of s.units) { const old = u.conformation.operator; const op = SymmetryOperator.create(old.name, transform, old); units.push(u.applyOperator(u.id, op)); } const cs = s.coordinateSystem; const newCS = SymmetryOperator.compose(SymmetryOperator.create(cs.name, transform, cs), cs); return create(units, { parent: s, coordinateSystem: newCS }); } export class StructureBuilder { private units: Unit[] = []; private invariantId = idFactory() private chainGroupId = -1; private inChainGroup = false; private p = Vec3(); private singleElementUnits = new Map<string, Unit>(); beginChainGroup() { this.chainGroupId++; this.inChainGroup = true; } endChainGroup() { this.inChainGroup = false; } addUnit(kind: Unit.Kind, model: Model, operator: SymmetryOperator, elements: StructureElement.Set, traits: Unit.Traits, invariantId?: number): Unit { if (invariantId === undefined) invariantId = this.invariantId(); const chainGroupId = this.inChainGroup ? this.chainGroupId : ++this.chainGroupId; const unit = Unit.create(this.units.length, invariantId, chainGroupId, traits, kind, model, operator, elements); return this.add(unit); } private add(unit: Unit) { // this is to avoid adding many identical single atom units, // for example, from 'degenerate' spacegroups // - Diamond (COD 9008564) if (unit.elements.length === 1) { unit.conformation.position(unit.elements[0], this.p); const hash = [unit.invariantId, this.p[0], this.p[1], this.p[2]].join('|'); if (this.singleElementUnits.has(hash)) { return this.singleElementUnits.get(hash)!; } else { this.singleElementUnits.set(hash, unit); } } this.units.push(unit); return unit; } addWithOperator(unit: Unit, operator: SymmetryOperator, dontCompose = false): Unit { return this.add(unit.applyOperator(this.units.length, operator, dontCompose)); } getStructure(): Structure { return create(this.units, this.props); } get isEmpty() { return this.units.length === 0; } constructor(private props: Props = {}) { } } export function Builder(props: Props = {}) { return new StructureBuilder(props); } export function hashCode(s: Structure) { return s.hashCode; } /** Hash based on all unit.model conformation values in the structure */ export function conformationHash(s: Structure) { return hashString(s.units.map(u => Unit.conformationId(u)).join('|')); } // TODO: there should be a version that properly supports partitioned units export function areUnitIdsEqual(a: Structure, b: Structure) { if (a === b) return true; if (a.elementCount !== b.elementCount) return false; const len = a.units.length; if (len !== b.units.length) return false; for (let i = 0; i < len; i++) { if (a.units[i].id !== b.units[i].id) return false; } return true; } export function areUnitIdsAndIndicesEqual(a: Structure, b: Structure) { if (!areUnitIdsEqual(a, b)) return false; for (let i = 0, il = a.units.length; i < il; i++) { if (!SortedArray.areEqual(a.units[i].elements, b.units[i].elements)) return false; } return true; } export function areHierarchiesEqual(a: Structure, b: Structure) { if (a.hashCode !== b.hashCode) return false; const len = a.models.length; if (len !== b.models.length) return false; for (let i = 0; i < len; i++) { if (!Model.areHierarchiesEqual(a.models[i], b.models[i])) return false; } return true; } export function areEquivalent(a: Structure, b: Structure) { return a === b || ( a.hashCode === b.hashCode && StructureSymmetry.areTransformGroupsEquivalent(a.unitSymmetryGroups, b.unitSymmetryGroups) ); } /** Check if the structures or their parents are equivalent */ export function areRootsEquivalent(a: Structure, b: Structure) { return areEquivalent(a.root, b.root); } /** Check if the structures or their parents are equal */ export function areRootsEqual(a: Structure, b: Structure) { return a.root === b.root; } export class ElementLocationIterator implements Iterator<StructureElement.Location> { private current: StructureElement.Location; private unitIndex = 0; private elements: StructureElement.Set; private maxIdx = 0; private idx = -1; hasNext: boolean; move(): StructureElement.Location { this.advance(); this.current.element = this.elements[this.idx]; return this.current; } private advance() { if (this.idx < this.maxIdx) { this.idx++; if (this.idx === this.maxIdx) this.hasNext = this.unitIndex + 1 < this.structure.units.length; return; } this.idx = 0; this.unitIndex++; if (this.unitIndex >= this.structure.units.length) { this.hasNext = false; return; } this.current.unit = this.structure.units[this.unitIndex]; this.elements = this.current.unit.elements; this.maxIdx = this.elements.length - 1; if (this.maxIdx === 0) { this.hasNext = this.unitIndex + 1 < this.structure.units.length; } } constructor(private structure: Structure) { this.current = StructureElement.Location.create(structure); this.hasNext = structure.elementCount > 0; if (this.hasNext) { this.elements = structure.units[0].elements; this.maxIdx = this.elements.length - 1; this.current.unit = structure.units[0]; } } } const distVec = Vec3(); function unitElementMinDistance(unit: Unit, p: Vec3, eRadius: number) { const { elements, conformation: { position, r } } = unit, dV = distVec; let minD = Number.MAX_VALUE; for (let i = 0, _i = elements.length; i < _i; i++) { const e = elements[i]; const d = Vec3.distance(p, position(e, dV)) - eRadius - r(e); if (d < minD) minD = d; } return minD; } export function minDistanceToPoint(s: Structure, point: Vec3, radius: number) { const { units } = s; let minD = Number.MAX_VALUE; for (let i = 0, _i = units.length; i < _i; i++) { const unit = units[i]; const d = unitElementMinDistance(unit, point, radius); if (d < minD) minD = d; } return minD; } const distPivot = Vec3(); export function distance(a: Structure, b: Structure) { if (a.elementCount === 0 || b.elementCount === 0) return 0; const { units } = a; let minD = Number.MAX_VALUE; for (let i = 0, _i = units.length; i < _i; i++) { const unit = units[i]; const { elements, conformation: { position, r } } = unit; for (let i = 0, _i = elements.length; i < _i; i++) { const e = elements[i]; const d = minDistanceToPoint(b, position(e, distPivot), r(e)); if (d < minD) minD = d; } } return minD; } export function elementDescription(s: Structure) { return s.elementCount === 1 ? '1 element' : `${s.elementCount} elements`; } export function validUnitPair(s: Structure, a: Unit, b: Unit) { return s.masterModel ? a.model === b.model || a.model === s.masterModel || b.model === s.masterModel : a.model === b.model; } export interface EachUnitPairProps { maxRadius: number validUnit: (unit: Unit) => boolean validUnitPair: (unitA: Unit, unitB: Unit) => boolean } /** * Iterate over all unit pairs of a structure and invokes callback for valid units * and unit pairs if within a max distance. */ export function eachUnitPair(structure: Structure, callback: (unitA: Unit, unitB: Unit) => void, props: EachUnitPairProps) { const { maxRadius, validUnit, validUnitPair } = props; if (!structure.units.some(u => validUnit(u))) return; const lookup = structure.lookup3d; const imageCenter = Vec3(); for (const unit of structure.units) { if (!validUnit(unit)) continue; const bs = unit.boundary.sphere; Vec3.transformMat4(imageCenter, bs.center, unit.conformation.operator.matrix); const closeUnits = lookup.findUnitIndices(imageCenter[0], imageCenter[1], imageCenter[2], bs.radius + maxRadius); for (let i = 0; i < closeUnits.count; i++) { const other = structure.units[closeUnits.indices[i]]; if (!validUnit(other) || unit.id >= other.id || !validUnitPair(unit, other)) continue; if (other.elements.length >= unit.elements.length) callback(unit, other); else callback(other, unit); } } } export interface ForEachAtomicHierarchyElementParams { // Called for 1st element of each chain // Note that chains can be split, meaning each chain would be called multiple times. chain?: (e: StructureElement.Location<Unit.Atomic>) => void, // Called for 1st element of each residue residue?: (e: StructureElement.Location<Unit.Atomic>) => void, // Called for each element atom?: (e: StructureElement.Location<Unit.Atomic>) => void, }; export function eachAtomicHierarchyElement(structure: Structure, { chain, residue, atom }: ForEachAtomicHierarchyElementParams) { const l = StructureElement.Location.create<Unit.Atomic>(structure); for (const unit of structure.units) { if (unit.kind !== Unit.Kind.Atomic) continue; l.unit = unit; const { elements } = unit; const chainsIt = Segmentation.transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements); const residuesIt = Segmentation.transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements); while (chainsIt.hasNext) { const chainSegment = chainsIt.move(); if (chain) { l.element = elements[chainSegment.start]; chain(l); } if (!residue && !atom) continue; residuesIt.setSegment(chainSegment); while (residuesIt.hasNext) { const residueSegment = residuesIt.move(); if (residue) { l.element = elements[residueSegment.start]; residue(l); } if (!atom) continue; for (let j = residueSegment.start, _j = residueSegment.end; j < _j; j++) { l.element = elements[j]; atom(l); } } } } } // export const DefaultSizeThresholds = { /** Must be lower to be small */ smallResidueCount: 10, /** Must be lower to be medium */ mediumResidueCount: 5000, /** Must be lower to be large (big ribosomes like 4UG0 should still be `large`) */ largeResidueCount: 30000, /** * Structures above `largeResidueCount` are consider huge when they have * a `highSymmetryUnitCount` or gigantic when not */ highSymmetryUnitCount: 10, /** Fiber-like structure are consider small when below this */ fiberResidueCount: 15, }; export type SizeThresholds = typeof DefaultSizeThresholds function getPolymerSymmetryGroups(structure: Structure) { return structure.unitSymmetryGroups.filter(ug => ug.units[0].polymerElements.length > 0); } /** * Try to match fiber-like structures like 6nk4 */ function isFiberLike(structure: Structure, thresholds: SizeThresholds) { const polymerSymmetryGroups = getPolymerSymmetryGroups(structure); return ( polymerSymmetryGroups.length === 1 && polymerSymmetryGroups[0].units.length > 2 && polymerSymmetryGroups[0].units[0].polymerElements.length < thresholds.fiberResidueCount ); } function hasHighSymmetry(structure: Structure, thresholds: SizeThresholds) { const polymerSymmetryGroups = getPolymerSymmetryGroups(structure); return ( polymerSymmetryGroups.length >= 1 && polymerSymmetryGroups[0].units.length > thresholds.highSymmetryUnitCount ); } export enum Size { Small, Medium, Large, Huge, Gigantic } /** * @param residueCountFactor - modifies the threshold counts, useful when estimating * the size of a structure comprised of multiple models */ export function getSize(structure: Structure, thresholds: Partial<SizeThresholds> = {}, residueCountFactor = 1): Size { const t = { ...DefaultSizeThresholds, ...thresholds }; if (structure.polymerResidueCount >= t.largeResidueCount * residueCountFactor) { if (hasHighSymmetry(structure, t)) { return Size.Huge; } else { return Size.Gigantic; } } else if (isFiberLike(structure, t)) { return Size.Small; } else if (structure.polymerResidueCount < t.smallResidueCount * residueCountFactor) { return Size.Small; } else if (structure.polymerResidueCount < t.mediumResidueCount * residueCountFactor) { return Size.Medium; } else { return Size.Large; } } // export type Index = number; export const Index = CustomStructureProperty.createSimple<Index>('index', 'root'); const PrincipalAxesProp = '__PrincipalAxes__'; export function getPrincipalAxes(structure: Structure): PrincipalAxes { if (structure.currentPropertyData[PrincipalAxesProp]) return structure.currentPropertyData[PrincipalAxesProp]; const principalAxes = StructureElement.Loci.getPrincipalAxes(Structure.toStructureElementLoci(structure)); structure.currentPropertyData[PrincipalAxesProp] = principalAxes; return principalAxes; } } export { Structure };
the_stack
import { inject, injectable } from 'inversify'; import _ from 'lodash'; import { inspect } from 'util'; import { IVCSService, ServicePagination } from '..'; import { debugLog } from '../../detectors/utils'; import { IssueState, ListGetterOptions, Paginated, PaginationParams, PullRequestState } from '../../inspectors'; import { ArgumentsProvider } from '../../scanner'; import { InMemoryCache } from '../../scanner/cache'; import { ICache } from '../../scanner/cache/ICache'; import { RepositoryConfig } from '../../scanner/RepositoryConfig'; import { Types } from '../../types'; import { Branch, Commit, Contributor, ContributorStats, CreatedUpdatedPullRequestComment, Directory, File, Issue, IssueComment, Lines, PullCommits, PullFiles, PullRequest, PullRequestComment, PullRequestReview, Symlink, UserInfo, } from '../git/model'; import { VCSServicesUtils } from '../git/VCSServicesUtils'; import { CustomAxiosResponse, GitLabClient, PaginationGitLabCustomResponse } from './gitlabClient/gitlabUtils'; @injectable() export class GitLabService implements IVCSService { private client: GitLabClient; private cache: ICache; private callCount = 0; private readonly argumentsProvider: ArgumentsProvider; private readonly host: string; private readonly repositoryConfig: RepositoryConfig; private readonly d: (...args: unknown[]) => void; constructor( @inject(Types.ArgumentsProvider) argumentsProvider: ArgumentsProvider, @inject(Types.RepositoryConfig) repositoryConfig: RepositoryConfig, ) { this.d = debugLog('cli:services:git:gitlab-service'); this.argumentsProvider = argumentsProvider; this.repositoryConfig = repositoryConfig; this.host = repositoryConfig.host!; this.cache = new InMemoryCache(); this.client = new GitLabClient({ token: this.argumentsProvider.auth, host: this.repositoryConfig.baseUrl, }); } purgeCache() { this.cache.purge(); } async checkVersion() { return (await this.client.Version.check()).data; } getRepo(owner: string, repo: string) { return this.unwrap(this.client.Projects.get(`${owner}/${repo}`)); } /** * Lists all pull requests in the repo. */ async listPullRequests( owner: string, repo: string, options?: { withDiffStat?: boolean } & ListGetterOptions<{ state?: PullRequestState }>, ): Promise<Paginated<PullRequest>> { const state = VCSServicesUtils.getGitLabPRState(options?.filter?.state); const { data, pagination } = await this.unwrap( this.client.MergeRequests.list(`${owner}/${repo}`, { pagination: options?.pagination, filter: { state }, }), ); const user = await this.getUserInfo(owner); const items: PullRequest[] = await Promise.all( data.map(async (val) => { const pullRequest = { user: { id: val.author.id.toString(), login: val.author.username, url: val.author.web_url, }, title: val.title, url: val.web_url, body: val.description, sha: val.sha, createdAt: val.created_at.toString(), updatedAt: val.updated_at.toString(), closedAt: val.closed_at ? val.closed_at?.toString() : null, mergedAt: val.merged_at ? val.merged_at?.toString() : null, state: val.state, id: val.iid, base: { repo: { url: `${this.host}/${owner}/${repo}`, name: repo, id: val.project_id.toString(), owner: user, }, }, }; // Get number of changes, additions and deletions in PullRequest if the withDiffStat is true if (options?.withDiffStat) { //TODO // https://gitlab.com/gitlab-org/gitlab/issues/206904 const lines = await this.getPullsDiffStat(owner, repo, val.iid); return { ...pullRequest, lines }; } return pullRequest; }), ); const customPagination = this.getPagination(pagination); return { items, ...customPagination }; } /** * Get a single pull request. */ async getPullRequest(owner: string, repo: string, prNumber: number, withDiffStat?: boolean): Promise<PullRequest> { const { data } = await this.unwrap(this.client.MergeRequests.get(`${owner}/${repo}`, prNumber)); const user = await this.getUserInfo(owner); const pullRequest: PullRequest = { user: { id: data.author.id.toString(), login: data.author.username, url: data.author.web_url, }, title: data.title, url: data.web_url, sha: data.sha, createdAt: data.created_at.toString(), updatedAt: data.updated_at.toString(), closedAt: data.closed_at ? data.closed_at?.toString() : null, mergedAt: data.merged_at ? data.merged_at?.toString() : null, state: data.state, id: data.iid, base: { repo: { url: `${this.host}/${owner}/${repo}`, name: repo, id: data.project_id.toString(), owner: user, }, }, }; if (withDiffStat) { const lines = await this.getPullsDiffStat(owner, repo, prNumber); return { ...pullRequest, lines }; } return pullRequest; } async listPullRequestFiles(_owner: string, _repo: string, _prNumber: number): Promise<Paginated<PullFiles>> { throw new Error('Method not implemented yet.'); } async listPullCommits(owner: string, repo: string, prNumber: number, options?: ListGetterOptions): Promise<Paginated<PullCommits>> { const { data, pagination } = await this.unwrap( this.client.MergeRequests.listCommits(`${owner}/${repo}`, prNumber, options?.pagination), ); const items = <PullCommits[]>await Promise.all( data.map(async (val) => { const commitDetail = await this.unwrap(this.client.Commits.get(`${owner}/${repo}`, val.id)); const commit = { sha: val.id, commit: { url: `${this.host}/${owner}/${repo}/merge_requests/${prNumber}/diffs?commit_id=${val.id}`, message: val.message, author: { name: val.author_name, //get username? email: val.author_email, date: val.created_at.toString(), }, tree: { sha: commitDetail.data.parent_ids[0], url: `${this.host}/${owner}/${repo}/merge_requests/${prNumber}/diffs?commit_id=${commitDetail.data.parent_ids[0]}`, }, //TODO verified: false, }, }; return commit; }), ); const customPagination = this.getPagination(pagination); return { items, ...customPagination }; } async listIssues(owner: string, repo: string, options?: ListGetterOptions<{ state?: IssueState }>): Promise<Paginated<Issue>> { const state = VCSServicesUtils.getGitLabIssueState(options?.filter?.state); const { data, pagination } = await this.unwrap( this.client.Issues.list(`${owner}/${repo}`, { pagination: options?.pagination, filter: { state }, }), ); const user: UserInfo = await this.getUserInfo(owner); const items: Issue[] = data.map((val) => ({ user: user, url: val.web_url, body: val.description, createdAt: val.created_at.toString(), updatedAt: val.updated_at.toString(), closedAt: val.closed_at ? val.closed_at?.toString() : null, state: val.state, id: val.iid, })); const customPagination = this.getPagination(pagination); return { items, ...customPagination }; } async getIssue(owner: string, repo: string, issueNumber: number): Promise<Issue> { const { data } = await this.unwrap(this.client.Issues.get(`${owner}/${repo}`, issueNumber)); return { id: data.iid, user: { login: data.author.username, id: data.author.id.toString(), url: data.author.web_url, }, url: data.web_url, body: data.description, createdAt: data.created_at.toString(), updatedAt: data.updated_at.toString(), closedAt: data.closed_at ? data.closed_at.toString() : null, state: data.state, }; } async listIssueComments(owner: string, repo: string, issueNumber: number, options?: ListGetterOptions): Promise<Paginated<IssueComment>> { const { data, pagination } = await this.unwrap(this.client.Issues.listComments(`${owner}/${repo}`, issueNumber, options?.pagination)); const items = data.map((val) => ({ user: { id: val.author.id.toString(), login: val.author.username, url: val.author.web_url, }, url: `${this.host}/projects/${owner}/${repo}/notes/${val.id}`, // https://docs.gitlab.com/ee/api/notes.html body: val.body, createdAt: val.created_at.toString(), updatedAt: val.updated_at.toString(), authorAssociation: val.author.username, id: val.id, })); const customPagination = this.getPagination(pagination); return { items, ...customPagination }; } async listBranches(owner: string, repo: string, options?: ListGetterOptions): Promise<Paginated<Branch>> { const { data, pagination } = await this.unwrap(this.client.Branches.list(`${owner}/${repo}`, options?.pagination)); const customPagination = this.getPagination(pagination); const items = data.map((val) => ({ ...val, type: val.default ? 'default' : 'unknown' })); return Promise.resolve({ items, ...customPagination }); } async listPullRequestReviews(_owner: string, _repo: string, _prNumber: number): Promise<Paginated<PullRequestReview>> { throw new Error('Method not implemented yet.'); } async listRepoCommits(owner: string, repo: string, options?: ListGetterOptions): Promise<Paginated<Commit>> { const { data, pagination } = await this.unwrap(this.client.Commits.list(`${owner}/${repo}`, options?.pagination)); const items = data.map((val) => { return { sha: val.id, url: `${this.host}/projects/${owner}/${repo}/repository/commits/${val.short_id}`, message: val.message, author: { name: val.author_name, email: val.author_email, date: val.committed_date.toString(), }, tree: { sha: val.parent_ids[0], url: `${this.host}/projects/${owner}/${repo}/repository/commits/${val.parent_ids[0]}`, }, // TODO verified: false, }; }); const customPagination = this.getPagination(pagination); return { items, ...customPagination }; } async getCommit(owner: string, repo: string, commitSha: string): Promise<Commit> { const { data } = await this.unwrap(this.client.Commits.get(`${owner}/${repo}`, commitSha)); return { sha: data.id, url: `${this.host}/projects/${owner}/${repo}/repository/commits/${data.short_id}`, message: data.message, author: { name: data.author_name, email: data.author_email, date: data.committed_date.toString(), }, tree: { sha: data.parent_ids[0], url: `${this.host}/projects/${owner}/${repo}/repository/commits/${data.parent_ids[0]}`, }, // TODO verified: false, }; } /** * List Comments for a Pull Request */ async listPullRequestComments( owner: string, repo: string, prNumber: number, options?: ListGetterOptions, ): Promise<Paginated<PullRequestComment>> { const { data, pagination } = await this.unwrap( this.client.MergeRequests.listComments(`${owner}/${repo}`, prNumber, options?.pagination), ); const items = data.map((val) => ({ user: { id: val.author.id.toString(), login: val.author.username, url: val.author.web_url }, id: val.id, url: `${this.host}/projects/${owner}/${repo}/merge_requests/${prNumber}/notes`, body: val.body, createdAt: val.created_at.toString(), updatedAt: val.updated_at.toString(), authorAssociation: val.author.username, })); const customPagination = this.getPagination(pagination); return { items, ...customPagination }; } /** * Add Comment to a Pull Request */ async createPullRequestComment(owner: string, repo: string, prNumber: number, body: string): Promise<CreatedUpdatedPullRequestComment> { const { data } = await this.unwrap(this.client.MergeRequests.createComment(`${owner}/${repo}`, prNumber, body)); return { user: { id: `${data.author.id}`, login: data.author.username, url: data.author.web_url }, id: data.id, url: `${this.host}/projects/${owner}/${repo}/merge_requests/${prNumber}/notes`, body: data.body, createdAt: data.created_at.toString(), updatedAt: data.updated_at.toString(), }; } /** * Update Comment on a Pull Request */ async updatePullRequestComment( owner: string, repo: string, commentId: number, body: string, pullRequestId: number, ): Promise<CreatedUpdatedPullRequestComment> { const { data } = await this.unwrap(this.client.MergeRequests.updateComment(`${owner}/${repo}`, pullRequestId, body, commentId)); return { user: { id: `${data.author.id}`, login: data.author.username, url: data.author.web_url }, id: data.id, url: `${this.host}/projects/${owner}/${repo}/merge_requests/${pullRequestId}/notes`, body: data.body, createdAt: data.created_at.toString(), updatedAt: data.updated_at.toString(), }; } async listRepos() { const { data } = await this.unwrap(this.client.Projects.list()); return data; } async listGroups() { const { data } = await this.unwrap(this.client.Users.listGroups()); return data; } async listContributors(owner: string, repo: string, options?: ListGetterOptions): Promise<Contributor[]> { const contributors = await this.getAllContributors(`${owner}/${repo}`, options?.pagination); //get user info and create contributor object return Promise.all( contributors //filter duplicate committer names or committer emails - we want to make sure that we don't count some contributor twice .filter( (contributor, index, array) => array.findIndex((c) => { return c.name === contributor.name || c.email === contributor.email; }) === index, ) //get user info and create contributor object .map(async (contributor) => { return { user: (await this.searchUser(contributor.email, contributor.name)) || { login: contributor.name, }, //count real number of commits contributions: contributors.filter((c) => c.name === contributor.name).reduce((sum, c) => sum + c.commits, 0), }; }), ); } private async getAllContributors(projectId: string, pagination?: PaginationParams) { let response = await this.unwrap(this.client.Contributors.list(projectId, pagination)); let data = response.data; while (response.pagination.next) { const updatedPagination = _.merge(pagination, { page: response.pagination.next }); response = await this.unwrap(this.client.Contributors.list(projectId, updatedPagination)); data = data.concat(response.data); } return data; } async listContributorsStats(_owner: string, _repo: string): Promise<Paginated<ContributorStats>> { throw new Error('Method not implemented yet.'); } async getRepoContent(_owner: string, _repo: string, _path: string): Promise<File | Symlink | Directory | null> { throw new Error('Method not implemented yet.'); } async getPullsDiffStat(_owner: string, _repo: string, _prNumber: number): Promise<Lines> { throw new Error('Method not implemented yet for GitLab.'); } private async getUserInfo(owner: string) { let userInfo; try { userInfo = await this.unwrap(this.client.Users.getUser(owner)); return { id: userInfo.data[0].id.toString(), login: userInfo.data[0].username, url: userInfo.data[0].web_url, }; } catch (error) { userInfo = await this.unwrap(this.client.Users.getGroup(owner)); return { id: userInfo.data.id.toString(), login: userInfo.data.name, url: userInfo.data.web_url, }; } } private async searchUser(email: string, name: string) { let userInfo; try { userInfo = await this.unwrap(this.client.Users.searchUsersByEmail(email)); if (userInfo.data.length === 0) { userInfo = await this.unwrap(this.client.Users.searchUsersByName(name)); } return { id: userInfo.data[0].id.toString(), login: userInfo.data[0].username, url: userInfo.data[0].web_url, }; } catch (error) { return; } } private getPagination(pagination: PaginationGitLabCustomResponse): ServicePagination { const hasNextPage = !!pagination.next; const hasPreviousPage = !!pagination.previous; const page = pagination.current; const perPage = pagination.perPage; let totalCount = pagination.total; if (Number.isNaN(totalCount)) { // If the number of resources is more than 10,000, the X-Total is not present in the response headers. // https://docs.gitlab.com/ee/api/#other-pagination-headers totalCount = 10000; } return { totalCount, hasNextPage, hasPreviousPage, page, perPage }; } /** * Debug GitLab request promise */ private unwrap<T>(clientPromise: Promise<CustomAxiosResponse<T>>): Promise<CustomAxiosResponse<T>> { return clientPromise .then((response) => { this.debugGitLabResponse(response); return response; }) .catch((error) => { if (error.response) { this.d(`${error.response.status} => ${inspect(error.response.data)}`); } else { this.d(inspect(error)); } throw error; }); } /** * Debug GitLab response * - count API calls and inform about remaining rate limit */ private debugGitLabResponse = <T>(response: CustomAxiosResponse<T>) => { this.callCount++; this.d(`GitLab API Hit: ${this.callCount}. Remaining ${response.headers['RateLimit-Remaining']} hits.`); }; }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormSite_Information { interface tab_address_Sections { primary_address: DevKit.Controls.Section; time_zone: DevKit.Controls.Section; } interface tab_General_Sections { section1: DevKit.Controls.Section; } interface tab_address extends DevKit.Controls.ITab { Section: tab_address_Sections; } interface tab_General extends DevKit.Controls.ITab { Section: tab_General_Sections; } interface Tabs { address: tab_address; General: tab_General; } interface Body { Tab: Tabs; /** City name for address 1. */ Address1_City: DevKit.Controls.String; /** Country/region name for address 1. */ Address1_Country: DevKit.Controls.String; /** Fax number for address 1. */ Address1_Fax: DevKit.Controls.String; /** First line for entering address 1 information. */ Address1_Line1: DevKit.Controls.String; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.Controls.String; /** Third line for entering address 1 information. */ Address1_Line3: DevKit.Controls.String; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.Controls.String; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.Controls.String; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.Controls.String; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.Controls.String; /** Email address for the site. */ EMailAddress: DevKit.Controls.String; /** Name of the site. */ Name: DevKit.Controls.String; /** Local time zone for the site. */ TimeZoneCode: DevKit.Controls.Integer; } } class FormSite_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form Site_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Site_Information */ Body: DevKit.FormSite_Information.Body; } class SiteApi { /** * DynamicsCrm.DevKit SiteApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier for address 1. */ Address1_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 1, such as billing, shipping, or primary address. */ Address1_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 1. */ Address1_City: DevKit.WebApi.StringValue; /** Country/region name for address 1. */ Address1_Country: DevKit.WebApi.StringValue; /** County name for address 1. */ Address1_County: DevKit.WebApi.StringValue; /** Fax number for address 1. */ Address1_Fax: DevKit.WebApi.StringValue; /** Latitude for address 1. */ Address1_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 1 information. */ Address1_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 1 information. */ Address1_Line3: DevKit.WebApi.StringValue; /** Longitude for address 1. */ Address1_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 1. */ Address1_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 1. */ Address1_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 1. */ Address1_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 1. */ Address1_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 1. */ Address1_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 1. This is the difference between local time and standard Coordinated Universal Time. */ Address1_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier for address 2. */ Address2_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 2, such as billing, shipping, or primary address. */ Address2_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 2. */ Address2_City: DevKit.WebApi.StringValue; /** Country/region name for address 2. */ Address2_Country: DevKit.WebApi.StringValue; /** County name for address 2. */ Address2_County: DevKit.WebApi.StringValue; /** Fax number for address 2. */ Address2_Fax: DevKit.WebApi.StringValue; /** Latitude for address 2. */ Address2_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 2 information. */ Address2_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 2 information. */ Address2_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 2 information. */ Address2_Line3: DevKit.WebApi.StringValue; /** Longitude for address 2. */ Address2_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 2. */ Address2_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 2. */ Address2_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 2. */ Address2_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 2. */ Address2_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 2. */ Address2_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 2. */ Address2_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 2. */ Address2_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 2. */ Address2_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 2. */ Address2_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 2. This is the difference between local time and standard Coordinated Universal Time. */ Address2_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who created the site. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the site was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the site. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Email address for the site. */ EMailAddress: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who last modified the site. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the site was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the site. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Name of the site. */ Name: DevKit.WebApi.StringValue; /** Unique identifier for the organization */ OrganizationId: DevKit.WebApi.LookupValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the site. */ SiteId: DevKit.WebApi.GuidValue; /** Local time zone for the site. */ TimeZoneCode: DevKit.WebApi.IntegerValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace Site { enum Address1_AddressTypeCode { /** 1 */ Default_Value } enum Address1_ShippingMethodCode { /** 1 */ Default_Value } enum Address2_AddressTypeCode { /** 1 */ Default_Value } enum Address2_ShippingMethodCode { /** 1 */ Default_Value } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Volume } from "../component/channel/Volume"; import "../core/context/Destination"; import "../core/clock/Transport"; import { Param } from "../core/context/Param"; import { OutputNode, ToneAudioNode, ToneAudioNodeOptions, } from "../core/context/ToneAudioNode"; import { Decibels, Seconds, Time } from "../core/type/Units"; import { defaultArg } from "../core/util/Defaults"; import { noOp, readOnly } from "../core/util/Interface"; import { BasicPlaybackState, StateTimeline, StateTimelineEvent, } from "../core/util/StateTimeline"; import { isDefined, isUndef } from "../core/util/TypeCheck"; import { assert, assertContextRunning } from "../core/util/Debug"; import { GT } from "../core/util/Math"; type onStopCallback = (source: Source<any>) => void; export interface SourceOptions extends ToneAudioNodeOptions { volume: Decibels; mute: boolean; onstop: onStopCallback; } /** * Base class for sources. * start/stop of this.context.transport. * * ``` * // Multiple state change events can be chained together, * // but must be set in the correct order and with ascending times * // OK * state.start().stop("+0.2"); * // OK * state.start().stop("+0.2").start("+0.4").stop("+0.7") * // BAD * state.stop("+0.2").start(); * // BAD * state.start("+0.3").stop("+0.2"); * ``` */ export abstract class Source< Options extends SourceOptions > extends ToneAudioNode<Options> { /** * The output volume node */ private _volume: Volume; /** * The output note */ output: OutputNode; /** * Sources have no inputs */ input = undefined; /** * The volume of the output in decibels. * @example * const source = new Tone.PWMOscillator().toDestination(); * source.volume.value = -6; */ volume: Param<"decibels">; /** * The callback to invoke when the source is stopped. */ onstop: onStopCallback; /** * Keep track of the scheduled state. */ protected _state: StateTimeline<{ duration?: Seconds; offset?: Seconds; /** * Either the buffer is explicitly scheduled to end using the stop method, * or it's implicitly ended when the buffer is over. */ implicitEnd?: boolean; }> = new StateTimeline("stopped"); /** * The synced `start` callback function from the transport */ protected _synced = false; /** * Keep track of all of the scheduled event ids */ private _scheduled: number[] = []; /** * Placeholder functions for syncing/unsyncing to transport */ private _syncedStart: (time: Seconds, offset: Seconds) => void = noOp; private _syncedStop: (time: Seconds) => void = noOp; constructor(options: SourceOptions) { super(options); this._state.memory = 100; this._state.increasing = true; this._volume = this.output = new Volume({ context: this.context, mute: options.mute, volume: options.volume, }); this.volume = this._volume.volume; readOnly(this, "volume"); this.onstop = options.onstop; } static getDefaults(): SourceOptions { return Object.assign(ToneAudioNode.getDefaults(), { mute: false, onstop: noOp, volume: 0, }); } /** * Returns the playback state of the source, either "started" or "stopped". * @example * const player = new Tone.Player("https://tonejs.github.io/audio/berklee/ahntone_c3.mp3", () => { * player.start(); * console.log(player.state); * }).toDestination(); */ get state(): BasicPlaybackState { if (this._synced) { if (this.context.transport.state === "started") { return this._state.getValueAtTime( this.context.transport.seconds ) as BasicPlaybackState; } else { return "stopped"; } } else { return this._state.getValueAtTime(this.now()) as BasicPlaybackState; } } /** * Mute the output. * @example * const osc = new Tone.Oscillator().toDestination().start(); * // mute the output * osc.mute = true; */ get mute(): boolean { return this._volume.mute; } set mute(mute: boolean) { this._volume.mute = mute; } // overwrite these functions protected abstract _start(time: Time, offset?: Time, duration?: Time): void; protected abstract _stop(time: Time): void; protected abstract _restart( time: Seconds, offset?: Time, duration?: Time ): void; /** * Ensure that the scheduled time is not before the current time. * Should only be used when scheduled unsynced. */ private _clampToCurrentTime(time: Seconds): Seconds { if (this._synced) { return time; } else { return Math.max(time, this.context.currentTime); } } /** * Start the source at the specified time. If no time is given, * start the source now. * @param time When the source should be started. * @example * const source = new Tone.Oscillator().toDestination(); * source.start("+0.5"); // starts the source 0.5 seconds from now */ start(time?: Time, offset?: Time, duration?: Time): this { let computedTime = isUndef(time) && this._synced ? this.context.transport.seconds : this.toSeconds(time); computedTime = this._clampToCurrentTime(computedTime); // if it's started, stop it and restart it if ( !this._synced && this._state.getValueAtTime(computedTime) === "started" ) { // time should be strictly greater than the previous start time assert( GT( computedTime, (this._state.get(computedTime) as StateTimelineEvent).time ), "Start time must be strictly greater than previous start time" ); this._state.cancel(computedTime); this._state.setStateAtTime("started", computedTime); this.log("restart", computedTime); this.restart(computedTime, offset, duration); } else { this.log("start", computedTime); this._state.setStateAtTime("started", computedTime); if (this._synced) { // add the offset time to the event const event = this._state.get(computedTime); if (event) { event.offset = this.toSeconds(defaultArg(offset, 0)); event.duration = duration ? this.toSeconds(duration) : undefined; } const sched = this.context.transport.schedule((t) => { this._start(t, offset, duration); }, computedTime); this._scheduled.push(sched); // if the transport is already started // and the time is greater than where the transport is if ( this.context.transport.state === "started" && this.context.transport.getSecondsAtTime(this.immediate()) > computedTime ) { this._syncedStart( this.now(), this.context.transport.seconds ); } } else { assertContextRunning(this.context); this._start(computedTime, offset, duration); } } return this; } /** * Stop the source at the specified time. If no time is given, * stop the source now. * @param time When the source should be stopped. * @example * const source = new Tone.Oscillator().toDestination(); * source.start(); * source.stop("+0.5"); // stops the source 0.5 seconds from now */ stop(time?: Time): this { let computedTime = isUndef(time) && this._synced ? this.context.transport.seconds : this.toSeconds(time); computedTime = this._clampToCurrentTime(computedTime); if ( this._state.getValueAtTime(computedTime) === "started" || isDefined(this._state.getNextState("started", computedTime)) ) { this.log("stop", computedTime); if (!this._synced) { this._stop(computedTime); } else { const sched = this.context.transport.schedule( this._stop.bind(this), computedTime ); this._scheduled.push(sched); } this._state.cancel(computedTime); this._state.setStateAtTime("stopped", computedTime); } return this; } /** * Restart the source. */ restart(time?: Time, offset?: Time, duration?: Time): this { time = this.toSeconds(time); if (this._state.getValueAtTime(time) === "started") { this._state.cancel(time); this._restart(time, offset, duration); } return this; } /** * Sync the source to the Transport so that all subsequent * calls to `start` and `stop` are synced to the TransportTime * instead of the AudioContext time. * * @example * const osc = new Tone.Oscillator().toDestination(); * // sync the source so that it plays between 0 and 0.3 on the Transport's timeline * osc.sync().start(0).stop(0.3); * // start the transport. * Tone.Transport.start(); * // set it to loop once a second * Tone.Transport.loop = true; * Tone.Transport.loopEnd = 1; */ sync(): this { if (!this._synced) { this._synced = true; this._syncedStart = (time, offset) => { if (GT(offset, 0)) { // get the playback state at that time const stateEvent = this._state.get(offset); // listen for start events which may occur in the middle of the sync'ed time if ( stateEvent && stateEvent.state === "started" && stateEvent.time !== offset ) { // get the offset const startOffset = offset - this.toSeconds(stateEvent.time); let duration: number | undefined; if (stateEvent.duration) { duration = this.toSeconds(stateEvent.duration) - startOffset; } this._start( time, this.toSeconds(stateEvent.offset) + startOffset, duration ); } } }; this._syncedStop = (time) => { const seconds = this.context.transport.getSecondsAtTime( Math.max(time - this.sampleTime, 0) ); if (this._state.getValueAtTime(seconds) === "started") { this._stop(time); } }; this.context.transport.on("start", this._syncedStart); this.context.transport.on("loopStart", this._syncedStart); this.context.transport.on("stop", this._syncedStop); this.context.transport.on("pause", this._syncedStop); this.context.transport.on("loopEnd", this._syncedStop); } return this; } /** * Unsync the source to the Transport. See Source.sync */ unsync(): this { if (this._synced) { this.context.transport.off("stop", this._syncedStop); this.context.transport.off("pause", this._syncedStop); this.context.transport.off("loopEnd", this._syncedStop); this.context.transport.off("start", this._syncedStart); this.context.transport.off("loopStart", this._syncedStart); } this._synced = false; // clear all of the scheduled ids this._scheduled.forEach((id) => this.context.transport.clear(id)); this._scheduled = []; this._state.cancel(0); // stop it also this._stop(0); return this; } /** * Clean up. */ dispose(): this { super.dispose(); this.onstop = noOp; this.unsync(); this._volume.dispose(); this._state.dispose(); return this; } }
the_stack
import { dew as _inflateDewDew } from "./zlib/inflate.dew.js"; import { dew as _commonDewDew } from "./utils/common.dew.js"; import { dew as _stringsDewDew } from "./utils/strings.dew.js"; import { dew as _constantsDewDew } from "./zlib/constants.dew.js"; import { dew as _messagesDewDew } from "./zlib/messages.dew.js"; import { dew as _zstreamDewDew } from "./zlib/zstream.dew.js"; import { dew as _gzheaderDewDew } from "./zlib/gzheader.dew.js"; var exports = {}, _dewExec = false; export function dew() { if (_dewExec) return exports; _dewExec = true; var zlib_inflate = _inflateDewDew(); var utils = _commonDewDew(); var strings = _stringsDewDew(); var c = _constantsDewDew(); var msg = _messagesDewDew(); var ZStream = _zstreamDewDew(); var GZheader = _gzheaderDewDew(); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overridden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * - `dictionary` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && opt.windowBits >= 0 && opt.windowBits < 16) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if (opt.windowBits >= 0 && opt.windowBits < 16 && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if (opt.windowBits > 15 && opt.windowBits < 48) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2(this.strm, opt.windowBits); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); // Setup dictionary if (opt.dictionary) { // Convert data if needed if (typeof opt.dictionary === 'string') { opt.dictionary = strings.string2buf(opt.dictionary); } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') { opt.dictionary = new Uint8Array(opt.dictionary); } if (opt.raw) { //In raw mode we need to set the dictionary early status = zlib_inflate.inflateSetDictionary(this.strm, opt.dictionary); if (status !== c.Z_OK) { throw new Error(msg[status]); } } } } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var dictionary = this.options.dictionary; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = mode === ~~mode ? mode : mode === true ? c.Z_FINISH : c.Z_NO_FLUSH; // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_NEED_DICT && dictionary) { status = zlib_inflate.inflateSetDictionary(this.strm, dictionary); } if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH)) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): output data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 aligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg || msg[inflator.err]; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; return exports; }
the_stack
import { userOwns } from '../../vulcan-users/permissions'; import { foreignKeyField, resolverOnlyField, denormalizedField, denormalizedCountOfReferences } from '../../../lib/utils/schemaUtils'; import { mongoFindOne } from '../../mongoQueries'; import { commentGetPageUrlFromDB } from './helpers'; import { userGetDisplayNameById } from '../../vulcan-users/helpers'; import { schemaDefaultValue } from '../../collectionUtils'; import { Utils } from '../../vulcan-lib'; const schema: SchemaType<DbComment> = { // The `_id` of the parent comment, if there is one parentCommentId: { ...foreignKeyField({ idFieldName: "parentCommentId", resolverName: "parentComment", collectionName: "Comments", type: "Comment", nullable: true, }), canRead: ['guests'], canCreate: ['members'], optional: true, hidden: true, }, // The `_id` of the top-level parent comment, if there is one topLevelCommentId: { ...foreignKeyField({ idFieldName: "topLevelCommentId", resolverName: "topLevelComment", collectionName: "Comments", type: "Comment", nullable: true, }), denormalized: true, canRead: ['guests'], canCreate: ['members'], optional: true, hidden: true, }, // The timestamp of comment creation createdAt: { type: Date, optional: true, canRead: ['admins'], onInsert: (document, currentUser) => new Date(), }, // The timestamp of the comment being posted. For now, comments are always // created and posted at the same time postedAt: { type: Date, optional: true, canRead: ['guests'], onInsert: (document, currentUser) => new Date(), }, // The comment author's name author: { type: String, optional: true, canRead: ['guests'], onInsert: async (document, currentUser) => { // if userId is changing, change the author name too if (document.userId) { return await userGetDisplayNameById(document.userId) } }, onEdit: async (modifier, document, currentUser) => { // if userId is changing, change the author name too if (modifier.$set && modifier.$set.userId) { return await userGetDisplayNameById(modifier.$set.userId) } } }, // If this comment is on a post, the _id of that post. postId: { ...foreignKeyField({ idFieldName: "postId", resolverName: "post", collectionName: "Posts", type: "Post", nullable: true, }), optional: true, canRead: ['guests'], canCreate: ['members'], hidden: true, }, // If this comment is in a tag discussion section, the _id of the tag. tagId: { ...foreignKeyField({ idFieldName: "tagId", resolverName: "tag", collectionName: "Tags", type: "Tag", nullable: true, }), optional: true, canRead: ['guests'], canCreate: ['members'], hidden: true, }, // The comment author's `_id` userId: { ...foreignKeyField({ idFieldName: "userId", resolverName: "user", collectionName: "Users", type: "User", nullable: true, }), optional: true, canRead: ['guests'], canCreate: ['members'], hidden: true, }, userIP: { type: String, optional: true, canRead: ['admins'], }, userAgent: { type: String, optional: true, canRead: ['admins'], }, referrer: { type: String, optional: true, canRead: ['admins'], }, authorIsUnreviewed: { type: Boolean, optional: true, denormalized: true, ...schemaDefaultValue(false), viewableBy: ['guests'], insertableBy: ['admins', 'sunshineRegiment'], editableBy: ['admins', 'sunshineRegiment'], hidden: true, }, // GraphQL only fields pageUrl: resolverOnlyField({ type: String, canRead: ['guests'], resolver: async (comment: DbComment, args: void, context: ResolverContext) => { return await commentGetPageUrlFromDB(comment, true) }, }), pageUrlRelative: resolverOnlyField({ type: String, canRead: ['guests'], resolver: async (comment: DbComment, args: void, context: ResolverContext) => { return await commentGetPageUrlFromDB(comment, false) }, }), answer: { type: Boolean, optional: true, hidden: true, canRead: ['guests'], canCreate: ['members'], canUpdate: [userOwns, 'sunshineRegiment', 'admins'], ...schemaDefaultValue(false), }, parentAnswerId: { ...foreignKeyField({ idFieldName: "parentAnswerId", resolverName: "parentAnswer", collectionName: "Comments", type: "Comment", nullable: true, }), denormalized: true, canRead: ['guests'], canCreate: ['members'], optional: true, hidden: true, }, directChildrenCount: { ...denormalizedCountOfReferences({ fieldName: "directChildrenCount", collectionName: "Comments", foreignCollectionName: "Comments", foreignTypeName: "comment", foreignFieldName: "parentCommentId", filterFn: (comment: DbComment) => !comment.deleted }), canRead: ['guests'], }, // Number of descendent comments (including indirect descendents). descendentCount: { type: Number, denormalized: true, canRead: ['guests'], optional: true, hidden: true, ...schemaDefaultValue(0), }, latestChildren: resolverOnlyField({ type: Array, graphQLtype: '[Comment]', viewableBy: ['guests'], resolver: async (comment: DbComment, args: void, context: ResolverContext) => { const { Comments } = context; const params = Comments.getParameters({view:"shortformLatestChildren", topLevelCommentId: comment._id}) return await Comments.find(params.selector, params.options).fetch() } }), 'latestChildren.$': { type: String, optional: true, }, shortform: { type: Boolean, optional: true, hidden: true, canRead: ['guests'], canCreate: ['members', 'admins'], canUpdate: [userOwns, 'admins'], ...denormalizedField({ needsUpdate: data => ('postId' in data), getValue: async (comment: DbComment): Promise<boolean> => { if (!comment.postId) return false; const post = await mongoFindOne("Posts", {_id: comment.postId}); if (!post) return false; return !!post.shortform; } }), }, // users can write comments nominating posts for a particular review period. // this field is generally set by a custom dialog, // set to the year of the review period (i.e. '2018') nominatedForReview: { type: String, optional: true, hidden: true, canRead: ['guests'], canCreate: ['members', 'admins'], canUpdate: [userOwns, 'admins'], }, reviewingForReview: { type: String, optional: true, hidden: true, canRead: ['guests'], canCreate: ['members', 'admins'], canUpdate: [userOwns, 'admins'], }, lastSubthreadActivity: { type: Date, denormalized: true, optional: true, viewableBy: ['guests'], onInsert: (document, currentUser) => new Date(), }, // The semver-style version of the post that this comment was made against // This gets automatically created in a callback on creation postVersion: { type: String, optional: true, canRead: ['guests'], onCreate: async ({newDocument}) => { if (!newDocument.postId) return "1.0.0"; const post = await mongoFindOne("Posts", {_id: newDocument.postId}) return (post && post.contents && post.contents.version) || "1.0.0" } }, promoted: { type: Boolean, optional: true, canRead: ['guests'], canUpdate: ['admins', 'sunshineRegiment'], }, promotedByUserId: { ...foreignKeyField({ idFieldName: "promotedByUserId", resolverName: "promotedByUser", collectionName: "Users", type: "User", nullable: true, }), optional: true, canRead: ['guests'], canUpdate: ['sunshineRegiment', 'admins'], canCreate: ['sunshineRegiment', 'admins'], hidden: true, onUpdate: async ({data, currentUser, document, oldDocument, context}: { data: Partial<DbComment>, currentUser: DbUser|null, document: DbComment, oldDocument: DbComment, context: ResolverContext, }) => { if (data?.promoted && !oldDocument.promoted && document.postId) { Utils.updateMutator({ collection: context.Posts, context, selector: {_id:document.postId}, data: { lastCommentPromotedAt: new Date() }, currentUser, validate: false }) return currentUser!._id } } }, promotedAt: { type: Date, optional: true, canRead: ['guests'], onUpdate: async ({data, document, oldDocument}) => { if (data?.promoted && !oldDocument.promoted) { return new Date() } if (!document.promoted && oldDocument.promoted) { return null } } }, // Comments store a duplicate of their post's hideCommentKarma data. The // source of truth remains the hideCommentKarma field of the post. If this // field is true, we do not report the baseScore to non-admins. We update it // if (for some reason) this comment gets transferred to a new post. The // trickier case is updating this on post change. For that we rely on the // UpdateCommentHideKarma callback. hideKarma: { type: Boolean, optional: true, hidden: true, canRead: ['guests'], canCreate: ['members', 'admins'], canUpdate: ['admins'], ...denormalizedField({ needsUpdate: data => ('postId' in data), getValue: async comment => { if (!comment.postId) return false; const post = await mongoFindOne("Posts", {_id: comment.postId}); if (!post) return false; return !!post.hideCommentKarma; } }), }, // DEPRECATED field for GreaterWrong backwards compatibility wordCount: resolverOnlyField({ type: Number, viewableBy: ['guests'], resolver: (comment: DbComment, args: void, context: ResolverContext) => { const contents = comment.contents; if (!contents) return 0; return contents.wordCount; } }), // DEPRECATED field for GreaterWrong backwards compatibility htmlBody: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: (comment: DbComment, args: void, context: ResolverContext) => { const contents = comment.contents; if (!contents) return ""; return contents.html; } }), votingSystem: resolverOnlyField({ type: String, viewableBy: ['guests'], resolver: async (comment: DbComment, args: void, context: ResolverContext) => { if (!comment?.postId) { return "default"; } const post = await context.loaders.Posts.load(comment.postId); return post.votingSystem || "default"; } }), }; export default schema;
the_stack
import Vue, { ComponentOptions, CreateElement } from 'vue'; import { PropsDefinition } from 'vue/types/options'; import { CombinedVueInstance } from 'vue/types/vue'; import { VNode } from 'vue/types/vnode'; import { createNamespace } from '../../utils'; declare const h: CreateElement; const [createComponent, bem] = createNamespace('tree'); const triangularIcon = `<svg class=${bem( 'triangular-icon', )} width="14" height="14" viewBox="0 0 14 14"> <path d="M5.54297 3.5L9.04297 7L5.54297 10.5L5.54297 3.5Z" stroke-width="1.16667" stroke-linejoin="round"/> </svg> `; const checkIcon = `<svg class=${bem('check-icon')} width="12" height="12" viewBox="0 0 12 12"> <path d="M2.50195 5.99988L5.00195 8.49988L10.002 3.49988" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> `; const checkPartiallyIcon = `<svg class=${bem( 'check-partially-icon', )} width="12" height="12" viewBox="0 0 12 12"> <path d="M1.5 6H10.5" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> `; // ================================ // Props export interface TreeValue { /** * The value of the node. */ value: string | number; /** * Status, 'all' means all of children are selected or the node itself is selected. */ status: 'all' | 'partial'; /** * The child nodes. */ children?: TreeValue[]; } export interface TreeOption { /** * The id attribute for HTML element. */ id?: string; /** * The text content for display. */ label: string; /** * The value of the option. */ value?: string | number; /** * The nested child options, if provided in flat mode, the value of the option itself will be ignored. */ children?: TreeOption[]; } /** * @internal * Maps tree options to selected value */ export interface TreeOptionSelectedMap { [p: string]: boolean | TreeOptionSelectedMap; [p: number]: boolean | TreeOptionSelectedMap; } export interface TreeProps { /** * Selected values, use for v-model two-way binding with event `change` */ value: (string | number)[] | TreeValue[]; /** * The options array for selecting */ options: TreeOption[]; /** * Change the behavior of partially selected options to 'unselect all'. */ partialToUnselectAll: boolean; /** * Flat mode, use on-dimensional array for bound value. * Note that the value of none-end nodes in options will be ignore. */ flat: boolean; } // ================================ // Events export interface TreeEvents { onChange(value: (string | number)[] | TreeValue[]): void; } // ================================ // Data export interface TreeData { expandedOptions: TreeOption[]; selectedMap: TreeOptionSelectedMap; } // ================================ // Methods export interface TreeMethods { switchExpand(option: TreeOption): void; change(option: TreeOption, valuePath: (string | number)[]): void; renderOption( option: TreeOption, index: number, level: number, indent: boolean, valuePath: (string | number)[], ): VNode; } // ================================ // Computed export interface TreeComputed {} // ================================ // Instance export type TreeInstance = CombinedVueInstance<Vue, TreeData, TreeMethods, TreeComputed, TreeProps>; // ================================ // Helpers function findValue(option: TreeOption, values: TreeValue[]): TreeValue | undefined { for (const curValue of values) { if (option.value === curValue.value) { return curValue; } if (curValue.children && curValue.children.length > 0) { const childResult = findValue(option, curValue.children); if (childResult) { return childResult; } } } return undefined; } function mapTreeOptionAllSelected(options: TreeOption[]): TreeOptionSelectedMap { const map: TreeOptionSelectedMap = {}; options.forEach(option => { const { value, children } = option; if (!children || children.length === 0) { map[value!] = true; return; } map[value!] = mapTreeOptionAllSelected(children); }); return map; } function mapTreeOptions(options: TreeOption[], values: TreeValue[]): TreeOptionSelectedMap { const map: TreeOptionSelectedMap = {}; options.forEach(option => { const value = findValue(option, values); if (!option.children || option.children.length === 0) { map[option.value!] = !!value; return; } map[option.value!] = value?.status === 'all' ? mapTreeOptionAllSelected(option.children) : mapTreeOptions(option.children, values); }); return map; } function formTreeValuesFromMap(options: TreeOption[], map: TreeOptionSelectedMap): TreeValue[] { return options .map<TreeValue | undefined>(option => { const { value, children: childOptions } = option; const subMap = map[value!]; if (!childOptions || childOptions.length === 0) { if (subMap) { return { value: value!, status: 'all', }; } return undefined; } const children = formTreeValuesFromMap(childOptions, subMap as TreeOptionSelectedMap); if (children.length === 0) { return undefined; } const status = children.length < childOptions.length || children.some(c => c.status === 'partial') ? 'partial' : 'all'; return { value: value!, children, status, }; }) .filter((v): v is TreeValue => !!v); } function getSubMap( map: TreeOptionSelectedMap, valuePath: (string | number)[], ): TreeOptionSelectedMap | boolean { let subMap: TreeOptionSelectedMap | boolean = map; valuePath.forEach(segment => { if (typeof subMap === 'object') { subMap = subMap[segment]; } }); return subMap; } function modifyMap(map: TreeOptionSelectedMap, target: boolean): void { Object.entries(map).forEach(([value, subMap]) => { if (typeof subMap === 'boolean') { map[value] = target; } else { modifyMap(subMap, target); } }); } type TreeSelectedStatus = 'all' | 'partial' | 'none'; function getOptionStatus( map: TreeOptionSelectedMap, option: TreeOption, valuePath: (string | number)[], ): TreeSelectedStatus { const { children } = option; const subMap = getSubMap(map, valuePath); if (!children || children.length === 0) { if (subMap) { return 'all'; } else { return 'none'; } } const { length } = children; let amountAll = 0; let amountNone = 0; children.forEach(c => { switch (getOptionStatus(map, c, [...valuePath, c.value!])) { case 'all': amountAll += 1; break; case 'none': amountNone += 1; break; default: break; } }); if (amountAll === length) { return 'all'; } if (amountNone === length) { return 'none'; } return 'partial'; } function getOptionStatusFlat( selectedValues: (string | number)[], option: TreeOption, ): TreeSelectedStatus { const { value, children } = option; if (!children || children.length === 0) { if (selectedValues.includes(value!)) { return 'all'; } else { return 'none'; } } const { length } = children; let amountAll = 0; let amountNone = 0; children.forEach(c => { switch (getOptionStatusFlat(selectedValues, c)) { case 'all': amountAll += 1; break; case 'none': amountNone += 1; break; default: break; } }); if (amountAll === length) { return 'all'; } if (amountNone === length) { return 'none'; } return 'partial'; } function getOptionValuesFlat(option: TreeOption): (string | number)[] { const { value, children } = option; if (!children || children.length === 0) { return [value!]; } return children.map(c => getOptionValuesFlat(c)).flat(1); } // ================================ // Component Options const Tree: ComponentOptions< Vue, () => TreeData, TreeMethods, TreeComputed, PropsDefinition<TreeProps> > = { data() { return { expandedOptions: [], selectedMap: {}, }; }, model: { prop: 'value', event: 'change', }, props: { value: { type: Array, required: true, }, options: { type: Array, required: true, }, partialToUnselectAll: { type: Boolean, default: false, }, flat: { type: Boolean, default: false, }, }, watch: { value: { immediate: true, handler( this: TreeInstance, val: (string | number)[] | TreeValue[], oldVal: (string | number)[] | TreeValue[], ): void { if (!this.flat) { if (val !== oldVal) { this.selectedMap = mapTreeOptions(this.options, val as TreeValue[]); } } }, }, options: { handler(this: TreeInstance, _options: TreeOption[]): void { this.expandedOptions = []; }, }, }, methods: { switchExpand(this: TreeInstance, option) { if (this.expandedOptions.includes(option)) { this.expandedOptions = this.expandedOptions.filter(o => o !== option); return; } this.expandedOptions.push(option); }, change(this: TreeInstance, option, valuePath) { const { value: selectedValues, options, partialToUnselectAll, flat, selectedMap } = this; if (flat) { const selectedValuesFlat = selectedValues as (string | number)[]; const optionStatus = getOptionStatusFlat(selectedValuesFlat, option); const optionValues = getOptionValuesFlat(option); const newValue: (string | number)[] = optionStatus === 'none' || (optionStatus === 'partial' && !partialToUnselectAll) ? Array.from(new Set([...selectedValuesFlat, ...optionValues])) : selectedValuesFlat.filter(v => !optionValues.includes(v)); this.$emit('change', newValue); } else { const optionStatus = getOptionStatus(selectedMap, option, valuePath); const subMap = getSubMap(selectedMap, valuePath); const target = optionStatus === 'none' || (optionStatus === 'partial' && !partialToUnselectAll); if (typeof subMap === 'object') { modifyMap(subMap, target); } else { const parentMap = getSubMap( selectedMap, valuePath.slice(0, valuePath.length - 1), ) as TreeOptionSelectedMap; parentMap[valuePath[valuePath.length - 1]] = target; } const newValue = formTreeValuesFromMap(options, selectedMap); this.$emit('change', newValue); } }, renderOption(this: TreeInstance, option, _index, level, indent, valuePath) { const { value: selectedValues, flat, expandedOptions, selectedMap } = this; const { id, label, value, children } = option; const hasChildren = !!children && children.length > 0; const hasGrandchildren = hasChildren && children!.some(c => c.children && c.children.length > 0); const expanded = expandedOptions.includes(option); const currentValuePath: (string | number)[] = [...valuePath, value!]; const status = flat ? getOptionStatusFlat(selectedValues as (string | number)[], option) : getOptionStatus(selectedMap, option, currentValuePath); const onExpand = (event: Event) => { event.stopPropagation(); event.preventDefault(); this.switchExpand(option); }; const onChange = (event: Event) => { event.stopPropagation(); event.preventDefault(); this.change(option, currentValuePath); }; return ( <div class={bem('node')}> <div class={bem('container')} id={id} onClick={(hasChildren && onExpand) || onChange}> {(hasChildren && ( <i class={bem('triangular', { expanded })} domPropsInnerHTML={triangularIcon}></i> )) || (indent && <i class={bem('triangular')}></i>)} <span class={bem('label')}>{label}</span> <i class={bem('check', `status-${status}`)} domPropsInnerHTML={ (status === 'all' && checkIcon) || (status === 'partial' && checkPartiallyIcon) || '' } onClick={onChange} ></i> </div> <div class={bem('children', { expanded })}> {hasChildren && children!.map((c, i) => this.renderOption(c, i, level + 1, hasGrandchildren, currentValuePath), )} </div> </div> ); }, }, render(this: TreeInstance) { const { options } = this; const hasChildren = options.some(o => o.children && o.children.length > 0); const currentValuePath: (string | number)[] = []; const classes = bem(); return ( <div class={classes}> {options.map((option, index) => this.renderOption(option, index, 0, hasChildren, currentValuePath), )} </div> ); }, }; export default createComponent(Tree as any);
the_stack
import PostgrestTransformBuilder from './PostgrestTransformBuilder' /** * Filters */ type FilterOperator = | 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'is' | 'in' | 'cs' | 'cd' | 'sl' | 'sr' | 'nxl' | 'nxr' | 'adj' | 'ov' | 'fts' | 'plfts' | 'phfts' | 'wfts' | 'not.eq' | 'not.neq' | 'not.gt' | 'not.gte' | 'not.lt' | 'not.lte' | 'not.like' | 'not.ilike' | 'not.is' | 'not.in' | 'not.cs' | 'not.cd' | 'not.sl' | 'not.sr' | 'not.nxl' | 'not.nxr' | 'not.adj' | 'not.ov' | 'not.fts' | 'not.plfts' | 'not.phfts' | 'not.wfts' export default class PostgrestFilterBuilder<T> extends PostgrestTransformBuilder<T> { /** * Finds all rows which doesn't satisfy the filter. * * @param column The column to filter on. * @param operator The operator to filter with. * @param value The value to filter with. */ not(column: keyof T, operator: FilterOperator, value: any): this { this.url.searchParams.append(`${column}`, `not.${operator}.${value}`) return this } /** * Finds all rows satisfying at least one of the filters. * * @param filters The filters to use, separated by commas. * @param foreignTable The foreign table to use (if `column` is a foreign column). */ or(filters: string, { foreignTable }: { foreignTable?: string } = {}): this { const key = typeof foreignTable === 'undefined' ? 'or' : `${foreignTable}.or` this.url.searchParams.append(key, `(${filters})`) return this } /** * Finds all rows whose value on the stated `column` exactly matches the * specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ eq(column: keyof T, value: T[keyof T]): this { this.url.searchParams.append(`${column}`, `eq.${value}`) return this } /** * Finds all rows whose value on the stated `column` doesn't match the * specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ neq(column: keyof T, value: T[keyof T]): this { this.url.searchParams.append(`${column}`, `neq.${value}`) return this } /** * Finds all rows whose value on the stated `column` is greater than the * specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ gt(column: keyof T, value: T[keyof T]): this { this.url.searchParams.append(`${column}`, `gt.${value}`) return this } /** * Finds all rows whose value on the stated `column` is greater than or * equal to the specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ gte(column: keyof T, value: T[keyof T]): this { this.url.searchParams.append(`${column}`, `gte.${value}`) return this } /** * Finds all rows whose value on the stated `column` is less than the * specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ lt(column: keyof T, value: T[keyof T]): this { this.url.searchParams.append(`${column}`, `lt.${value}`) return this } /** * Finds all rows whose value on the stated `column` is less than or equal * to the specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ lte(column: keyof T, value: T[keyof T]): this { this.url.searchParams.append(`${column}`, `lte.${value}`) return this } /** * Finds all rows whose value in the stated `column` matches the supplied * `pattern` (case sensitive). * * @param column The column to filter on. * @param pattern The pattern to filter with. */ like(column: keyof T, pattern: string): this { this.url.searchParams.append(`${column}`, `like.${pattern}`) return this } /** * Finds all rows whose value in the stated `column` matches the supplied * `pattern` (case insensitive). * * @param column The column to filter on. * @param pattern The pattern to filter with. */ ilike(column: keyof T, pattern: string): this { this.url.searchParams.append(`${column}`, `ilike.${pattern}`) return this } /** * A check for exact equality (null, true, false), finds all rows whose * value on the stated `column` exactly match the specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ is(column: keyof T, value: boolean | null): this { this.url.searchParams.append(`${column}`, `is.${value}`) return this } /** * Finds all rows whose value on the stated `column` is found on the * specified `values`. * * @param column The column to filter on. * @param values The values to filter with. */ in(column: keyof T, values: T[keyof T][]): this { const cleanedValues = values .map((s) => { // handle postgrest reserved characters // https://postgrest.org/en/v7.0.0/api.html#reserved-characters if (typeof s === 'string' && new RegExp('[,()]').test(s)) return `"${s}"` else return `${s}` }) .join(',') this.url.searchParams.append(`${column}`, `in.(${cleanedValues})`) return this } /** * Finds all rows whose json, array, or range value on the stated `column` * contains the values specified in `value`. * * @param column The column to filter on. * @param value The value to filter with. */ contains(column: keyof T, value: string | T[keyof T][] | object): this { if (typeof value === 'string') { // range types can be inclusive '[', ']' or exclusive '(', ')' so just // keep it simple and accept a string this.url.searchParams.append(`${column}`, `cs.${value}`) } else if (Array.isArray(value)) { // array this.url.searchParams.append(`${column}`, `cs.{${value.join(',')}}`) } else { // json this.url.searchParams.append(`${column}`, `cs.${JSON.stringify(value)}`) } return this } /** @deprecated Use `contains()` instead. */ cs = this.contains /** * Finds all rows whose json, array, or range value on the stated `column` is * contained by the specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ containedBy(column: keyof T, value: string | T[keyof T][] | object): this { if (typeof value === 'string') { // range this.url.searchParams.append(`${column}`, `cd.${value}`) } else if (Array.isArray(value)) { // array this.url.searchParams.append(`${column}`, `cd.{${value.join(',')}}`) } else { // json this.url.searchParams.append(`${column}`, `cd.${JSON.stringify(value)}`) } return this } /** @deprecated Use `containedBy()` instead. */ cd = this.containedBy /** * Finds all rows whose range value on the stated `column` is strictly to the * left of the specified `range`. * * @param column The column to filter on. * @param range The range to filter with. */ rangeLt(column: keyof T, range: string): this { this.url.searchParams.append(`${column}`, `sl.${range}`) return this } /** @deprecated Use `rangeLt()` instead. */ sl = this.rangeLt /** * Finds all rows whose range value on the stated `column` is strictly to * the right of the specified `range`. * * @param column The column to filter on. * @param range The range to filter with. */ rangeGt(column: keyof T, range: string): this { this.url.searchParams.append(`${column}`, `sr.${range}`) return this } /** @deprecated Use `rangeGt()` instead. */ sr = this.rangeGt /** * Finds all rows whose range value on the stated `column` does not extend * to the left of the specified `range`. * * @param column The column to filter on. * @param range The range to filter with. */ rangeGte(column: keyof T, range: string): this { this.url.searchParams.append(`${column}`, `nxl.${range}`) return this } /** @deprecated Use `rangeGte()` instead. */ nxl = this.rangeGte /** * Finds all rows whose range value on the stated `column` does not extend * to the right of the specified `range`. * * @param column The column to filter on. * @param range The range to filter with. */ rangeLte(column: keyof T, range: string): this { this.url.searchParams.append(`${column}`, `nxr.${range}`) return this } /** @deprecated Use `rangeLte()` instead. */ nxr = this.rangeLte /** * Finds all rows whose range value on the stated `column` is adjacent to * the specified `range`. * * @param column The column to filter on. * @param range The range to filter with. */ rangeAdjacent(column: keyof T, range: string): this { this.url.searchParams.append(`${column}`, `adj.${range}`) return this } /** @deprecated Use `rangeAdjacent()` instead. */ adj = this.rangeAdjacent /** * Finds all rows whose array or range value on the stated `column` overlaps * (has a value in common) with the specified `value`. * * @param column The column to filter on. * @param value The value to filter with. */ overlaps(column: keyof T, value: string | T[keyof T][]): this { if (typeof value === 'string') { // range this.url.searchParams.append(`${column}`, `ov.${value}`) } else { // array this.url.searchParams.append(`${column}`, `ov.{${value.join(',')}}`) } return this } /** @deprecated Use `overlaps()` instead. */ ov = this.overlaps /** * Finds all rows whose text or tsvector value on the stated `column` matches * the tsquery in `query`. * * @param column The column to filter on. * @param query The Postgres tsquery string to filter with. * @param config The text search configuration to use. * @param type The type of tsquery conversion to use on `query`. */ textSearch( column: keyof T, query: string, { config, type = null, }: { config?: string; type?: 'plain' | 'phrase' | 'websearch' | null } = {} ): this { let typePart = '' if (type === 'plain') { typePart = 'pl' } else if (type === 'phrase') { typePart = 'ph' } else if (type === 'websearch') { typePart = 'w' } const configPart = config === undefined ? '' : `(${config})` this.url.searchParams.append(`${column}`, `${typePart}fts${configPart}.${query}`) return this } /** * Finds all rows whose tsvector value on the stated `column` matches * to_tsquery(`query`). * * @param column The column to filter on. * @param query The Postgres tsquery string to filter with. * @param config The text search configuration to use. * * @deprecated Use `textSearch()` instead. */ fts(column: keyof T, query: string, { config }: { config?: string } = {}): this { const configPart = typeof config === 'undefined' ? '' : `(${config})` this.url.searchParams.append(`${column}`, `fts${configPart}.${query}`) return this } /** * Finds all rows whose tsvector value on the stated `column` matches * plainto_tsquery(`query`). * * @param column The column to filter on. * @param query The Postgres tsquery string to filter with. * @param config The text search configuration to use. * * @deprecated Use `textSearch()` with `type: 'plain'` instead. */ plfts(column: keyof T, query: string, { config }: { config?: string } = {}): this { const configPart = typeof config === 'undefined' ? '' : `(${config})` this.url.searchParams.append(`${column}`, `plfts${configPart}.${query}`) return this } /** * Finds all rows whose tsvector value on the stated `column` matches * phraseto_tsquery(`query`). * * @param column The column to filter on. * @param query The Postgres tsquery string to filter with. * @param config The text search configuration to use. * * @deprecated Use `textSearch()` with `type: 'phrase'` instead. */ phfts(column: keyof T, query: string, { config }: { config?: string } = {}): this { const configPart = typeof config === 'undefined' ? '' : `(${config})` this.url.searchParams.append(`${column}`, `phfts${configPart}.${query}`) return this } /** * Finds all rows whose tsvector value on the stated `column` matches * websearch_to_tsquery(`query`). * * @param column The column to filter on. * @param query The Postgres tsquery string to filter with. * @param config The text search configuration to use. * * @deprecated Use `textSearch()` with `type: 'websearch'` instead. */ wfts(column: keyof T, query: string, { config }: { config?: string } = {}): this { const configPart = typeof config === 'undefined' ? '' : `(${config})` this.url.searchParams.append(`${column}`, `wfts${configPart}.${query}`) return this } /** * Finds all rows whose `column` satisfies the filter. * * @param column The column to filter on. * @param operator The operator to filter with. * @param value The value to filter with. */ filter(column: keyof T, operator: FilterOperator, value: any): this { this.url.searchParams.append(`${column}`, `${operator}.${value}`) return this } /** * Finds all rows whose columns match the specified `query` object. * * @param query The object to filter with, with column names as keys mapped * to their filter values. */ match(query: Record<string, unknown>): this { Object.keys(query).forEach((key) => { this.url.searchParams.append(`${key}`, `eq.${query[key]}`) }) return this } }
the_stack
import * as debug_ from "debug"; import { app } from "electron"; import { appendFileSync, promises as fsp } from "fs"; import { clone } from "ramda"; import { LocaleConfigIdentifier, LocaleConfigValueType } from "readium-desktop/common/config"; import { LocatorType } from "readium-desktop/common/models/locator"; import { TBookmarkState } from "readium-desktop/common/redux/states/bookmark"; import { I18NState } from "readium-desktop/common/redux/states/i18n"; import { AvailableLanguages } from "readium-desktop/common/services/translator"; import { deepStrictEqual, ok } from "readium-desktop/common/utils/assert"; import { ConfigDocument } from "readium-desktop/main/db/document/config"; import { OpdsFeedDocument } from "readium-desktop/main/db/document/opds"; import { ConfigRepository } from "readium-desktop/main/db/repository/config"; import { backupStateFilePathFn, CONFIGREPOSITORY_REDUX_PERSISTENCE, diMainGet, memoryLoggerFilename, patchFilePath, runtimeStateFilePath, stateFilePath, } from "readium-desktop/main/di"; import { reduxSyncMiddleware } from "readium-desktop/main/redux/middleware/sync"; import { rootReducer } from "readium-desktop/main/redux/reducers"; import { rootSaga } from "readium-desktop/main/redux/sagas"; import { PersistRootState, RootState } from "readium-desktop/main/redux/states"; import { IS_DEV } from "readium-desktop/preprocessor-directives"; import { ObjectKeys } from "readium-desktop/utils/object-keys-values"; import { tryCatch, tryCatchSync } from "readium-desktop/utils/tryCatch"; import { applyMiddleware, createStore, Store } from "redux"; import createSagaMiddleware, { SagaMiddleware } from "redux-saga"; import { applyPatch } from "rfc6902"; import { reduxPersistMiddleware } from "../middleware/persistence"; import { IDictPublicationState } from "../states/publication"; import { IDictWinRegistryReaderState } from "../states/win/registry/reader"; // import { composeWithDevTools } from "remote-redux-devtools"; const REDUX_REMOTE_DEVTOOLS_PORT = 7770; const debugStdout = debug_("readium-desktop:main:store:memory"); // Logger const debug = (...a: Parameters<debug_.Debugger>) => { debugStdout(...a); tryCatchSync(() => appendFileSync(memoryLoggerFilename, a.map((v) => `${+new Date()} ${JSON.stringify(v)}`).join("\n") + "\n"), "", ); }; const defaultLocale = (): LocaleConfigValueType => { const loc = app.getLocale().split("-")[0]; const langCodes = ObjectKeys(AvailableLanguages); const lang = langCodes.find((l) => l === loc) || "en"; return { locale: lang, }; }; const absorbBookmarkToReduxState = async (registryReader: IDictWinRegistryReaderState) => { const locatorRepository = diMainGet("locator-repository"); const bookmarkFromDb = await locatorRepository.find( { selector: { locatorType: LocatorType.Bookmark }, sort: [{ updatedAt: "asc" }], }, ); let counter = 0; for (const locator of bookmarkFromDb) { if (locator.publicationIdentifier) { const reader = registryReader[locator.publicationIdentifier]?.reduxState; if (reader) { const bookmarkFromRedux = reader.bookmark || []; const bookmarkFromPouchdbConverted = bookmarkFromDb.reduce<TBookmarkState>((pv, cv) => cv.publicationIdentifier === locator.publicationIdentifier && !bookmarkFromRedux.find(([, v]) => v.uuid === cv.identifier) ? [ ...pv, [ ++counter, { uuid: cv.identifier, name: cv.name || "", locator: cv.locator, }, ], ] : pv, [], ); const bookmark = [ ...bookmarkFromRedux, ...bookmarkFromPouchdbConverted, ]; reader.bookmark = bookmark; } } } return registryReader; }; const absorbOpdsFeedToReduxState = async (docs: OpdsFeedDocument[] | undefined) => { const opdsFeedRepository = diMainGet("opds-feed-repository"); const opdsFromDb = await opdsFeedRepository.findAllFromPouchdb(); let newDocs = docs || []; debug("DB ABSORB OPDS init", newDocs); for (const doc of opdsFromDb) { const { identifier } = doc; const idx = newDocs.findIndex((v) => v.identifier === identifier); if (newDocs[idx]) { if (newDocs[idx].removedButPreservedToAvoidReMigration) { debug(`DB ABSORB OPDS removedButPreservedToAvoidReMigration: ${identifier} ${idx}`); continue; } // note that this actually never occurs because OPDS feeds are immutable (no dynamic tags, no title rename) if (newDocs[idx].doNotMigrateAnymore) { debug(`DB ABSORB OPDS doNotMigrateAnymore: ${identifier} ${idx}`); continue; } debug(`DB ABSORB OPDS override: ${identifier} ${idx}`); const newDoc = clone(doc); // we DO NOT set this here (see opdsActions.addOpdsFeed, and comment for OpdsFeedDocument.doNotMigrateAnymore) // newDoc.doNotMigrateAnymore = true; newDoc.migratedFrom1_6Database = true; newDocs = [ ...newDocs.slice(0, idx), newDoc, ...newDocs.slice(idx + 1), ]; } else { debug(`DB ABSORB OPDS append: ${identifier} ${idx}`); const newDoc = clone(doc); // we DO NOT set this here (see opdsActions.addOpdsFeed, and comment for OpdsFeedDocument.doNotMigrateAnymore) // newDoc.doNotMigrateAnymore = true; newDoc.migratedFrom1_6Database = true; newDocs = [ ...newDocs, newDoc, ]; } } return newDocs; }; const absorbPublicationToReduxState = async (pubs: IDictPublicationState | undefined) => { const publicationRepository = diMainGet("publication-repository"); // const PublicationViewConverter = diMainGet("publication-view-converter"); const pubsFromDb = await publicationRepository.findAllFromPouchdb(); const newPubs = pubs || {}; debug("DB ABSORB PUB init", newPubs); for (const pub of pubsFromDb) { const { identifier } = pub; if (newPubs[identifier]?.removedButPreservedToAvoidReMigration) { debug(`DB ABSORB PUB removedButPreservedToAvoidReMigration: ${identifier}`); continue; } if (newPubs[identifier]?.doNotMigrateAnymore) { debug(`DB ABSORB PUB doNotMigrateAnymore: ${identifier}`); continue; } if (!newPubs[identifier] || !newPubs[identifier].doNotMigrateAnymore) { if (typeof ((pub as any)["r2PublicationBase64"]) !== "undefined") { delete (pub as any)["r2PublicationBase64"]; } if (typeof ((pub as any)["r2OpdsPublicationBase64"]) !== "undefined") { delete (pub as any)["r2OpdsPublicationBase64"]; } if (pub.lcp) { if (typeof ((pub.lcp as any)["r2LCPBase64"]) !== "undefined") { delete (pub.lcp as any)["r2LCPBase64"]; } if (pub.lcp.lsd) { if (typeof ((pub.lcp.lsd as any)["r2LSDBase64"]) !== "undefined") { delete (pub.lcp.lsd as any)["r2LSDBase64"]; } if (pub.lcp.lsd.lsdStatus) { if (typeof ((pub.lcp.lsd.lsdStatus as any)["events"]) !== "undefined") { delete (pub.lcp.lsd.lsdStatus as any)["events"]; } } } } debug(`DB ABSORB PUB override: ${identifier}`); const newDoc = clone(pub); // we DO NOT set this here (see publicationActions.addPublication, and comment for PublicationDocument.doNotMigrateAnymore) // newDoc.doNotMigrateAnymore = true; newDoc.migratedFrom1_6Database = true; newPubs[identifier] = newDoc; } } return newPubs; }; const absorbI18nToReduxState = async ( configRepository: ConfigRepository<LocaleConfigValueType>, i18n: I18NState) => { if (i18n) { return i18n; } const i18nStateRepository = await configRepository.get(LocaleConfigIdentifier); i18n = i18nStateRepository?.value?.locale ? i18nStateRepository.value : defaultLocale(); debug("LOCALE FROM POUCHDB", i18n); return i18n; }; const checkReduxState = async (runtimeState: object, reduxState: PersistRootState) => { deepStrictEqual(runtimeState, reduxState); debug("hydration state is certified compliant"); return reduxState; }; const runtimeState = async (): Promise<object> => { const runtimeStateStr = await tryCatch(() => fsp.readFile(runtimeStateFilePath, { encoding: "utf8" }), ""); const runtimeState = await tryCatch(() => JSON.parse(runtimeStateStr), ""); ok(typeof runtimeState === "object"); return runtimeState; }; const recoveryReduxState = async (runtimeState: object): Promise<object> => { const patchFileStrRaw = await tryCatch(() => fsp.readFile(patchFilePath, { encoding: "utf8" }), ""); const patchFileStr = "[" + patchFileStrRaw.slice(0, -2) + "]"; // remove the last comma const patch = await tryCatch(() => JSON.parse(patchFileStr), ""); ok(Array.isArray(patch)); const errors = applyPatch(runtimeState, patch); ok(errors.reduce((pv, cv) => pv && !cv, true)); ok(typeof runtimeState === "object", "state not defined after patch"); return runtimeState; }; const test = (stateRaw: any): stateRaw is PersistRootState => { ok(typeof stateRaw === "object"); ok(stateRaw.win); ok(stateRaw.publication); ok(stateRaw.reader); ok(stateRaw.session); return stateRaw; }; export async function initStore(configRepository: ConfigRepository<any>) : Promise<[Store<RootState>, SagaMiddleware<object>]> { let reduxStateWinRepository: ConfigDocument<PersistRootState>; let reduxState: PersistRootState | undefined; debug(""); debug("MEMORY INIT STORE"); try { const jsonStr = await fsp.readFile(stateFilePath, { encoding: "utf8" }); const json = JSON.parse(jsonStr); if (test(json)) reduxState = json; debug("STATE LOADED FROM FS"); debug("the state doesn't come from pouchDb !"); debug("😍😍😍😍😍😍😍😍"); } catch { try { const reduxStateRepositoryResult = await configRepository.get(CONFIGREPOSITORY_REDUX_PERSISTENCE); reduxStateWinRepository = reduxStateRepositoryResult; reduxState = reduxStateWinRepository?.value ? reduxStateWinRepository.value : undefined; // TODO: // see main/redux/actions/win/registry/registerReaderPublication.ts // action creator also deletes highlight + info if (reduxState?.win?.registry?.reader) { const keys = Object.keys(reduxState.win.registry.reader); for (const key of keys) { const obj = reduxState.win.registry.reader[key]; if (obj?.reduxState?.info) { delete obj.reduxState.info; } if (obj?.reduxState?.highlight) { delete obj.reduxState.highlight; } } } if (reduxState) { debug("STATE LOADED FROM POUCHDB"); debug("the state doesn't come from the new json filesystem database"); debug("😩😩😩😩😩😩😩"); } } catch (err) { debug("ERR when trying to get the state in Pouchb configRepository", err); } } try { const state = await recoveryReduxState(await runtimeState()); reduxState = await checkReduxState(state, reduxState); debug("RECOVERY WORKS lvl 1/4"); } catch (e) { debug("N-1 STATE + PATCH != STATE"); debug("Your state is probably corrupted"); debug("If it is a fresh thorium installation do not worry"); debug("If it is a migration from Thorium 1.6 to Thorium 1.7 do not worry too, migrtion process will start"); debug(e); try { test(reduxState); debug("RECOVERY : the state is provided from the pouchdb database or from potentially corrupted state.json file"); debug("the last state.json seems good after a quick test on it !"); debug("state - 1 + patch is not used"); debug("recovery state come from state.json"); debug("REVOVERY WORKS lvl 2/4"); } catch { try { const stateRawFirst = await runtimeState(); test(stateRawFirst); const stateRaw: any = await recoveryReduxState(stateRawFirst); test(stateRaw); reduxState = stateRaw; debug("RECOVERY : the state is provided from the state - 1 + patch"); debug("There should be no data loss"); debug("REVOVERY WORKS lvl 3/4"); } catch { try { const stateRawFirst: any = await runtimeState(); test(stateRawFirst); reduxState = stateRawFirst; debug("RECOVERY : the state is the previous runtime snapshot"); debug("There should be data loss !"); debug("RECOVERY WORKS 4/4"); } catch { // do not erase reduxState for security purpose // reduxState = undefined; debug("REDUX STATE IS CORRUPTED THE TEST FAILED"); debug("For security purpose the state is not erase"); debug("Be carefull, an unexpected behaviour may occur"); debug("RECOVERY FAILED none of the 4 recoveries mode worked"); } } } finally { const p = backupStateFilePathFn(); await tryCatch(() => fsp.writeFile(p, JSON.stringify(reduxState), { encoding: "utf8" }), ""); debug("RECOVERY : a state backup file is copied in " + p); debug("keep it safe, you may restore a corrupted state with it"); } } finally { await tryCatch(() => fsp.writeFile( runtimeStateFilePath, reduxState ? JSON.stringify(reduxState) : "", { encoding: "utf8" }, ) , ""); // the file doen't have a top array [...] // we need to add it before the parsing await tryCatch(() => fsp.writeFile(patchFilePath, "", { encoding: "utf8" }), ""); } if (!reduxState) { debug("####### WARNING ######"); debug("Thorium starts with a fresh new session"); debug("There are no DATABASE on the filesystem"); debug("####### WARNING ######"); } debug("REDUX STATE VALUE :: ", typeof reduxState, reduxState ? Object.keys(reduxState) : "nil"); // debug(reduxState); try { // Be carefull not an object copy / same reference reduxState.win.registry.reader = await absorbBookmarkToReduxState(reduxState.win.registry.reader); } catch (e) { debug("ERR on absorb bookmark to redux state", e); } try { // Be carefull not an object copy / same reference reduxState.publication.db = await absorbPublicationToReduxState(reduxState.publication.db); } catch (e) { debug("ERR on absorb publication to redux state", e); } try { reduxState.i18n = await absorbI18nToReduxState(configRepository, reduxState.i18n); } catch (e) { debug("ERR on absorb i18n to redux state", e); } try { reduxState.opds = { catalog: await absorbOpdsFeedToReduxState(reduxState.opds?.catalog), }; } catch (e) { debug("ERR on absorb opds to redux state", e); } const preloadedState = reduxState ? { ...reduxState, } : {}; const sagaMiddleware = createSagaMiddleware(); const mware = applyMiddleware( reduxSyncMiddleware, sagaMiddleware, reduxPersistMiddleware, ); // eslint-disable-next-line @typescript-eslint/no-var-requires const middleware = IS_DEV ? require("remote-redux-devtools").composeWithDevTools( { port: REDUX_REMOTE_DEVTOOLS_PORT, }, )(mware) : mware; const store = createStore( rootReducer, preloadedState, middleware, ); sagaMiddleware.run(rootSaga); return [store as Store<RootState>, sagaMiddleware]; }
the_stack
import { BuildsService } from "@modules/resources/builds/service"; import { Job } from "bullmq"; import Container from "typedi"; import { BuildTestInstanceScreenshotService } from "@modules/resources/builds/instances/screenshots.service"; import { getScreenshotActionsResult, getTemplateFileContent } from "@utils/helper"; import { BuildTestInstancesService } from "@modules/resources/builds/instances/service"; import * as RedisLock from "redlock"; import { RedisManager } from "@modules/redis"; import { BuildReportService } from "@modules/resources/buildReports/service"; import { ITestCompleteQueuePayload } from "@crusher-shared/types/queues/"; import { BuildReportStatusEnum, IBuildReportTable } from "@modules/resources/buildReports/interface"; import { BuildStatusEnum, IBuildTable } from "@modules/resources/builds/interface"; import { ProjectsService } from "@modules/resources/projects/service"; import { BuildApproveService } from "@modules/resources/buildReports/build.approve.service"; import { KeysToCamelCase } from "@modules/common/typescript/interface"; import { UsersService } from "@modules/resources/users/service"; import * as ejs from "ejs"; import { resolvePathToFrontendURI } from "@utils/uri"; import { EmailManager } from "@modules/email"; import { TestsRunner } from ".."; import { iAction } from "@crusher-shared/types/action"; import { ActionStatusEnum } from "@crusher-shared/lib/runnerLog/interface"; import { ActionsInTestEnum } from "@crusher-shared/constants/recordedActions"; import { IntegrationsService } from "@modules/resources/integrations/service"; import { IUserTable } from "@modules/resources/users/interface"; import { IProjectTable } from "@modules/resources/projects/interface"; const buildService = Container.get(BuildsService); const buildReportService: BuildReportService = Container.get(BuildReportService); const buildTestInstanceService = Container.get(BuildTestInstancesService); const buildTestInstanceScreenshotService = Container.get(BuildTestInstanceScreenshotService); const projectsService = Container.get(ProjectsService); const buildApproveService = Container.get(BuildApproveService); const usersService = Container.get(UsersService); const projectIntegrationsService = Container.get(IntegrationsService); const emailManager = Container.get(EmailManager); const testRunner = Container.get(TestsRunner); const redisManager: RedisManager = Container.get(RedisManager); const redisLock = new RedisLock([redisManager.redisClient], { driftFactor: 0.01, retryCount: -1, retryDelay: 150, retryJitter: 200, }); interface ITestResultWorkerJob extends Job { data: ITestCompleteQueuePayload; } async function handleNextTestsForExecution(testCompletePayload: ITestResultWorkerJob["data"], buildRecord: KeysToCamelCase<IBuildTable>) { for (const testInstance of testCompletePayload.nextTestDependencies) { const testInstanceFullInfoRecord = await buildTestInstanceService.getInstanceAllInformation(testInstance.testInstanceId); const testActions: Array<iAction> = JSON.parse(testInstanceFullInfoRecord.testEvents); if (testCompletePayload.hasPassed && testCompletePayload.storageState) { const finalTestActions = testActions.map((action) => { if (action.type === ActionsInTestEnum.RUN_AFTER_TEST) { action.payload.meta.storageState = testCompletePayload.storageState; } return action; }); await testRunner.addTestRequestToQueue( { ...testCompletePayload.buildExecutionPayload, exports: testCompletePayload.exports, startingStorageState: testCompletePayload.storageState, actions: finalTestActions, config: { ...testCompletePayload.buildExecutionPayload.config, browser: testInstanceFullInfoRecord.browser, }, testInstanceId: testInstance.testInstanceId, testName: testInstanceFullInfoRecord.testName, nextTestDependencies: testInstance.nextTestDependencies, startingPersistentContext: testCompletePayload.persistenContextZipURL, }, buildRecord.host && buildRecord.host !== "null" ? buildRecord.host : null, ); } else { await processTestAfterExecution({ name: `${testCompletePayload.buildId}/${testCompletePayload.testInstanceId}`, data: { ...testCompletePayload, exports: [], nextTestDependencies: testInstance.nextTestDependencies, actionResults: testActions.map((action) => ({ actionType: action.type, status: ActionStatusEnum.FAILED, message: "Parent test failed", })), testInstanceId: testInstance.testInstanceId, hasPassed: false, failedReason: new Error("Parent test failed"), }, } as any); } } return true; } const processTestAfterExecution = async function (bullJob: ITestResultWorkerJob): Promise<any> { const buildRecord = await buildService.getBuild(bullJob.data.buildId); const buildReportRecord = await buildReportService.getBuildReportRecord(buildRecord.latestReportId); await handleNextTestsForExecution(bullJob.data, buildRecord); const actionsResultWithIndex = bullJob.data.actionResults.map((actionResult, index) => ({ ...actionResult, actionIndex: index })); const screenshotActionsResultWithIndex = getScreenshotActionsResult(actionsResultWithIndex); const savedScreenshotRecords = await buildTestInstanceScreenshotService.saveScreenshots(screenshotActionsResultWithIndex, bullJob.data.testInstanceId); // Compare visual diffs and save the final result await buildTestInstanceService.saveResult( actionsResultWithIndex, savedScreenshotRecords, bullJob.data.testInstanceId, buildRecord.projectId, bullJob.name, bullJob.data.hasPassed, ); // Wait for the final test in the list here const completedTestCount = await redisLock.lock(`${bullJob.data.buildId}:completed:lock`, 5000).then(async function (lock) { return redisManager.incr(`${bullJob.data.buildId}:completed`); }); if (completedTestCount === bullJob.data.buildTestCount) { // This is the last test result to finish const buildReportStatus = await buildReportService.calculateResultAndSave(buildRecord.latestReportId, bullJob.data.buildTestCount); await buildService.updateStatus(BuildStatusEnum.FINISHED, buildRecord.id); const buildRecordMeta = buildRecord.meta ? JSON.parse(buildRecord.meta) : null; if (buildRecordMeta?.isProjectLevelBuild && buildReportStatus === BuildReportStatusEnum.PASSED) { // Automatically update the baseline to the latest build await projectsService.updateBaselineBuild(buildRecord.id, buildRecord.projectId); } // @TODO: Add integrations here (Notify slack, etc.) console.log("Build status: ", buildReportStatus); await handleIntegrations(buildRecord, buildReportRecord, buildReportStatus); // await Promise.all(await sendReportStatusEmails(buildRecord, buildReportStatus)); return "SHOULD_CALL_POST_EXECUTION_INTEGRATIONS_NOW"; } }; async function getSlackMessageBlockForBuildReport( buildRecord: KeysToCamelCase<IBuildTable>, projectRecord: KeysToCamelCase<IProjectTable>, buildReportRecord: KeysToCamelCase<IBuildReportTable>, userInfo: KeysToCamelCase<IUserTable>, reportStatus: BuildReportStatusEnum, ): Promise<Array<any>> { const infoFields = [ { type: "mrkdwn", text: `*Build Id:*\n${buildRecord.id}`, }, { type: "mrkdwn", text: `*Tests Count:*\n${buildReportRecord.totalTestCount}`, }, { type: "mrkdwn", text: `*Triggerred By:*\n${userInfo.name}`, }, { type: "mrkdwn", text: `*Status:*\n${reportStatus}`, }, ]; if (buildRecord.host && buildRecord.host !== "null") { infoFields.push({ type: "mrkdwn", text: `*Host*:\n${buildRecord.host}`, }); } return [ { type: "section", text: { type: "mrkdwn", text: `A build was triggered for project ${projectRecord.name}:\n*<${resolvePathToFrontendURI(`/app/build/${buildRecord.id}`)}|#${ buildRecord.latestReportId }>*`, }, }, { type: "section", fields: infoFields, }, { type: "actions", elements: [ { type: "button", text: { type: "plain_text", text: "View Reports", emoji: true, }, value: "click_me_123", url: resolvePathToFrontendURI(`/app/build/${buildRecord.id}`), action_id: "button-action", }, ], }, ]; } async function handleIntegrations( buildRecord: KeysToCamelCase<IBuildTable>, buildReportRecord: KeysToCamelCase<IBuildReportTable>, reportStatus: BuildReportStatusEnum, ) { const userInfo = await usersService.getUserInfo(buildRecord.userId); const projectRecord = await projectsService.getProject(buildRecord.projectId); // Github Integration await buildService.markGithubCheckFlowFinished(reportStatus, buildRecord.id); // Slack Integration await projectIntegrationsService.postSlackMessageIfNeeded( buildRecord.projectId, await getSlackMessageBlockForBuildReport(buildRecord, projectRecord, buildReportRecord, userInfo, reportStatus), reportStatus === BuildReportStatusEnum.PASSED ? "normal" : "alert", ); } async function sendReportStatusEmails(buildRecord: KeysToCamelCase<IBuildTable>, buildReportStatus: BuildReportStatusEnum): Promise<Array<Promise<boolean>>> { if (buildReportStatus === BuildReportStatusEnum.PASSED) return; const usersInProject = await usersService.getUsersInProject(buildRecord.projectId); const emailTemplateFilePathMap = { [BuildReportStatusEnum.PASSED]: typeof __non_webpack_require__ !== "undefined" ? "/email/templates/passedJob.ejs" : "/../../email/templates/passedJob.ejs", [BuildReportStatusEnum.MANUAL_REVIEW_REQUIRED]: typeof __non_webpack_require__ !== "undefined" ? "/email/templates/manualReviewRequiredJob.ejs" : "/../../email/templates/manualReviewRequiredJob.ejs", [BuildReportStatusEnum.FAILED]: typeof __non_webpack_require__ !== "undefined" ? "/email/templates/failedJob.ejs" : "/../../email/templates/failedJob.ejs", }; console.log("Reading email template from: ", __dirname + emailTemplateFilePathMap[buildReportStatus]); const emailTemplate = await getTemplateFileContent(__dirname + emailTemplateFilePathMap[buildReportStatus], { buildId: buildRecord.id, branchName: buildRecord.branchName, buildReviewUrl: resolvePathToFrontendURI(`/app/build/${buildRecord.id}`), }); return usersInProject.map((user) => { return emailManager.sendEmail(user.email, `Build ${buildRecord.id} ${buildReportStatus}`, emailTemplate); }); } export default processTestAfterExecution;
the_stack
import { Store, Event, launch, step, createNode, withRegion, restore, createEvent, } from 'effector' import type {Scope} from '../effector/unit.h' import type {StateRef} from '../effector/index.h' import type {Stack} from '../effector/kernel' import type { Leaf, NSType, DOMElement, LeafData, Template, NodeDraft, Root, } from './index.h' import type {OpGroup} from './plan/index.h' import {handlers} from './templateHandlers' let templateID = 0 let spawnID = 0 export let currentTemplate: Template | null = null export let currentLeaf: Leaf | null = null export function createTemplate<Api extends {[method: string]: any}>(config: { fn: ( state: { [field: string]: Store<any> }, triggers: { mount: Event<Leaf> }, ) => {[K in keyof Api]: Event<Api[K]>} state?: {[field: string]: any} defer?: boolean name: string isSvgRoot: boolean draft: NodeDraft namespace: NSType env: { document: Document } isBlock?: boolean }): Template //@ts-expect-error export function createTemplate(config: { fn: ( state: { [field: string]: Store<any> }, triggers: { mount: Event<Leaf> }, ) => void state?: {[field: string]: any} defer?: boolean name: string isSvgRoot: boolean draft: NodeDraft namespace: NSType env: { document: Document } isBlock?: boolean }): Template export function createTemplate<Api extends {[method: string]: any}>({ fn, state: values = {}, defer = false, name = '', draft, isSvgRoot, namespace, env, isBlock = false, }: { fn: ( state: { [field: string]: Store<any> }, triggers: { mount: Event<Leaf> }, ) => {[K in keyof Api]: Event<Api[K]>} state?: {[field: string]: any} defer?: boolean name: string isSvgRoot: boolean draft: NodeDraft namespace: NSType env: { document: Document } isBlock?: boolean }): Template { const parent = currentTemplate const template: Template = { id: ++templateID, name, plain: [], watch: [], nameMap: {}, pages: [], closure: [], childTemplates: [], handlers, upward: step.filter({ //@ts-expect-error fn(upd, scope, stack: Stack) { if (!stack.page) { if (stack.parent && stack.parent.page) { stack.page = stack.parent.page } else { // console.error('context lost', stack) return true } } if (!stack.page.root.activeSpawns.has(stack.page.fullID)) { console.count('inactive page upward') return false } const stackTemplates = [stack.page.template] const stackPages = [stack.page] { let currentStackPage = stack.page.parent while (currentStackPage) { stackPages.push(currentStackPage) stackTemplates.push(currentStackPage.template) currentStackPage = currentStackPage.parent } } stack.node.next.forEach(node => { /** * node.meta.nativeTemplate is used in units * it represents template in which unit was created (belongs to) */ const targetTemplate: Template | void = node.meta.nativeTemplate if (targetTemplate) { if (stackTemplates.includes(targetTemplate)) { const page = stackPages[stackTemplates.indexOf(targetTemplate)] launch({ //@ts-expect-error target: node, params: upd, defer: true, page, stack, //@ts-expect-error scope: stack.scope, }) } else { console.error('context drift', {stack, node}) } } else { launch({ //@ts-expect-error target: node, params: upd, defer: true, page: stack.page, stack, //@ts-expect-error scope: stack.scope, }) } }) return false }, }), loader: step.filter({ //@ts-expect-error fn(upd, scope, stack: Stack) { if (stack.parent) { const forkId = stack.scope ? stack.scope.graphite.id : null if (stack.page) { if (!stack.page.root.activeSpawns.has(stack.page.fullID)) { console.count('inactive page loader') return false } if (stack.page.template === template) { return true } if (stack.page.root.childSpawns[stack.page.fullID][template.id]) { const fullID = stack.page!.fullID stack.page.root.childSpawns[fullID][template.id].forEach(page => { if (forkId) { if ( !page.root.scope || forkId !== page.root.scope.graphite.id ) return } launch({ params: upd, //@ts-expect-error target: stack.node, page, defer: true, //@ts-expect-error scope: stack.scope, }) }) } else { const fullID = stack.page.fullID const isRecTemplate = stack.page.template.name === 'rec' template.pages.forEach(page => { if (forkId) { if ( !page.root.scope || forkId !== page.root.scope.graphite.id ) return } if ( page.fullID === fullID || page.fullID.startsWith(`${fullID}_`) ) { let validTarget = true if (isRecTemplate) { const recID = stack.page!.template.id let parentPage = page.parent while (parentPage) { if (parentPage === stack.page) { break } if (parentPage.template.id === recID) { validTarget = false break } parentPage = parentPage.parent } } if (validTarget) { launch({ params: upd, //@ts-expect-error target: stack.node, page, defer: true, //@ts-expect-error scope: stack.scope, }) } } else { if (fullID.startsWith(`${page.fullID}_`)) { launch({ params: upd, //@ts-expect-error target: stack.node, page: stack.page, defer: true, //@ts-expect-error scope: stack.scope, }) } else { // console.count('no page match') } } }) } } else { template.pages.forEach(page => { if (forkId) { if (!page.root.scope || forkId !== page.root.scope.graphite.id) return } launch({ params: upd, //@ts-expect-error target: stack.node, page, defer: true, //@ts-expect-error scope: stack.scope, }) }) } return false } return true }, }), parent, node: null as any, api: null as any, trigger: { //@ts-expect-error mount: createEvent<Leaf>({named: 'mount'}), }, draft, isSvgRoot, namespace, env, isBlock: isBlock || !!(parent && parent.isBlock), } if (parent) { parent.childTemplates.push(template) } const node = createNode({ meta: { template, }, }) template.node = node currentTemplate = template if (!defer) { withRegion(node, () => { const state = restore(values) template.api = fn(state, template.trigger) template.nameMap = state }) } else { template.deferredInit = () => { const prevTemplate = currentTemplate currentTemplate = template template.deferredInit = null try { withRegion(node, () => { const state = restore(values) template.api = fn(state, template.trigger) template.nameMap = state }) } finally { currentTemplate = prevTemplate } } } currentTemplate = parent return template } function getCurrent(ref: StateRef, forkPage?: Scope) { let result if (forkPage) result = forkPage.getState(ref) else result = ref.current switch (ref.type) { case 'list': return [...result] case 'shape': return {...result} default: return result } } function findRef( ref: StateRef, targetLeaf: Leaf | null, forkPage?: Scope, ): StateRef { let currentLeaf = targetLeaf while (currentLeaf && !regRef(currentLeaf, ref)) { currentLeaf = currentLeaf.parent } if (!currentLeaf) { if (forkPage) { forkPage.getState(ref) return forkPage.reg[ref.id] } return ref } return regRef(currentLeaf, ref) } function findRefValue( ref: StateRef, targetLeaf: Leaf | null, forkPage?: Scope, ) { return findRef(ref, targetLeaf, forkPage).current } function ensureLeafHasRef(ref: StateRef, leaf: Leaf) { if (!regRef(leaf, ref)) { leaf.reg[ref.id] = findRef(ref, leaf.parent, leaf.root.scope) } } const regRef = (page: {reg: Record<string, StateRef>}, ref: StateRef) => page.reg[ref.id] function addMapItems<T>( values: T[], id: string | number, record: Record<string | number, T[]>, ) { if (!(id in record)) { record[id] = [] } record[id].push(...values) } export function spawn( template: Template, { values = {}, parentLeaf, mountNode, svgRoot, leafData, opGroup, domSubtree, hydration, root, }: { values?: {[field: string]: any} parentLeaf: Leaf | null mountNode: DOMElement svgRoot: SVGSVGElement | null leafData: LeafData opGroup: OpGroup domSubtree: OpGroup hydration: boolean root: Root }, ): Leaf { const page = {} as Record<string, StateRef> const leaf: Leaf = { draft: template.draft, svgRoot, data: leafData, parent: parentLeaf, hydration, mountNode, root, id: ++spawnID, fullID: '', reg: page, template, } template.pages.push(leaf) const previousSpawn = currentLeaf currentLeaf = leaf if (parentLeaf) { addMapItems([leaf], template.id, root.childSpawns[parentLeaf.fullID]) } if (parentLeaf) { leaf.fullID = `${parentLeaf.fullID}_${leaf.id}` } else { leaf.fullID = `${leaf.id}` } root.childSpawns[leaf.fullID] = {} root.activeSpawns.add(leaf.fullID) root.leafOps[leaf.fullID] = {group: opGroup, domSubtree} for (let i = 0; i < template.closure.length; i++) { const ref = template.closure[i] let closureRef = ref let parent = leaf.parent findClosure: while (parent) { if (regRef(parent, ref)) { closureRef = regRef(parent, ref) break findClosure } parent = parent.parent } if (!parent && root.scope) { root.scope.getState(ref) closureRef = root.scope.reg[ref.id] } page[ref.id] = closureRef } for (let i = 0; i < template.plain.length; i++) { const ref = template.plain[i] const next: StateRef = { id: ref.id, current: getCurrent(ref, root.scope), } page[ref.id] = next } for (const name in values) { const id = template.nameMap[name].stateRef.id page[id] = { id, current: values[name], } } function execRef(ref: StateRef) { if (ref.before) { for (let i = 0; i < ref.before.length; i++) { const cmd = ref.before[i] switch (cmd.type) { case 'map': { const from = cmd.from if (!cmd.fn && !from) break let value if (from) { ensureLeafHasRef(from, leaf) value = page[from.id].current } page[ref.id].current = cmd.fn ? cmd.fn(value) : value break } case 'field': { const from = cmd.from ensureLeafHasRef(from, leaf) page[ref.id].current[cmd.field] = page[from.id].current break } case 'closure': ensureLeafHasRef(cmd.of, leaf) break } } } } template.closure.forEach(execRef) template.plain.forEach(execRef) function runWatchersFrom( list: any[], state: {i: number; stop: boolean}, page: Record<string, StateRef>, ) { state.stop = true let val try { while (state.i < list.length) { val = list[state.i] state.i++ val.fn( page[val.of.id] ? page[val.of.id].current : findRefValue(val.of, leaf.parent, leaf.root.scope), ) } } catch (err) { console.error(err) state.stop = false } } const state = {i: 0, stop: false} while (!state.stop) { runWatchersFrom(template.watch, state, page) } if (parentLeaf) { for (const id in root.childSpawns[leaf.fullID]) { addMapItems( root.childSpawns[leaf.fullID][id], id, root.childSpawns[parentLeaf.fullID], ) } } if (mountQueue) { mountQueue.steps.push({ target: template.trigger.mount, params: leaf, defer: true, page: leaf, scope: root.scope, }) } else { mountQueue = { parent: mountQueue, steps: [ { target: template.trigger.mount, params: leaf, defer: true, page: leaf, scope: root.scope, }, ], } let step: any do { while ((step = mountQueue.steps.shift())) { mountQueue = { parent: mountQueue, steps: [], } launch(step) } } while ((mountQueue = mountQueue.parent)) } currentLeaf = previousSpawn return leaf } type MountQueue = { parent: MountQueue | null steps: any[] } let mountQueue: MountQueue | null = null
the_stack
import setupLogger from '@/config/logger'; import { IExplorer } from '@/services/datastores/base/datastore'; import Cursor from '@/services/datastores/dynomite/lib/Cursor'; import { MAX_KEY_STRING_SIZE_CHARS } from '@/services/datastores/dynomite/lib/dynomite-constants'; import DynomiteCluster from '@/services/datastores/dynomite/lib/DynomiteCluster'; import types from '@/services/datastores/dynomite/lib/DynomiteTypes'; import { FieldOperationsNotSupportedForTypeError, KeyNotFoundError, KeyTooLargeError, } from '@/services/datastores/dynomite/lib/errors'; import { getKeyCountFromInfo, parseInfoString, } from '@/services/datastores/dynomite/lib/utils/redis-info-utils'; import { scan } from '@/services/datastores/dynomite/lib/utils/scan-utils'; import { IClientCursor, IDynoCollectionKeyValue, IDynomiteInfo, IKeyValue, IScanResult, } from '@/services/datastores/dynomite/typings/dynomite'; import { IClusterDefinition } from '@/typings/typings'; import { deleteHashKeys, deleteListItems, deleteSetMembers, deleteZsetMembers, } from './collections'; import { ValueType } from 'ioredis'; const logger = setupLogger(module); const EMPTY_RESULT = { cursor: { complete: true }, keys: [], count: 0, } as IScanResult; /** * @class */ export default class DynomiteExplorer implements IExplorer { private dynomiteCluster: DynomiteCluster; constructor(readonly cluster: IClusterDefinition) { // setup a dynomite cluster to handle delegated calls that require region-awareness this.dynomiteCluster = new DynomiteCluster(cluster); } /** * Adds fields to the given key. If the key doesn't exist, it will be created. * Operation is performed via a single call to the database wherever possible. * @param type The type of the key. * @param key The name of the key to add fields to. * @param fieldValues Array of field definitions */ public async addFields( type: string, key: string, fieldValues: IDynoCollectionKeyValue[], ): Promise<any> { const conn = await this.dynomiteCluster.getConnection(); switch (type) { case types.string: throw new Error( 'Cannot add fields to strings. Please create a key of a type that supports fields.', ); case types.list: return conn.rpush( key, fieldValues.map((r) => r.value), ); // list members don't provide indices case types.set: return conn.sadd( key, fieldValues.map((r) => r.value), ); case types.hash: const keyValuePairs = new Array<string>(); fieldValues.forEach((r) => { if (r.type === 'hash') { keyValuePairs.push(r.key, r.value); } }); if (keyValuePairs.length === 0) { throw Error('No hash key/value pairs provided'); } return conn.hmset(key, keyValuePairs); case types.zset: const zsetItems = new Array<string>(); fieldValues.forEach((r) => { if (r.type === 'zset') { zsetItems.push(r.score); zsetItems.push(r.value); } }); if (zsetItems.length === 0) { throw Error('No zset score/value pairs provided'); } return conn.zadd(key, zsetItems as any); case types.none: throw new KeyNotFoundError(key); default: throw new Error(`Unsupported key type: ${type}`); } } /** * Deletes the list of fields from the given key. * Note, not all data types support fields. * @param key The name of the key. * @param fields Array of field names to delete. */ public async deleteFields( key: string, fieldValues: IDynoCollectionKeyValue[], ): Promise<any> { const conn = await this.dynomiteCluster.getConnection(); const keyType = await conn.type(key); switch (keyType) { case types.string: { throw new Error( 'Cannot delete field from string types. Please use deleteKey() method instead.', ); } case types.list: return deleteListItems(conn, key, fieldValues); case types.set: return deleteSetMembers(conn, key, fieldValues); case types.hash: return deleteHashKeys(conn, key, fieldValues); case types.zset: return deleteZsetMembers(conn, key, fieldValues); case types.none: throw new KeyNotFoundError(key); default: throw new Error(`Unsupported key type: ${keyType}`); } } /** * Deletes a given key. * @param {String} key The name of the key to delete. * @returns {Promise.<Object>} */ public async deleteKey(key: string): Promise<{ count: number }> { logger.info('DynomiteExplorer:deleteKey()'); const conn = await this.dynomiteCluster.getConnection(); const result = await conn.del(key); if (result === 0) { throw new KeyNotFoundError(key); } return { count: result }; } /** * Returns an object containing cluster level information. * @returns Returns a Promise that will resolve with an Array of info objects for each of the * nodes in the availability zone / rack / ring. */ public async getInfo(): Promise<IDynomiteInfo[]> { logger.info('DynomiteExplorer:getInfo()'); const results = (await this.dynomiteCluster.executeCommandInSingleZone( (conn) => conn.info() as any, )) as string[]; return results.map((result) => parseInfoString(result)); } /** * Returns the total number of keys available. */ public async getKeyCount(): Promise<number> { const results = (await this.dynomiteCluster.executeCommandInSingleZone( (conn) => conn.info() as any, )) as string[]; return results.reduce( (previous, current) => previous + getKeyCountFromInfo(current), 0, ); } /** * Fetches the value of a specific key. * * Returns an object of the following format: * * { * type: "String", * ttl: Number, * value: <Object> * } * * @param {String} key * @returns {Promise.<Object>} */ public async getValue(key: string): Promise<IKeyValue> { const conn = await this.dynomiteCluster.getConnection(); const type = await conn.type(key); let value; switch (type) { case types.string: const len = await conn.strlen(key); if (len > MAX_KEY_STRING_SIZE_CHARS) { throw new KeyTooLargeError(key, len); } value = await conn.get(key); break; case types.list: value = await conn.lrange(key, 0, -1); break; case types.set: value = await conn.smembers(key); break; case types.hash: value = await conn.hgetall(key); break; case types.zset: value = await conn.zrange(key, 0, -1, 'WITHSCORES'); break; case types.none: throw new KeyNotFoundError(key); default: throw new Error(`Unsupported key type: ${type}`); } const ttl = await conn.ttl(key); return { name: key, value, type, ttl }; } /** * Updates the fields of an aggregate key type. * @param key The name of the key to be updated. * @param fieldValues An array of field value pairs. */ public async updateFields( key: string, fieldValues: IDynoCollectionKeyValue[], ): Promise<boolean> { const conn = await this.dynomiteCluster.getConnection(); const type = await conn.type(key); const supportedKeyTypes = [types.list, types.hash, types.zset]; if (!supportedKeyTypes.includes(type)) { throw new FieldOperationsNotSupportedForTypeError( key, type, supportedKeyTypes, ); } const fieldPairs = [] as string[]; switch (type) { case types.list: { // redis doesn't support setting multiple list members in a single call const promises = fieldValues.map((r) => { if (r.type === 'list') { return conn.lset(key, r.index, r.value); } return Promise.resolve('OK'); }); await Promise.all(promises); break; } case types.hash: fieldValues.forEach((r) => { if (r.type === 'hash') { fieldPairs.push(r.key); fieldPairs.push(r.value); } }); await conn.hmset(key, fieldPairs); break; case types.zset: fieldValues.forEach((r) => { if (r.type === 'zset') { fieldPairs.push(r.score); fieldPairs.push(r.value); } }); await conn.zadd(key, fieldPairs as any); break; } logger.info('field updated successfully'); return true; } /** * Sets the given key to the given value. * @param key * @param value * @returns */ public async setValue(key: string, value: ValueType): Promise<any> { const conn = await this.dynomiteCluster.getConnection(); return conn.set(key, value); } /** * Sets the expiration value for the given key. * @param key The name of the key to set expiration. * @param ttl The expiration value in seconds. Set to null to persist the key * (i.e. remove the expiration). */ public async setExpiration( key: string, ttl: number | undefined, ): Promise<any> { const conn = await this.dynomiteCluster.getConnection(); if (ttl === undefined) { return conn.persist(key); } return conn.expire(key, ttl); } /** * Returns a set of matching keys. * @param cursor * @param match * @param count * @param pageSize */ public async getKeys( cursorObj: IClientCursor, match: string, count: number, pageSize: number, ): Promise<IScanResult> { if (match.indexOf('*') < 0) { // as an optimization, if the user isn't search for a wildcard key, just try direct key access try { await this.getValue(match); return { cursor: { complete: true }, keys: [match], count: 1, }; } catch (err) { if (err instanceof KeyNotFoundError) { return EMPTY_RESULT; } throw err; } } else { // otherwise we need to perform a scan to find matching keys let cursor: Cursor; if (cursorObj) { // reuse the existing client cursor if provided cursor = Cursor.fromClientCursor(cursorObj); } else { // create a new cursor with knowledge of all the hosts in the AZ const ringMembers = this.dynomiteCluster.getFirstRingMembers(); logger.debug( `no scan cursor provided. setting up cursor: ${JSON.stringify( ringMembers, )}`, ); cursor = new Cursor(ringMembers); } const result = await scan( this.dynomiteCluster, cursor, match, count, pageSize, ); return result; } } public async shutdown(): Promise<void> { this.dynomiteCluster.disconnect(); } }
the_stack
import { SelectionModel } from '@angular/cdk/collections'; import { FlatTreeControl } from '@angular/cdk/tree'; import { Component, Injectable, ElementRef, ViewChild } from '@angular/core'; import { MatTreeFlatDataSource, MatTreeFlattener } from '@angular/material/tree'; import { BehaviorSubject } from 'rxjs'; /** * Node for to-do item */ export class TodoItemNode { children: TodoItemNode[]; item: string; } /** Flat to-do item node with expandable and level information */ export class TodoItemFlatNode { item: string; level: number; expandable: boolean; } /** * The Json object for to-do list data. */ const TREE_DATA = { Groceries: { 'Almond Meal flour': null, 'Organic eggs': null, 'Protein Powder': null, Fruits: { Apple: null, Berries: ['Blueberry', 'Raspberry'], Orange: null } }, Reminders: [ 'Cook dinner', 'Read the Material Design spec', 'Upgrade Application to Angular' ] }; /** * Checklist database, it can build a tree structured Json object. * Each node in Json object represents a to-do item or a category. * If a node is a category, it has children items and new items can be added under the category. */ @Injectable() export class ChecklistDatabase { dataChange = new BehaviorSubject<TodoItemNode[]>([]); get data(): TodoItemNode[] { return this.dataChange.value; } constructor() { this.initialize(); } initialize() { // Build the tree nodes from Json object. The result is a list of `TodoItemNode` with nested // file node as children. const data = this.buildFileTree(TREE_DATA, 0); // Notify the change. this.dataChange.next(data); } /** * Build the file structure tree. The `value` is the Json object, or a sub-tree of a Json object. * The return value is the list of `TodoItemNode`. */ buildFileTree(obj: object, level: number): TodoItemNode[] { return Object.keys(obj).reduce<TodoItemNode[]>((accumulator, key) => { const value = obj[key]; const node = new TodoItemNode(); node.item = key; if (value != null) { if (typeof value === 'object') { node.children = this.buildFileTree(value, level + 1); } else { node.item = value; } } return accumulator.concat(node); }, []); } /** Add an item to to-do list */ insertItem(parent: TodoItemNode, name: string): TodoItemNode { if (!parent.children) { parent.children = []; } const newItem = { item: name } as TodoItemNode; parent.children.push(newItem); this.dataChange.next(this.data); return newItem; } insertItemAbove(node: TodoItemNode, name: string): TodoItemNode { const parentNode = this.getParentFromNodes(node); const newItem = { item: name } as TodoItemNode; if (parentNode != null) { parentNode.children.splice(parentNode.children.indexOf(node), 0, newItem); } else { this.data.splice(this.data.indexOf(node), 0, newItem); } this.dataChange.next(this.data); return newItem; } insertItemBelow(node: TodoItemNode, name: string): TodoItemNode { const parentNode = this.getParentFromNodes(node); const newItem = { item: name } as TodoItemNode; if (parentNode != null) { parentNode.children.splice(parentNode.children.indexOf(node) + 1, 0, newItem); } else { this.data.splice(this.data.indexOf(node) + 1, 0, newItem); } this.dataChange.next(this.data); return newItem; } getParentFromNodes(node: TodoItemNode): TodoItemNode { for (let i = 0; i < this.data.length; ++i) { const currentRoot = this.data[i]; const parent = this.getParent(currentRoot, node); if (parent != null) { return parent; } } return null; } getParent(currentRoot: TodoItemNode, node: TodoItemNode): TodoItemNode { if (currentRoot.children && currentRoot.children.length > 0) { for (let i = 0; i < currentRoot.children.length; ++i) { const child = currentRoot.children[i]; if (child === node) { return currentRoot; } else if (child.children && child.children.length > 0) { const parent = this.getParent(child, node); if (parent != null) { return parent; } } } } return null; } updateItem(node: TodoItemNode, name: string) { node.item = name; this.dataChange.next(this.data); } deleteItem(node: TodoItemNode) { this.deleteNode(this.data, node); this.dataChange.next(this.data); } copyPasteItem(from: TodoItemNode, to: TodoItemNode): TodoItemNode { const newItem = this.insertItem(to, from.item); if (from.children) { from.children.forEach(child => { this.copyPasteItem(child, newItem); }); } return newItem; } copyPasteItemAbove(from: TodoItemNode, to: TodoItemNode): TodoItemNode { const newItem = this.insertItemAbove(to, from.item); if (from.children) { from.children.forEach(child => { this.copyPasteItem(child, newItem); }); } return newItem; } copyPasteItemBelow(from: TodoItemNode, to: TodoItemNode): TodoItemNode { const newItem = this.insertItemBelow(to, from.item); if (from.children) { from.children.forEach(child => { this.copyPasteItem(child, newItem); }); } return newItem; } deleteNode(nodes: TodoItemNode[], nodeToDelete: TodoItemNode) { const index = nodes.indexOf(nodeToDelete, 0); if (index > -1) { nodes.splice(index, 1); } else { nodes.forEach(node => { if (node.children && node.children.length > 0) { this.deleteNode(node.children, nodeToDelete); } }); } } } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [ChecklistDatabase] }) export class AppComponent { /** Map from flat node to nested node. This helps us finding the nested node to be modified */ flatNodeMap = new Map<TodoItemFlatNode, TodoItemNode>(); /** Map from nested node to flattened node. This helps us to keep the same object for selection */ nestedNodeMap = new Map<TodoItemNode, TodoItemFlatNode>(); /** A selected parent node to be inserted */ selectedParent: TodoItemFlatNode | null = null; /** The new item's name */ newItemName = ''; treeControl: FlatTreeControl<TodoItemFlatNode>; treeFlattener: MatTreeFlattener<TodoItemNode, TodoItemFlatNode>; dataSource: MatTreeFlatDataSource<TodoItemNode, TodoItemFlatNode>; /** The selection for checklist */ checklistSelection = new SelectionModel<TodoItemFlatNode>(true /* multiple */); /* Drag and drop */ dragNode: any; dragNodeExpandOverWaitTimeMs = 300; dragNodeExpandOverNode: any; dragNodeExpandOverTime: number; dragNodeExpandOverArea: string; @ViewChild('emptyItem') emptyItem: ElementRef; constructor(private database: ChecklistDatabase) { this.treeFlattener = new MatTreeFlattener(this.transformer, this.getLevel, this.isExpandable, this.getChildren); this.treeControl = new FlatTreeControl<TodoItemFlatNode>(this.getLevel, this.isExpandable); this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener); database.dataChange.subscribe(data => { this.dataSource.data = []; this.dataSource.data = data; }); } getLevel = (node: TodoItemFlatNode) => node.level; isExpandable = (node: TodoItemFlatNode) => node.expandable; getChildren = (node: TodoItemNode): TodoItemNode[] => node.children; hasChild = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.expandable; hasNoContent = (_: number, _nodeData: TodoItemFlatNode) => _nodeData.item === ''; /** * Transformer to convert nested node to flat node. Record the nodes in maps for later use. */ transformer = (node: TodoItemNode, level: number) => { const existingNode = this.nestedNodeMap.get(node); const flatNode = existingNode && existingNode.item === node.item ? existingNode : new TodoItemFlatNode(); flatNode.item = node.item; flatNode.level = level; flatNode.expandable = (node.children && node.children.length > 0); this.flatNodeMap.set(flatNode, node); this.nestedNodeMap.set(node, flatNode); return flatNode; } /** Whether all the descendants of the node are selected */ descendantsAllSelected(node: TodoItemFlatNode): boolean { const descendants = this.treeControl.getDescendants(node); return descendants.every(child => this.checklistSelection.isSelected(child)); } /** Whether part of the descendants are selected */ descendantsPartiallySelected(node: TodoItemFlatNode): boolean { const descendants = this.treeControl.getDescendants(node); const result = descendants.some(child => this.checklistSelection.isSelected(child)); return result && !this.descendantsAllSelected(node); } /** Toggle the to-do item selection. Select/deselect all the descendants node */ todoItemSelectionToggle(node: TodoItemFlatNode): void { this.checklistSelection.toggle(node); const descendants = this.treeControl.getDescendants(node); this.checklistSelection.isSelected(node) ? this.checklistSelection.select(...descendants) : this.checklistSelection.deselect(...descendants); } /** Select the category so we can insert the new item. */ addNewItem(node: TodoItemFlatNode) { const parentNode = this.flatNodeMap.get(node); this.database.insertItem(parentNode, ''); this.treeControl.expand(node); } /** Save the node to database */ saveNode(node: TodoItemFlatNode, itemValue: string) { const nestedNode = this.flatNodeMap.get(node); this.database.updateItem(nestedNode, itemValue); } handleDragStart(event, node) { // Required by Firefox (https://stackoverflow.com/questions/19055264/why-doesnt-html5-drag-and-drop-work-in-firefox) event.dataTransfer.setData('foo', 'bar'); event.dataTransfer.setDragImage(this.emptyItem.nativeElement, 0, 0); this.dragNode = node; this.treeControl.collapse(node); } handleDragOver(event, node) { event.preventDefault(); // Handle node expand if (node === this.dragNodeExpandOverNode) { if (this.dragNode !== node && !this.treeControl.isExpanded(node)) { if ((new Date().getTime() - this.dragNodeExpandOverTime) > this.dragNodeExpandOverWaitTimeMs) { this.treeControl.expand(node); } } } else { this.dragNodeExpandOverNode = node; this.dragNodeExpandOverTime = new Date().getTime(); } // Handle drag area const percentageX = event.offsetX / event.target.clientWidth; const percentageY = event.offsetY / event.target.clientHeight; if (percentageY < 0.25) { this.dragNodeExpandOverArea = 'above'; } else if (percentageY > 0.75) { this.dragNodeExpandOverArea = 'below'; } else { this.dragNodeExpandOverArea = 'center'; } } handleDrop(event, node) { event.preventDefault(); if (node !== this.dragNode) { let newItem: TodoItemNode; if (this.dragNodeExpandOverArea === 'above') { newItem = this.database.copyPasteItemAbove(this.flatNodeMap.get(this.dragNode), this.flatNodeMap.get(node)); } else if (this.dragNodeExpandOverArea === 'below') { newItem = this.database.copyPasteItemBelow(this.flatNodeMap.get(this.dragNode), this.flatNodeMap.get(node)); } else { newItem = this.database.copyPasteItem(this.flatNodeMap.get(this.dragNode), this.flatNodeMap.get(node)); } this.database.deleteItem(this.flatNodeMap.get(this.dragNode)); this.treeControl.expandDescendants(this.nestedNodeMap.get(newItem)); } this.dragNode = null; this.dragNodeExpandOverNode = null; this.dragNodeExpandOverTime = 0; } handleDragEnd(event) { this.dragNode = null; this.dragNodeExpandOverNode = null; this.dragNodeExpandOverTime = 0; } }
the_stack
import { computed, ComputedRef, reactive, Ref, toRef, unref, UnwrapRef } from "vue" import { watch, watchEffect, WatchStopHandle } from "vue" import { inject, InjectionKey, provide } from "vue" import { nonNull, Reactive } from "../common/common" import { Config, Configs, EdgeConfig, MarkerStyle, NodeConfig } from "../common/configs" import { ShapeStyle, NodeLabelStyle, StrokeStyle } from "../common/configs" import { Edge, Edges, Layouts, Node, Nodes } from "../common/types" import { LinePosition, NodePositions, Position } from "../common/types" import { EdgeGroupStates } from "../common/edge-group" import { clearMarker, makeMarker } from "./marker" import * as EdgeGroup from "../common/edge-group" import * as v2d from "../common/2d" import * as V from "../common/vector" // ----------------------------------------------------------------------- // Type definitions // ----------------------------------------------------------------------- export type { EdgeGroupStates } // States of nodes interface NodeStateDatum { shape: Ref<ShapeStyle> staticShape: Ref<ShapeStyle> label: Ref<NodeLabelStyle> labelText: Ref<string> selected: boolean hovered: boolean draggable: Ref<boolean> selectable: Ref<boolean | number> } export type NodeState = UnwrapRef<NodeStateDatum> export type NodeStates = Record<string, NodeState> // States of edges interface Line { stroke: StrokeStyle normalWidth: number // stroke width when not hovered source: MarkerStyle target: MarkerStyle } export interface Curve { center: V.Vector theta: number // theta: direction of source to center circle: { center: V.Vector radius: number } control: Position[] } interface EdgeStateDatum { line: Ref<Line> selectable: Ref<boolean | number> selected: boolean hovered: boolean origin: LinePosition // line segment between center of nodes labelPosition: LinePosition // line segment between the outermost of the nodes for labels position: LinePosition // line segments to be displayed with margins applied curve?: Curve sourceMarkerId?: string targetMarkerId?: string stopWatchHandle: WatchStopHandle } interface SummarizedEdgeStateDatum { stroke: Ref<StrokeStyle> } export type EdgeState = UnwrapRef<EdgeStateDatum> export type EdgeStates = Record<string, EdgeState> export type SummarizedEdgeState = UnwrapRef<SummarizedEdgeStateDatum> export type SummarizedEdgeStates = Record<string, SummarizedEdgeState> // Provide states interface States { nodeStates: NodeStates edgeStates: EdgeStates edgeGroupStates: EdgeGroupStates summarizedEdgeStates: SummarizedEdgeStates layouts: Layouts } export type ReadonlyStates = Readonly<States> // ----------------------------------------------------------------------- // Constants // ----------------------------------------------------------------------- const statesKey = Symbol("states") as InjectionKey<States> const NONE_MARKER: MarkerStyle = { type: "none", width: 0, height: 0, margin: 0, units: "strokeWidth", color: null, } // ----------------------------------------------------------------------- // Exported functions // ----------------------------------------------------------------------- export function provideStates( nodes: Readonly<Nodes>, edges: Readonly<Edges>, selectedNodes: Reactive<Set<string>>, selectedEdges: Reactive<Set<string>>, hoveredNodes: Reactive<Set<string>>, hoveredEdges: Reactive<Set<string>>, configs: Readonly<Configs>, layouts: Reactive<Layouts>, scale: ComputedRef<number> ) { const nodeStates: NodeStates = reactive({}) const edgeStates: EdgeStates = reactive({}) const summarizedEdgeStates: SummarizedEdgeStates = reactive({}) // ----------------------------------------------------------------------- // States for nodes // ----------------------------------------------------------------------- Object.keys(nodes).forEach(id => { createNodeState(nodeStates, nodes, id, selectedNodes.has(id), false, configs.node) }) // update `node.selected` flag watch( () => [...selectedNodes], (nodes, prev) => { const append = nodes.filter(n => !prev.includes(n)) const removed = prev.filter(n => !nodes.includes(n)) append.forEach(id => { const state = nodeStates[id] if (state && !state.selected) state.selected = true }) removed.forEach(id => { const state = nodeStates[id] if (state && state.selected) state.selected = false }) } ) // update `node.hovered` flag watch( () => [...hoveredNodes], (nodes, prev) => { const append = nodes.filter(n => !prev.includes(n)) const removed = prev.filter(n => !nodes.includes(n)) append.forEach(id => { const state = nodeStates[id] if (state && !state.hovered) state.hovered = true }) removed.forEach(id => { const state = nodeStates[id] if (state && state.hovered) state.hovered = false }) } ) // handle increase/decrease nodes watch( () => new Set(Object.keys(nodes)), (idSet, prev) => { for (const nodeId of idSet) { if (prev.has(nodeId)) continue // node added createNodeState(nodeStates, nodes, nodeId, false, false, configs.node) // adding to layouts is done by layout handler } const positions = layouts.nodes for (const nodeId of prev) { if (idSet.has(nodeId)) continue // node removed delete positions[nodeId] selectedNodes.delete(nodeId) hoveredNodes.delete(nodeId) delete nodeStates[nodeId] } } ) // ----------------------------------------------------------------------- // States for edges // ----------------------------------------------------------------------- // grouping const edgeGroupStates = EdgeGroup.makeEdgeGroupStates(nodes, edges, configs) Object.keys(edges).forEach(id => { createEdgeState( edgeStates, edgeGroupStates, nodeStates, edges, id, selectedEdges.has(id), configs.edge, layouts.nodes, scale ) }) watch( edgeGroupStates.edgeGroups, _ => createSummarizedEdgeStates(summarizedEdgeStates, edgeGroupStates, configs), { immediate: true } ) // update `edge.selected` flag watch( () => [...selectedEdges], (nodes, prev) => { const append = nodes.filter(n => !prev.includes(n)) const removed = prev.filter(n => !nodes.includes(n)) append.forEach(id => { const state = edgeStates[id] if (state && !state.selected) state.selected = true }) removed.forEach(id => { const state = edgeStates[id] if (state && state.selected) state.selected = false }) } ) // update `edge.hovered` flag watch( () => [...hoveredEdges], (nodes, prev) => { const append = nodes.filter(n => !prev.includes(n)) const removed = prev.filter(n => !nodes.includes(n)) append.forEach(id => { const state = edgeStates[id] if (state && !state.hovered) { state.hovered = true } }) removed.forEach(id => { const state = edgeStates[id] if (state && state.hovered) { state.hovered = false } }) } ) // handle increase/decrease edges watch( () => new Set(Object.keys(edges)), (idSet, prev) => { for (const edgeId of idSet) { if (prev.has(edgeId)) continue // edge added createEdgeState( edgeStates, edgeGroupStates, nodeStates, edges, edgeId, false, // selected configs.edge, layouts.nodes, scale ) } for (const edgeId of prev) { if (idSet.has(edgeId)) continue // remove edge selectedEdges.delete(edgeId) hoveredEdges.delete(edgeId) edgeStates[edgeId].stopWatchHandle() delete edgeStates[edgeId] } } ) const states = { nodeStates, edgeStates, edgeGroupStates, summarizedEdgeStates, layouts } provide(statesKey, states) return states } export function useStates() { return nonNull(inject(statesKey), "states") as ReadonlyStates } // ----------------------------------------------------------------------- // Local functions // ----------------------------------------------------------------------- function getNodeShape(node: Node, selected: boolean, hovered: boolean, config: NodeConfig) { if (hovered && config.hover) { return Config.values(config.hover, node) } else { return getNodeStaticShape(node, selected, config) } } function getNodeStaticShape(node: Node, selected: boolean, config: NodeConfig) { // get shape without hovered state if (selected && config.selected) { return Config.values(config.selected, node) } else { return Config.values(config.normal, node) } } function getEdgeStroke(edge: Edge, selected: boolean, hovered: boolean, config: EdgeConfig) { if (selected) { return Config.values(config.selected, edge) } else if (hovered && config.hover) { return Config.values(config.hover, edge) } else { return Config.values(config.normal, edge) } } function createNodeState( states: NodeStates, nodes: Nodes, id: string, selected: boolean, hovered: boolean, config: NodeConfig ) { states[id] = { selected, hovered } as any const state = states[id] as any as NodeStateDatum state.shape = computed(() => { if (!nodes[id]) return unref(state.shape) // 前回の値を返す return getNodeShape(nodes[id], state.selected, state.hovered, config) }) state.staticShape = computed(() => { if (!nodes[id]) return unref(state.staticShape) // 前回の値を返す return getNodeStaticShape(nodes[id], state.selected, config) }) state.label = computed(() => { if (!nodes[id]) return unref(state.label) // 前回の値を返す return Config.values(config.label, nodes[id]) }) state.labelText = computed(() => { if (config.label.text instanceof Function) { return unref(state.label).text } else { if (!nodes[id]) return unref(state.labelText) // 前回の値を返す return nodes[id]?.[unref(state.label).text] ?? "" } }) state.draggable = computed(() => { if (!nodes[id]) return unref(state.draggable) // 前回の値を返す return Config.value(config.draggable, nodes[id]) }) state.selectable = computed(() => { if (!nodes[id]) return unref(state.selectable) // 前回の値を返す return Config.value(config.selectable, nodes[id]) }) } function toEdgeMarker(marker: MarkerStyle): MarkerStyle { if (marker.type === "none") { return NONE_MARKER } else { return marker } } function createEdgeState( states: EdgeStates, groupStates: Reactive<EdgeGroupStates>, nodeStates: NodeStates, edges: Edges, id: string, selected: boolean, config: EdgeConfig, layouts: NodePositions, scale: ComputedRef<number> ) { const edge = edges[id] if (!edge) return states[id] = { line: undefined as any, // specify later selectable: false, // specify later selected, hovered: false, curve: undefined, origin: { x1: 0, y1: 0, x2: 0, y2: 0 }, labelPosition: { x1: 0, y1: 0, x2: 0, y2: 0 }, position: { x1: 0, y1: 0, x2: 0, y2: 0 }, stopWatchHandle: () => {}, } const state = states[id] as any as EdgeStateDatum const line = computed<Line>(() => { const edge = edges[id] const stroke = getEdgeStroke(edge, state.selected, state.hovered, config) const normalWidth = Config.value(config.normal.width, edge) const source = toEdgeMarker(Config.values(config.marker.source, [edge, stroke])) const target = toEdgeMarker(Config.values(config.marker.target, [edge, stroke])) return { stroke, normalWidth, source, target } }) state.line = line state.selectable = computed(() => Config.value(config.selectable, edges[id])) const edgeLayoutPoint = toRef(groupStates.edgeLayoutPoints, id) const isEdgeSummarized = toRef(groupStates.summarizedEdges, id) const stopCalcHandle = watchEffect(() => { const edge = edges[id] if (!edge) return const source = layouts[edge?.source] const target = layouts[edge?.target] const sourceShape = nodeStates[edge?.source]?.staticShape const targetShape = nodeStates[edge?.target]?.staticShape if (!source || !target || !sourceShape || !targetShape) { return } // calculate the line segment between center of nodes const shiftedPosition = EdgeGroup.calculateEdgeShiftedPosition( edgeLayoutPoint.value, isEdgeSummarized.value, source, target, scale.value, config.keepOrder ) const [sourceShapeMargin, targetShapeMargin] = v2d.calculateDistancesFromCenterOfNodeToEndOfNode(source, target, sourceShape, targetShape) const s = scale.value // calculate the line segment between the outermost of the nodes state.labelPosition = v2d.applyMarginToLine( shiftedPosition, sourceShapeMargin * s, targetShapeMargin * s ) // calculate margins let sourceMargin = 0 let targetMargin = 0 const l = line.value if (l.source.type !== "none") { const marker = l.source sourceMargin = marker.margin + marker.width if (marker.units === "strokeWidth") { sourceMargin *= l.normalWidth } } if (l.target.type !== "none") { const marker = l.target targetMargin = marker.margin + marker.width if (marker.units === "strokeWidth") { targetMargin *= l.normalWidth } } if (config.margin === null || config.margin === undefined) { if (l.source.type !== "none" || l.target.type !== "none") { sourceMargin += sourceShapeMargin targetMargin += targetShapeMargin } } else { sourceMargin += config.margin + sourceShapeMargin targetMargin += config.margin + targetShapeMargin } // calculate the line segments to be displayed with margins applied const type = config.type if (type === "straight") { state.origin = shiftedPosition state.curve = undefined if (sourceMargin === 0 && targetMargin === 0) { state.position = state.origin } else { state.position = v2d.applyMarginToLine(state.origin, sourceMargin * s, targetMargin * s) } } else { // curve state.origin = v2d.positionsToLinePosition(source, target) const shift = edgeLayoutPoint.value.groupWidth / 2 - edgeLayoutPoint.value.pointInGroup const [position, curve] = calculateCurvePositionAndState( state.origin, shiftedPosition, shift, sourceMargin * s, targetMargin * s ) state.position = position state.curve = curve } }) const stopUpdateMarkerHandle = watchEffect(() => { if (!edges[id]) return state.sourceMarkerId = makeMarker( line.value.source, true /* isSource */, state.sourceMarkerId, line.value.stroke.color ) state.targetMarkerId = makeMarker( line.value.target, false /* isSource */, state.targetMarkerId, line.value.stroke.color ) }) states[id].stopWatchHandle = () => { stopCalcHandle() stopUpdateMarkerHandle() clearMarker(state.sourceMarkerId) clearMarker(state.targetMarkerId) } } function calculateCurvePositionAndState( originPosition: LinePosition, shiftedPosition: LinePosition, shift: number, sourceMargin: number, targetMargin: number ): [LinePosition, Curve | undefined] { // The curve is assumed to be part of a perfect circle and is drawn // as a Bezier curve. const origin = V.fromLinePosition(originPosition) const shifted = V.fromLinePosition(shiftedPosition) const shiftedCenter = V.getCenterOfLinePosition(shiftedPosition) // Calculate the center and radius of the circle of the curve. const [center, radius] = V.calculateCircleCenterAndRadiusBy3Points( origin.source, origin.target, shiftedCenter ) let position: LinePosition let curve: Curve | undefined = undefined if (shift === 0) { // The line connecting the centers of the nodes is regarded as a straight line. if (sourceMargin === 0 && targetMargin === 0) { position = originPosition } else { position = v2d.applyMarginToLine(originPosition, sourceMargin, targetMargin) } return [position, curve] } // Apply margin to the line. const centerToTop = V.fromVectors(center, shiftedCenter) // Direction of rotation from source to center: const theta0 = V.calculateRelativeAngleRadian(V.fromVectors(center, origin.source), centerToTop) if (sourceMargin === 0 && targetMargin === 0) { position = originPosition } else { // The endpoints of the display line are the point on the circumference // moved by the margin from the origin end points. let sourceMoveRad = sourceMargin / radius let targetMoveRad = targetMargin / radius // Determine which direction to move. if (theta0 > 0) { sourceMoveRad *= -1 targetMoveRad *= -1 } position = v2d.positionsToLinePosition( v2d.moveOnCircumference(origin.source, center, sourceMoveRad), v2d.moveOnCircumference(origin.target, center, -targetMoveRad) ) // If the endpoints are swapped by applying the margin, // a short line is shown at the center. let theta1 = V.calculateRelativeAngleRadian( V.fromVectors(center, origin.source), V.fromVectors(center, origin.target) ) let theta2 = V.calculateRelativeAngleRadian( V.fromPositions(center, { x: position.x1, y: position.y1 }), V.fromPositions(center, { x: position.x2, y: position.y2 }) ) if (theta0 * theta1 < 0) { theta1 = v2d.reverseAngleRadian(theta1) if (theta0 * theta2 < 0) { theta2 = v2d.reverseAngleRadian(theta2) } } if (theta1 * theta2 < 0) { // reversed const c = shiftedCenter.clone().add(shifted.v.normalize().multiplyScalar(0.5)) position = v2d.positionsToLinePosition(shiftedCenter, c) return [position, curve] } } // Calculate the control/via points of a Bezier curve. const [p1, p2] = V.toVectorsFromLinePosition(position) const control = v2d .calculateBezierCurveControlPoint(p1, center, p2, theta0) .map(p => p.toObject()) curve = { center: shiftedCenter, theta: theta0, circle: { center, radius }, control, } return [position, curve] } function createSummarizedEdgeStates( summarizedEdgeStates: SummarizedEdgeStates, edgeGroupStates: Reactive<EdgeGroupStates>, configs: Configs ) { const groups = edgeGroupStates.edgeGroups Object.entries(groups) .filter(([id, group]) => group.summarize && !(id in summarizedEdgeStates)) .forEach(([id, group]) => { const state = { stroke: undefined as any } state.stroke = computed<StrokeStyle>(() => Config.values(configs.edge.summarized.stroke, group.edges) ) summarizedEdgeStates[id] = state }) Object.keys(summarizedEdgeStates).forEach(id => { if (!edgeGroupStates.edgeGroups[id]?.summarize) { delete summarizedEdgeStates[id] } }) }
the_stack
import InfoCircle from '@assets/icons/InfoCircle'; import { BrandedButton, CheckboxItem, CheckboxList, ColourHighlightHeaderTextText, ErrorText, HeaderText, RegularText, TextareaWithCharCount, } from '@covid/components'; import { Form } from '@covid/components/Form'; import { GenericTextField } from '@covid/components/GenericTextField'; import { RadioInput } from '@covid/components/inputs/RadioInput'; import { Screen } from '@covid/components/Screen'; import { homeScreenName, thankYouScreenName } from '@covid/core/localisation/LocalisationService'; import { ILongCovid } from '@covid/features/long-covid/types'; import { TScreenParamList } from '@covid/features/ScreenParamList'; import i18n from '@covid/locale/i18n'; import NavigatorService from '@covid/NavigatorService'; import { longCovidApiClient } from '@covid/services'; import { sizes, styling } from '@covid/themes'; import { RouteProp } from '@react-navigation/native'; import { colors } from '@theme'; import { Formik, FormikProps } from 'formik'; import * as React from 'react'; import { StyleSheet, View } from 'react-native'; import { checkboxIndexOffset, longCovidQuestionPageOneDataInitialState, symptomChangesKeyList, validations, } from './consts.questions'; interface IProps { route: RouteProp<TScreenParamList, 'LongCovidStart'>; } const renderBulletLine = (text: string) => ( <View style={{ flexDirection: 'row', paddingRight: sizes.m, paddingTop: sizes.m }}> <RegularText style={styles.bullet}>{'\u2B24'}</RegularText> <RegularText style={{ flex: 1, paddingLeft: sizes.m }}>{text}</RegularText> </View> ); export default function LongCovidQuestionScreen({ route }: IProps) { const dropdownItemsQ1 = [ { label: i18n.t('long-covid.q1-a5'), value: 'NO' }, { label: i18n.t('long-covid.q1-a1'), value: 'YES_TEST' }, { label: i18n.t('long-covid.q1-a2'), value: 'YES_ADVICE' }, { label: i18n.t('long-covid.q1-a3'), value: 'YES_SUSPICION' }, { label: i18n.t('long-covid.q1-a4'), value: 'UNSURE' }, { label: i18n.t('long-covid.q1-a6'), value: 'DECLINE_TO_SAY' }, ]; const dropdownItemsQ2 = [ { label: i18n.t('long-covid.q2-a1'), value: 'LESS_THAN_TWO_WEEKS' }, { label: i18n.t('long-covid.q2-a2'), value: '2_TO_3_WEEKS' }, { label: i18n.t('long-covid.q2-a3'), value: '4_TO_12_WEEKS' }, { label: i18n.t('long-covid.q2-a4'), value: 'MORE_THAN_12_WEEKS' }, ]; const dropdownItemsQ3 = [ { label: i18n.t('long-covid.q3-a1'), value: 'ALWAYS_FUNCTION_NORMAL' }, { label: i18n.t('long-covid.q3-a2'), value: '1_TO_3_DAYS' }, { label: i18n.t('long-covid.q3-a3'), value: '4_TO_6_DAYS' }, { label: i18n.t('long-covid.q3-a4'), value: '7_TO_13_DAYS' }, { label: i18n.t('long-covid.q3-a5'), value: '2_TO_3_WEEKS' }, { label: i18n.t('long-covid.q3-a6'), value: '4_TO_12_WEEKS' }, { label: i18n.t('long-covid.q3-a7'), value: 'MORE_THAN_12_WEEKS' }, ]; const checkBoxQuestions4To17 = [ 'problems_thinking_and_communicating', 'mood_changes', 'poor_sleep', 'body_aches', 'muscle_aches', 'skin_rashes', 'bone_or_joint_pain', 'headaches', 'light_headed', 'altered_taste_or_smell', 'breathing_problems', 'heart_problems', 'abdominal_pain_diarrhoea', 'other_checkbox', ]; const dropdownItemsQ18 = [ { label: i18n.t('long-covid.q18-a1'), value: 'YES' }, { label: i18n.t('long-covid.q18-a2'), value: 'NO' }, ]; const dropdownItemsQ19 = [ { label: i18n.t('long-covid.q19-a1'), value: 'YES' }, { label: i18n.t('long-covid.q19-a2'), value: 'NO' }, { label: i18n.t('long-covid.q19-a3'), value: 'UNSURE' }, ]; const dropdownItemsSymptomsChange = [ { label: i18n.t('long-covid.symptoms-change-a1'), value: 'YES_ALL_BETTER' }, { label: i18n.t('long-covid.symptoms-change-a2'), value: 'YES_SOME_BETTER' }, { label: i18n.t('long-covid.symptoms-change-a3'), value: 'NO_CHANGE' }, { label: i18n.t('long-covid.symptoms-change-a4'), value: 'YES_SOME_WORSE' }, { label: i18n.t('long-covid.symptoms-change-a5'), value: 'YES_ALL_WORSE' }, { label: i18n.t('long-covid.symptoms-change-a6'), value: 'SOME_IMPROVED' }, { label: i18n.t('long-covid.symptoms-change-a7'), value: 'NOT_YET_TWO_WEEKS' }, { label: i18n.t('long-covid.symptoms-change-a8'), value: 'OTHER' }, ]; const dropdownItemsSymptomsChangeSeverity = [ { label: i18n.t('long-covid.symptoms-change-severity-a1'), value: 'COMPLETELY_DISAPPEARED' }, { label: i18n.t('long-covid.symptoms-change-severity-a2'), value: 'DECREASED' }, { label: i18n.t('long-covid.symptoms-change-severity-a3'), value: 'NO_CHANGE' }, { label: i18n.t('long-covid.symptoms-change-severity-a4'), value: 'INCREASED' }, { label: i18n.t('long-covid.symptoms-change-severity-a5'), value: 'CAME_BACK' }, { label: i18n.t('long-covid.symptoms-change-severity-a6'), value: 'NOT_APPLICABLE' }, ]; const [isSubmitting, setSubmitting] = React.useState<boolean>(false); const onSubmit = async (values: ILongCovid) => { if (isSubmitting) { return; } delete values.other_checkbox; setSubmitting(true); longCovidApiClient.add(route.params?.patientData?.patientId, values).then(() => { NavigatorService.reset([{ name: homeScreenName() }, { name: thankYouScreenName() }], 1); }); }; const renderFormCheckboxes = (props: FormikProps<ILongCovid>) => ( <View style={{ marginVertical: sizes.m }}> <CheckboxList> {checkBoxQuestions4To17.map((key: string, index: number) => ( <View style={{ marginBottom: sizes.m }}> <CheckboxItem dark onChange={() => props.setFieldValue(key, !props.values[key])} value={props.values[key]}> {i18n.t(`long-covid.q${index + checkboxIndexOffset}`)} </CheckboxItem> </View> ))} {props.values.other_checkbox ? <GenericTextField formikProps={props} name="other" /> : null} </CheckboxList> </View> ); const renderError = (props: FormikProps<ILongCovid>, propertyKey: keyof ILongCovid) => props.touched[propertyKey] && props.errors[propertyKey] ? ( <View style={{ marginBottom: sizes.m }}> <ErrorText>{props.errors[propertyKey]}</ErrorText> </View> ) : null; const renderExtendedForm = (props: FormikProps<ILongCovid>) => props.values.had_covid && (props.values.had_covid.startsWith('YES') || props.values.had_covid === 'UNSURE') ? ( <View> <View style={styles.hr} /> <HeaderText>{i18n.t('long-covid.q2')}</HeaderText> <View style={styles.infoBox}> <RegularText>{i18n.t('long-covid.q2-info-1')}</RegularText> {renderBulletLine(i18n.t('long-covid.q2-info-2'))} {renderBulletLine(i18n.t('long-covid.q2-info-3'))} {renderBulletLine(i18n.t('long-covid.q2-info-4'))} {renderBulletLine(i18n.t('long-covid.q2-info-5'))} </View> <RadioInput error={props.touched.duration ? props.errors.duration : ''} items={dropdownItemsQ2} onValueChange={props.handleChange('duration')} selectedValue={props.values.duration} /> {renderError(props, 'duration')} <View style={styles.hr} /> <HeaderText>{i18n.t('long-covid.q3')}</HeaderText> <RadioInput error={props.touched.restriction ? props.errors.restriction : ''} items={dropdownItemsQ3} onValueChange={props.handleChange('restriction')} selectedValue={props.values.restriction} /> {renderError(props, 'restriction')} <View style={styles.hr} /> <ColourHighlightHeaderTextText highlightColor={colors.purple} text={i18n.t('long-covid.q4-header')} /> <View style={{ ...styles.infoBox, marginBottom: sizes.l }}> <View style={{ flexDirection: 'row', paddingRight: sizes.l, paddingTop: sizes.m }}> <View style={{ paddingRight: sizes.s }}> <InfoCircle color={colors.primary} /> </View> <RegularText>{i18n.t('long-covid.q4-info-1')}</RegularText> </View> <View style={{ marginTop: sizes.m, paddingLeft: sizes.xl }}> <RegularText>{i18n.t('long-covid.q4-info-2')}</RegularText> </View> </View> <RegularText>{i18n.t('long-covid.q4-info-3')}</RegularText> {renderFormCheckboxes(props)} <View style={styles.hr} /> {/* Have you had at least one COVID-19 vaccine done? */} <HeaderText>{i18n.t('long-covid.q18')}</HeaderText> <RadioInput error={props.touched.at_least_one_vaccine ? props.errors.at_least_one_vaccine : ''} items={dropdownItemsQ18} onValueChange={props.handleChange('at_least_one_vaccine')} selectedValue={props.values.at_least_one_vaccine} /> {renderError(props, 'at_least_one_vaccine')} {renderExtendedVaccineForm(props)} </View> ) : null; const renderExtendedVaccineForm = (props: FormikProps<ILongCovid>) => props.values.at_least_one_vaccine && props.values.at_least_one_vaccine === 'YES' ? ( <View> <View style={styles.hr} /> {/* Did you have ongoing COVID-19 symptoms in the week before your first COVID-19 vaccine injection? */} <ColourHighlightHeaderTextText highlightColor={colors.purple} text={i18n.t('long-covid.q19')} /> <RadioInput error={ props.touched.ongoing_symptom_week_before_first_vaccine ? props.errors.ongoing_symptom_week_before_first_vaccine : '' } items={dropdownItemsQ19} onValueChange={props.handleChange('ongoing_symptom_week_before_first_vaccine')} selectedValue={props.values.ongoing_symptom_week_before_first_vaccine} /> {renderError(props, 'ongoing_symptom_week_before_first_vaccine')} <View style={styles.hr} /> {/* Did your symptoms change 2 weeks (or more) after your first COVID-19 vaccine injection? */} <ColourHighlightHeaderTextText highlightColor={colors.purple} text={i18n.t('long-covid.q20')} /> <RadioInput error={ props.touched.symptom_change_2_weeks_after_first_vaccine ? props.errors.symptom_change_2_weeks_after_first_vaccine : '' } items={dropdownItemsSymptomsChange} onValueChange={props.handleChange('symptom_change_2_weeks_after_first_vaccine')} selectedValue={props.values.symptom_change_2_weeks_after_first_vaccine} /> {renderError(props, 'symptom_change_2_weeks_after_first_vaccine')} <View style={styles.hr} /> {/* Have your symptoms changed in the week after your vaccination (excluding the first 2 days)? */} <ColourHighlightHeaderTextText highlightColor={colors.purple} text={i18n.t('long-covid.q21')} /> {symptomChangesKeyList.map((key: string) => ( <RadioInput error={props.touched[key] && props.errors[key]} items={dropdownItemsSymptomsChangeSeverity} label={i18n.t(`long-covid.q21-${key}`)} onValueChange={props.handleChange(key)} selectedValue={props.values[key]} /> ))} <View style={styles.hr} /> {/* Do you have anything else to share regarding the evolution of your COVID-19 symptoms? */} <HeaderText style={{ marginBottom: sizes.m }}>{i18n.t('long-covid.comments')}</HeaderText> <TextareaWithCharCount bordered onChangeText={props.handleChange('symptom_change_comments')} placeholder={i18n.t('placeholder-optional-question')} textAreaStyle={styles.textarea} value={props.values.symptom_change_comments} /> </View> ) : null; return ( <Screen backgroundColor={colors.backgroundSecondary} testID="long-covid-question-screen"> <Formik initialValues={{ ...LongCovidQuestionScreen.initialFormValues(), }} onSubmit={onSubmit} validationSchema={LongCovidQuestionScreen.schema} > {(props: FormikProps<ILongCovid>) => { return ( <Form> <HeaderText>{i18n.t('long-covid.q1')}</HeaderText> <RadioInput error={props.touched.had_covid && props.errors.had_covid} items={dropdownItemsQ1} onValueChange={props.handleChange('had_covid')} selectedValue={props.values.had_covid} testID="input-had-covid" /> {renderExtendedForm(props)} <View style={styling.flex} /> <BrandedButton enabled={props.values.had_covid !== null && Object.keys(props.errors).length < 1} onPress={props.handleSubmit} style={styles.marginTop} testID="button-submit" > <RegularText style={{ color: colors.white }}>{i18n.t('long-covid.finish')}</RegularText> </BrandedButton> </Form> ); }} </Formik> </Screen> ); } LongCovidQuestionScreen.initialFormValues = (): ILongCovid => longCovidQuestionPageOneDataInitialState; LongCovidQuestionScreen.schema = () => validations; const styles = StyleSheet.create({ bullet: { fontSize: 4, }, hr: { borderBottomColor: colors.hrColor, borderBottomWidth: 1, marginBottom: sizes.xxl, marginTop: sizes.m, }, infoBox: { backgroundColor: colors.white, borderRadius: sizes.xs, marginTop: sizes.m, padding: sizes.m, paddingBottom: sizes.l, textAlign: 'left', }, marginTop: { marginTop: sizes.xl, }, textarea: { backgroundColor: colors.backgroundTertiary, borderRadius: sizes.xs, paddingVertical: sizes.xxl, }, });
the_stack
import * as admin from "firebase-admin"; import * as betterAjvErrors from "better-ajv-errors"; import * as crypto from "crypto"; import * as firestore from "@google-cloud/firestore"; import * as functions from "firebase-functions"; import { API_ANIMATION_CREATE, API_ANIMATION_JSON, API_ANIMATION_VIDEO, API_FEEDBACK, API_HEALTH, API_POST_CREATE, API_POST_DELETE, API_POST_LIKE, API_PROFILE_AVATAR, API_PROFILE_AVATAR_UPDATE, API_PROFILE_UPDATE, API_VIEWED_THREAD, AnimationData, Api, AttributedSource, COLLECTION_ANIMATIONS, COLLECTION_AVATARS, COLLECTION_LIKED, COLLECTION_POSTS, COLLECTION_USERS, COLLECTION_VIDEOS, COLLECTION_VIEWED, ClientPost, PostData, PostType, SchemaValidator, StoredPost, StoredUser, makeLikedKey, userHasPermission } from "../../common/common"; import {TEST_EMAIL} from "../../common/test"; import {TextDecoder} from "util"; import fetch from "node-fetch"; import {uuid} from "uuidv4"; admin.initializeApp(functions.config().firebase); const store = admin.firestore(); const expect = <T>(name: string, value: T | null | undefined | false) => { if (!value) { throw new Error(`Expected ${name} but got ${value}`); } return value; }; const ajvErrorsToString = (validator: SchemaValidator, json: Record<string, any>) => { const errors = betterAjvErrors( validator.schema, json, validator.errors, {format: "js", indent: null} ); if (!errors || errors.length === 0) { return JSON.stringify(validator.errors); } return errors.map((error) => error.error + (error.suggestion ? `\n${error.suggestion}` : "")).join("\n"); }; type UserId = string; type PostId = string; type IPHash = string; const SECONDS_PER_DAY = 86400; const docUser = (userId: UserId) => store.collection(COLLECTION_USERS).doc(userId); const dbGetUser = async (userId: UserId): Promise<StoredUser | null> => { const userDoc = await docUser(userId).get(); return userDoc.data() as StoredUser; }; const addRandomNumbersToEnd = (text: string) => `${text}${Math.floor(Math.random() * 90000) + 10000}`; const sanitizeOrGenerateUsername = (unsantizedUsername: string) => { // The output of this must be valid according to the regex in API_PROFILE_UPDATE. const invalidReplaceCharacter = "."; // Replace all invalid characters with "." and don't allow multiple in a row. const sanitizedUsername = unsantizedUsername. replace(/[^a-zA-Z0-9.]/gu, invalidReplaceCharacter). replace(/\.+/gu, invalidReplaceCharacter); // If the username is empty or just the invalid character then pick a generic name. const pickedUsername = !sanitizedUsername || sanitizedUsername === invalidReplaceCharacter ? "user" : sanitizedUsername; // If the username is too short, append random digits; const usernameMinLength = expect("username.minLength", API_PROFILE_UPDATE.props.username.minLength); const usernameMaxLength = expect("username.maxLength", API_PROFILE_UPDATE.props.username.maxLength); const username = pickedUsername.length < usernameMinLength ? addRandomNumbersToEnd(pickedUsername) : pickedUsername; return username.slice(0, usernameMaxLength); }; const dbPutUser = async (user: StoredUser, allowNameNumbers: boolean): Promise<void> => { const success = await store.runTransaction(async (transaction) => { for (;;) { const result = await transaction.get(store.collection(COLLECTION_USERS).where("username", "==", user.username)); if (result.size > 1) { throw new Error("More than one user with the same username"); } if (result.size === 0) { break; } if (result.size === 1) { const foundUser = result.docs[0].data() as StoredUser; if (foundUser.id === user.id) { break; } } if (allowNameNumbers) { user.username = addRandomNumbersToEnd(user.username); } else { return false; } } transaction.set(docUser(user.id), user); return true; }); if (!success) { throw new Error(`The username ${user.username} was already taken`); } }; const docPost = (postId: PostId) => store.collection(COLLECTION_POSTS).doc(postId); const dbGetPost = async (postId: PostId): Promise<StoredPost | undefined> => { const postDoc = await docPost(postId).get(); return postDoc.data() as StoredPost | undefined; }; const dbExpectPost = async (postId: PostId): Promise<StoredPost> => { const post = await dbGetPost(postId); if (!post) { throw new Error(`Attempting to get a post by id ${postId} returned null`); } return post; }; interface StoredVideo { buffer: Buffer; } const docVideo = (postId: PostId) => store.collection(COLLECTION_VIDEOS).doc(postId); const docAnimation = (postId: PostId) => store.collection(COLLECTION_ANIMATIONS).doc(postId); const dbDeletePost = async (post: StoredPost): Promise<void> => { const postId = post.id; await store.runTransaction(async (transaction) => { const postDoc = await transaction.get(docPost(postId)); const storedPost = postDoc.data() as StoredPost | undefined; if (!storedPost) { return; } const likedDocs = await store.collection(COLLECTION_LIKED).where("postId", "==", postId).get(); for (const doc of likedDocs.docs) { transaction.delete(doc.ref); } const viewedDocs = await store.collection(COLLECTION_VIEWED).where("threadId", "==", postId).get(); for (const doc of viewedDocs.docs) { transaction.delete(doc.ref); } if (storedPost.type === "thread") { const threadPostDocs = await store.collection(COLLECTION_POSTS).where("threadId", "==", postId).get(); for (const doc of threadPostDocs.docs) { transaction.delete(doc.ref); } } transaction.delete(docPost(postId)); transaction.delete(docAnimation(postId)); transaction.delete(docVideo(postId)); }); // TODO(Trevor): Need to remove viewed and liked entries for this post (and child posts if this is a thread). await Promise.all([ docPost(postId).delete(), docAnimation(postId).delete(), docVideo(postId).delete() ]); }; // We use a custom epoch to avoid massive floating point numbers, especially when averaging. const BIRTH_MS = 1593820800000; interface UserLikedInfo { postId: PostId; userId: UserId; secondsFromBirth: number; } interface UserViewedInfo { threadId: PostId; ipHash: UserId; } const map0To1Asymptote = (x: number) => -1 / (Math.max(x, 0) + 1) ** 2 + 1; const computeTrendingScore = (post: StoredPost) => { const secondsAddedPerLike = 100; const likeSeconds = post.likes * secondsAddedPerLike; const addedSeconds = map0To1Asymptote(likeSeconds / SECONDS_PER_DAY) * SECONDS_PER_DAY; // The || 0 is to protect against NaN for any reason return post.likesSecondsFromBirthAverage + addedSeconds || 0; }; const dbAddView = async (threadId: PostId, ipHash: IPHash): Promise<void> => { const userViewedInfo: UserViewedInfo = { threadId, ipHash }; try { await store.runTransaction(async (transaction) => { transaction.create(store.collection(COLLECTION_VIEWED).doc(`${threadId}_${ipHash}`), userViewedInfo); transaction.update(docPost(threadId), {views: admin.firestore.FieldValue.increment(1)}); }); } catch (err) { if (err.code !== firestore.GrpcStatus.ALREADY_EXISTS) { throw err; } } }; const isDevEnvironment = () => process.env.FUNCTIONS_EMULATOR === "true"; const CONTENT_TYPE_APPLICATION_JSON = "application/json"; const CONTENT_TYPE_APPLICATION_OCTET_STREAM = "application/octet-stream"; const CONTENT_TYPE_VIDEO_MP4 = "video/mp4"; const CONTENT_TYPE_IMAGE_JPEG = "image/jpeg"; const CACHE_CONTROL_IMMUTABLE = "public,max-age=31536000,immutable"; const parseBinaryChunks = (buffer: Buffer) => { const result: Buffer[] = []; for (let index = 0; index < buffer.byteLength;) { const size = buffer.readUInt32LE(index); const start = index + 4; const data = buffer.slice(start, start + size); result.push(data); index = start + size; } return result; }; interface RawRequest { // All methods are uppercase. method: string; url: URL; ipHash: string; authorization: string | null; range: string | null; body: Buffer; onHandlerNotFound: () => Promise<RequestOutput<any>>; } class RequestInput<T> { public readonly request: RawRequest; public readonly url: URL; public readonly json: T; private authedUser?: StoredUser = undefined; public constructor (request: RawRequest, json: T) { this.request = request; this.url = request.url; this.json = json; } private async validateJwtAndGetUser (): Promise<StoredUser> { const idToken = expect("authorization", this.request.authorization); const decodedToken = await admin.auth().verifyIdToken(idToken); if (!isDevEnvironment() && decodedToken.email === TEST_EMAIL) { throw new Error("Attempting to login as test user in production"); } const firebaseUser = await admin.auth().getUser(decodedToken.uid); if (firebaseUser.disabled) { throw new Error("The account has been disabled"); } const existingUser = await dbGetUser(decodedToken.uid); if (existingUser) { return existingUser; } const unsanitizedName = decodedToken.email ? decodedToken.email.split("@")[0] : decodedToken.given_name || decodedToken.name || ""; const storedUsed: StoredUser = { id: decodedToken.uid, avatarId: null, username: sanitizeOrGenerateUsername(unsanitizedName), bio: "", role: "user" }; await dbPutUser(storedUsed, true); return storedUsed; } public async getAuthedUser (): Promise<StoredUser | null> { if (this.authedUser) { return this.authedUser; } if (this.request.authorization) { this.authedUser = await this.validateJwtAndGetUser(); return this.authedUser; } return null; } public async requireAuthedUser (): Promise<StoredUser> { return expect("auth", await this.getAuthedUser()); } } interface RequestOutput<OutputType> { result: OutputType; contentType?: string; immutable?: boolean; headers?: Record<string, string>; // Any RequestOutput is assumed to be 200 or this status value (null means 404, and throw is 500). status?: number; } type HandlerCallback<InputType, OutputType> = (input: RequestInput<InputType>) => Promise<RequestOutput<OutputType>>; interface Handler { api: Api<any, any>; callback: HandlerCallback<any, any>; } const handlers: Record<string, Handler> = {}; const addHandler = <InputType, OutputType>( api: Api<InputType, OutputType>, // It's bizarre that we use Omit here, however we're forcing the template inference to only work on Api. callback: HandlerCallback<Omit<InputType, "">, Omit<OutputType, "">>) => { handlers[api.pathname] = { api, callback }; }; const videoMp4Header = Buffer.from([ 0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6d, 0x70, 0x34, 0x32, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x70, 0x34, 0x32, 0x69, 0x73, 0x6f, 0x6d ]); const imageGifHeader = Buffer.from([0x47, 0x49, 0x46, 0x38]); const imageJpegHeader = Buffer.from([0xFF, 0xD8]); const imagePngHeader = Buffer.from([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]); const expectFileHeader = (name: string, types: string, buffer: Buffer, possibleHeaders: Buffer[]) => { for (const possibleHeader of possibleHeaders) { if (buffer.compare(possibleHeader, 0, possibleHeader.byteLength, 0, possibleHeader.byteLength) === 0) { return; } } throw new Error(`File ${name} was not the correct type. Expected ${types}`); }; interface PostCreateGeneric { message: string; title?: string; threadId?: string; replyId?: string | null | undefined; } const postCreate = async ( input: RequestInput<PostCreateGeneric>, allowCreateThread: boolean, hasTitle: boolean, userdata: PostData) => { const user = await input.requireAuthedUser(); const title = hasTitle ? input.json.title || null : null; const replyId = input.json.replyId || null; const {message} = input.json; const id = uuid(); const threadId = await (async () => { if (allowCreateThread && !input.json.threadId && !replyId) { return id; } if (input.json.threadId) { if (replyId) { const replyPost = await dbExpectPost(replyId); if (replyPost.threadId !== input.json.threadId) { throw new Error("Attempting to reply to a post that was in the wrong thread"); } } return input.json.threadId; } const replyPost = await dbExpectPost(expect("replyId", replyId)); return replyPost.threadId; })(); const type: PostType = (() => { if (threadId === id) { return "thread"; } if (userdata.type === "animation") { return "remix"; } return "comment"; })(); const post: StoredPost = { id, type, threadId, title, message, userdata, userId: user.id, replyId, dateMsSinceEpoch: Date.now(), likes: 0, likesSecondsFromBirthAverage: 0, trendingScore: 0, views: 0 }; await docPost(post.id).create(post); // We return what the post would actually look like if it were listed (for quick display in React). const result: ClientPost = { ...post, username: user!.username, avatarId: user!.avatarId, liked: false, likes: 0, views: 0, canDelete: true }; return { result, threadId, id }; }; addHandler(API_POST_CREATE, async (input) => postCreate(input, false, false, {type: "comment"})); addHandler(API_VIEWED_THREAD, async (input) => { await dbAddView(input.json.threadId, input.request.ipHash); return {result: {}}; }); addHandler(API_ANIMATION_CREATE, async (input) => { const [ jsonBinary, video ] = parseBinaryChunks(input.request.body); const json: string = new TextDecoder().decode(jsonBinary); const animationData: AnimationData = JSON.parse(json); // eslint-disable-next-line @typescript-eslint/no-var-requires const validator = require("../../ts-schema-loader/dist/main.js!../../common/common.ts?AnimationData"); if (!validator(animationData)) { throw new Error(`AnimationData was invalid:\n${ajvErrorsToString(validator, animationData)}`); } const attribution: AttributedSource[] = [ animationData.videoAttributedSource, ...animationData.widgets.map((widget) => widget.attributedSource) ]; expectFileHeader("video", "mp4", video, [videoMp4Header]); const output = await postCreate(input, true, true, { type: "animation", attribution: attribution.filter((attribute) => Boolean(attribute.originUrl)), width: input.json.width, height: input.json.height }); const {id} = output; const storedVideo: StoredVideo = { buffer: Buffer.from(video) }; await Promise.all([ docVideo(id).create(storedVideo), docAnimation(id).create(animationData) ]); return output; }); addHandler(API_ANIMATION_JSON, async (input) => { const animationDoc = await docAnimation(input.json.id).get(); const result = animationDoc.data() as AnimationData; return {result, immutable: true}; }); addHandler(API_ANIMATION_VIDEO, async (input) => { const videoDoc = await docVideo(input.json.id).get(); const storedVideo = videoDoc.data() as StoredVideo; const result = storedVideo.buffer; return { result, immutable: true, contentType: CONTENT_TYPE_VIDEO_MP4 }; }); addHandler(API_PROFILE_UPDATE, async (input) => { const user = await input.requireAuthedUser(); user.username = input.json.username; user.bio = input.json.bio; await dbPutUser(user, false); return {result: user}; }); interface StoredAvatar { buffer: Buffer; } const docAvatar = (avatarId: string) => store.collection(COLLECTION_AVATARS).doc(avatarId); addHandler(API_PROFILE_AVATAR, async (input) => { const avatarDoc = await docAvatar(input.json.avatarId).get(); const avatarData = expect("avatar", avatarDoc.data()) as StoredAvatar; return { result: avatarData.buffer, immutable: true, contentType: CONTENT_TYPE_IMAGE_JPEG }; }); addHandler(API_PROFILE_AVATAR_UPDATE, async (input) => { const imageData = input.request.body; const avatarMaxSizeKB = 256; if (imageData.byteLength > avatarMaxSizeKB * 1024) { throw new Error(`The size of the avatar must not be larger than ${avatarMaxSizeKB}KB`); } expectFileHeader("avatar", "gif, jpeg, png", imageData, [imageGifHeader, imageJpegHeader, imagePngHeader]); const user = await input.requireAuthedUser(); const avatarId = await store.runTransaction(async (transaction) => { const userRef = docUser(user.id); const userDoc = await transaction.get(userRef); const storedUser = userDoc.data() as StoredUser; if (storedUser.avatarId) { transaction.delete(docAvatar(storedUser.avatarId)); } const newAvatar = store.collection(COLLECTION_AVATARS).doc(); transaction.create(newAvatar, { buffer: Buffer.from(imageData) }); transaction.update(userRef, {avatarId: newAvatar.id}); return newAvatar.id; }); return {result: {...user, avatarId}}; }); addHandler(API_POST_LIKE, async (input) => { const postId = input.json.id; const newValue = input.json.liked; const user = await input.requireAuthedUser(); const doc = store.collection(COLLECTION_LIKED).doc(makeLikedKey(postId, user.id)); const likes = await store.runTransaction(async (transaction) => { const postLikedDoc = await transaction.get(doc); const oldValue = postLikedDoc.exists; const post = expect("post", (await transaction.get(docPost(postId))).data()) as StoredPost; if (newValue !== oldValue) { if (newValue) { const secondsFromBirth = (Date.now() - BIRTH_MS) / 1000; const newUserLikedInfo: UserLikedInfo = { postId, userId: user.id, secondsFromBirth }; post.likesSecondsFromBirthAverage = (post.likesSecondsFromBirthAverage * post.likes + secondsFromBirth) / (post.likes + 1); ++post.likes; transaction.create(doc, newUserLikedInfo); } else { --post.likes; if (post.likes === 0) { post.likesSecondsFromBirthAverage = 0; } else { const userLikedInfo = postLikedDoc.data() as UserLikedInfo; const likesSecondsFromBirthAverageNew = (post.likesSecondsFromBirthAverage * (post.likes + 1) - userLikedInfo!.secondsFromBirth) / post.likes; post.likesSecondsFromBirthAverage = Math.max(0, likesSecondsFromBirthAverageNew); } transaction.delete(doc); } post.trendingScore = computeTrendingScore(post); transaction.update(docPost(postId), post); } return post.likes; }); return {result: {likes}}; }); addHandler(API_FEEDBACK, async (input) => { const {title} = input.json; const response = await fetch("https://api.github.com/repos/TrevorSundberg/gifygram/issues", { method: "POST", body: JSON.stringify({title}), headers: { accept: "application/vnd.github.v3+json", authorization: `token ${process.env.GITHUB_TOKEN}` } }); await response.json(); return {result: {}}; }); addHandler(API_HEALTH, async () => { await store.collection(COLLECTION_VIDEOS).doc("health").get(); return {result: {}}; }); addHandler(API_POST_DELETE, async (input) => { const user = await input.requireAuthedUser(); const postId = input.json.id; const post = await dbExpectPost(postId); if (!userHasPermission(user, post.userId)) { throw new Error("Attempting to delete post that did not belong to the user"); } await dbDeletePost(post); return {result: {}}; }); const handleRequest = async (request: RawRequest): Promise<RequestOutput<any>> => { const {url} = request; const handler = handlers[url.pathname]; if (handler) { // Convert the url parameters back to json so we can validate it. const jsonInput: Record<string, any> = {}; const decodeUriValue = (input: string) => decodeURIComponent(input.replace(/\+/gu, "%20")); const searchParamsRegex = /(?:\?|&|;)([^=]+)=([^&|;]+)/gu; for (;;) { // Unfortunately CF workers does not have url.searchParams.forEach const result = searchParamsRegex.exec(url.search); if (!result) { break; } jsonInput[decodeUriValue(result[1])] = JSON.parse(decodeUriValue(result[2])); } const result = handler.api.validator(jsonInput); if (!result) { throw new Error(ajvErrorsToString(handler.api.validator, jsonInput)); } const input = new RequestInput<any>(request, jsonInput); const output = await handler.callback(input); return output; } return request.onHandlerNotFound(); }; const handleRanges = async (request: RawRequest): Promise<RequestOutput<any>> => { const response = await handleRequest(request); if (response.result instanceof Buffer) { response.headers = response.headers || {}; response.headers["accept-ranges"] = "bytes"; const rangeHeader = request.range; if (request.method === "GET" && rangeHeader) { const rangeResults = (/bytes=([0-9]+)-([0-9]+)?/u).exec(rangeHeader); if (!rangeResults) { throw new Error(`Invalid range header: ${rangeHeader}`); } const buffer = response.result; const begin = parseInt(rangeResults[1], 10); const end = parseInt(rangeResults[2], 10) || buffer.byteLength - 1; response.result = buffer.slice(begin, end + 1); response.headers["content-range"] = `bytes ${begin}-${end}/${buffer.byteLength}`; response.status = 206; return response; } } return response; }; const handleErrors = async (request: RawRequest): Promise<RequestOutput<any>> => { try { return await handleRanges(request); } catch (err) { const stack = err && err.stack || err; console.error(stack); return { result: { err: `${err && err.message || err}`, stack, url: request.url.href }, status: 500 }; } }; const handle = async (request: RawRequest): Promise<RequestOutput<any>> => { const output = await handleErrors(request); output.headers = output.headers || {}; if (output.result instanceof Buffer) { output.contentType = output.contentType || CONTENT_TYPE_APPLICATION_OCTET_STREAM; } else { output.contentType = output.contentType || CONTENT_TYPE_APPLICATION_JSON; output.result = JSON.stringify(output.result); } output.headers = { ...output.headers, "content-type": output.contentType || CONTENT_TYPE_APPLICATION_JSON, ...output.immutable ? {"cache-control": CACHE_CONTROL_IMMUTABLE} : {} }; return output; }; // See firebase/functions/node_modules/@google-cloud/firestore/build/src/v1/firestore_client.js isBrowser checks delete (global as any).window; export const api = functions.https.onRequest(async (request, response) => { const apiIndex = request.originalUrl.lastIndexOf("/api/"); const ipHasher = crypto.createHash("sha256"); const ipOrHost = request.ip || request.header("x-forwarded-host") || ""; ipHasher.update(ipOrHost); const output = await handle({ ipHash: ipHasher.digest("hex"), authorization: request.headers.authorization || null, body: request.rawBody || Buffer.alloc(0), method: request.method, range: (request.headers.range as string | undefined) || null, url: new URL(`${request.protocol}://${request.get("host")}${request.originalUrl.substr(apiIndex)}`), onHandlerNotFound: async () => { throw new Error("The onHandlerNotFound is not implemented"); } }); if (output.headers) { for (const headerKey of Object.keys(output.headers)) { response.header(headerKey, output.headers[headerKey]); } } response.status(output.status || 200); response.send(output.result); }); export const scheduledFunction = functions.pubsub.schedule("every 1 minutes").onRun(async () => { console.log("Start warmup"); const response = await fetch("https://gifygram.com/api/health"); console.log("End warmup", await response.json()); return null; });
the_stack
import { Dictionary, DictionaryWithStringKey } from "../../AltDictionary"; import { EwsLogging } from "../EwsLogging"; import { EwsServiceJsonReader } from "../EwsServiceJsonReader"; import { ExchangeService } from "../ExchangeService"; import { ExtendedPropertyDefinition } from "../../PropertyDefinitions/ExtendedPropertyDefinition"; import { IndexedPropertyDefinition } from "../../PropertyDefinitions/IndexedPropertyDefinition"; import { PropertyDefinitionBase } from "../../PropertyDefinitions/PropertyDefinitionBase"; import { ServiceError } from "../../Enumerations/ServiceError"; import { ServiceObjectSchema } from "../ServiceObjects/Schemas/ServiceObjectSchema"; import { ServiceResponseException } from "../../Exceptions/ServiceResponseException"; import { ServiceResult } from "../../Enumerations/ServiceResult"; import { SoapFaultDetails } from "../../Misc/SoapFaultDetails"; import { Strings } from "../../Strings"; import { XmlAttributeNames } from "../XmlAttributeNames"; import { XmlElementNames } from "../XmlElementNames"; import { XmlNamespace } from "../../Enumerations/XmlNamespace"; /** * Represents the standard response to an Exchange Web Services operation. */ export class ServiceResponse { private result: ServiceResult; private errorCode: ServiceError; private errorMessage: string; private errorDetails: Dictionary<string, string> = new DictionaryWithStringKey<string>(); private errorProperties: PropertyDefinitionBase[] = [];; /** * @internal Gets a value indicating whether a batch request stopped processing before the end. */ get BatchProcessingStopped(): boolean { return (this.result == ServiceResult.Warning) && (this.errorCode == ServiceError.ErrorBatchProcessingStopped); } /** * Gets the result associated with this response. */ get Result(): ServiceResult { return this.result; } /** * Gets the error code associated with this response. */ get ErrorCode(): ServiceError { return this.errorCode; } /** * Gets a detailed error message associated with the response. If Result is set to Success, ErrorMessage returns null. * ErrorMessage is localized according to the PreferredCulture property of the ExchangeService object that was used to call the method that generated the response. */ get ErrorMessage(): string { return this.errorMessage; } /** * Gets error details associated with the response. If Result is set to Success, ErrorDetailsDictionary returns null. * Error details will only available for some error codes. For example, when error code is ErrorRecurrenceHasNoOccurrence, the ErrorDetailsDictionary will contain keys for EffectiveStartDate and EffectiveEndDate. * * @value The error details dictionary. */ get ErrorDetails(): Dictionary<string, string> { return this.errorDetails; } /** * Gets information about property errors associated with the response. If Result is set to Success, ErrorProperties returns null. * ErrorProperties is only available for some error codes. For example, when the error code is ErrorInvalidPropertyForOperation, ErrorProperties will contain the definition of the property that was invalid for the request. * * @value The error properties list. */ get ErrorProperties(): PropertyDefinitionBase[] { return this.errorProperties; } /** * @internal Initializes a new instance of the **ServiceResponse** class. */ constructor(); /** * @internal Initializes a new instance of the **ServiceResponse** class. * * @param {SoapFaultDetails} soapFaultDetails The SOAP fault details. */ constructor(soapFaultDetails: SoapFaultDetails); /** * @internal Initializes a new instance of the **ServiceResponse** class. * This is intended to be used by unit tests to create a fake service error response * * @param {ServiceError} responseCode Response code * @param {string} errorMessage Detailed error message */ constructor(responseCode: ServiceError, errorMessage: string); constructor(soapFaultDetailsOrResponseCode?: SoapFaultDetails | ServiceError, errorMessage?: string) { var argsLength = arguments.length; if (argsLength == 0) return; if (typeof soapFaultDetailsOrResponseCode === 'number') {//(responseCode: ServiceError, errorMessage: string) this.result = ServiceResult.Error; this.errorCode = soapFaultDetailsOrResponseCode; this.errorMessage = errorMessage; this.errorDetails = null; } else {//(soapFaultDetails: SoapFaultDetails) this.result = ServiceResult.Error; this.errorCode = soapFaultDetailsOrResponseCode.ResponseCode; this.errorMessage = soapFaultDetailsOrResponseCode.FaultString; this.errorDetails = soapFaultDetailsOrResponseCode.ErrorDetails; } } /** * @internal Internal method that throws a ServiceResponseException if this response has its Result property set to Error. */ InternalThrowIfNecessary(): void { if (this.Result == ServiceResult.Error) { throw new ServiceResponseException(this); } } /** * @internal Called when the response has been loaded from XML. */ Loaded(): void { /* virtual void to be implemented throw new Error("Not implemented.");*/ } /** * @internal Loads extra error details from XML * * @param {any} responseObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadExtraErrorDetailsFromXmlJsObject(responseObject: any, service: ExchangeService): void { if (responseObject[XmlElementNames.MessageXml]) { this.ParseMessageXml(responseObject[XmlElementNames.MessageXml]); } } /** * @internal Loads service object from XML. * * @param {any} responseObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadFromXmlJsObject(responseObject: any, service: ExchangeService): any { this.result = ServiceResult[<string>responseObject[XmlAttributeNames.ResponseClass]]; this.errorCode = ServiceError[<string>responseObject[XmlElementNames.ResponseCode]]; // TODO: Deal with a JSON version of "LoadExtraDetailsFromXml" if (this.result == ServiceResult.Warning || this.result == ServiceResult.Error) { this.errorMessage = responseObject[XmlElementNames.MessageText]; this.LoadExtraErrorDetailsFromXmlJsObject(responseObject, service); } if (this.result == ServiceResult.Success || this.result == ServiceResult.Warning) { if (!this.BatchProcessingStopped) { this.ReadElementsFromXmlJsObject(responseObject, service); } } this.MapErrorCodeToErrorMessage(); this.Loaded(); } /** * @internal Called after the response has been loaded from XML in order to map error codes to "better" error messages. */ MapErrorCodeToErrorMessage(): void { // Use a better error message when an item cannot be updated because its changeKey is old. if (this.ErrorCode == ServiceError.ErrorIrresolvableConflict) { this.errorMessage = Strings.ItemIsOutOfDate; } } /** * Parses the message XML. * * @param {any} jsObject The MessageXml Object. */ ParseMessageXml(jsObject: any): void { for (var key in jsObject) { if (key.indexOf("__") === 0) { continue; } switch (key) { case XmlElementNames.Value: let values = EwsServiceJsonReader.ReadAsArray(jsObject, key); values.forEach((value, index) => { let name = value[XmlAttributeNames.Name]; if (name) { if (this.ErrorDetails.containsKey(name)) { name = name + " - " + (index + 1) } this.errorDetails.Add(name, value[key]); } }); break; case XmlElementNames.FieldURI: this.errorProperties.push(ServiceObjectSchema.FindPropertyDefinition(jsObject[key][XmlAttributeNames.FieldURI])); break; case XmlElementNames.IndexedFieldURI: let indexFieldUriObject = jsObject[key]; this.errorProperties.push( new IndexedPropertyDefinition( indexFieldUriObject[XmlAttributeNames.FieldURI], indexFieldUriObject[XmlAttributeNames.FieldIndex])); break; case XmlElementNames.ExtendedFieldURI: let extendedPropDef = new ExtendedPropertyDefinition(); extendedPropDef.LoadPropertyValueFromXmlJsObject(jsObject[key]); this.errorProperties.push(extendedPropDef); break; default: EwsLogging.Assert(false, "ServiceResponse.ParseMessageXml", "Element: " + key + " - Please report example of this operation to ews-javascript-api repo to improve SoapFault parsing"); break; } } } /** * @internal Reads response elements from Xml JsObject. * * @param {any} jsObject The response object. * @param {ExchangeService} service The service. */ ReadElementsFromXmlJsObject(jsObject: any, service: ExchangeService): void { /* virtualvoid to be implemented throw new Error("Not implemented.");*/ let caller = "ServiceResponse->child"; try { caller = (<any>this.constructor).name; } catch (e) { } EwsLogging.Assert(caller === "ServiceResponse", caller + ".ReadElementsFromXmlJsObject", "BatchProcessingStopped is false but ReadElementsFromXmlJsObject is not available in derived class to call.") } /** * @internal Throws a ServiceResponseException if this response has its Result property set to Error. */ ThrowIfNecessary(): void { this.InternalThrowIfNecessary(); } }
the_stack
import $RefParser from '@apidevtools/json-schema-ref-parser' import retry, { Options } from 'async-retry' import Debug, { Debugger as DebugDebugger } from 'debug' import { AnyAaaaRecord, AnyARecord } from 'dns' // eslint-disable-next-line import/no-unresolved import { resolveAny } from 'dns/promises' import { existsSync, readdirSync, readFileSync, writeFileSync } from 'fs' import { Agent } from 'https' import walk from 'ignore-walk' import { dump, load } from 'js-yaml' import { cloneDeep, isEmpty, merge, omit, pick, set } from 'lodash' import fetch, { RequestInit } from 'node-fetch' import { resolve } from 'path' import { Writable, WritableOptions } from 'stream' import yargs, { Arguments as YargsArguments } from 'yargs' import { $, nothrow, ProcessOutput, sleep } from 'zx' import pkg from '../../package.json' import { DEPLOYMENT_STATUS_CONFIGMAP } from './constants' import { cleanEnvironment, env, isChart } from './envalid' const packagePath = process.cwd() $.verbose = false // https://github.com/google/zx#verbose - don't need to print the SHELL executed commands $.prefix = 'set -euo pipefail;' // https://github.com/google/zx/blob/main/index.mjs#L103 // we keep the rootDir for zx, but have to fix it for drone, which starts in /home/app/stack/env (to accommodate write perms): export const rootDir = process.cwd() === '/home/app/stack/env' ? '/home/app/stack' : process.cwd() export const parser = yargs(process.argv.slice(3)) export const getFilename = (path: string): string => path.split('/').pop()?.split('.')[0] as string export interface BasicArguments extends YargsArguments { logLevel?: string nonInteractive?: boolean skipCleanup?: boolean trace?: boolean verbose?: number debug?: boolean } let parsedArgs: BasicArguments const debuggers = {} export const setParsedArgs = (args: BasicArguments): void => { parsedArgs = args // Call needed to init LL for debugger and ZX calls: logLevel() } export const getParsedArgs = (): BasicArguments => { return parsedArgs } const commonDebug: DebugDebugger = Debug('otomi') commonDebug.enabled = true type DebuggerType = DebugDebugger | ((message?: any, ...optionalParams: any[]) => void) export class DebugStream extends Writable { output: DebuggerType constructor(output: DebuggerType, opts?: WritableOptions) { super(opts) this.output = output } // eslint-disable-next-line no-underscore-dangle,@typescript-eslint/explicit-module-boundary-types _write(chunk: any, encoding: any, callback: (error?: Error | null) => void): void { const data = chunk.toString().trim() if (data.length > 0) this.output(data) callback() } } type OtomiStreamDebugger = { log: DebugStream trace: DebugStream debug: DebugStream info: DebugStream warn: DebugStream error: DebugStream } export type OtomiDebugger = { base: DebuggerType log: DebuggerType trace: DebuggerType debug: DebuggerType info: DebuggerType warn: DebuggerType error: DebuggerType stream: OtomiStreamDebugger } // const xtermColors = { // red: [52, 124, 9, 202, 211], // orange: [58, 130, 202, 208, 214], // green: [2, 28, 34, 46, 78, 119], // } // const setColor = (term: DebuggerType, color: number[]) => { // // Console.{log,warn,error} don't have namespace, so we know if it is in there that we use the DebugDebugger // if (!('namespace' in term && env.STATIC_COLORS)) return // const t: DebugDebugger = term // const colons = (t.namespace.match(/:/g) || ['']).length - 1 // t.color = color[Math.max(0, Math.min(colons, color.length - 1))].toString() // } /* * Must be function to be able to export overrides. */ /* eslint-disable no-redeclare */ export const terminal = (namespace: string): OtomiDebugger => { const createDebugger = (baseNamespace: string, cons = console.log): DebuggerType => { const signature = namespace + baseNamespace if (env.OTOMI_IN_TERMINAL) { if (debuggers[signature]) return debuggers[signature] const debugObj: DebugDebugger = commonDebug.extend(baseNamespace) debuggers[signature] = debugObj debugObj.enabled = true return debugObj } return cons } // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = () => {} const base = (...args: any[]) => createDebugger(`${namespace}`).call(undefined, ...args) const log = (...args: any[]) => createDebugger(`${namespace}:log`).call(undefined, ...args) const error = (...args: any[]) => createDebugger(`${namespace}:error`, console.error).call(undefined, ...args) const trace = (...args: any[]) => (logLevel() >= logLevels.TRACE ? createDebugger(`${namespace}:trace`) : noop).call(undefined, ...args) const debug = (...args: any[]) => (logLevel() >= logLevels.DEBUG ? createDebugger(`${namespace}:debug`) : noop).call(undefined, ...args) const info = (...args: any[]) => (logLevel() >= logLevels.INFO ? createDebugger(`${namespace}:info`) : noop).call(undefined, ...args) const warn = (...args: any[]) => (logLevel() >= logLevels.WARN ? createDebugger(`${namespace}:warn`, console.warn) : noop).call(undefined, ...args) // setColor(error, xtermColors.red) // setColor(warn, xtermColors.orange) // setColor(info, xtermColors.green) return { base, log, trace, debug, info, warn, error, stream: { log: new DebugStream(log), trace: new DebugStream(trace), debug: new DebugStream(debug), info: new DebugStream(info), warn: new DebugStream(warn), error: new DebugStream(error), }, } } export const asArray = (args: string | string[]): string[] => { return Array.isArray(args) ? args : [args] } export const readdirRecurse = async (dir: string, opts?: { skipHidden: boolean }): Promise<string[]> => { const dirs = readdirSync(dir, { withFileTypes: true }) const files = await Promise.all( dirs.map(async (dirOrFile) => { const res = resolve(dir, dirOrFile.name) if (opts?.skipHidden && dirOrFile.name.startsWith('.')) return [] return dirOrFile.isDirectory() ? readdirRecurse(res) : res }), ) return files.flat() } export const getEnvFiles = (): Promise<string[]> => { return walk({ path: env.ENV_DIR, ignoreFiles: ['.gitignore'], follow: true, }) } export const loadYaml = (path: string, opts?: { noError: boolean }): Record<string, any> | undefined => { if (!existsSync(path)) { if (opts?.noError) return undefined throw new Error(`${path} does not exist`) } return load(readFileSync(path, 'utf-8')) as Record<string, any> } export enum logLevels { FATAL = -2, ERROR = -1, WARN = 0, INFO = 1, DEBUG = 2, TRACE = 3, } let logLevelVar = Number.NEGATIVE_INFINITY /** * Determines loglevel from 4 different sources * - Parsed Argument: LOG_LEVEL [string] * - Parsed Argument: Verbose (v) [number] * - Parsed Argument: Trace (t) [boolean] * - Environment variable: TRACE [(un)set] * @returns highest loglevel */ export const logLevel = (): number => { if (!getParsedArgs()) return logLevels.ERROR if (logLevelVar > Number.NEGATIVE_INFINITY) return logLevelVar let logLevelNum = Number(logLevels[getParsedArgs().logLevel?.toUpperCase() ?? 'WARN']) const verbosity = Number(getParsedArgs().verbose ?? 0) const boolTrace = env.TRACE || getParsedArgs().trace logLevelNum = boolTrace ? logLevels.TRACE : logLevelNum logLevelVar = logLevelNum < 0 && verbosity === 0 ? logLevelNum : Math.max(logLevelNum, verbosity) if (logLevelVar === logLevels.TRACE) { $.verbose = true $.prefix = 'set -xeuo pipefail;' } return logLevelVar } export const logLevelString = (): string => { return logLevels[logLevel()].toString() } type WaitTillAvailableOptions = { status?: number retries?: number skipSsl?: boolean username?: string password?: string } export const waitTillAvailable = async (url: string, opts?: WaitTillAvailableOptions): Promise<void> => { const debug = terminal('waitTillAvailable') const defaultOptions: WaitTillAvailableOptions = { status: 200, retries: 10, skipSsl: false } const options: WaitTillAvailableOptions = { ...defaultOptions, ...opts } const retryOptions: Options = { retries: options.retries === 0 ? 10 : options.retries, forever: options.retries === 0, factor: 2, // minTimeout: The number of milliseconds before starting the first retry. Default is 1000. minTimeout: 1000, // The maximum number of milliseconds between two retries. maxTimeout: 30000, } // apply.ts:commitOnFirstRun can modify NODE_TLS_REJECT_UNAUTHORIZED // So the process.env needs to be re-parsed const clnEnv = cleanEnvironment() // Due to Boolean OR statement, first NODE_TLS_REJECT_UNAUTORIZED needs to be inverted // It is false if needs to skip SSL, and that doesn't work with OR // Then it needs to be negated again const rejectUnauthorized = !(options.skipSsl || !clnEnv.NODE_TLS_REJECT_UNAUTHORIZED) const fetchOptions: RequestInit = { redirect: 'follow', agent: new Agent({ rejectUnauthorized }), } if (options.username && options.password) { fetchOptions.headers = { Authorization: `Basic ${Buffer.from(`${options.username}:${options.password}`).toString('base64')}`, } } // we don't trust dns in the cluster and want a lot of confirmations // but we don't care about those when we call the cluster from outside const minimumSuccessful = isChart ? 10 : 0 let count = 0 try { do { await retry(async (bail) => { try { const res = await fetch(url, fetchOptions) if (res.status !== options.status) { debug.warn(`GET ${res.url} ${res.status} ${options.status}`) bail(new Error(`Retry`)) } else { count += 1 debug.debug(`${count}/${minimumSuccessful} success`) await sleep(1000) } } catch (e) { // Print system errors like ECONNREFUSED debug.error(e.message) count = 0 throw e } }, retryOptions) } while (count < minimumSuccessful) debug.debug(`Waiting done, ${count}/${minimumSuccessful} found`) } catch (e) { throw new Error(`Max retries (${retryOptions.retries}) has been reached!`) } } export const flattenObject = (obj: Record<string, any>, path = ''): { [key: string]: string } => { return Object.entries(obj) .flatMap(([key, value]) => { const subPath = path.length ? `${path}.${key}` : key if (typeof value === 'object' && !Array.isArray(value)) return flattenObject(value, subPath) return { [subPath]: value } }) .reduce((acc, base) => { return { ...acc, ...base } }, {}) } export interface GucciOptions { asObject?: boolean } export const gucci = async ( tmpl: string | unknown, args: { [key: string]: any }, opts?: GucciOptions, ): Promise<string | Record<string, unknown>> => { const kv = flattenObject(args) const gucciArgs = Object.entries(kv).map(([k, v]) => { // Cannot template if key contains regex characters, so skip if (stringContainsSome(k, ...'^()[]$'.split(''))) return '' return `-s ${k}='${v ?? ''}'` }) const quoteBackup = $.quote $.quote = (v) => v try { let processOutput: ProcessOutput const templateContent: string = typeof tmpl === 'string' ? tmpl : dump(tmpl, { lineWidth: -1 }) // Cannot be a path if it wasn't a string if (typeof tmpl === 'string' && existsSync(templateContent)) { processOutput = await $`gucci -o missingkey=zero ${gucciArgs} ${templateContent}` } else { // input string is a go template content processOutput = await $`echo "${templateContent.replaceAll('"', '\\"')}" | gucci -o missingkey=zero ${gucciArgs}` } // Defaults to returning string, unless stated otherwise if (!opts?.asObject) return processOutput.stdout.trim() return load(processOutput.stdout.trim()) as Record<string, unknown> } finally { $.quote = quoteBackup } } /* Can't use for now because of: https://github.com/homeport/dyff/issues/173 export const gitDyff = async(filePath: string, jsonPathFilter: string = ''): Promise<boolean> => { const result = await nothrow($`git show HEAD:${filePath} | dyff between --filter "${jsonPathFilter}" --set-exit-code --omit-header - ${filePath}`) const isThereADiff = result.exitCode === 1 return isThereADiff } */ export const extract = (schema: Record<string, any>, leaf: string, mapValue = (val: any) => val): any => { const schemaKeywords = ['properties', 'anyOf', 'allOf', 'oneOf', 'default', 'x-secret'] return Object.keys(schema) .map((key) => { const childObj = schema[key] if (key === leaf) return schemaKeywords.includes(key) ? mapValue(childObj) : { [key]: mapValue(childObj) } if (typeof childObj !== 'object') return {} const obj = extract(childObj, leaf, mapValue) if ('extractedValue' in obj) return { [key]: obj.extractedValue } // eslint-disable-next-line no-nested-ternary return schemaKeywords.includes(key) || !Object.keys(obj).length || !Number.isNaN(Number(key)) ? obj === '{}' ? undefined : obj : { [key]: obj } }) .reduce((accumulator, extractedValue) => { return typeof extractedValue !== 'object' ? { ...accumulator, extractedValue } : { ...accumulator, ...extractedValue } }, {}) } let valuesSchema: Record<string, unknown> export const getValuesSchema = async (): Promise<Record<string, unknown>> => { if (valuesSchema) return valuesSchema const schema = loadYaml(`${rootDir}/values-schema.yaml`) const derefSchema = await $RefParser.dereference(schema as $RefParser.JSONSchema) valuesSchema = omit(derefSchema, ['definitions', 'properties.teamConfig']) return valuesSchema } export const stringContainsSome = (str: string, ...args: string[]): boolean => { return args.some((arg) => str.includes(arg)) } export const generateSecrets = async (values: Record<string, unknown> = {}): Promise<Record<string, unknown>> => { const debug: OtomiDebugger = terminal('generateSecrets') const leaf = 'x-secret' const localRefs = ['.dot.', '.v.', '.root.', '.o.'] const schema = await getValuesSchema() debug.info('Extracting secrets') const secrets = extract(schema, leaf, (val: any) => { if (val.length > 0) { if (stringContainsSome(val, ...localRefs)) return val return `{{ ${val} }}` } return undefined }) debug.debug('secrets: ', secrets) debug.info('First round of templating') const firstTemplateRound = (await gucci(secrets, {}, { asObject: true })) as Record<string, unknown> const firstTemplateFlattend = flattenObject(firstTemplateRound) debug.info('Parsing values for second round of templating') const expandedTemplates = Object.entries(firstTemplateFlattend) // eslint-disable-next-line no-unused-vars,@typescript-eslint/no-unused-vars .filter(([_, v]) => stringContainsSome(v, ...localRefs)) .map(([path, v]: string[]) => { /* * dotDot: * Get full path, except last item, this allows to parse for siblings * dotV: * Get .v by getting the second . after charts * charts.hello.world * ^----------^ Get this content (charts.hello) */ const dotDot = path.slice(0, path.lastIndexOf('.')) const dotV = path.slice(0, path.indexOf('.', path.indexOf('charts.') + 'charts.'.length)) const sDot = v.replaceAll('.dot.', `.${dotDot}.`) const vDot = sDot.replaceAll('.v.', `.${dotV}.`) const oDot = vDot.replaceAll('.o.', '.otomi.') const rootDot = oDot.replaceAll('.root.', '.') return [path, rootDot] }) expandedTemplates.map(([k, v]) => { // Activate these templates and put them back into the object set(firstTemplateRound, k, `{{ ${v} }}`) return [k, v] }) debug.debug('firstTemplateRound: ', firstTemplateRound) debug.info('Gather all values for the second round of templating') const gucciOutputAsTemplate = merge(cloneDeep(firstTemplateRound), values) debug.debug('gucciOutputAsTemplate: ', gucciOutputAsTemplate) debug.info('Second round of templating') const secondTemplateRound = (await gucci(firstTemplateRound, gucciOutputAsTemplate, { asObject: true, })) as Record<string, unknown> debug.debug('secondTemplateRound: ', secondTemplateRound) debug.info('Generated all secrets') const res = pick(secondTemplateRound, Object.keys(flattenObject(secrets))) // Only return values that belonged to x-secrets and are now fully templated debug.debug('generateSecrets result: ', res) return res } export const createK8sSecret = async ( name: string, namespace: string, data: Record<string, any> | string, ): Promise<void> => { const debug: OtomiDebugger = terminal('createK8sSecret') const rawString = dump(data) const path = `/tmp/${name}` writeFileSync(path, rawString) const result = await $`kubectl create secret generic ${name} -n ${namespace} --from-file ${path} --dry-run=client -o yaml | kubectl apply -f -` if (result.stderr) debug.error(result.stderr) debug.debug(`kubectl create secret output: \n ${result.stdout}`) } export const getK8sSecret = async (name: string, namespace: string): Promise<Record<string, any> | undefined> => { const result = await nothrow( $`kubectl get secret ${name} -n ${namespace} -ojsonpath='{.data.${name}}' | base64 --decode`, ) if (result.exitCode === 0) return load(result.stdout) as Record<string, any> return undefined } export const getOtomiDeploymentStatus = async (): Promise<string> => { const result = await nothrow( $`kubectl get cm -n ${env.DEPLOYMENT_NAMESPACE} ${DEPLOYMENT_STATUS_CONFIGMAP} -o jsonpath='{.data.status}'`, ) return result.stdout } const fetchLoadBalancerIngressData = async (): Promise<string> => { const d = terminal('fetchLoadBalancerIngressData') let ingressDataString = '' let count = 0 for (;;) { ingressDataString = ( await $`kubectl get -n ingress svc nginx-ingress-controller -o jsonpath="{.status.loadBalancer.ingress}"` ).stdout.trim() count += 1 if (isEmpty(ingressDataString)) break await sleep(250) d.debug(`Trying to get LoadBalancer ingress information, trial ${count}`) } return ingressDataString } interface IngressRecord { ip?: string hostname?: string } export const getOtomiLoadBalancerIP = async (): Promise<string> => { const d = terminal('getOtomiLoadBalancerIP') d.debug('Find LoadBalancer IP or Hostname') const ingressDataString = await fetchLoadBalancerIngressData() const ingressDataList = JSON.parse(ingressDataString) as IngressRecord[] // We sort by IP first, and order those, and then hostname and order them as well const ingressDataListSorted = [ ...ingressDataList.filter((val) => !!val.ip).sort((a, b) => a.ip!.localeCompare(b.ip!)), ...ingressDataList.filter((val) => !!val.hostname).sort((a, b) => a.hostname!.localeCompare(b.hostname!)), ] d.debug(ingressDataListSorted) if (ingressDataListSorted.length === 0) throw new Error('No LoadBalancer Ingress definitions found') /* A load balancer can have a hostname, ip or any list of those items. We select the first item, as we only need one. * And we prefer IP over hostname, as it reduces the fact that we need to resolve & select an ip. */ const firstIngressData = ingressDataListSorted[0] if (firstIngressData.ip) return firstIngressData.ip if (firstIngressData.hostname) { const resolveData = await resolveAny(firstIngressData.hostname) const resolveDataFiltered = resolveData.filter((val) => val.type === 'A' || val.type === 'AAAA') as ( | AnyARecord | AnyAaaaRecord )[] /* Sorting the filtered list * Prefer IPv4 over IPv6; then sort by lowest address (basic string compare) * This way we get always the same first IP back on a cluster */ const resolveDataSorted = resolveDataFiltered.sort((a, b) => { const typeCompare = a.type.localeCompare(b.type) return !typeCompare ? typeCompare : a.address.localeCompare(b.address) }) if (isEmpty(resolveDataSorted)) throw new Error(`No A or AAAA records found for ${firstIngressData.hostname} - could not determine IP`) /* For consistency reasons, after sorting (and preferring the lowest numbered IPv4 address) we pick the first one * As there can be multiple A or AAAA records, and we only need one */ const firstIP = resolveDataSorted[0].address return firstIP } throw new Error('LoadBalancer Ingress data did not container ip or hostname') } const isCoreCheck = (): boolean => { if (packagePath === '/home/app/stack' || !existsSync(`${packagePath}/package.json`)) return false return pkg.name === 'otomi-core' } export const isCore = isCoreCheck()
the_stack
import { ActivityType, DynamicScopeType, FullSourceCoordinate, PassiveEntityType, ReceiveOpType, SendOpType, SymbolMessage } from "./messages"; import { EntityRefType, KomposMetaModel } from "./meta-model"; import { TraceParser } from "./trace-parser"; export interface EntityProperties { id: number; origin?: FullSourceCoordinate; creationScope?: DynamicScope; creationActivity: Activity; } export interface PassiveEntity extends EntityProperties { type: PassiveEntityType; } export interface Activity extends EntityProperties { type: ActivityType; name: string; running: boolean; completed: boolean; } export interface DynamicScope extends EntityProperties { type: DynamicScopeType; active: boolean; } export interface SendOp extends EntityProperties { type: SendOpType; entity: Activity | PassiveEntity | DynamicScope | number; target: Activity | PassiveEntity | DynamicScope | number; } export interface ReceiveOp extends EntityProperties { type: ReceiveOpType; source: Activity | PassiveEntity | DynamicScope | number; } /** Some raw data, which is only available partially and contains ids that need to be resolved. */ abstract class RawData { /** Returns the resolved datum, or false if not all data is available. */ public abstract resolve(data: ExecutionData); } export class RawSourceCoordinate extends RawData { private fileUriId: number; // needs to be looked up in the string id table private charLength: number; private startLine: number; private startColumn: number; constructor(fileUriId: number, charLength: number, startLine: number, startColumn: number) { super(); this.fileUriId = fileUriId; this.charLength = charLength; this.startLine = startLine; this.startColumn = startColumn; } public resolve(data: ExecutionData): FullSourceCoordinate | false { const uri = data.getSymbol(this.fileUriId); if (uri === undefined) { return false; } return { uri: uri, charLength: this.charLength, startLine: this.startLine, startColumn: this.startColumn }; } } export abstract class RawEntity extends RawData { private creationActivity?: number; private creationScope?: number; constructor(creationActivity: number, creationScope: number) { super(); this.creationActivity = creationActivity; this.creationScope = creationScope; } protected resolveCreationActivity(data: ExecutionData) { if (this.creationActivity === null) { return null; } else { return data.getActivity(this.creationActivity); } } protected resolveCreationScope(data: ExecutionData) { if (this.creationScope === null) { return null; } else { return data.getScope(this.creationScope); } } protected resolveEntity(data: ExecutionData, entityId: number, type: EntityRefType): Activity | PassiveEntity | DynamicScope | number { switch (type) { case EntityRefType.None: return entityId; case EntityRefType.Activity: return data.getActivity(entityId); case EntityRefType.DynamicScope: return data.getScope(entityId); case EntityRefType.PassiveEntity: return data.getPassiveEntity(entityId); } } } export class RawActivity extends RawEntity { private type: ActivityType; private activityId: number; private symbolId: number; private sourceSection: RawSourceCoordinate; constructor(type: ActivityType, activityId: number, symbolId: number, sourceSection: RawSourceCoordinate, creationActivity: number, creationScope: number) { super(creationActivity, creationScope); this.type = type; this.activityId = activityId; this.symbolId = symbolId; this.sourceSection = sourceSection; } public resolve(data: ExecutionData): Activity | false { const name = data.getSymbol(this.symbolId); if (name === undefined) { return false; } const creationScope = this.resolveCreationScope(data); if (creationScope === undefined) { return false; } const source = this.sourceSection.resolve(data); if (source === false) { return false; } let creationActivity; if (this.activityId === 0) { creationActivity = null; } else { creationActivity = this.resolveCreationActivity(data); if (creationActivity === undefined) { return false; } } return { id: this.activityId, name: name, running: true, type: this.type, creationScope: creationScope, creationActivity: creationActivity, origin: source, completed: false }; } } export class RawScope extends RawEntity { private type: DynamicScopeType; private scopeId: number; private sourceSection: RawSourceCoordinate; constructor(type: DynamicScopeType, scopeId: number, sourceSection: RawSourceCoordinate, creationActivity: number, creationScope: number) { super(creationActivity, creationScope); this.type = type; this.scopeId = scopeId; this.sourceSection = sourceSection; } public resolve(data: ExecutionData): DynamicScope | false { const source = this.sourceSection.resolve(data); if (source === false) { return false; } const creationActivity = this.resolveCreationActivity(data); if (creationActivity === undefined) { return false; } const creationScope = this.resolveCreationScope(data); if (creationScope === undefined) { return false; } return { type: this.type, id: this.scopeId, active: true, creationActivity: creationActivity, creationScope: creationScope, origin: source }; } } export class RawPassiveEntity extends RawEntity { private type: PassiveEntityType; private entityId: number; private sourceSection: RawSourceCoordinate; constructor(type: PassiveEntityType, entityId: number, sourceSection: RawSourceCoordinate, creationActivity: number, creationScope: number) { super(creationActivity, creationScope); this.type = type; this.entityId = entityId; this.sourceSection = sourceSection; } public resolve(data: ExecutionData): PassiveEntity | false { const source = this.sourceSection.resolve(data); if (source === false) { return false; } const creationActivity = this.resolveCreationActivity(data); if (creationActivity === undefined) { return false; } const creationScope = this.resolveCreationScope(data); if (creationScope === undefined) { return false; } return { type: this.type, id: this.entityId, creationActivity: creationActivity, creationScope: creationScope, origin: source }; } } export class RawSendOp extends RawEntity { private readonly type: SendOpType; private readonly entityId: number; private readonly targetId: number; constructor(type: SendOpType, entityId: number, targetId: number, creationActivity: number, creationScope: number) { super(creationActivity, creationScope); this.type = type; this.entityId = entityId; this.targetId = targetId; } public resolve(data: ExecutionData): SendOp | false { const creationActivity = this.resolveCreationActivity(data); if (creationActivity === undefined) { return false; } const creationScope = this.resolveCreationScope(data); if (creationScope === undefined) { return false; } const entity = this.resolveEntity(data, this.entityId, data.getSendOpModel(this.type).entity); if (entity === undefined) { return false; } const target = this.resolveEntity(data, this.targetId, data.getSendOpModel(this.type).target); if (target === undefined) { return false; } return { id: null, type: this.type, entity: entity, target: target, creationActivity: creationActivity, creationScope: creationScope }; } } export class RawReceiveOp extends RawEntity { private readonly type: ReceiveOpType; private readonly sourceId: number; constructor(type: ReceiveOpType, sourceId: number, creationActivity: number, creationScope: number) { super(creationActivity, creationScope); this.type = type; this.sourceId = sourceId; } public resolve(data: ExecutionData): ReceiveOp | false { const creationActivity = this.resolveCreationActivity(data); if (creationActivity === undefined) { return false; } const creationScope = this.resolveCreationScope(data); if (creationScope === undefined) { return false; } const entity = this.resolveEntity(data, this.sourceId, data.getReceiveOpModel(this.type).source); if (entity === undefined) { return false; } return { id: null, type: this.type, source: entity, creationActivity: creationActivity, creationScope: creationScope }; } } export class TraceDataUpdate { public readonly activities: Activity[]; public readonly scopes: DynamicScope[]; public readonly passiveEntities: PassiveEntity[]; public readonly sendOps: SendOp[]; public readonly receiveOps: ReceiveOp[]; constructor() { this.activities = []; this.scopes = []; this.passiveEntities = []; this.sendOps = []; this.receiveOps = []; } } /** Maintains all data about the programs execution. It is also the place where partial data gets resolved once missing pieces are found. */ export class ExecutionData { private metaModel: KomposMetaModel; private traceParser?: TraceParser; private readonly symbols: string[]; private rawActivities: RawActivity[]; private rawScopes: RawScope[]; private rawPassiveEntities: RawPassiveEntity[]; private rawSends: RawSendOp[]; private rawReceives: RawReceiveOp[]; private newData: TraceDataUpdate; private activities: Activity[]; private scopes: DynamicScope[]; private passiveEntities: PassiveEntity[]; private sendOps: SendOp[]; private receiveOps: ReceiveOp[]; private endedScopes: number[]; private completedActivities: number[]; constructor() { this.symbols = []; this.activities = []; this.scopes = []; this.passiveEntities = []; this.sendOps = []; this.receiveOps = []; this.rawScopes = []; this.rawActivities = []; this.rawPassiveEntities = []; this.rawSends = []; this.rawReceives = []; this.endedScopes = []; this.completedActivities = []; this.newData = new TraceDataUpdate(); } public reset() { this.symbols.length = 0; this.activities.length = 0; this.scopes.length = 0; this.passiveEntities.length = 0; this.newData = new TraceDataUpdate(); } public getSendOpModel(marker: number) { return this.metaModel.sendOps[marker]; } public getReceiveOpModel(marker: number) { return this.metaModel.receiveOps[marker]; } public getSymbol(id: number) { return this.symbols[id]; } public getScope(id: number) { return this.scopes[id]; } /** @param id is a global unique id, unique for all types of activities. */ public getActivity(id: number): Activity { return this.activities[id]; } public getPassiveEntity(id: number): PassiveEntity { return this.passiveEntities[id]; } public setCapabilities(metaModel: KomposMetaModel) { this.metaModel = metaModel; this.traceParser = new TraceParser(metaModel, this); } public updateTraceData(data: DataView) { this.traceParser.parseTrace(data); this.resolveData(); } public addSymbols(msg: SymbolMessage) { for (let i = 0; i < msg.ids.length; i++) { this.symbols[msg.ids[i]] = msg.symbols[i]; } this.resolveData(); } public addRawActivity(activity: RawActivity) { this.rawActivities.push(activity); } public completeActivity(activityId: number) { this.completedActivities.push(activityId); } public addRawScope(scope: RawScope) { this.rawScopes.push(scope); } public endScope(scopeId: number) { this.endedScopes.push(scopeId); } public addRawPassiveEntity(entity: RawPassiveEntity) { this.rawPassiveEntities.push(entity); } public addRawSendOp(send: RawSendOp) { this.rawSends.push(send); } public addRawReceiveOp(receive: RawReceiveOp) { this.rawReceives.push(receive); } public getNewestDataSinceLastUpdate(): TraceDataUpdate { const result = this.newData; this.newData = new TraceDataUpdate(); return result; } private resolveData() { for (const i in this.rawActivities) { const a = this.rawActivities[i].resolve(this); if (a !== false) { delete this.rawActivities[i]; console.assert(this.activities[a.id] === undefined); this.activities[a.id] = a; this.newData.activities.push(a); } } for (const i in this.rawScopes) { const s = this.rawScopes[i].resolve(this); if (s !== false) { delete this.rawScopes[i]; this.scopes[s.id] = s; this.newData.scopes.push(s); } } for (const i in this.rawPassiveEntities) { const e = this.rawPassiveEntities[i].resolve(this); if (e !== false) { delete this.rawPassiveEntities[i]; this.passiveEntities[e.id] = e; this.newData.passiveEntities.push(e); } } for (const i in this.rawSends) { const s = this.rawSends[i].resolve(this); if (s !== false) { delete this.rawSends[i]; this.sendOps.push(s); this.newData.sendOps.push(s); } } for (const i in this.rawReceives) { const r = this.rawReceives[i].resolve(this); if (r !== false) { delete this.rawReceives[i]; this.receiveOps.push(r); this.newData.receiveOps.push(r); } } for (const i in this.endedScopes) { const sId = this.endedScopes[i]; if (this.scopes[sId]) { delete this.endedScopes[i]; this.scopes[sId].active = false; } } for (const i in this.completedActivities) { const aId = this.completedActivities[i]; if (this.activities[aId]) { delete this.completedActivities[i]; this.activities[aId].completed = true; } } } }
the_stack
import assert from 'assert'; import { Readable } from 'stream'; import { r } from '../src'; import config from './config'; import { uuid } from './util/common'; describe('stream', () => { let dbName: string; let tableName: string; let tableName2: string; let dumpTable: string; const numDocs = 100; // Number of documents in the "big table" used to test the SUCCESS_PARTIAL const smallNumDocs = 5; // Number of documents in the "small table" before(async () => { await r.connectPool(config); dbName = uuid(); tableName = uuid(); // Big table to test partial sequence tableName2 = uuid(); // small table to test success sequence dumpTable = uuid(); // dump table const result1 = await r.dbCreate(dbName).run(); assert.equal(result1.dbs_created, 1); const result2 = await Promise.all([ r .db(dbName) .tableCreate(tableName)('tables_created') .run(), r .db(dbName) .tableCreate(tableName2)('tables_created') .run(), r .db(dbName) .tableCreate(dumpTable)('tables_created') .run() ]); assert.deepEqual(result2, [1, 1, 1]); const result3 = await r .db(dbName) .table(tableName) .insert(Array(numDocs).fill({})) .run(); assert.equal(result3.inserted, numDocs); const result4 = await r .db(dbName) .table(tableName2) .insert(Array(smallNumDocs).fill({})) .run(); assert.equal(result4.inserted, smallNumDocs); const result5 = await r .db(dbName) .table(tableName) .update({ date: r.now() }) .run(); assert.equal(result5.replaced, numDocs); }); after(async () => { // remove any dbs created await r .dbList() .filter(db => r .expr(['rethinkdb', 'test']) .contains(db) .not() ) .forEach(db => r.dbDrop(db)) .run(); await r.getPoolMaster().drain(); }); it('`table` should return a stream', async () => { const stream = await r .db(dbName) .table(tableName) .getCursor(); assert(stream); assert(stream instanceof Readable); stream.close(); }); it('Arrays should return a stream', async () => { const data = [10, 11, 12, 13, 14, 15, 16]; const stream = await r.expr(data).getCursor(); assert(stream); assert(stream instanceof Readable); await new Promise((resolve, reject) => { let count = 0; stream.on('data', () => { count++; if (count === data.length) { resolve(); } }); }); }); it('changes() should return a stream', async () => { const data = [ { n: 1 }, { n: 2 }, { n: 3 }, { n: 4 }, { n: 5 }, { n: 6 }, { n: 7 } ]; // added include initial, so it won't hang on some extreame cases const stream = await r .db(dbName) .table(tableName) .changes({ includeInitial: true }) .getCursor(); assert(stream); assert(stream instanceof Readable); const promise = new Promise((resolve, reject) => { let count = 0; stream.on('data', d => { if (!!d.new_val.n) { count++; if (count === data.length) { resolve(); stream.close(); } } }); }); await r .db(dbName) .table(tableName) .insert(data) .run(); await promise; }); it('get().changes() should return a stream', async () => { const id = uuid(); await r .db(dbName) .table(tableName) .insert({ id }) .run(); const stream = await r .db(dbName) .table(tableName) .get(id) .changes() .getCursor(); assert(stream); assert(stream instanceof Readable); const promise = new Promise((resolve, reject) => { let count = 0; stream.on('data', () => { count++; if (count === 3) { resolve(); stream.close(); } }); }); await new Promise(resolve => setTimeout(resolve, 200)); await r .db(dbName) .table(tableName) .get(id) .update({ update: 1 }) .run(); await r .db(dbName) .table(tableName) .get(id) .update({ update: 2 }) .run(); await r .db(dbName) .table(tableName) .get(id) .update({ update: 3 }) .run(); await promise; }); it('`table` should return a stream - testing empty SUCCESS_COMPLETE', async () => { const connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const stream = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); assert(stream); assert(stream instanceof Readable); await stream.close(); await connection.close(); }); it('Test flowing - event data', async () => { const connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const stream = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); await new Promise((resolve, reject) => { let count = 0; stream.on('data', () => { count++; if (count === numDocs) { resolve(); } }); }); await stream.close(); await connection.close(); }); it('Test read', async () => { const connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const stream = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); await new Promise((resolve, reject) => { stream.once('readable', () => { const doc = stream.read(); if (doc === null) { reject( new Error( 'stream.read() should not return null when readable was emitted' ) ); } let count = 1; stream.on('data', data => { count++; if (count === numDocs) { resolve(); } }); }); }); await stream.close(); await connection.close(); }); it('Test flowing - event data', async () => { const connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const stream = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); await new Promise((resolve, reject) => { let count = 0; stream.on('data', () => { count++; if (count === numDocs) { resolve(); } }); stream.pause(); if (count > 0) { reject(new Error('The stream should have been paused')); } stream.resume(); }); await stream.close(); await connection.close(); }); it('Test read with null value', async () => { const connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const stream = await r .db(dbName) .table(tableName) .limit(10) .union([null]) .union( r .db(dbName) .table(tableName) .limit(10) ) .getCursor(connection, { maxBatchRows: 1 }); await new Promise((resolve, reject) => { stream.once('readable', () => { let count = 0; stream.on('data', data => { count++; if (count === 20) { resolve(); } else if (count > 20) { reject(new Error('Should not get null')); } }); }); }); await stream.close(); await connection.close(); }); it('Test read', async () => { const connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password }); assert(connection); const stream = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); await new Promise((resolve, reject) => { stream.once('readable', () => { stream.read() === null ? reject( new Error( 'stream.read() should not return null when readable was emitted' ) ) : resolve(); }); }); await stream.close(); await connection.close(); }); // it('Import with stream as default', async () => { // const r1 = rethinkdbdash({ // host: config.host, // port: config.port, // authKey: config.authKey, // buffer: config.buffer, // max: config.max, // discovery: false, // silent: true // }); // const stream = await r1 // .db(dbName) // .table(tableName) // .run(); // assert(stream instanceof Readable); // await stream.close(); // await r1.getPool().drain(); // }); it('toStream', async () => { const stream = await r .db(dbName) .table(tableName) .getCursor(); await new Promise((resolve, reject) => { stream.once('readable', () => { const doc = stream.read(); if (doc === null) { reject( new Error( 'stream.read() should not return null when readable was emitted' ) ); } let count = 1; stream.on('data', data => { count++; if (count === numDocs) { resolve(); } }); }); }); await stream.close(); }); it('toStream - with grouped data', async () => { const stream = await r .db(dbName) .table(tableName) .group({ index: 'id' }) .getCursor(); await new Promise((resolve, reject) => { stream.once('readable', () => { const doc = stream.read(); if (doc === null) { reject( new Error( 'stream.read() should not return null when readable was emitted' ) ); } let count = 1; stream.on('data', data => { count++; if (count === numDocs) { resolve(); } }); }); }); await stream.close(); }); // it('pipe should work with a writable stream - 200-200', function (done) { // await r.connectPool({ buffer: 1, max: 2, discovery: false, silent: true }) // r1.db(dbName).table(tableName).toStream({ highWaterMark: 200 }) // .pipe(r1.db(dbName).table(dumpTable).toStream({ writable: true, highWaterMark: 200 })) // .on('finish', function () { // r.expr([ // r1.db(dbName).table(tableName).count(), // r1.db(dbName).table(dumpTable).count() // ]) // .run().then(function (result) { // if (result[0] !== result[1]) { // done(new Error('All the data should have been streamed')) // } // return r1.db(dbName).table(dumpTable).delete() // }).then((_) => r1.getPool().drain()).then(done).error(done) // }) // }) // it('pipe should work with a writable stream - 200-20', function (done) { // const r1 = rethinkdbdash({ buffer: 1, max: 2, discovery: false, silent: true }) // r1.db(dbName).table(tableName).toStream({ highWaterMark: 200 }) // .pipe(r1.db(dbName).table(dumpTable).toStream({ writable: true, highWaterMark: 20 })) // .on('finish', function () { // r.expr([ // r1.db(dbName).table(tableName).count(), // r1.db(dbName).table(dumpTable).count() // ]).run().then(function (result) { // if (result[0] !== result[1]) { // done(new Error('All the data should have been streamed')) // } // return r1.db(dbName).table(dumpTable).delete() // }).then((_) => r1.getPool().drain()).then(done).error(done) // }) // }) // it('pipe should work with a writable stream - 20-200', function (done) { // const r1 = rethinkdbdash({ buffer: 1, max: 2, discovery: false, silent: true }) // r1.db(dbName).table(tableName).toStream({ highWaterMark: 20 }) // .pipe(r1.db(dbName).table(dumpTable).toStream({ writable: true, highWaterMark: 200 })) // .on('finish', function () { // r.expr([ // r1.db(dbName).table(tableName).count(), // r1.db(dbName).table(dumpTable).count() // ]).run().then(function (result) { // if (result[0] !== result[1]) { // done(new Error('All the data should have been streamed')) // } // return r1.db(dbName).table(dumpTable).delete() // }).then((_) => r1.getPool().drain()).then(done).error(done) // }) // }) // it('pipe should work with a writable stream - 50-50', function (done) { // const r1 = rethinkdbdash({ buffer: 1, max: 2, discovery: false, silent: true }) // r1.db(dbName).table(tableName).toStream({ highWaterMark: 50 }) // .pipe(r1.db(dbName).table(dumpTable).toStream({ writable: true, highWaterMark: 50 })) // .on('finish', function () { // r.expr([ // r1.db(dbName).table(tableName).count(), // r1.db(dbName).table(dumpTable).count() // ]).run().then(function (result) { // if (result[0] !== result[1]) { // done(new Error('All the data should have been streamed')) // } // return r1.db(dbName).table(dumpTable).delete() // }).then((_) => r1.getPool(0).drain()).then(done).error(done) // }) // }) // it('toStream((writable: true}) should handle options', function (done) { // const r1 = rethinkdbdash({ buffer: 1, max: 2, discovery: false, silent: true }) // const stream = // r1.db(dbName).table(dumpTable).toStream({ writable: true, highWaterMark: 50, conflict: 'replace' }) // stream.write({ id: 1, foo: 1 }) // stream.write({ id: 1, foo: 2 }) // stream.end({ id: 1, foo: 3 }) // stream.on('finish', function () { // r1.db(dbName).table(dumpTable).count().then(function (result) { // assert.equal(result, 1) // return r1.db(dbName).table(dumpTable).get(1) // }).then(function (result) { // assert.deepEqual(result, { id: 1, foo: 3 }) // return r1.db(dbName).table(dumpTable).delete() // }).then((_) => r1.getPool(0).drain()).then(done).error(done) // }) // }) // it('test pipe all streams', function (done) { // // Create a transform stream that will convert data to a string // const stream = require('stream') // const addfoobar = new stream.Transform() // addfoobar._writableState.objectMode = true // addfoobar._readableState.objectMode = true // addfoobar._transform = function (data, encoding, done) { // data.transform = true // this.push(data) // done() // } // const addbuzzlol = new stream.Transform() // addbuzzlol._writableState.objectMode = true // addbuzzlol._readableState.objectMode = true // addbuzzlol._transform = function (data, encoding, done) { // delete data.id // data.written = true // this.push(data) // done() // } // r.db(dbName).table(tableName).without('id').toStream() // .on('error', done) // .pipe(addfoobar) // .on('error', done) // .pipe(r.db(dbName).table(dumpTable).toStream({ transform: true })) // .on('error', done) // .pipe(addbuzzlol) // .on('error', done) // .pipe(r.db(dbName).table(dumpTable).toStream({ writable: true })) // .on('error', done) // .on('finish', function () { // r.db(dbName).table(dumpTable).filter({ written: true }).count().run().then(function (result) { // assert(result, numDocs) // return r.db(dbName).table(dumpTable).filter({ transform: true }).count().run() // }).then(function (result) { // assert(result, numDocs * 2) // return r.db(dbName).table(dumpTable).delete() // }).then((_) => r.getPoolMaster().drain()).then(done).error(done) // }) // }) // it('toStream({writable: true}) should throw on something else than a table', async function () { // const r1 = rethinkdbdash({ buffer: 1, max: 2, discovery: false, silent: true }) // try { // r.expr(dumpTable).toStream({ writable: true }) // assert.fail('should throw') // } catch (err) { // assert(err.message.match(/^Cannot create a writable stream on something else than a table/)) // } finally { // r1.getPool().drain() // } // }) // it('toStream({transform: true}) should throw on something else than a table', async function () { // const r1 = rethinkdbdash({ buffer: 1, max: 2, discovery: false, silent: true }) // try { // r.expr(dumpTable).toStream({ transform: true }) // assert.fail('should throw') // } catch (err) { // assert(err.message.match(/^Cannot create a writable stream on something else than a table/)) // } finally { // r1.getPool().drain() // } // }) });
the_stack
declare namespace DeployJava { /** * @summary Interface for {@link deployJava} object. * @author Cyril Schumacher * @version 1.0 */ interface DeployJavaStatic { /** * @summary Brand name. * @member {string} */ brand: string; /** * @summary Debug mode. * @member {boolean} */ debug: boolean; /** * @summary Early Access state. * @member {string} */ EAInstallEnabled: boolean; /** * @summary URL to early access. * @member {string} */ EarlyAccessURL: string; /** * @summary Preferred install type (null, online, kernel). * @member {string} */ installType: string; /** * @summary Locale. * @member {string} */ locale: string; /** * @summary Interval for check versions of JRE available. * @member {number} */ myInterval: number; /** * @summary JRE versions installed. * @member {Array<string>} */ preInstallJREList: Array<string>; /** * @summary URL of current document. * @member {string} */ returnPage: string; /** * @summary Determines if the browser has allowed the Java plugin. * @return {boolean} True if the Java plugin is allowed, otherwise, False. */ allowPlugin(): boolean; /** * @summary Compares a installed version and required version. * @param {string} installed JRE installed version. * @param {string} required JRE required version. * @return {boolean} True if installed version is greater than or equal to required version. */ compareVersions(installed: string, required: string): boolean; /** * @summary Compares a version with a pattern. * @param {string} version Version to compare. * @param {Array<string>} patternArray Patterns to compare. * @param {boolean} familyMatch Family match. * @param {boolean} minMatch Minimum version match. * @return {boolean} True if a or many patterns are identical to version, otherwise, False. */ compareVersionToPattern(version: string, patternArray: Array<string>, familyMatch: boolean, minMatch: boolean): boolean; /** * @summary Enable alerts. */ enableAlerts(): void; /** * @summary Redirect to Java plugin website for Mozilla Firefox. * @return {boolean} True if the redirection to Java plugin website was performed, otherwise, False. */ FFInstall(): boolean; /** * @summary Gets browser name. * @return {string} Browser name. */ getBrowser(): string; /** * @summary Obtains JPI version using {@link navigator.mimeTypes} array if found, * set the version to {@link firefoxJavaVersion}. */ getJPIVersionUsingMimeType(): void; /** * @summary Get JRE versions (in format : "#.#[.#[_#]]") installed. * @return {Array<string>} JRE Version list. */ getJREs(): Array<string>; /** * Gets a Java plugin. * @return {HTMLElement} Java plugin. */ getPlugin(): HTMLElement; /** * Redirect to Java plugin website for Internet Explorer. * @return {boolean} True if the redirection to Java plugin website was performed, otherwise, False. */ IEInstall(): boolean; /** * @summary Triggers a JRE installation. * @param {string} requestVersion JRE request version. * @return {boolean} True if the install is succeeded, otherwise, False. */ installJRE(requestVersion: string): boolean; /** * @summary Triggers a installation of the latest version of JRE. * @param {Function} installCallback A reference to a javascript callback function for reporting install status. * @return {boolean} True if the install is succeeded, otherwise, False. */ installLatestJRE(installCallback?: Function): boolean; /** * @summary Determines if JRE auto install for the version is enabled for the local system. * * DT plugin for 6uX only knows about JRE installer signed by SUN cert. * If it encounter Oracle signed JRE installer, it will have chance of * deadlock when running with IE. This function is to guard against this. * * @param {string} requestedJREVersion JRE version. If not specified, it will be treated as installing any JRE version. * @return {boolean} True if JRE auto install for the version is enabled for the local system, otherwise, False. */ isAutoInstallEnabled(requestedJREVersion?: string): boolean; /** * @summary Determines if the plugin is installed and AutoUpdate is enabled. * @return {boolean} True if the plugin is installed and AutoUpdate is enabled, otherwise, False. */ isAutoUpdateEnabled(): boolean; /** * @summary Determines if JRE install callback is supported. * @return {boolean} True if JRE install callback is supported, otherwise, False. */ isCallbackSupported(): boolean; /** * @summary Determines if the next generation plugin (Plugin II) is default. * @return {boolean} True if next generation plugin is default, otherwise, False. */ isPlugin2(): boolean; /** * @summary Determines if the ActiveX or XPI plugin is installed. * @return {boolean} True if the ActiveX or XPI plugin is installed, otherwise, False. */ isPluginInstalled(): boolean; /** * @summary Checks if an installation of Java Web Start of the specified minimum version can be detected. * @param {string} minimumVersion Minimum version. * @return {boolean} True if an installation of Java Web Start of the specified minimum version can be detected */ isWebStartInstalled(minimumVersion?: string): boolean; /** * @summary Launch a JNLP application (using the plugin if available). * @param {string} jnlp JNLP file. * @return {boolean} True if a JNLP application is launched, otherwise, False. */ launch(jnlp: string): boolean; /** * @summary Launch the specified JNLP application using the passed in jnlp file. * @param {string} jnlp JNLP file. */ launchWebStartApplication(jnlp: string): void; /** * @summary Checks versions of JRE available. */ poll(): void; /** * @summary Writes embed tags if JRE plugin is available. */ refresh(): void; /** * @summary Ensures that an appropriate JRE is installed and then runs an applet. * * After installJRE() is called, the script will attempt to detect that the * JRE installation has completed and begin running the applet, but there * are circumstances (such as when the JRE installation requires a browser * restart) when this cannot be fulfilled. * As with writeAppletTag(), this function should only be called prior to * the web page being completely rendered. Note that version wildcards * (star (*) and plus (+)) are not supported, and including them in the * minimumVersion will result in an error message. * * @param {Object} attributes Names and values of the attributes of the generated <applet> tag. * @param {Object} parameters Names and values of the <param> tags in the generated <applet> tag. * @param {string} minimumVersion A minimum version of the JRE software that is required to run this applet. Default value is : "1.1". */ runApplet(attributes: Object, parameters: Object, minimumVersion?: string): void; /** * @summary Sets additional package list. * * Note: To be used by kernel installer. * * @param {string} packageList Package list. * @return {boolean} True if the value was set, otherwise, False if the plugin is already installed. */ setAdditionalPackages(packageList: string): boolean; /** * @summary Sets AutoUpdate on if plugin is installed. */ setAutoUpdateEnabled(): void; /** * @summary Sets preference to install Early Access versions if available. * @param {string} enabled Preference to install Early Access versions. */ setEarlyAccess(enabled: string): void; /** * @summary Sets the preferred install type. * @param {string} type Preferred install (null, online or kernel). * @return {boolean} True if the value was set, otherwise, False if the plugin is already installed. */ setInstallerType(type: string): boolean; /** * @summary Detects the Microsoft virtual machine. * @return {boolean} True if the Microsoft virtual machine exists, otherwise, False. */ testForMSVM(): boolean; /** * @summary Checks if ActiveX can be used with Java plugin. * @param {string} Java version. * @return {boolean} True if ActiveX can be used, otherwise, False. */ testUsingActiveX(version: string): boolean; /** * @summary Checks if MIME types can be used with Java plugin. * @param {string} Java version. * @return {boolean} True if MIME types can be used, otherwise, False. */ testUsingMimeTypes(version: string): boolean; /** * @summary Checks if plugins can be used with Java plugin. * @param {string} Java version. * @return {boolean} True if plugins can be used, otherwise, False. */ testUsingPluginsArray(version: string): boolean; /** * @summary Check if there is a matching JRE version currently installed. * @param {string} versionPattern Java version pattern (in format : #[.#[.#[_#]]][+|*]). * @return {boolean} True if there is a matching JRE version currently installed, otherwise, False. */ versionCheck(versionPattern: string): boolean; /** * @summary Write in outputs an applet tag for applet with the specified attributes and parameters. * * Each key/value pair in attributes becomes an attribute of the applet tag * itself, while key/value pairs in parameters become <PARAM> tags. * No version checking or other special behaviors are performed; the tag is * simply written to the page using document.writeln(). * As document.writeln() is generally only safe to use while the page is * being rendered, you should never call this function after the page * has been completed. * * @param {Object} attributes Names and values of the attributes of the generated <applet> tag. * @param {Object} parameters Names and values of the <param> tags in the generated <applet> tag. */ writeAppletTag(attributes: Object, parameters: Object): void; /** * @summary Write in outputs an embed tag for applet. */ writeEmbedTag(): void; } } declare var deployJava: DeployJava.DeployJavaStatic;
the_stack
import * as assert from "assert" import * as http from "http" import { get } from "lodash" import * as url from "url" import { testCli } from "." import distbin from "../" import { discoverOutbox } from "../src/activitypub" import * as activitypub from "../src/activitypub" import { ASJsonLdProfileContentType } from "../src/activitystreams" import { createLogger } from "../src/logger" import { Activity, ASObject, DistbinActivity, Extendable, HttpRequestResponder, isActivity, JSONLD, LDObject, LDValue, LDValues } from "../src/types" import { ensureArray, first, isProbablyAbsoluteUrl, linkToHref, readableToString, sendRequest } from "../src/util" import { listen, postActivity, requestForListener } from "./util" const logger = createLogger("test/distbin") const tests = module.exports tests.discoverOutbox = async () => { const distbinUrl = await listen(http.createServer(distbin())) const outbox = await discoverOutbox(distbinUrl) assert.equal(outbox, `${distbinUrl}/activitypub/outbox`) } tests["distbin can be imported"] = () => { assert(distbin, "distbin is truthy") } tests["can create a distbin"] = () => { distbin() } tests["can send http requests to a distbin.Server"] = async () => { const res = await sendRequest(await requestForListener(distbin())) assert.equal(res.statusCode, 200) } tests["/ route can be fetched as JSONLD and includes pointers to things like outbox"] = async () => { const res = await sendRequest(await requestForListener(distbin(), { headers: { accept: "application/ld+json", }, })) assert.equal(res.statusCode, 200) const resBody = await readableToString(res) const rootResource = JSON.parse(resBody) // #TODO: maybe a more fancy JSON-LD-aware check assert(Object.keys(rootResource).includes("outbox"), "/ points to outbox") assert(Object.keys(rootResource).includes("inbox"), "/ points to inbox") } tests["can fetch /recent to see what's been going on"] = async () => { const res = await sendRequest(await requestForListener(distbin(), { headers: { accept: "application/ld+json", }, path: "/recent", })) assert.equal(res.statusCode, 200) const resBody = await readableToString(res) const recentCollection = JSON.parse(resBody) assert.equal(recentCollection.type, "OrderedCollection") assert(Array.isArray(recentCollection.items), ".items is an Array") } tests["can page through /public collection.current"] = async () => { const d = distbin() const toCreate = [ { name: "first!" }, { name: "second" }, { name: "third" }, { name: "forth" }, ].map((a) => Object.assign(a, { cc: ["https://www.w3.org/ns/activitystreams#Public"], })) const created: string[] = [] for (const a of toCreate) { created.push(await postActivity(d, a)) } // const createdFull = await Promise.all(created.map(async function (url) { // return JSON.parse(await readableToString(await sendRequest(http.request(url)))) // })) // console.log('createdFull', createdFull) assert.equal(created.length, 4) const collectionUrl = "/activitypub/public" const collectionRes = await sendRequest(await requestForListener(d, { headers: { Prefer: 'return=representation; max-member-count="1"', accept: "application/ld+json", }, path: collectionUrl, })) const collection = JSON.parse(await readableToString(collectionRes)) assert.equal(collection.type, "Collection") assert.equal(collection.items.length, 1) // we get the most recently created one ensureArray(collection.items[0].url).forEach((itemUrl: string) => { assert.equal(url.parse(itemUrl).pathname, url.parse(created[created.length - 1]).pathname) }) assert(!collection.next, "collection does not have a next property") assert(collection.current, "collection has a .current property") assert(collection.first, "collection has a .first property") const page1Url = url.resolve(collectionUrl, linkToHref(collection.current)) // page 1 const page1Res = await sendRequest(await requestForListener(d, { headers: { // NOTE! getting 2 this time Prefer: 'return=representation; max-member-count="1"', accept: "application/ld+json", }, path: page1Url, })) assert.equal(page1Res.statusCode, 200) const page1 = JSON.parse(await readableToString(page1Res)) assert.equal(page1.type, "OrderedCollectionPage") assert.equal(page1.startIndex, 0) assert.equal(page1.orderedItems.length, 1) assert(page1.next, "has a next property") // page 2 (get 2 items, not 1) const page2Url = url.resolve(page1Url, page1.next) const page2Res = await sendRequest(await requestForListener(d, { headers: { // NOTE! getting 2 this time Prefer: 'return=representation; max-member-count="2"', accept: "application/ld+json", }, path: page2Url, })) assert.equal(page2Res.statusCode, 200) const page2 = JSON.parse(await readableToString(page2Res)) assert.equal(page2.type, "OrderedCollectionPage") assert.equal(page2.startIndex, 1) assert.equal(page2.orderedItems.length, 2) assert(page2.next, "has a next property") // should have second most recently created ensureArray(page2.orderedItems[0].url).forEach((itemUrl: string) => assert.equal(url.parse(itemUrl).pathname, url.parse(created[created.length - 2]).pathname)) ensureArray(page2.orderedItems[1].url).forEach((itemUrl: string) => assert.equal(url.parse(itemUrl).pathname, url.parse(created[created.length - 3]).pathname)) // ok so if we post one more new thing, the startIndex on page2 should go up by one. const fifth = { cc: ["https://www.w3.org/ns/activitystreams#Public"], name: "fifth", } created.push(await postActivity(d, fifth)) const page2AfterFifthRes = await sendRequest(await requestForListener(d, { headers: { Prefer: 'return=representation; max-member-count="2"', accept: "application/ld+json", }, path: page2Url, })) const page2AfterFifth = JSON.parse(await readableToString(page2AfterFifthRes)) assert.equal(page2AfterFifth.startIndex, 2) // page 3 const page3Url = url.resolve(page2Url, page2.next) const page3Res = await sendRequest(await requestForListener(d, { headers: { Prefer: 'return=representation; max-member-count="2"', accept: "application/ld+json", }, path: page3Url, })) assert.equal(page3Res.statusCode, 200) const page3 = JSON.parse(await readableToString(page3Res)) assert.equal(page3.type, "OrderedCollectionPage") assert.equal(page3.startIndex, 4) assert.equal(page3.orderedItems.length, 1) // assert.equal(url.parse(page3.orderedItems[0].url).pathname, url.parse(created[created.length - 5]).pathname) ensureArray(page3.orderedItems[0].url).forEach((itemUrl: string) => assert.equal(url.parse(itemUrl).pathname, url.parse(created[created.length - 5]).pathname)) // page3 can specify a next, but when fetched it shouldn't have any items // or continue pointing to next if (page3.next) { const page4Url = url.resolve(page3Url, page3.next) const page4Res = await sendRequest(await requestForListener(d, { headers: { Prefer: 'return=representation; max-member-count="2"', accept: "application/ld+json", }, path: page4Url, })) assert.equal(page4Res.statusCode, 200) const page4 = JSON.parse(await readableToString(page4Res)) assert.equal(page4.orderedItems.length, 0) assert(!page4.next) } } // Example 8,9: Submitting an Activity to the Outbox tests["posted activities have an .inbox (e.g. to receive replies in)"] = async () => { // Create an Activity by POSTing to outbox const distbinListener = distbin() const req = await requestForListener(distbinListener, { headers: activitypub.clientHeaders({ "content-type": ASJsonLdProfileContentType, }), method: "post", path: "/activitypub/outbox", }) req.write(JSON.stringify({ "@context": "https://www.w3.org/ns/activitypub", "content": "Hello, world", "type": "Article", })) const postActivityRequest = await sendRequest(req) assert.equal(postActivityRequest.statusCode, 201) // Determine Location of new Activity const location = first(postActivityRequest.headers.location) assert(location, "Location header is present in response") // Now get the new Activity const getActivityResponse = await sendRequest( await requestForListener(distbinListener, { headers: activitypub.clientHeaders(), path: location, }), ) assert.equal(getActivityResponse.statusCode, 200) const newActivity = JSON.parse(await readableToString(getActivityResponse)) assert(newActivity.inbox, "activity should have an .inbox property") } // #TODO is notifying the .inReplyTo inbox even encouraged/allowed by activitypub? tests["Posting a reply will notify the inReplyTo inbox (even if another distbin)"] = async () => { // ok so we're going to make two distbins, A and B, and test that A delivers to B const distbinA = distbin() const distbinB = distbin({ deliverToLocalhost: true }) // post a parent to distbinA const parentUrl = await postActivity(distbinA, { content: "Reply to this if you think FSW could happen", type: "Note", }) // ok now to post the reply to distbinB const replyUrl = await postActivity(distbinB, { cc: [parentUrl], content: "Dear Anonymous, I believe in FSW", inReplyTo: parentUrl, type: "Note", }) // then verify that it is in distbinA's inbox const replyId = JSON.parse(await readableToString(await sendRequest(http.request(replyUrl)))).id const distbinAInbox = JSON.parse(await readableToString(await sendRequest( await requestForListener(distbinA, "/activitypub/inbox")))) const replyFromDistbinAInbox = distbinAInbox.items.find((a: DistbinActivity) => { const idMatches = a.id === replyId if (idMatches) { return true } const wasDerivedFrom = a["http://www.w3.org/ns/prov#wasDerivedFrom"] if ( ! wasDerivedFrom) { return false } function nodeWasDerivedFrom(o: ASObject|string, nodeId: string): boolean { if (typeof o === "object") { return o.id === nodeId } else if (typeof o === "string") { return o === nodeId } return false } const matchesReplyId = (o: DistbinActivity|string): boolean => nodeWasDerivedFrom(o, replyId) if (wasDerivedFrom instanceof Array) { return wasDerivedFrom.some(matchesReplyId) } else if (isActivity(wasDerivedFrom) || typeof wasDerivedFrom === "string") { return matchesReplyId(wasDerivedFrom) } else if (typeof wasDerivedFrom === "object") { for (const id of [(wasDerivedFrom as ASObject).id, (wasDerivedFrom as JSONLD)["@id"]]) { if (typeof id === "string") { return matchesReplyId(id) } } return false } else { const exhaustiveCheck: never = wasDerivedFrom; } }) assert(replyFromDistbinAInbox, "distbinA inbox contains reply") assert.equal(isProbablyAbsoluteUrl(replyFromDistbinAInbox.replies), true, "activity is delivered with .replies as a valid absolute url") // So now distbinA is storing a replicated copy of the reply canonically hosted on distbinB. // What happens if we try to request this reply's id on distbinA // const replicatedReplyResponse = await sendRequest(await requestForListener(distbinA, { // path: '/activities/'+replyFromDistbinAInbox.uuid // })) // assert.equal(replicatedReplyResponse.statusCode, 302) // assert(isProbablyAbsoluteUrl(replicatedReplyResponse.headers.location), 'location header is absolute URL') } // #TODO is notifying the .inReplyTo inbox even encouraged/allowed by activitypub? tests["can configure spam checking for inbox to reject some things" + "(server:security-considerations:filter-incoming-content)"] = async () => { // ok so we're going to make two distbins, A and B, and test that A delivers to B const distbinA = distbin({ inboxFilter: async (obj: ASObject) => { const content = get(obj, "object.content") if (content && content.toLowerCase().includes("viagra")) { return false } return true }, }) const distbinB = distbin({ deliverToLocalhost: true, }) // post a parent to distbinA const parentUrl = await postActivity(distbinA, { content: "Spam me", type: "Note", }) // ok now to post the reply to distbinB const replyUrl = await postActivity(distbinB, { cc: [parentUrl], content: "Click here for free Viagra", inReplyTo: parentUrl, type: "Note", }) // then verify that it is NOT in distbinA's inbox const reply = JSON.parse(await readableToString(await sendRequest(http.request(replyUrl)))) const deliveryFailures = reply["distbin:activityPubDeliveryFailures"] assert.ok(deliveryFailures) assert.ok(deliveryFailures.some((failure: {message: string, name: string}) => { return failure.message.includes("This activity has been blocked by the configured inboxFilter") })) const distbinAInbox = JSON.parse(await readableToString(await sendRequest( await requestForListener(distbinA, "/activitypub/inbox")))) assert.equal(distbinAInbox.totalItems, 0, "distbinA inbox does NOT contain spam reply") } tests["When GET an activity, it has information about any replies it may have"] = async () => { // ok so we're going to make to distbins, A and B, and test that A delivers to B const distbinA = distbin() // post a parent to distbinA const parentUrl = await postActivity(distbinA, { content: "Reply to this if you think FSW could happen", type: "Note", }) // ok now to post the reply const replyUrl = await postActivity(distbinA, { cc: [parentUrl], content: "Dear Anonymous, I believe in FSW", inReplyTo: parentUrl, type: "Note", }) const reply = JSON.parse(await readableToString(await sendRequest(http.get(replyUrl)))) const parent = JSON.parse(await readableToString(await sendRequest(http.get(parentUrl)))) assert.equal(typeof parent.replies, "string", "has .replies URL") const repliesResponse = await sendRequest(http.get(url.resolve(parentUrl, parent.replies))) assert.equal(repliesResponse.statusCode, 200, "can fetch URL of .replies and get response") const repliesCollection = JSON.parse(await readableToString(repliesResponse)) // should be one reply assert.equal(repliesCollection.totalItems, 1, "replies collection .totalItems is right") assert(repliesCollection.items, "has .items") assert.equal(repliesCollection.items[0].id, reply.id, ".items contains the reply") } tests["Activities can have a .generator"] = async () => { const distbinA = distbin() const activityToPost = { content: "this has a generator", generator: { name: "distbin-html", type: "Application", url: "http://distbin.com", }, type: "Note", } const activityUrl = await postActivity(distbinA, activityToPost) const activity = JSON.parse(await readableToString(await sendRequest(http.get(activityUrl)))) // note: it was converted to a 'Create' activity assert(activity.object.generator, "has a generator") } tests["GET an activity has a .url that resolves"] = async () => { const activityUrl = await postActivity(distbin(), { content: "you can read this without knowing wtf JSON is!", type: "Note", }) const activityResponse = await sendRequest(http.request(Object.assign(url.parse(activityUrl), { headers: { accept: "text/html", }, }))) assert.equal(activityResponse.statusCode, 200) const fetchedActivity = JSON.parse(await readableToString(activityResponse)) assert(fetchedActivity.url, "has .url property") await Promise.all(ensureArray(fetchedActivity.url).map(async (fetchedActivityUrl: string) => { const resolvedUrl = url.resolve(activityUrl, fetchedActivityUrl) logger.debug("resolvedUrl", JSON.stringify({ fetchedActivityUrl, resolvedUrl, activityUrl, fetchedActivity }, null, 2)) const urlResponse = await sendRequest(http.request(resolvedUrl)) assert.equal(urlResponse.statusCode, 200) })) } tests["GET {activity.id}.json always sends json response, even if html if preferred by user-agent"] = async () => { const activityUrl = await postActivity(distbin(), { content: "Hi", type: "Note", }) const activityResponse = await sendRequest(http.request(Object.assign(url.parse(activityUrl + ".json"), { headers: { accept: "text/html,*/*", }, }))) assert.equal(activityResponse.statusCode, 200) const fetchedActivity = JSON.parse(await readableToString(activityResponse)) assert.ok(fetchedActivity) } if (require.main === module) { testCli(tests) }
the_stack
import 'mocha'; import expect from 'expect'; import { gitSyncDetector } from '../src'; import { GitResourceAttributes } from '../src/types'; import * as fetchGitData from '../src/fecth-git-data'; import * as sinon from 'sinon'; import { Resource } from '@opentelemetry/resources'; describe('git detector', () => { before(() => { // clear env, so it does not affect the tests when run in CI with CI git variables process.env = {}; }); const defaultHeadSha = '3333333333111111111100000000002222222222'; let executeGitCommandStub; let gitRevParseHeadStub; let gitBranchShowCurrentStub; beforeEach(() => { executeGitCommandStub = sinon.stub(fetchGitData, 'executeGitCommand'); // defaults for git commands so test will work in CI and not try to execute actual git commands which will fail. // specific tests can then override this default executeGitCommandStub.returns(''); // by default, git rev-parse HEAD returns defaultHeadSha, because it mandatory for tests to run. // specific tests can then override this value as needed gitRevParseHeadStub = executeGitCommandStub.withArgs('git rev-parse HEAD'); gitRevParseHeadStub.returns(defaultHeadSha); gitBranchShowCurrentStub = executeGitCommandStub.withArgs('git branch --show-current'); }); afterEach(() => { sinon.restore(); }); describe('HEAD sha', () => { it('from CI env vars', () => { process.env.GIT_COMMIT_SHA = '0123456789012345678901234567890123456789'; const resource1 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource1.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(process.env.GIT_COMMIT_SHA); delete process.env.GIT_COMMIT_SHA; process.env.VCS_COMMIT_ID = '0123401234012340123401234012340123401234'; const resource2 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource2.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(process.env.VCS_COMMIT_ID); delete process.env.VCS_COMMIT_ID; process.env.GITHUB_SHA = 'abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde'; const resource3 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource3.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(process.env.GITHUB_SHA); delete process.env.GITHUB_SHA; process.env.CIRCLE_SHA1 = '0000000000111111111122222222223333333333'; const resource4 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource4.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(process.env.CIRCLE_SHA1); delete process.env.CIRCLE_SHA1; process.env.TRAVIS_PULL_REQUEST_SHA = '0101010101989898989845454545453434343434'; const resource5 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource5.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch( process.env.TRAVIS_PULL_REQUEST_SHA ); delete process.env.TRAVIS_PULL_REQUEST_SHA; process.env.CI_COMMIT_SHA = 'abababababcdcdcdcdcdefefefefef0101010101'; const resource6 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource6.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(process.env.CI_COMMIT_SHA); delete process.env.CI_COMMIT_SHA; }); it('read from git cli', () => { const expectedHeadSha = '0000000000111111111122222222223333333333'; gitRevParseHeadStub.returns(expectedHeadSha); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(expectedHeadSha); }); it('read from git dir when HEAD is SHA', () => { const expectedHeadSha = '3333333333222222222211111111110000000000'; // running the command returns empty result -> thus fails and fallback to git dir gitRevParseHeadStub.returns(''); // reading HEAD returns a SHA value (like what you'll get in detached HEAD setup) sinon.stub(fetchGitData, 'readFileFromGitDir').withArgs('HEAD').returns(expectedHeadSha); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(expectedHeadSha); }); it('read from git dir when HEAD is ref to branch', () => { const expectedHeadSha = '3333333333111111111100000000002222222222'; const headRef = 'refs/heads/my-testing-branch'; // running the command returns empty result -> thus fails and fallback to git dir gitRevParseHeadStub.returns(''); // reading HEAD returns a SHA value (like what you'll get in detached HEAD setup) const fsStub = sinon.stub(fetchGitData, 'readFileFromGitDir'); fsStub.withArgs('HEAD').returns(`ref: ${headRef}`); fsStub.withArgs(headRef).returns(expectedHeadSha); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(expectedHeadSha); }); it('read from git dir when HEAD is ref to tag', () => { const tagHeadSha = '3333333333111111111100000000002222222222'; const headRef = 'refs/tags/my-testing-branch'; // running the command returns empty result -> thus fails and fallback to git dir gitRevParseHeadStub.returns(''); // reading HEAD returns a SHA value (like what you'll get in detached HEAD setup) const fsStub = sinon.stub(fetchGitData, 'readFileFromGitDir'); fsStub.withArgs('HEAD').returns(`ref: ${headRef}`); fsStub.withArgs(headRef).returns(tagHeadSha); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_COMMIT_ID]).toMatch(tagHeadSha); }); it('read from git dir when HEAD is ref and is not SHA', () => { const nonShaContent = 'this is not a SHA value'; const headRef = 'refs/heads/my-testing-branch'; // running the command returns empty result -> thus fails and fallback to git dir gitRevParseHeadStub.returns(''); // reading HEAD returns a SHA value (like what you'll get in detached HEAD setup) const fsStub = sinon.stub(fetchGitData, 'readFileFromGitDir'); fsStub.withArgs('HEAD').returns(`ref: ${headRef}`); fsStub.withArgs(headRef).returns(nonShaContent); // when we could not resolve a SHA, we return empty resource const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource).toStrictEqual(Resource.empty()); }); }); // these test are using the current git repo setting. // in case of detached HEAD, they might not work. // maybe they can be improved... describe('git branch', () => { it('read from env variable as explicit branch name', () => { process.env.GIT_BRANCH_NAME = 'git-branch-name'; const resource1 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource1.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toMatch(process.env.GIT_BRANCH_NAME); delete process.env.GIT_BRANCH_NAME; process.env.VCS_BRANCH_NAME = 'vcs-branch-name'; const resource2 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource2.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toMatch(process.env.VCS_BRANCH_NAME); delete process.env.VCS_BRANCH_NAME; process.env.GITHUB_HEAD_REF = 'github-head-ref'; const resource3 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource3.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toMatch(process.env.GITHUB_HEAD_REF); delete process.env.GITHUB_HEAD_REF; }); it('read from env variable as ref', () => { process.env.GITHUB_REF = 'refs/heads/github-ref'; const resource1 = gitSyncDetector.createGitResourceFromGitDb(); expect(resource1.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toMatch('github-ref'); delete process.env.GITHUB_REF; }); it('read with git cli', () => { const expectedBranchName = 'my-testing-branch'; gitBranchShowCurrentStub.returns(expectedBranchName); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toMatch(expectedBranchName); }); it('read with git dir detached HEAD', () => { gitBranchShowCurrentStub.returns(''); const fsStub = sinon.stub(fetchGitData, 'readFileFromGitDir'); fsStub.withArgs('HEAD').returns(defaultHeadSha); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toBeUndefined(); }); it('read with git dir with heads ref', () => { const branchName = 'my-testing-branch'; gitBranchShowCurrentStub.returns(''); const fsStub = sinon.stub(fetchGitData, 'readFileFromGitDir'); fsStub.withArgs('HEAD').returns(`ref: refs/heads/${branchName}`); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_BRANCH_NAME]).toMatch(branchName); }); }); describe('git clone id', () => { it('should read existing value', () => { const expectedGitCloneId = 'git-clone-id-from-tests'; executeGitCommandStub .withArgs('git config --local opentelemetry.resource.clone.id') .returns(expectedGitCloneId); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_CLONE_ID]).toMatch(expectedGitCloneId); }); it('should write git clone id when reading fails', () => { const expectedGitCloneId = 'git-clone-id-from-tests'; executeGitCommandStub .withArgs('git config --local opentelemetry.resource.clone.id') .onFirstCall() .returns('') .onSecondCall() .returns(expectedGitCloneId); executeGitCommandStub .withArgs(sinon.match((cmd) => cmd.startsWith('git config --local opentelemetry.resource.clone.id '))) .onFirstCall() .returns('0'); const resource = gitSyncDetector.createGitResourceFromGitDb(); expect(resource.attributes[GitResourceAttributes.VCS_CLONE_ID]).toMatch(expectedGitCloneId); // assert that writing git config is with valid uuid const gitWriteCommand = executeGitCommandStub.getCall(2).args[0]; expect(gitWriteCommand.split(' ')[4]).toMatch( /^[0-9a-f]{8}\b-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-\b[0-9a-f]{12}$/ ); }); }); });
the_stack
import * as React from 'react'; import { Modal, Tag, Input, DatePicker, Select, Tooltip } from 'antd'; import { IBaseInfo } from '../../interface/common'; import { renderOperationBtns, IBtn, NavRouterLink, renderTooltip } from '../../component/CustomComponent'; import { healthMap, hostTypeMap, healthTypes, hostTypes } from '../../constants/common'; import { IAgentHostSet, IAgentVersion, IService, IOperationTasksParams } from '../../interface/agent'; import { deleteHost, getTaskExists, createOperationTasks } from '../../api/agent' import { timeFormat } from '../../constants/time'; import { cellStyle } from '../../constants/table'; import moment from 'moment'; import store from '../../store' import './index.less'; const { confirm } = Modal; const { RangePicker } = DatePicker; const { Option } = Select; export const agentBreadcrumb = [{ label: 'Agent中心', }, { label: 'Agent管理', }]; export const agentDetailBreadcrumb = [{ aHref: '/list', label: '主机列表', }, { label: '详情', }]; export const getQueryFormColumns = (agentVersions: IAgentVersion[], versionRef: any, healthRef: any, containerRef: any, form: any) => { const queryFormColumns = [ { type: 'custom', title: '主机名/IP', dataIndex: 'hostNameOrIp', component: (<Input placeholder='请输入' />), }, { type: 'custom', title: 'Agent版本号', dataIndex: 'agentVersionIdList', component: ( <Select // mode="multiple" placeholder='请选择' ref={versionRef} allowClear={true} showArrow={true} // onInputKeyDown={() => { // form.resetFields(['agentVersionIdList']); // versionRef.current.blur(); // }} // maxTagCount={0} // maxTagPlaceholder={(values) => values?.length ? `已选择${values?.length}项` : '请选择'} > {agentVersions.map((d: IAgentVersion, index: number) => <Option value={d.agentVersionId} key={index}>{d.agentVersion}</Option> )} </Select> ), }, { type: 'custom', title: '健康度', dataIndex: 'agentHealthLevelList', component: ( <Select mode="multiple" placeholder='请选择' ref={healthRef} allowClear={true} showArrow={true} onInputKeyDown={() => { form.resetFields(['agentHealthLevelList']); healthRef.current.blur(); }} maxTagCount={0} maxTagPlaceholder={(values) => values?.length ? `已选择${values?.length}项` : '请选择'} > {healthTypes.map((d, index) => <Option value={d.value} key={index}>{d.label}</Option> )} </Select> ), }, { type: 'custom', title: '主机类型', dataIndex: 'containerList', component: ( <Select // mode="multiple" placeholder='请选择' ref={containerRef} allowClear={true} showArrow={true} // onInputKeyDown={() => { // form.resetFields(['containerList']); // containerRef.current.blur(); // }} // maxTagCount={0} // maxTagPlaceholder={(values) => values?.length ? `已选择${values?.length}项` : '请选择'} > {hostTypes.map((d, index) => <Option value={d.value} key={index}>{d.label}</Option> )} </Select> ) }, { type: 'custom', title: '新增时间', dataIndex: 'hostCreateTime', // hostCreateTimeStart hostCreateTimeEnd component: ( <RangePicker showTime={{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')], }} style={{ width: '100%' }} /> ), }, ]; return queryFormColumns; } export const getAgentListColumns = (cb: any, drawer: any, getData: any) => { const agentListColumns = [{ title: '主机名', dataIndex: 'hostName', key: 'hostName', width: '10%', onCell: () => ({ style: { ...cellStyle, maxWidth: 130, }, }), sorter: (a: IAgentHostSet, b: IAgentHostSet) => a.hostName?.charCodeAt(0) - b.hostName?.charCodeAt(0), render: (text: string, record: IAgentHostSet) => ( <NavRouterLink needToolTip element={text} href={`/detail`} state={{ hostId: `${record.hostId}`, agentId: `${record.agentId || ''}` }} /> ), }, { title: '主机IP', dataIndex: 'ip', key: 'ip', width: '10%', }, { title: '主机类型', dataIndex: 'container', key: 'container', width: '9%', sorter: (a: IAgentHostSet, b: IAgentHostSet) => a.container - b.container, render: (t: number) => hostTypeMap[t], }, { title: '承载应用', dataIndex: 'serviceList', key: 'serviceList', width: '10%', onCell: () => ({ style: { ...cellStyle, maxWidth: 130, }, }), render: (text: IService[]) => { const servicenames = text.map((ele: IService) => ele.servicename) return (<>{renderTooltip(servicenames?.join(','))}</>) } }, { title: 'Agent版本号', dataIndex: 'agentVersion', key: 'agentVersion', width: '10%', render: (text: string) => <>{text ? text : '未安装'}</>, }, { title: 'Agent健康度', dataIndex: 'agentHealthLevel', key: 'agentHealthLevel', width: '14%', sorter: (a: IAgentHostSet, b: IAgentHostSet) => a.agentHealthLevel - b.agentHealthLevel, render: (t: number, record: IAgentHostSet) => { return (<> <Tag color={healthMap[t]}>{healthMap[t]}</Tag> {(t === 0 || t === 1) && <Tooltip placement="topLeft" title={'更多功能请关注商业版'}> <span><a style={{ color: '#00000040' }}>诊断报告</a></span> </Tooltip>} </>); }, }, { title: '所属机房', dataIndex: 'machineZone', key: 'machineZone', width: '9%', onCell: () => ({ style: { ...cellStyle, maxWidth: 130, }, }), sorter: (a: IAgentHostSet, b: IAgentHostSet) => a.machineZone?.charCodeAt(0) - b.machineZone?.charCodeAt(0), render: (t: string) => renderTooltip(t), }, { title: '新增时间', dataIndex: 'hostCreateTime', key: 'hostCreateTime', width: '10%', sorter: (a: IAgentHostSet, b: IAgentHostSet) => a.hostCreateTime - b.hostCreateTime, render: (t: number) => moment(t).format(timeFormat), }, { title: '操作', width: '18%', render: (text: any, record: IAgentHostSet) => { const btns = getAgentListBtns(record, cb, getData); return renderOperationBtns(btns, record); }, }, ]; return agentListColumns; }; const handleHost = (cb: any, getData: any, taskType: number, host: IAgentHostSet) => { const hosts = []; hosts.push(host); cb('InstallHost', { taskType, hosts, cb: () => getData, }); } export const getAgentListBtns = (record: IAgentHostSet, cb: any, getData: any): IBtn[] => [{ label: '编辑', clickFunc: (record: IAgentHostSet) => { const params = { hostObj: record, getData } cb('ModifyHost', params); }, }, { label: '安装', invisible: !!record.agentId, needTooltip: true, clickFunc: (record: IAgentHostSet) => { handleHost(cb, getData, 0, record); }, }, { label: '升级', invisible: !record.agentId, needTooltip: true, clickFunc: (record: IAgentHostSet) => { handleHost(cb, getData, 2, record); }, }, { label: '卸载', invisible: !record.agentId, needTooltip: true, clickFunc: (record: IAgentHostSet) => { const agentIds = []; agentIds.push(record.agentId); getTaskExists(JSON.stringify(agentIds)).then((res: boolean) => { if (res) { return Modal.confirm({ title: <a className='fail'>选中agent有采集任务正在运行,需要操作将会中断采集,是否继续?</a>, onOk: () => uninstallHostModal(getData, record, res), }); } return uninstallHostModal(getData, record, res); }).catch((err: any) => { // console.log(err); }); }, }, { label: '删除主机', clickFunc: (record: IAgentHostSet) => { judgeDeleteHost(record, getData); }, } ]; export const uninstallHostModal = (getData: any, record: IAgentHostSet, check: boolean) => { Modal.confirm({ title: `确认卸载选中Agent吗?`, content: <a className="fail">卸载操作不可恢复,请谨慎操作!</a>, onOk: () => uninstallHost(getData, record, check), }); } export const uninstallHost = (getData: any, record: IAgentHostSet, check: boolean) => { const params = { agentIds: [record.agentId], checkAgentCompleteCollect: check ? 1 : 0, // 1检查 0 不检查 agentVersionId: '', hostIds: [], taskType: 1, } as unknown as IOperationTasksParams; createOperationTasks(params).then((res: number) => { Modal.success({ title: <><a href="/agent/operationTasks">{record?.hostName}卸载Agent任务(任务ID:{res})</a>创建成功!</>, content: '可点击标题跳转,或至“Agent中心”>“运维任务”模块查看详情', okText: '确认', onOk: () => getData(), }); }).catch((err: any) => { // console.log(err); }); } //有agent不能删, //有容器不能删除 const judgeDeleteHost = (record: IAgentHostSet, getData: any) => { confirm({ title: record.agentId ? '该主机已安装Agent,请先卸载' : `是否确认删除${record.hostName}?`, content: <span className="fail">{!record.agentId && '删除操作不可恢复,请谨慎操作!'}</span>, okText: '确认', cancelText: '取消', onOk() { !record.agentId && deleteHost(record.hostId, 0).then((res: any) => { // 0:不忽略数据未采集完 1:忽略数据未采集完 // 删除主机 0:删除成功 // 10000:参数错误 ==> 不可删除 // 23000:待删除主机在系统不存在 ==> 不可删除 // 23004:主机存在关联的容器导致主机删除失败 ==> 不可删除 // 22001:Agent存在未采集完的日志 ==> 不可能存在这种情况 if (res.code === 0) { Modal.success({ content: '删除成功!' }); getData(); } else if (res.code === 10000 || res.code === 23000 || res.code === 23004) { Modal.error({ content: res.message }); } }); }, }); } const getDiagnosisReport = (drawer: any, record: any) => { drawer('DiagnosisReport', record); } export const hostDetailBaseInfo = (info: IAgentHostSet) => { const hostDetailList: IBaseInfo[] = [{ label: '主机IP', key: 'ip', }, { label: '主机类型', key: 'container', render: (t: number) => hostTypeMap[t], }, { label: '宿主机名', key: 'parentHostName', invisible: info?.container === 0, }, // { // label: 'Agent版本名', // key: 'agentVersion', // }, // { // label: '已开启日志采集任务数', // key: 'openedLogCollectTaskNum', // }, { // label: '已开启日志采集路径数', // key: 'openedLogPathNum', // }, { label: '最近 agent 启动时间', key: 'lastestAgentStartupTime', render: (t: number) => moment(t).format(timeFormat), invisible: !(info.agentId !== null), }, // { // label: '所属机房', // key: 'machineZone', // }, { label: '新增时间', key: 'hostCreateTime', render: (t: number) => moment(t).format(timeFormat), }]; return hostDetailList; } export const getCollectTaskConfig = (drawer: any) => { const collectTaskConfig: any = [ { title: '采集任务ID', dataIndex: 'clusterId', key: 'clusterId', align: 'center', }, { title: '采集路径ID', dataIndex: 'pathId', key: 'pathId', align: 'center', }, { title: '主文件名', dataIndex: 'masterFile', key: 'masterFile', align: 'center', }, { title: '当前采集流量 & 条数/30s', dataIndex: 'sendByte', key: 'sendByte', align: 'center', width: 160, render: (text: any, record: any) => { return `${text} & ${record.sendCount}` } }, { title: '当前最大延迟', dataIndex: 'maxTimeGap', key: 'maxTimeGap', align: 'center', }, { title: '当前采集时间', dataIndex: 'logTime', key: 'logTime', align: 'center', width: 160, render: (t: number) => moment(t).format(timeFormat), }, { title: '文件最近修改时间', dataIndex: 'lastModifyTime', key: 'lastModifyTime', width: 160, align: 'center', render: (text: any, record: any) => { const collectFilesSort = record?.collectFiles.sort((a: any, b: any) => b.lastModifyTime - a.lastModifyTime) return moment(collectFilesSort[0]?.lastModifyTime).format(timeFormat) } }, { title: '限流时长/30s', dataIndex: 'limitTime', key: 'limitTime', align: 'center', }, { title: '异常截断条数/30s', dataIndex: 'filterTooLargeCount', key: 'filterTooLargeCount', align: 'center', }, { title: '文件是否存在', dataIndex: 'fileExist', key: 'fileExist', align: 'center', render: (t: any) => { return t ? '是' : '否' }, }, { title: '文件是否存在乱序', dataIndex: 'isFileOrder', key: 'isFileOrder', align: 'center', render: (t: any, recoud: any) => { const isFileOrder = recoud?.collectFiles && recoud?.collectFiles.filter((item: any) => !item.isFileOrder).length return isFileOrder ? '是' : '否' }, }, { title: '文件是否存在日志切片错误', dataIndex: 'validTimeConfig', key: 'validTimeConfig', align: 'center', render: (t: any, recoud: any) => { const validTimeConfig = recoud?.validTimeConfig && recoud?.validTimeConfig.filter((item: any) => !item.validTimeConfig).length return validTimeConfig ? '是' : '否' } }, { title: '文件过滤量/30s', dataIndex: 'filterOut', key: 'filterOut', align: 'center', }, { title: '近一次心跳时间', dataIndex: 'heartbeatTime', key: 'heartbeatTime', align: 'center', width: 160, render: (t: number) => moment(t).format(timeFormat), }, { title: '采集状态', dataIndex: 'taskStatus', key: 'taskStatus', align: 'center', render: (text: any) => { const status: any = { 0: '停止', 1: '运行中', 2: '完成' } return status[text] } }, { title: '采集文件信息', dataIndex: 'collectFiles', key: 'collectFiles', // fixed: 'right', align: 'center', width: 120, render: (text: any, record: any) => { return <div> <span>共{text.length}个</span><a style={{ display: 'inline-block', marginLeft: '15px' }} onClick={() => { drawer('CollectFileInfoDetail', text) }}>查看</a> </div> } }, { title: '近一次指标详情', dataIndex: 'MetricDetail', key: 'MetricDetail', align: 'center', // fixed: 'right', width: 120, render: (text: any, record: any) => { return <div> <span>共1个</span><a style={{ display: 'inline-block', marginLeft: '15px' }} onClick={() => { drawer('MetricDetail', record) }}>查看</a> </div> } }, ] return collectTaskConfig }
the_stack
import { detach } from '@syncfusion/ej2-base'; import { NodeSelection } from '../../src/selection/selection' describe('Selection', () => { //HTML value let innervalue: string = '<p id="selectionTag"><b>Description:</b></p>' + '<p>The <span id="spantag">Rich Text Editor (RTE)</span> control is an easy to render in' + 'client side. Customer easy to edit the contents and get the HTML content for' + 'the displayed content. A rich text editor control provides users with a toolbar' + 'that helps them to apply rich text formats to the text entered in the text' + 'area. </p>' + '<p><b>ABCD</b><span id="complex1">Hello World</span></p>'+ '<p><b id="complex2">Functional' + 'Specifications/Requirements:</b><span>EFGH</span></p>' + '<ol><li><p>Provide' + 'the tool bar support, it’s also customizable.</p></li><li><p>Options' + 'to get the HTML elements with styles.</p></li><li><p>Support' + 'to insert image from a defined path.</p></li><li><p>Footer' + 'elements and styles(tag / Element information , Action button (Upload, Cancel))' + '</p></li><li><p>Re-size' + 'the editor support.</p></li><li><p>Provide' + 'efficient public methods and client side events.</p></li><li><p>Keyboard' + 'navigation support.</p></li></ol>' + '<p id="first-p-node">Functional Specifications/Requirements:</p>'; //IFRAME Element let iframeElement: HTMLIFrameElement = document.createElement('iframe'); iframeElement.id = 'iframe'; let editor: Document; iframeElement.onload = function (args: Event): void { editor = iframeElement.contentDocument; editor.open(); editor.write('<!DOCTYPE html> <html> <head> <meta charset="utf-8" /></head><body spellcheck="false"' + 'autocorrect="off"></body></html>'); editor.close(); editor.body.contentEditable = 'true'; editor.body.innerHTML = innervalue; }; let domSelection: NodeSelection = new NodeSelection(); //DIV Element let divElement: HTMLDivElement = document.createElement('div'); let brElement: HTMLBRElement = document.createElement('br'); divElement.id = 'divElement'; divElement.contentEditable = 'true'; divElement.innerHTML = innervalue; beforeAll(() => { document.body.appendChild(divElement); document.body.appendChild(brElement); document.body.appendChild(iframeElement); }); afterAll(() => { detach(divElement); detach(brElement); detach(iframeElement); }); /** * DIV initialize */ it('DIV Element check GetRange & setSelectionNode public method', () => { domSelection.Clear(document); let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionNode(document, node); let range: Range = domSelection.getRange(document); expect(range.commonAncestorContainer).toEqual(node); expect(range.startContainer).toEqual(node); expect(range.endContainer).toEqual(node); }); it('DIV Element check GetRange & setSelectionContents public method', () => { domSelection.Clear(document); let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionContents(document, node); let range: Range = domSelection.getRange(document); expect(range.toString()).toEqual('Description:'); }); it('DIV Element check removeAllSelection public method', () => { domSelection.Clear(document); let range: Range = domSelection.getRange(document); expect(range.commonAncestorContainer).toEqual(document.body); }); it('DIV Element check getSelection public method', () => { let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionNode(document, node); let selection: Selection = domSelection.get(document); expect(selection.focusNode).toEqual(node); domSelection.Clear(document); }); it('DIV Element check saveSelection public method', () => { let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionNode(document, node); let range: Range = domSelection.getRange(document); let selectionObj: NodeSelection = domSelection.save(range,document); let childNodes: HTMLSpanElement = document.createElement('span'); childNodes.innerHTML = 'Span Element'; node.appendChild(childNodes); selectionObj.restore(); range = domSelection.getRange(document); expect(range.commonAncestorContainer).toEqual(node); expect(range.startContainer).toEqual(node); expect(range.endContainer).toEqual(node); domSelection.Clear(document); }); it('DIV Element check getParentNodeCollection public method', () => { let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionContents(document, node); let parentNodes: Node[] = domSelection.getParentNodeCollection(domSelection.getRange(document)); expect(parentNodes[0]).toEqual(node); expect(parentNodes.length).toEqual(1); domSelection.Clear(document); }); it('DIV Element check setSelectionText public method', () => { let node: Node = document.getElementById('selectionTag').childNodes[0]; domSelection.setSelectionText(document, node.childNodes[0], node.childNodes[0], 1,3); let parentNodes: Node[] = domSelection.getParentNodeCollection(domSelection.getRange(document)); expect(parentNodes[0]).toEqual(node); domSelection.Clear(document); }); it('DIV Element check getSelectionNodeCollection public method', () => { let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionNode(document, node); let selectNodes: Node[] = domSelection.getSelectionNodeCollection(domSelection.getRange(document)); expect(selectNodes[0].nodeType).toEqual(3); domSelection.Clear(document); }); it('DIV Element check getSelectedNodes public method', () => { let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionNode(document, node); let selectNodes: Node[] = domSelection.getSelectedNodes(document); expect(selectNodes.length).toEqual(4); domSelection.Clear(document); }); it('DIV Element check insertParentNode public method', () => { let node: Node = document.getElementById('selectionTag'); domSelection.setSelectionNode(document, node); domSelection.insertParentNode(document,document.createElement('h1'), domSelection.getRange(document)); expect(node.childNodes[0].nodeName.toLowerCase()).toEqual('h1'); domSelection.Clear(document); }); it('DIV Element check mulitple parent Selection', () => { let complex1: Node = document.getElementById('complex1'); let complex2: Node = document.getElementById('complex2'); domSelection.setSelectionText(document, complex1.childNodes[0], complex2.childNodes[0], 1,3); let parentNodes: Node[] = domSelection.getParentNodeCollection(domSelection.getRange(document)); expect(parentNodes[0]).toEqual(complex2.parentNode); domSelection.Clear(document); }); /** * IFRAME initialize */ it('IFRAME Element GetRange & setSelectionNode', () => { domSelection.Clear(document); let node: Node = editor.getElementById('selectionTag'); domSelection.setSelectionNode(editor, node); let range: Range = domSelection.getRange(editor); expect(range.commonAncestorContainer).toEqual(node); expect(range.startContainer).toEqual(node); expect(range.endContainer).toEqual(node); }); it('IFRAME Element remove all selection', () => { domSelection.Clear(editor); let range: Range = domSelection.getRange(editor); expect(range.commonAncestorContainer).toEqual(editor.body); }); it('IFRAME Element check getSelection public method', () => { let node: Node = editor.getElementById('selectionTag'); domSelection.setSelectionNode(editor, node); let selection: Selection = domSelection.get(editor); expect(selection.focusNode).toEqual(node); domSelection.Clear(editor); }); it('IFRAME Element check saveSelection public method', () => { let node: Node = editor.getElementById('selectionTag'); domSelection.setSelectionNode(editor, node); let range: Range = domSelection.getRange(editor); let selectionObj: NodeSelection = domSelection.save(range,editor); let childNodes: HTMLSpanElement = editor.createElement('span'); childNodes.innerHTML = 'Span Element'; node.appendChild(childNodes); selectionObj.restore(); range = domSelection.getRange(editor); expect(range.commonAncestorContainer).toEqual(node); expect(range.startContainer).toEqual(node); expect(range.endContainer).toEqual(node); domSelection.Clear(editor); }); it('DIV Element get document from range', () => { domSelection.setSelectionText(document, document, document, 0,1); let inst: NodeSelection = domSelection.save(domSelection.getRange(document), document); expect(inst.rootNode).toEqual(document); domSelection.Clear(document); }); it('DIV Element get document without range', () => { domSelection.setSelectionText(document, document, document, 0,1); let inst: NodeSelection = domSelection.save( null, document); expect(inst.rootNode).toEqual(document); domSelection.Clear(document); }); it('DIV Element restore splitted text node', () => { let p: HTMLElement = document.getElementById('first-p-node'); let textnode1: Text = p.firstChild as Text; textnode1.splitText(10); let textnode2: Text = p.childNodes[1] as Text; textnode2.splitText(16); domSelection.setSelectionText(document, p.childNodes[2], p.childNodes[2], 0, 5); let inst: NodeSelection = domSelection.save( domSelection.getRange(document), document); inst.restore(); expect(inst.startOffset).toEqual(0); domSelection.Clear(document); }); it('DIV Element check get node array', () => { let p: HTMLElement = document.getElementById('first-p-node'); domSelection.rootNode = null; let inst: number[] = domSelection.getNodeArray( p, true, document ); expect(inst.length).toEqual(4); domSelection.Clear(document); }); });
the_stack
import { BufferAttribute, Texture, Vector2 } from "three"; import { Geometry } from "three/examples/jsm/deprecated/Geometry"; import { DoubleSide, NearestFilter } from "three/src/constants"; import { Object3D } from "three/src/core/Object3D"; import { BoxGeometry } from "three/src/geometries/BoxGeometry"; import { BoxHelper } from "three/src/helpers/BoxHelper"; import { MeshBasicMaterial } from "three/src/materials/MeshBasicMaterial"; import { Color } from "three/src/math/Color"; import { Mesh } from "three/src/objects/Mesh"; import { CanvasTexture } from "three/src/textures/CanvasTexture"; import format, { CubeUVMapping, ModelTemplate } from "./player-model"; function convertLegacySkin(context: CanvasRenderingContext2D, width: number) { const scale = width / 64.0; function copySkin(ctx: CanvasRenderingContext2D, sX: number, sY: number, w: number, h: number, dX: number, dY: number, flipHorizontal: boolean) { sX *= scale; sY *= scale; w *= scale; h *= scale; dX *= scale; dY *= scale; const imgData = ctx.getImageData(sX, sY, w, h); if (flipHorizontal) { for (let y = 0; y < h; y++) { for (let x = 0; x < (w / 2); x++) { const index = (x + y * w) * 4; const index2 = ((w - x - 1) + y * w) * 4; const pA1 = imgData.data[index]; const pA2 = imgData.data[index + 1]; const pA3 = imgData.data[index + 2]; const pA4 = imgData.data[index + 3]; const pB1 = imgData.data[index2]; const pB2 = imgData.data[index2 + 1]; const pB3 = imgData.data[index2 + 2]; const pB4 = imgData.data[index2 + 3]; imgData.data[index] = pB1; imgData.data[index + 1] = pB2; imgData.data[index + 2] = pB3; imgData.data[index + 3] = pB4; imgData.data[index2] = pA1; imgData.data[index2 + 1] = pA2; imgData.data[index2 + 2] = pA3; imgData.data[index2 + 3] = pA4; } } } ctx.putImageData(imgData, dX, dY); } copySkin(context, 4, 16, 4, 4, 20, 48, true); // Top Leg copySkin(context, 8, 16, 4, 4, 24, 48, true); // Bottom Leg copySkin(context, 0, 20, 4, 12, 24, 52, true); // Outer Leg copySkin(context, 4, 20, 4, 12, 20, 52, true); // Front Leg copySkin(context, 8, 20, 4, 12, 16, 52, true); // Inner Leg copySkin(context, 12, 20, 4, 12, 28, 52, true); // Back Leg copySkin(context, 44, 16, 4, 4, 36, 48, true); // Top Arm copySkin(context, 48, 16, 4, 4, 40, 48, true); // Bottom Arm copySkin(context, 40, 20, 4, 12, 40, 52, true); // Outer Arm copySkin(context, 44, 20, 4, 12, 36, 52, true); // Front Arm copySkin(context, 48, 20, 4, 12, 32, 52, true); // Inner Arm copySkin(context, 52, 20, 4, 12, 44, 52, true); // Back Arm } type TextureSource = string | HTMLImageElement | URL; function mapCubeUV(mesh: Mesh, src: CubeUVMapping) { const material = mesh.material as MeshBasicMaterial; const texture = material.map!; const tileUvW = 1 / texture.image.width; const tileUvH = 1 / texture.image.height; const uvs: Vector2[] = [] /** * Set the box mesh UV to the Minecraft skin texture */ function mapUV(x1: number, y1: number, x2: number, y2: number) { x1 *= tileUvW; x2 *= tileUvW; y1 = 1 - (y1 * tileUvH); y2 = 1 - (y2 * tileUvH); uvs.push( new Vector2(x1, y1), new Vector2(x2, y1), new Vector2(x1, y2), new Vector2(x2, y2), ) } const faces = ["left", "right", "top", "bottom", "front", "back"] as const; for (let i = 0; i < faces.length; i++) { const uvs = src[faces[i]]; mapUV(uvs[0], uvs[1], uvs[2], uvs[3]); } const attr = new BufferAttribute(new Float32Array(uvs.length * 2), 2).copyVector2sArray(uvs) mesh.geometry.setAttribute("uv", attr); } export class PlayerObject3D extends Object3D { private _slim: boolean = false; constructor(skin: MeshBasicMaterial, cape: MeshBasicMaterial, tranparent: MeshBasicMaterial, slim: boolean) { super(); this._slim = slim; buildPlayerModel(this, skin, cape, tranparent, slim); } get slim() { return this._slim; } set slim(s: boolean) { if (s !== this._slim) { const template = s ? format.alex : format.steve; const leftArm = this.getObjectByName("leftArm")! as Mesh; const rightArm = this.getObjectByName("rightArm")! as Mesh; leftArm.geometry = new BoxGeometry(template.leftArm.w, template.leftArm.h, template.leftArm.d); mapCubeUV(leftArm, template.leftArm); rightArm.geometry = new BoxGeometry(template.rightArm.w, template.rightArm.h, template.rightArm.d); mapCubeUV(rightArm, template.rightArm); const leftArmLayer = this.getObjectByName("leftArmLayer")! as Mesh; const rightArmLayer = this.getObjectByName("rightArmLayer")! as Mesh; if (leftArmLayer) { leftArmLayer.geometry = new BoxGeometry(template.leftArm.layer.w, template.leftArm.layer.h, template.leftArm.layer.d); mapCubeUV(leftArmLayer, template.leftArm.layer); } if (rightArmLayer) { rightArmLayer.geometry = new BoxGeometry(template.rightArm.layer.w, template.rightArm.layer.h, template.rightArm.layer.d); mapCubeUV(rightArmLayer, template.rightArm.layer); } } this._slim = s; } } function buildPlayerModel(root: Object3D, skin: MeshBasicMaterial, cape: MeshBasicMaterial, tranparent: MeshBasicMaterial, slim: boolean): Object3D { const template = slim ? format.alex : format.steve; const partsNames: Array<keyof ModelTemplate> = Object.keys(template) as any; for (const partName of partsNames) { const model = template[partName]; const mesh = new Mesh(new BoxGeometry(model.w, model.h, model.d), partName === "cape" ? cape : skin); mesh.name = partName; if (model.y) { mesh.position.y = model.y; } if (model.x) { mesh.position.x = model.x; } if (model.z) { mesh.position.z = model.z; } if (partName === "cape") { mesh.rotation.x = 25 * (Math.PI / 180); } mapCubeUV(mesh, model); const box = new BoxHelper(mesh, new Color(0xffffff)); box.name = `${partName}Box`; box.visible = false; mesh.add(box); if ("layer" in model) { const layer = model.layer; const layerMesh = new Mesh(new BoxGeometry(layer.w, layer.h, layer.d), tranparent); layerMesh.name = `${partName}Layer`; if (layer.y) { layerMesh.position.y = layer.y; } if (layer.x) { layerMesh.position.x = layer.x; } if (layer.z) { layerMesh.position.z = layer.z; } mapCubeUV(layerMesh, layer); mesh.add(layerMesh); } root.add(mesh); } return root; } function ensureImage(textureSource: TextureSource) { if (textureSource instanceof Image) { return textureSource; } return new Promise<HTMLImageElement>((resolve, reject) => { const img = new Image(); img.onload = () => { resolve(img); }; img.onerror = (e, source, lineno, colno, error) => { reject(error) } if (textureSource instanceof URL) { img.src = textureSource.toString() } else { img.src = textureSource } }); } export class PlayerModel { static create() { return new PlayerModel(); } readonly playerObject3d: PlayerObject3D; readonly materialPlayer: MeshBasicMaterial; readonly materialTransparent: MeshBasicMaterial; readonly materialCape: MeshBasicMaterial; readonly textureCape: CanvasTexture; readonly texturePlayer: CanvasTexture; constructor() { const canvas = document.createElement("canvas"); canvas.width = 64; canvas.height = 64; const texture = new CanvasTexture(canvas); texture.magFilter = NearestFilter; texture.minFilter = NearestFilter; this.texturePlayer = texture; texture.name = "skinTexture"; this.materialPlayer = new MeshBasicMaterial({ map: texture }); this.materialTransparent = new MeshBasicMaterial({ map: texture, transparent: true, depthWrite: false, side: DoubleSide, }); const textureCape = new CanvasTexture(document.createElement("canvas")); textureCape.magFilter = NearestFilter; textureCape.minFilter = NearestFilter; textureCape.name = "capeTexture"; this.textureCape = textureCape; const materialCape = new MeshBasicMaterial({ map: this.textureCape, }); materialCape.name = "capeMaterial"; materialCape.visible = false; this.materialCape = materialCape; this.playerObject3d = new PlayerObject3D(this.materialPlayer, this.materialCape, this.materialTransparent, false); } /** * @param skin The skin texture source. Should be url string, URL object, or a Image HTML element * @param isSlim Is this skin slim */ async setSkin(skin: TextureSource, isSlim: boolean = false) { this.playerObject3d.slim = isSlim; const texture = this.texturePlayer; const i = await ensureImage(skin); const legacy = i.width !== i.height; const canvas = texture.image; const context = canvas.getContext("2d"); canvas.width = i.width; canvas.height = i.width; context.clearRect(0, 0, i.width, i.width); if (legacy) { context.drawImage(i, 0, 0, i.width, i.width / 2.0); convertLegacySkin(context, i.width); } else { context.drawImage(i, 0, 0, i.width, i.width); } texture.needsUpdate = true; } async setCape(cape: TextureSource | undefined) { if (cape === undefined) { this.materialCape.visible = false; return; } this.materialCape.visible = true; const img = await ensureImage(cape); const texture = this.textureCape; texture.image = img; texture.needsUpdate = true; } // name(name) { // if (name === undefined || name === "" || name === null) { // if (this.nameTagObject === null) { return this; } // this.root.remove(this.nameTagObject); // this.nameTagObject = null; // } // if (this.nameTagObject) { this.clear(); } // // build the texture // const canvas = buildNameTag(name); // const texture = new Texture(canvas); // texture.needsUpdate = true; // // build the sprite itself // const material = new SpriteMaterial({ // map: texture, // // useScreenCoordinates: false // }); // const sprite = new Sprite(material); // this.nameTagObject = sprite; // sprite.position.y = 1.15; // // add sprite to the character // this.root.add(this.nameTagObject); // return this; // } // load(option) { // if (!option) { return this; } // if (option.skin) { this.loadSkin(option.skin); } // if (option.cape) { this.loadCape(option.skin); } // return this; // } // say(text, expire = 4) { // expire *= 1000; // if (this.speakExpire) { // clearTimeout(this.speakExpire); // this.root.remove(this.speakBox); // this.speakBox = null; // this.speakExpire = null; // } // this.speakExpire = setTimeout(() => { // this.root.remove(this.speakBox); // this.speakBox = null; // this.speakExpire = null; // }, expire); // // build the texture // const canvas = buildChatBox(text); // const texture = new Texture(canvas); // texture.needsUpdate = true; // // build the sprite itself // const material = new SpriteMaterial({ // map: texture, // // useScreenCoordinates: false // }); // const sprite = new Sprite(material); // this.speakBox = sprite; // sprite.scale.multiplyScalar(4); // sprite.position.y = 1.5; // // add sprite to the character // this.root.add(this.speakBox); // return this; // } } export default PlayerModel;
the_stack
import { CancellationToken } from 'vs/base/common/cancellation'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { isArray } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { IChannel, IServerChannel } from 'vs/base/parts/ipc/common/ipc'; import { ILogService } from 'vs/platform/log/common/log'; import { IManualSyncTask, IResourcePreview, ISyncResourceHandle, ISyncResourcePreview, ISyncTask, IUserDataManifest, IUserDataSyncService, SyncResource, SyncStatus, UserDataSyncError } from 'vs/platform/userDataSync/common/userDataSync'; type ManualSyncTaskEvent<T> = { manualSyncTaskId: string; data: T }; export class UserDataSyncChannel implements IServerChannel { private readonly manualSyncTasks = new Map<string, { manualSyncTask: IManualSyncTask; disposables: DisposableStore }>(); private readonly onManualSynchronizeResources = new Emitter<ManualSyncTaskEvent<[SyncResource, URI[]][]>>(); constructor(private readonly service: IUserDataSyncService, private readonly logService: ILogService) { } listen(_: unknown, event: string): Event<any> { switch (event) { // sync case 'onDidChangeStatus': return this.service.onDidChangeStatus; case 'onDidChangeConflicts': return this.service.onDidChangeConflicts; case 'onDidChangeLocal': return this.service.onDidChangeLocal; case 'onDidChangeLastSyncTime': return this.service.onDidChangeLastSyncTime; case 'onSyncErrors': return this.service.onSyncErrors; case 'onDidResetLocal': return this.service.onDidResetLocal; case 'onDidResetRemote': return this.service.onDidResetRemote; // manual sync case 'manualSync/onSynchronizeResources': return this.onManualSynchronizeResources.event; } throw new Error(`Event not found: ${event}`); } async call(context: any, command: string, args?: any): Promise<any> { try { const result = await this._call(context, command, args); return result; } catch (e) { this.logService.error(e); throw e; } } private async _call(context: any, command: string, args?: any): Promise<any> { switch (command) { // sync case '_getInitialData': return Promise.resolve([this.service.status, this.service.conflicts, this.service.lastSyncTime]); case 'replace': return this.service.replace(URI.revive(args[0])); case 'reset': return this.service.reset(); case 'resetRemote': return this.service.resetRemote(); case 'resetLocal': return this.service.resetLocal(); case 'hasPreviouslySynced': return this.service.hasPreviouslySynced(); case 'hasLocalData': return this.service.hasLocalData(); case 'accept': return this.service.accept(args[0], URI.revive(args[1]), args[2], args[3]); case 'resolveContent': return this.service.resolveContent(URI.revive(args[0])); case 'getLocalSyncResourceHandles': return this.service.getLocalSyncResourceHandles(args[0]); case 'getRemoteSyncResourceHandles': return this.service.getRemoteSyncResourceHandles(args[0]); case 'getAssociatedResources': return this.service.getAssociatedResources(args[0], { created: args[1].created, uri: URI.revive(args[1].uri) }); case 'getMachineId': return this.service.getMachineId(args[0], { created: args[1].created, uri: URI.revive(args[1].uri) }); case 'createManualSyncTask': return this.createManualSyncTask(); } // manual sync if (command.startsWith('manualSync/')) { const manualSyncTaskCommand = command.substring('manualSync/'.length); const manualSyncTaskId = args[0]; const manualSyncTask = this.getManualSyncTask(manualSyncTaskId); args = (<Array<any>>args).slice(1); switch (manualSyncTaskCommand) { case 'preview': return manualSyncTask.preview(); case 'accept': return manualSyncTask.accept(URI.revive(args[0]), args[1]); case 'merge': return manualSyncTask.merge(URI.revive(args[0])); case 'discard': return manualSyncTask.discard(URI.revive(args[0])); case 'discardConflicts': return manualSyncTask.discardConflicts(); case 'apply': return manualSyncTask.apply(); case 'pull': return manualSyncTask.pull(); case 'push': return manualSyncTask.push(); case 'stop': return manualSyncTask.stop(); case '_getStatus': return manualSyncTask.status; case 'dispose': return this.disposeManualSyncTask(manualSyncTask); } } throw new Error('Invalid call'); } private getManualSyncTask(manualSyncTaskId: string): IManualSyncTask { const value = this.manualSyncTasks.get(this.createKey(manualSyncTaskId)); if (!value) { throw new Error(`Manual sync taks not found: ${manualSyncTaskId}`); } return value.manualSyncTask; } private async createManualSyncTask(): Promise<{ id: string; manifest: IUserDataManifest | null; status: SyncStatus }> { const disposables = new DisposableStore(); const manualSyncTask = disposables.add(await this.service.createManualSyncTask()); disposables.add(manualSyncTask.onSynchronizeResources(synchronizeResources => this.onManualSynchronizeResources.fire({ manualSyncTaskId: manualSyncTask.id, data: synchronizeResources }))); this.manualSyncTasks.set(this.createKey(manualSyncTask.id), { manualSyncTask, disposables }); return { id: manualSyncTask.id, manifest: manualSyncTask.manifest, status: manualSyncTask.status }; } private disposeManualSyncTask(manualSyncTask: IManualSyncTask): void { manualSyncTask.dispose(); const key = this.createKey(manualSyncTask.id); this.manualSyncTasks.get(key)?.disposables.dispose(); this.manualSyncTasks.delete(key); } private createKey(manualSyncTaskId: string): string { return `manualSyncTask-${manualSyncTaskId}`; } } export class UserDataSyncChannelClient extends Disposable implements IUserDataSyncService { declare readonly _serviceBrand: undefined; private readonly channel: IChannel; private _status: SyncStatus = SyncStatus.Uninitialized; get status(): SyncStatus { return this._status; } private _onDidChangeStatus: Emitter<SyncStatus> = this._register(new Emitter<SyncStatus>()); readonly onDidChangeStatus: Event<SyncStatus> = this._onDidChangeStatus.event; get onDidChangeLocal(): Event<SyncResource> { return this.channel.listen<SyncResource>('onDidChangeLocal'); } private _conflicts: [SyncResource, IResourcePreview[]][] = []; get conflicts(): [SyncResource, IResourcePreview[]][] { return this._conflicts; } private _onDidChangeConflicts: Emitter<[SyncResource, IResourcePreview[]][]> = this._register(new Emitter<[SyncResource, IResourcePreview[]][]>()); readonly onDidChangeConflicts: Event<[SyncResource, IResourcePreview[]][]> = this._onDidChangeConflicts.event; private _lastSyncTime: number | undefined = undefined; get lastSyncTime(): number | undefined { return this._lastSyncTime; } private _onDidChangeLastSyncTime: Emitter<number> = this._register(new Emitter<number>()); readonly onDidChangeLastSyncTime: Event<number> = this._onDidChangeLastSyncTime.event; private _onSyncErrors: Emitter<[SyncResource, UserDataSyncError][]> = this._register(new Emitter<[SyncResource, UserDataSyncError][]>()); readonly onSyncErrors: Event<[SyncResource, UserDataSyncError][]> = this._onSyncErrors.event; get onDidResetLocal(): Event<void> { return this.channel.listen<void>('onDidResetLocal'); } get onDidResetRemote(): Event<void> { return this.channel.listen<void>('onDidResetRemote'); } constructor(userDataSyncChannel: IChannel) { super(); this.channel = { call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> { return userDataSyncChannel.call(command, arg, cancellationToken) .then(null, error => { throw UserDataSyncError.toUserDataSyncError(error); }); }, listen<T>(event: string, arg?: any): Event<T> { return userDataSyncChannel.listen(event, arg); } }; this.channel.call<[SyncStatus, [SyncResource, IResourcePreview[]][], number | undefined]>('_getInitialData').then(([status, conflicts, lastSyncTime]) => { this.updateStatus(status); this.updateConflicts(conflicts); if (lastSyncTime) { this.updateLastSyncTime(lastSyncTime); } this._register(this.channel.listen<SyncStatus>('onDidChangeStatus')(status => this.updateStatus(status))); this._register(this.channel.listen<number>('onDidChangeLastSyncTime')(lastSyncTime => this.updateLastSyncTime(lastSyncTime))); }); this._register(this.channel.listen<[SyncResource, IResourcePreview[]][]>('onDidChangeConflicts')(conflicts => this.updateConflicts(conflicts))); this._register(this.channel.listen<[SyncResource, Error][]>('onSyncErrors')(errors => this._onSyncErrors.fire(errors.map(([source, error]) => ([source, UserDataSyncError.toUserDataSyncError(error)]))))); } createSyncTask(): Promise<ISyncTask> { throw new Error('not supported'); } async createManualSyncTask(): Promise<IManualSyncTask> { const { id, manifest, status } = await this.channel.call<{ id: string; manifest: IUserDataManifest | null; status: SyncStatus }>('createManualSyncTask'); const that = this; const manualSyncTaskChannelClient = new ManualSyncTaskChannelClient(id, manifest, status, { async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> { return that.channel.call<T>(`manualSync/${command}`, [id, ...(isArray(arg) ? arg : [arg])], cancellationToken); }, listen<T>(event: string, arg?: any): Event<T> { return Event.map( Event.filter(that.channel.listen<{ manualSyncTaskId: string; data: T }>(`manualSync/${event}`, arg), e => !manualSyncTaskChannelClient.isDiposed() && e.manualSyncTaskId === id), e => e.data); } }); return manualSyncTaskChannelClient; } replace(uri: URI): Promise<void> { return this.channel.call('replace', [uri]); } reset(): Promise<void> { return this.channel.call('reset'); } resetRemote(): Promise<void> { return this.channel.call('resetRemote'); } resetLocal(): Promise<void> { return this.channel.call('resetLocal'); } hasPreviouslySynced(): Promise<boolean> { return this.channel.call('hasPreviouslySynced'); } hasLocalData(): Promise<boolean> { return this.channel.call('hasLocalData'); } accept(syncResource: SyncResource, resource: URI, content: string | null, apply: boolean): Promise<void> { return this.channel.call('accept', [syncResource, resource, content, apply]); } resolveContent(resource: URI): Promise<string | null> { return this.channel.call('resolveContent', [resource]); } async getLocalSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> { const handles = await this.channel.call<ISyncResourceHandle[]>('getLocalSyncResourceHandles', [resource]); return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) })); } async getRemoteSyncResourceHandles(resource: SyncResource): Promise<ISyncResourceHandle[]> { const handles = await this.channel.call<ISyncResourceHandle[]>('getRemoteSyncResourceHandles', [resource]); return handles.map(({ created, uri }) => ({ created, uri: URI.revive(uri) })); } async getAssociatedResources(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<{ resource: URI; comparableResource: URI }[]> { const result = await this.channel.call<{ resource: URI; comparableResource: URI }[]>('getAssociatedResources', [resource, syncResourceHandle]); return result.map(({ resource, comparableResource }) => ({ resource: URI.revive(resource), comparableResource: URI.revive(comparableResource) })); } async getMachineId(resource: SyncResource, syncResourceHandle: ISyncResourceHandle): Promise<string | undefined> { return this.channel.call<string | undefined>('getMachineId', [resource, syncResourceHandle]); } private async updateStatus(status: SyncStatus): Promise<void> { this._status = status; this._onDidChangeStatus.fire(status); } private async updateConflicts(conflicts: [SyncResource, IResourcePreview[]][]): Promise<void> { // Revive URIs this._conflicts = conflicts.map(([syncResource, conflicts]) => ([ syncResource, conflicts.map(r => ({ ...r, localResource: URI.revive(r.localResource), remoteResource: URI.revive(r.remoteResource), previewResource: URI.revive(r.previewResource), })) ])); this._onDidChangeConflicts.fire(this._conflicts); } private updateLastSyncTime(lastSyncTime: number): void { if (this._lastSyncTime !== lastSyncTime) { this._lastSyncTime = lastSyncTime; this._onDidChangeLastSyncTime.fire(lastSyncTime); } } } class ManualSyncTaskChannelClient extends Disposable implements IManualSyncTask { private readonly channel: IChannel; get onSynchronizeResources(): Event<[SyncResource, URI[]][]> { return this.channel.listen<[SyncResource, URI[]][]>('onSynchronizeResources'); } private _status: SyncStatus; get status(): SyncStatus { return this._status; } constructor( readonly id: string, readonly manifest: IUserDataManifest | null, status: SyncStatus, manualSyncTaskChannel: IChannel ) { super(); this._status = status; const that = this; this.channel = { async call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T> { try { const result = await manualSyncTaskChannel.call<T>(command, arg, cancellationToken); if (!that.isDiposed()) { that._status = await manualSyncTaskChannel.call<SyncStatus>('_getStatus'); } return result; } catch (error) { throw UserDataSyncError.toUserDataSyncError(error); } }, listen<T>(event: string, arg?: any): Event<T> { return manualSyncTaskChannel.listen(event, arg); } }; } async preview(): Promise<[SyncResource, ISyncResourcePreview][]> { const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('preview'); return this.deserializePreviews(previews); } async accept(resource: URI, content?: string | null): Promise<[SyncResource, ISyncResourcePreview][]> { const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('accept', [resource, content]); return this.deserializePreviews(previews); } async merge(resource?: URI): Promise<[SyncResource, ISyncResourcePreview][]> { const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('merge', [resource]); return this.deserializePreviews(previews); } async discard(resource: URI): Promise<[SyncResource, ISyncResourcePreview][]> { const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discard', [resource]); return this.deserializePreviews(previews); } async discardConflicts(): Promise<[SyncResource, ISyncResourcePreview][]> { const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('discardConflicts'); return this.deserializePreviews(previews); } async apply(): Promise<[SyncResource, ISyncResourcePreview][]> { const previews = await this.channel.call<[SyncResource, ISyncResourcePreview][]>('apply'); return this.deserializePreviews(previews); } pull(): Promise<void> { return this.channel.call('pull'); } push(): Promise<void> { return this.channel.call('push'); } stop(): Promise<void> { return this.channel.call('stop'); } private _disposed = false; isDiposed() { return this._disposed; } override dispose(): void { this._disposed = true; this.channel.call('dispose'); } private deserializePreviews(previews: [SyncResource, ISyncResourcePreview][]): [SyncResource, ISyncResourcePreview][] { return previews.map(([syncResource, preview]) => ([ syncResource, { isLastSyncFromCurrentMachine: preview.isLastSyncFromCurrentMachine, resourcePreviews: preview.resourcePreviews.map(r => ({ ...r, localResource: URI.revive(r.localResource), remoteResource: URI.revive(r.remoteResource), previewResource: URI.revive(r.previewResource), acceptedResource: URI.revive(r.acceptedResource), })) } ])); } }
the_stack
import { createUserAndSession, beforeAllDb, afterAllTests, beforeEachDb, models, createItemTree, createResource, createNote, createItemTree3, db, tempDir, expectNotThrow, expectHttpError } from '../utils/testing/testUtils'; import { shareFolderWithUser } from '../utils/testing/shareApiUtils'; import { resourceBlobPath } from '../utils/joplinUtils'; import newModelFactory from './factory'; import { StorageDriverType } from '../utils/types'; import config from '../config'; import { msleep } from '../utils/time'; import loadStorageDriver from './items/storage/loadStorageDriver'; import { ErrorPayloadTooLarge } from '../utils/errors'; import { isSqlite } from '../db'; describe('ItemModel', function() { beforeAll(async () => { await beforeAllDb('ItemModel'); }); afterAll(async () => { await afterAllTests(); }); beforeEach(async () => { await beforeEachDb(); }); // test('should find exclusively owned items 1', async function() { // const { user: user1 } = await createUserAndSession(1, true); // const { session: session2, user: user2 } = await createUserAndSession(2); // const tree: any = { // '000000000000000000000000000000F1': { // '00000000000000000000000000000001': null, // }, // }; // await createItemTree(user1.id, '', tree); // await createItem(session2.id, 'root:/test.txt:', 'testing'); // { // const itemIds = await models().item().exclusivelyOwnedItemIds(user1.id); // expect(itemIds.length).toBe(2); // const item1 = await models().item().load(itemIds[0]); // const item2 = await models().item().load(itemIds[1]); // expect([item1.jop_id, item2.jop_id].sort()).toEqual(['000000000000000000000000000000F1', '00000000000000000000000000000001'].sort()); // } // { // const itemIds = await models().item().exclusivelyOwnedItemIds(user2.id); // expect(itemIds.length).toBe(1); // } // }); // test('should find exclusively owned items 2', async function() { // const { session: session1, user: user1 } = await createUserAndSession(1, true); // const { session: session2, user: user2 } = await createUserAndSession(2); // await shareFolderWithUser(session1.id, session2.id, '000000000000000000000000000000F1', { // '000000000000000000000000000000F1': { // '00000000000000000000000000000001': null, // }, // }); // await createFolder(session2.id, { id: '000000000000000000000000000000F2' }); // { // const itemIds = await models().item().exclusivelyOwnedItemIds(user1.id); // expect(itemIds.length).toBe(0); // } // { // const itemIds = await models().item().exclusivelyOwnedItemIds(user2.id); // expect(itemIds.length).toBe(1); // } // await models().user().delete(user2.id); // { // const itemIds = await models().item().exclusivelyOwnedItemIds(user1.id); // expect(itemIds.length).toBe(2); // } // }); test('should find all items within a shared folder', async function() { const { user: user1, session: session1 } = await createUserAndSession(1); const { session: session2 } = await createUserAndSession(2); const resourceItem1 = await createResource(session1.id, { id: '000000000000000000000000000000E1' }, 'testing1'); const resourceItem2 = await createResource(session1.id, { id: '000000000000000000000000000000E2' }, 'testing2'); const { share } = await shareFolderWithUser(session1.id, session2.id, '000000000000000000000000000000F1', [ { id: '000000000000000000000000000000F1', children: [ { id: '00000000000000000000000000000001', title: 'note test 1', body: `[testing 1](:/${resourceItem1.jop_id}) [testing 2](:/${resourceItem2.jop_id})`, }, { id: '00000000000000000000000000000002', title: 'note test 2', body: '', }, ], }, { id: '000000000000000000000000000000F2', children: [], }, ]); await createNote(session2.id, { id: '00000000000000000000000000000003', parent_id: '000000000000000000000000000000F1' }); { const shareUserIds = await models().share().allShareUserIds(share); const children = await models().item().sharedFolderChildrenItems(shareUserIds, '000000000000000000000000000000F1'); expect(children.filter(c => !!c.jop_id).map(c => c.jop_id).sort()).toEqual([ '00000000000000000000000000000001', '00000000000000000000000000000002', '00000000000000000000000000000003', '000000000000000000000000000000E1', '000000000000000000000000000000E2', ].sort()); expect(children.filter(c => !c.jop_id).map(c => c.name).sort()).toEqual([ resourceBlobPath('000000000000000000000000000000E1'), resourceBlobPath('000000000000000000000000000000E2'), ].sort()); } { const children = await models().item().sharedFolderChildrenItems([user1.id], '000000000000000000000000000000F2'); expect(children.map(c => c.jop_id).sort()).toEqual([].sort()); } }); test('should count items', async function() { const { user: user1 } = await createUserAndSession(1, true); await createItemTree(user1.id, '', { '000000000000000000000000000000F1': { '00000000000000000000000000000001': null, }, }); expect(await models().item().childrenCount(user1.id)).toBe(2); }); test('should calculate the total size', async function() { const { user: user1 } = await createUserAndSession(1); const { user: user2 } = await createUserAndSession(2); const { user: user3 } = await createUserAndSession(3); await createItemTree3(user1.id, '', '', [ { id: '000000000000000000000000000000F1', children: [ { id: '00000000000000000000000000000001', }, ], }, ]); await createItemTree3(user2.id, '', '', [ { id: '000000000000000000000000000000F2', children: [ { id: '00000000000000000000000000000002', }, { id: '00000000000000000000000000000003', }, ], }, ]); const folder1 = await models().item().loadByJopId(user1.id, '000000000000000000000000000000F1'); const folder2 = await models().item().loadByJopId(user2.id, '000000000000000000000000000000F2'); const note1 = await models().item().loadByJopId(user1.id, '00000000000000000000000000000001'); const note2 = await models().item().loadByJopId(user2.id, '00000000000000000000000000000002'); const note3 = await models().item().loadByJopId(user2.id, '00000000000000000000000000000003'); const totalSize1 = await models().item().calculateUserTotalSize(user1.id); const totalSize2 = await models().item().calculateUserTotalSize(user2.id); const totalSize3 = await models().item().calculateUserTotalSize(user3.id); const expected1 = folder1.content_size + note1.content_size; const expected2 = folder2.content_size + note2.content_size + note3.content_size; const expected3 = 0; expect(totalSize1).toBe(expected1); expect(totalSize2).toBe(expected2); expect(totalSize3).toBe(expected3); await models().item().updateTotalSizes(); expect((await models().user().load(user1.id)).total_item_size).toBe(totalSize1); expect((await models().user().load(user2.id)).total_item_size).toBe(totalSize2); expect((await models().user().load(user3.id)).total_item_size).toBe(totalSize3); }); test('should update total size when an item is deleted', async function() { const { user: user1 } = await createUserAndSession(1); await createItemTree3(user1.id, '', '', [ { id: '000000000000000000000000000000F1', children: [ { id: '00000000000000000000000000000001', }, ], }, ]); const folder1 = await models().item().loadByJopId(user1.id, '000000000000000000000000000000F1'); const note1 = await models().item().loadByJopId(user1.id, '00000000000000000000000000000001'); await models().item().updateTotalSizes(); expect((await models().user().load(user1.id)).total_item_size).toBe(folder1.content_size + note1.content_size); await models().item().delete(note1.id); await models().item().updateTotalSizes(); expect((await models().user().load(user1.id)).total_item_size).toBe(folder1.content_size); }); test('should include shared items in total size calculation', async function() { const { user: user1, session: session1 } = await createUserAndSession(1); const { user: user2, session: session2 } = await createUserAndSession(2); const { user: user3 } = await createUserAndSession(3); await shareFolderWithUser(session1.id, session2.id, '000000000000000000000000000000F1', [ { id: '000000000000000000000000000000F1', children: [ { id: '00000000000000000000000000000001', }, ], }, { id: '000000000000000000000000000000F2', }, ]); const folder1 = await models().item().loadByJopId(user1.id, '000000000000000000000000000000F1'); const folder2 = await models().item().loadByJopId(user1.id, '000000000000000000000000000000F2'); const note1 = await models().item().loadByJopId(user1.id, '00000000000000000000000000000001'); const totalSize1 = await models().item().calculateUserTotalSize(user1.id); const totalSize2 = await models().item().calculateUserTotalSize(user2.id); const totalSize3 = await models().item().calculateUserTotalSize(user3.id); const expected1 = folder1.content_size + folder2.content_size + note1.content_size; const expected2 = folder1.content_size + note1.content_size; const expected3 = 0; expect(totalSize1).toBe(expected1); expect(totalSize2).toBe(expected2); expect(totalSize3).toBe(expected3); await models().item().updateTotalSizes(); expect((await models().user().load(user1.id)).total_item_size).toBe(expected1); expect((await models().user().load(user2.id)).total_item_size).toBe(expected2); expect((await models().user().load(user3.id)).total_item_size).toBe(expected3); }); test('should respect the hard item size limit', async function() { const { user: user1 } = await createUserAndSession(1); let models = newModelFactory(db(), config()); let result = await models.item().saveFromRawContent(user1, { body: Buffer.from('1234'), name: 'test1.txt', }); const item = result['test1.txt'].item; config().itemSizeHardLimit = 3; models = newModelFactory(db(), config()); result = await models.item().saveFromRawContent(user1, { body: Buffer.from('1234'), name: 'test2.txt', }); expect(result['test2.txt'].error.httpCode).toBe(ErrorPayloadTooLarge.httpCode); await expectHttpError(async () => models.item().loadWithContent(item.id), ErrorPayloadTooLarge.httpCode); config().itemSizeHardLimit = 1000; models = newModelFactory(db(), config()); await expectNotThrow(async () => models.item().loadWithContent(item.id)); }); const setupImportContentTest = async () => { const tempDir1 = await tempDir('storage1'); const tempDir2 = await tempDir('storage2'); const fromStorageConfig = { type: StorageDriverType.Filesystem, path: tempDir1, }; const toStorageConfig = { type: StorageDriverType.Filesystem, path: tempDir2, }; const fromModels = newModelFactory(db(), { ...config(), storageDriver: fromStorageConfig, }); const toModels = newModelFactory(db(), { ...config(), storageDriver: toStorageConfig, }); const fromDriver = await loadStorageDriver(fromStorageConfig, db()); const toDriver = await loadStorageDriver(toStorageConfig, db()); return { fromStorageConfig, toStorageConfig, fromModels, toModels, fromDriver, toDriver, }; }; test('should allow importing content to item storage', async function() { const { user: user1 } = await createUserAndSession(1); const { toStorageConfig, fromModels, fromDriver, toDriver, } = await setupImportContentTest(); await fromModels.item().saveFromRawContent(user1, { body: Buffer.from(JSON.stringify({ 'version': 1 })), name: 'info.json', }); const itemBefore = (await fromModels.item().all())[0]; const fromContent = await fromDriver.read(itemBefore.id, { models: fromModels }); expect(fromContent.toString()).toBe('{"version":1}'); expect(itemBefore.content_storage_id).toBe(1); await msleep(2); const toModels = newModelFactory(db(), { ...config(), storageDriver: toStorageConfig, }); const result = await toModels.item().saveFromRawContent(user1, { body: Buffer.from(JSON.stringify({ 'version': 2 })), name: 'info2.json', }); const itemBefore2 = result['info2.json'].item; await fromModels.item().importContentToStorage(toStorageConfig); const itemAfter = (await fromModels.item().all()).find(it => it.id === itemBefore.id); expect(itemAfter.content_storage_id).toBe(2); expect(itemAfter.updated_time).toBe(itemBefore.updated_time); // Just check the second item has not been processed since it was // already on the right storage const itemAfter2 = (await fromModels.item().all()).find(it => it.id === itemBefore2.id); expect(itemAfter2.content_storage_id).toBe(2); expect(itemAfter2.updated_time).toBe(itemBefore2.updated_time); const toContent = await toDriver.read(itemAfter.id, { models: fromModels }); expect(toContent.toString()).toBe(fromContent.toString()); }); test('should skip large items when importing content to item storage', async function() { const { user: user1 } = await createUserAndSession(1); const { toStorageConfig, fromModels, fromDriver, toDriver, } = await setupImportContentTest(); const result = await fromModels.item().saveFromRawContent(user1, { body: Buffer.from(JSON.stringify({ 'version': 1 })), name: 'info.json', }); const itemId = result['info.json'].item.id; expect(await fromDriver.exists(itemId, { models: fromModels })).toBe(true); await fromModels.item().importContentToStorage(toStorageConfig, { maxContentSize: 1, }); expect(await toDriver.exists(itemId, { models: fromModels })).toBe(false); await fromModels.item().importContentToStorage(toStorageConfig, { maxContentSize: 999999, }); expect(await toDriver.exists(itemId, { models: fromModels })).toBe(true); }); test('should delete the database item content', async function() { if (isSqlite(db())) { expect(1).toBe(1); return; } const { user: user1 } = await createUserAndSession(1); await createItemTree3(user1.id, '', '', [ { id: '000000000000000000000000000000F1', children: [ { id: '00000000000000000000000000000001' }, ], }, ]); const folder1 = await models().item().loadByName(user1.id, '000000000000000000000000000000F1.md'); const note1 = await models().item().loadByName(user1.id, '00000000000000000000000000000001.md'); await msleep(1); expect(await models().item().dbContent(folder1.id)).not.toEqual(Buffer.from('')); expect(await models().item().dbContent(note1.id)).not.toEqual(Buffer.from('')); await models().item().deleteDatabaseContentColumn({ batchSize: 1 }); const folder1_v2 = await models().item().loadByName(user1.id, '000000000000000000000000000000F1.md'); const note1_v2 = await models().item().loadByName(user1.id, '00000000000000000000000000000001.md'); expect(folder1.updated_time).toBe(folder1_v2.updated_time); expect(note1.updated_time).toBe(note1_v2.updated_time); expect(await models().item().dbContent(folder1.id)).toEqual(Buffer.from('')); expect(await models().item().dbContent(note1.id)).toEqual(Buffer.from('')); }); test('should delete the database item content - maxProcessedItems handling', async function() { if (isSqlite(db())) { expect(1).toBe(1); return; } const { user: user1 } = await createUserAndSession(1); await createItemTree3(user1.id, '', '', [ { id: '000000000000000000000000000000F1', children: [ { id: '00000000000000000000000000000001' }, { id: '00000000000000000000000000000002' }, { id: '00000000000000000000000000000003' }, { id: '00000000000000000000000000000004' }, ], }, ]); await models().item().deleteDatabaseContentColumn({ batchSize: 2, maxProcessedItems: 4 }); const itemIds = (await models().item().all()).map(it => it.id); const contents = await Promise.all([ models().item().dbContent(itemIds[0]), models().item().dbContent(itemIds[1]), models().item().dbContent(itemIds[2]), models().item().dbContent(itemIds[3]), models().item().dbContent(itemIds[4]), ]); const emptyOnes = contents.filter(c => c.toString() === ''); expect(emptyOnes.length).toBe(4); }); // test('should stop importing item if it has been deleted', async function() { // const { user: user1 } = await createUserAndSession(1); // const tempDir1 = await tempDir('storage1'); // const driver = await loadStorageDriver({ // type: StorageDriverType.Filesystem, // path: tempDir1, // }, db()); // let waitWrite = false; // const previousWrite = driver.write.bind(driver); // driver.write = async (itemId:string, content:Buffer, context: Context) => { // return new Promise((resolve) => { // const iid = setInterval(async () => { // if (waitWrite) return; // clearInterval(iid); // await previousWrite(itemId, content, context); // resolve(null); // }, 10); // }); // } // await models().item().saveFromRawContent(user1, { // body: Buffer.from(JSON.stringify({ 'version': 1 })), // name: 'info.json', // }); // const item = (await models().item().all())[0]; // const promise = models().item().importContentToStorage(driver); // waitWrite = false; // await promise; // expect(await driver.exists(item.id, { models: models() })).toBe(true); // { // const result = await models().item().saveFromRawContent(user1, { // body: Buffer.from(JSON.stringify({ 'version': 2 })), // name: 'info2.json', // }); // const item2 = result['info2.json'].item; // waitWrite = true; // const promise = models().item().importContentToStorage(driver); // await msleep(100); // await models().item().delete(item2.id); // waitWrite = false; // await promise; // expect(await driver.exists(item2.id, { models: models() })).toBe(false); // } // }); });
the_stack
import { AfterContentInit, Directive, ElementRef, forwardRef, HostBinding, Input, OnDestroy, OnInit, Renderer2, Self, ContentChildren, QueryList, Host, SkipSelf, HostListener, Inject, Output, EventEmitter } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { MDCLineRippleFoundation, MDCLineRippleAdapter } from '@material/line-ripple'; import { MDCSelectFoundation, MDCSelectAdapter, cssClasses, strings } from '@material/select'; import { Subject, merge } from 'rxjs'; import { takeUntil, debounceTime } from 'rxjs/operators'; import { MdcFloatingLabelDirective } from '../floating-label/mdc.floating-label.directive'; import { AbstractMdcRipple } from '../ripple/abstract.mdc.ripple'; import { MdcEventRegistry } from '../../utils/mdc.event.registry'; import { MdcNotchedOutlineDirective } from '../notched-outline/mdc.notched-outline.directive'; import { MdcMenuDirective } from '../menu/mdc.menu.directive'; import { MdcMenuSurfaceDirective } from '../menu-surface/mdc.menu-surface.directive'; import { MdcListFunction, MdcListDirective } from '../list/mdc.list.directive'; import { HasId } from '../abstract/mixin.mdc.hasid'; import { applyMixins } from '../../utils/mixins'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; import { asBoolean } from '../../utils/value.utils'; @Directive() class MdcSelectTextDirectiveBase {} interface MdcSelectTextDirectiveBase extends HasId {} applyMixins(MdcSelectTextDirectiveBase, [HasId]); /** * Directive for showing the text of the currently selected `mdcSelect` item. It is the responsibility * of the host component to set the actual text (see examples). This makes the `mdcSelect` more flexible, * so that e.g. the text of options can also contain markup to style parts of it differently. * When no value is selected, the embedded text must be empty. * * # Accessibility * * When no `id` is assigned, the component will generate a unique `id`, so that the `mdcSelectAnchor` * and `mdcList` for this select can be labelled (with `aria-labelledBy`) appropriately. * * The element will be made focusable and tabbable (with `tabindex=0`), unless disabled. * * The `aria-disabled` will get a value based on the `disabled` property of the `mdcSelect`. * * The `aria-required` will get a value based on the `required` property of the `mdcSelect`. * * The `role` attribute will be set to `button`. * * The `aria-haspopup` attribute will be set to `listbox`. * * The `aria-labelledBy` attribute will list the ids of the `mdcFloatinglabel` and the `mdcSelectText` self. * * The `aria-expanded` attribute will reflect whether this element is focused (the menu-surface is open). */ @Directive({ selector: '[mdcSelectText]' }) export class MdcSelectTextDirective extends MdcSelectTextDirectiveBase implements OnInit { /** @internal */ @HostBinding('class.mdc-select__selected-text') readonly _cls = true; /** @internal */ @HostBinding('attr.role') _role = 'button'; /** @internal */ @HostBinding('attr.aria-haspopup') _haspop = 'listbox'; /** @internal */ @HostBinding('attr.aria-labelledby') _labelledBy: string | null = null; constructor(public _elm: ElementRef, @Host() @SkipSelf() @Inject(forwardRef(() => MdcSelectDirective)) private select: MdcSelectDirective) { super(); } ngOnInit() { this.initId(); } /** @internal */ @HostListener('focus') _onFocus() { this.select.foundation?.handleFocus(); } /** @internal */ @HostListener('blur') _onBlur() { this.select.onBlur(); } /** @internal */ @HostListener('keydown', ['$event']) _onKeydown(event: KeyboardEvent) { this.select.foundation?.handleKeydown(event); } /** @internal */ @HostListener('click', ['$event']) _onClick(event: MouseEvent | TouchEvent) { this.select.foundation?.handleClick(this.getNormalizedXCoordinate(event)); } private getNormalizedXCoordinate(event: MouseEvent | TouchEvent): number { const targetClientRect = (event.target as Element).getBoundingClientRect(); const xCoordinate = !!((event as TouchEvent).touches) ? (event as TouchEvent).touches[0].clientX : (event as MouseEvent).clientX; return xCoordinate - targetClientRect.left; } } /** * The `mdcSelectAnchor` should be the first child of an `mdcSelect`. It contains the dropdown-icon, * `mdcSelectText`, `mdcFloatingLabel`, ripples, and may contain an optional `mdcNotchedOutline`. * See the examples for the required structure of these directives. */ @Directive({ selector: '[mdcSelectAnchor]' }) export class MdcSelectAnchorDirective extends AbstractMdcRipple implements AfterContentInit, OnDestroy { private onDestroy$: Subject<any> = new Subject(); private onLabelsChange$: Subject<any> = new Subject(); /** @internal */ @HostBinding('class.mdc-select__anchor') readonly _cls = true; /** @internal */ @ContentChildren(MdcFloatingLabelDirective, {descendants: true}) _floatingLabels?: QueryList<MdcFloatingLabelDirective>; /** @internal */ @ContentChildren(MdcNotchedOutlineDirective) _outlines?: QueryList<MdcNotchedOutlineDirective>; /** @internal */ @ContentChildren(MdcSelectTextDirective) _texts?: QueryList<MdcSelectTextDirective>; private _bottomLineElm: HTMLElement | null = null; /** @internal */ bottomLineFoundation: MDCLineRippleFoundation | null = null; private mdcLineRippleAdapter: MDCLineRippleAdapter = { addClass: (className) => this.rndr.addClass(this._bottomLineElm, className), removeClass: (className) => this.rndr.removeClass(this._bottomLineElm, className), hasClass: (className) => this._bottomLineElm!.classList.contains(className), setStyle: (name, value) => this.rndr.setStyle(this._bottomLineElm, name, value), registerEventHandler: (evtType, handler) => this._registry.listenElm(this.rndr, evtType, handler, this._bottomLineElm!), deregisterEventHandler: (evtType, handler) => this._registry.unlisten(evtType, handler) }; constructor(public _elm: ElementRef, private rndr: Renderer2, registry: MdcEventRegistry, @Host() @SkipSelf() @Inject(forwardRef(() => MdcSelectDirective)) private select: MdcSelectDirective, @Inject(DOCUMENT) doc: any) { super(_elm, rndr, registry, doc as Document); } ngAfterContentInit() { merge( this._floatingLabels!.changes, this._outlines!.changes ).pipe( takeUntil(this.onDestroy$), debounceTime(1) ).subscribe(() => { this.reconstructComponent(); }); merge(this._floatingLabels!.changes, this._texts!.changes).pipe(takeUntil(this.onDestroy$)).subscribe(() => { this.onLabelsChange$.next(); this._label?.idChange().pipe(takeUntil(this.onLabelsChange$)).subscribe(() => { this.computeLabelledBy(); }); this._text?.idChange().pipe(takeUntil(this.onLabelsChange$)).subscribe(() => { this.computeLabelledBy(); }); this.computeLabelledBy(); }); this.addIcon(); this.initComponent(); this.computeLabelledBy(); } ngOnDestroy() { this.onLabelsChange$.next(); this.onLabelsChange$.complete(); this.onDestroy$.next(); this.onDestroy$.complete(); this.destroyRipple(); this.destroyLineRipple(); } private initComponent() { if (!this._outline) { this.initLineRipple(); this.initRipple(); } } private destroyComponent() { this.destroyRipple(); this.destroyLineRipple(); } private reconstructComponent() { this.destroyComponent(); this.initComponent(); } private addIcon() { const icon = this.rndr.createElement('i'); this.rndr.addClass(icon, 'mdc-select__dropdown-icon'); if (this._elm.nativeElement.children.length > 0) this.rndr.insertBefore(this._elm.nativeElement, icon, this._elm.nativeElement.children.item(0)); else this.rndr.appendChild(this._elm.nativeElement, icon); } private initLineRipple() { if (!this._bottomLineElm) { this._bottomLineElm = this.rndr.createElement('div'); this.rndr.addClass(this._bottomLineElm, 'mdc-line-ripple'); this.rndr.appendChild(this._elm.nativeElement, this._bottomLineElm); this.bottomLineFoundation = new MDCLineRippleFoundation(this.mdcLineRippleAdapter); this.bottomLineFoundation.init(); } } private destroyLineRipple() { if (this._bottomLineElm) { this.bottomLineFoundation!.destroy(); this.bottomLineFoundation = null; this.rndr.removeChild(this._elm.nativeElement, this._bottomLineElm); this._bottomLineElm = null; } } private computeLabelledBy() { let ids = []; const labelId = this._label?.id; if (labelId) ids.push(labelId) const textId = this._text?.id; if (textId) ids.push(textId); if (this._text) this._text._labelledBy = ids.join(' '); this.select.setListLabelledBy(labelId || null); // the list should only use the id of the label } /** @internal */ get _outline() { return this._outlines?.first; } /** @internal */ get _label() { return this._floatingLabels?.first; } /** @internal */ get _text() { return this._texts?.first; } } /** * Directive for the options list of an `mdcSelect`. This directive should be the second (last) child * of an `mdcSelect`, and should wrap an `mdcList` with all selection options. * See the examples for the required structure of these directives. * * An `mdcSelectMenu` element will also match with the selector of the menu surface directive, documented * <a href="/components/menu-surface#mdcMenuSurface">here: mdcMenuSurface API</a>. */ @Directive({ selector: '[mdcSelectMenu]' }) export class MdcSelectMenuDirective { /** @internal */ @HostBinding('class.mdc-select__menu') readonly _cls = true; constructor(@Self() public _menu: MdcMenuDirective, @Self() public _surface: MdcMenuSurfaceDirective) {} } /** @docs-private */ enum ValueSource { control, foundation, program }; /** * Directive for a spec aligned material design 'Select Control'. This directive should contain * and `mdcSelectAnchor` and an `mdcSelectMenu`. See the examples for the required structure of * these directives. * * If leaving the select empty should be a valid option, include an `mdcListItem` as first element in the list, * with an ampty string as `value`. * * # Accessibility * * This directive implements the aria practices recommendations for a * [listbox](https://www.w3.org/TR/wai-aria-practices/examples/listbox/listbox-collapsible.html). * Most `aria-*` and `role` attributes affect the embedded `mdcSelectAnchor`, and `mdcList`, and are * explained in the documentation for these directives. */ @Directive({ selector: '[mdcSelect]' }) export class MdcSelectDirective implements AfterContentInit, OnDestroy { /** @internal */ @HostBinding('class.mdc-select') readonly _cls = true; private onDestroy$: Subject<any> = new Subject(); private onMenuChange$: Subject<any> = new Subject(); private onItemsChange$: Subject<any> = new Subject(); private document: Document; private _onChange: (value: any) => void = () => {}; private _onTouched: () => any = () => {}; private _lastMenu: MdcSelectMenuDirective | null = null; private _value: string | null = null; private _valueSource: ValueSource | null = null; private _disabled = false; private _required = false; private _listLabelledBy: string | null = null; /** * emits the value of the item when the selected item changes */ @Output() readonly valueChange: EventEmitter<string | null> = new EventEmitter(); /** @internal */ @ContentChildren(MdcSelectAnchorDirective) _anchors?: QueryList<MdcSelectAnchorDirective>; /** @internal */ @ContentChildren(MdcNotchedOutlineDirective, {descendants: true}) _outlines?: QueryList<MdcNotchedOutlineDirective>; /** @internal */ @ContentChildren(MdcSelectMenuDirective) _menus?: QueryList<MdcSelectMenuDirective>; /** @internal */ @ContentChildren(MdcListDirective, {descendants: true}) _lists?: QueryList<MdcListDirective>; /** @internal */ @ContentChildren(MdcSelectTextDirective, {descendants: true}) _texts?: QueryList<MdcSelectTextDirective>; private mdcAdapter: MDCSelectAdapter = { addClass: (className) => this.rndr.addClass(this.elm.nativeElement, className), removeClass: (className) => this.rndr.removeClass(this.elm.nativeElement, className), hasClass: (className) => this.elm.nativeElement.classList.contains(className), activateBottomLine: () => this.anchor?.bottomLineFoundation?.activate(), deactivateBottomLine: () => this.anchor?.bottomLineFoundation?.deactivate(), getSelectedMenuItem: () => this.getSelectedItem()?._elm.nativeElement, hasLabel: () => !!this.label, floatLabel: (shouldFloat) => this.label?.float(shouldFloat), getLabelWidth: () => this.label?.getWidth() || 0, hasOutline: () => !!this.anchor?._outline, notchOutline: (labelWidth) => this.anchor?._outline!.open(labelWidth), closeOutline: () => this.anchor?._outline!.close(), setRippleCenter: (normalizedX) => this.anchor?.bottomLineFoundation?.setRippleCenter(normalizedX), notifyChange: (value) => this.updateValue(value, ValueSource.foundation), // setSelectedText does nothing, library consumer should set the text; gives them more freedom to e.g. also use markup: setSelectedText: () => undefined, isSelectedTextFocused: () => !!(this.document.activeElement && this.document.activeElement === this.text?._elm.nativeElement), getSelectedTextAttr: (attr) => this.text?._elm.nativeElement.getAttribute(attr), setSelectedTextAttr: (attr, value) => this.text ? this.rndr.setAttribute(this.text._elm.nativeElement, attr, value) : undefined, openMenu: () => this.menu!.openAndFocus(<any>null), closeMenu: () => this.menu!.doClose(), getAnchorElement: () => this.anchor!._elm.nativeElement, setMenuAnchorElement: (anchorEl) => this.surface!.menuAnchor = anchorEl, setMenuAnchorCorner: (anchorCorner) => this.surface!.setFoundationAnchorCorner(anchorCorner), setMenuWrapFocus: () => undefined, // foundation always sets this to false, which is the default anyway - skip setAttributeAtIndex: (index, name, value) => { if (name != strings.ARIA_SELECTED_ATTR) { const item = this.menu?._list?.getItem(index)?._elm.nativeElement; if (item) this.rndr.setAttribute(item, name, value); } }, removeAttributeAtIndex: (index, name) => { if (name !== strings.ARIA_SELECTED_ATTR) { const item = this.menu?._list?.getItem(index)?._elm.nativeElement; if (item) this.rndr.removeAttribute(item, name); } }, focusMenuItemAtIndex: (index) => { const item = this.menu?._list?.getItem(index)?._elm.nativeElement; if (item) item.focus(); }, getMenuItemCount: () => this.menu?._list?.getItems().length || 0, getMenuItemValues: () => this.menu?._list?.getItems().map(item => item.value || '') || [], // foundation uses this to 'setSelectedText', but that's ignored in our implementation (see remark on setSelectedText): getMenuItemTextAtIndex: () => '', getMenuItemAttr: (menuItem, attr) => { if (attr === strings.VALUE_ATTR) return this.menu?._list?.getItemByElement(menuItem)?.value || null; return menuItem.getAttribute(attr); }, addClassAtIndex: (index, className) => { const item = this.menu?._list?.getItem(index); if (item && className === cssClasses.SELECTED_ITEM_CLASS) { item.active = true; } else if (item) this.rndr.addClass(item._elm.nativeElement, className); }, removeClassAtIndex: (index, className) => { const item = this.menu?._list?.getItem(index); if (item && className === cssClasses.SELECTED_ITEM_CLASS) { item.active = false; } else if (item) this.rndr.removeClass(this.menu!._list.getItem(index)!._elm.nativeElement, className); } }; /** @internal */ foundation: MDCSelectFoundation | null = null; constructor(private elm: ElementRef, private rndr: Renderer2, @Inject(DOCUMENT) doc: any) { this.document = doc as Document; } ngAfterContentInit() { this._lastMenu = this._menus!.first; this._menus!.changes.subscribe(() => { if (this._lastMenu !== this._menus!.first) { this.onMenuChange$.next(); this._lastMenu?._menu.itemValuesChanged.pipe(takeUntil(this.onMenuChange$)).subscribe(() => this.onItemsChange$.next()); this._lastMenu = this._menus!.first; this.setupMenuHandlers(); } }); this._lists!.changes.subscribe(() => this.initListLabel()); merge( this.onMenuChange$, // the foundation initializes with the values of the items, so if they change, the foundation must be reconstructed: this.onItemsChange$, // mdcSelectText change needs a complete re-init as well: this._texts!.changes, // when an outline is added/removed, a re-init is needed as well: this._outlines!.changes ).pipe( takeUntil(this.onDestroy$), debounceTime(1) ).subscribe(() => { this.reconstructComponent(); }); this.initComponent(); this.setupMenuHandlers(); this.initListLabel(); } ngOnDestroy() { this.onMenuChange$.next(); this.onMenuChange$.complete(); this.onDestroy$.next(); this.onDestroy$.complete(); this.onItemsChange$.complete(); this.destroyComponent(); } private initComponent() { this.foundation = new class extends MDCSelectFoundation { isValid() { //TODO: required effect on validity in combination with @angular/forms //TODO: setValid/aria-invalid/helpertext validity return super.isValid(); } }(this.mdcAdapter, { helperText: undefined, leadingIcon: undefined }); this.foundation.init(); // foundation needs a call to setDisabled (even when false), because otherwise // tabindex will not be set correctly: this.foundation.setDisabled(this._disabled); this.foundation.setRequired(this._required); // foundation only updates aria-expanded on open/close, not on initialization: this.mdcAdapter.setSelectedTextAttr('aria-expanded', `${this.surface!.open}`); // TODO: it looks like the foundation doesn't update aria-expanded when the surface is // opened programmatically. } private destroyComponent() { this.foundation?.destroy(); this.foundation = null; } private reconstructComponent() { this.destroyComponent(); this.initComponent(); } private setupMenuHandlers() { if (this.menu) { this.menu._listFunction = MdcListFunction.select; this.menu.pick.pipe(takeUntil(this.onMenuChange$)).subscribe((evt) => { this.foundation?.handleMenuItemAction(evt.index); }); this.surface!.afterOpened.pipe(takeUntil(this.onMenuChange$)).subscribe(() => { this.foundation?.handleMenuOpened(); }); this.surface!.afterClosed.pipe(takeUntil(this.onMenuChange$)).subscribe(() => { this.foundation?.handleMenuClosed(); }); } } private initListLabel() { this._lists!.forEach(list => { list.labelledBy = this._listLabelledBy; }); } /** * The value of the selected item. */ @Input() get value() { return this._value; } set value(value: string | null) { this.updateValue(value, ValueSource.program); } /** @internal */ updateValue(value: string | null, source: ValueSource) { const oldSource = this._valueSource; try { if (!this._valueSource) this._valueSource = source; if (source === ValueSource.foundation) { this._value = value; Promise.resolve().then(() => { this.valueChange.emit(value); if (this._valueSource !== ValueSource.control) this._onChange(value); }); } else if (value !== this.value) { if (this.foundation) { this.foundation.setValue(value!); // foundation should also accept null value // foundation will do a nested call for this function with source===foundation // there we will handle the value change and emit to observers (see the if block preceding this) } else { this._value = value; Promise.resolve().then(() => { this.valueChange.emit(value); if (this._valueSource !== ValueSource.control) this._onChange(value); }); } } } finally { this._valueSource = oldSource; } } /** * To disable the select, set this input to a value other then false. */ @Input() get disabled() { return this._disabled; } set disabled(value: boolean) { this._disabled = asBoolean(value); this.foundation?.setDisabled(this._disabled); } static ngAcceptInputType_disabled: boolean | ''; /** * To make the select a required input, set this input to a value other then false. */ @Input() get required() { return this._required; } set required(value: boolean) { this._required = asBoolean(value); this.foundation?.setRequired(this._required); } static ngAcceptInputType_required: boolean | ''; /** @internal */ @HostBinding('class.mdc-select--outlined') get outlined() { return !!this.anchor?._outline; } /** @internal */ @HostBinding('class.mdc-select--no-label') get labeled() { return !this.anchor?._label; } /** @internal */ setListLabelledBy(id: string | null) { this._listLabelledBy = id; this.initListLabel(); } /** @internal */ get expanded() { return !!this.surface?.open; } private get menu() { return this._menus?.first?._menu; } private get surface() { return this._menus?.first?._surface; } private get anchor() { return this._anchors?.first; } private get label() { return this.anchor?._label; } private get text() { return this._texts?.first; } private getSelectedItem() { return this.menu?._list?.getSelectedItem(); } /** @internal */ registerOnChange(onChange: (value: any) => void) { this._onChange = onChange; } /** @internal */ registerOnTouched(onTouched: () => any) { this._onTouched = onTouched; } /** @internal */ onBlur() { this.foundation?.handleBlur(); this._onTouched(); } } /** * Directive for adding Angular Forms (<code>ControlValueAccessor</code>) behavior to an * `mdcSelect`. Allows the use of the Angular Forms API with select inputs, * e.g. binding to <code>[(ngModel)]</code>, form validation, etc. */ @Directive({ selector: '[mdcSelect][formControlName],[mdcSelect][formControl],[mdcSelect][ngModel]', providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdcFormsSelectDirective), multi: true} ] }) export class MdcFormsSelectDirective implements ControlValueAccessor { constructor(@Self() private mdcSelect: MdcSelectDirective) { } /** @docs-private */ writeValue(obj: any) { this.mdcSelect.updateValue(obj, ValueSource.control); } /** @docs-private */ registerOnChange(onChange: (value: any) => void) { this.mdcSelect.registerOnChange(onChange); } /** @docs-private */ registerOnTouched(onTouched: () => any) { this.mdcSelect.registerOnTouched(onTouched); } /** @docs-private */ setDisabledState(disabled: boolean) { this.mdcSelect.disabled = disabled; } } export const SELECT_DIRECTIVES = [ MdcSelectTextDirective, MdcSelectAnchorDirective, MdcSelectMenuDirective, MdcSelectDirective, MdcFormsSelectDirective ];
the_stack
import * as ko from "knockout"; import React from "react"; import NewVertexIcon from "../../../images/NewVertex.svg"; import StyleIcon from "../../../images/Style.svg"; import { DatabaseAccount } from "../../Contracts/DataModels"; import * as ViewModels from "../../Contracts/ViewModels"; import { useSidePanel } from "../../hooks/useSidePanel"; import { CommandButtonComponentProps } from "../Controls/CommandButton/CommandButtonComponent"; import { GraphAccessor, GraphExplorer, GraphExplorerError, GraphExplorerProps, } from "../Graph/GraphExplorerComponent/GraphExplorer"; import { GraphStylingPanel } from "../Panes/GraphStylingPanel/GraphStylingPanel"; import { NewVertexPanel } from "../Panes/NewVertexPanel/NewVertexPanel"; import TabsBase from "./TabsBase"; export interface GraphIconMap { [key: string]: { data: string; format: string }; } export interface GraphConfig { nodeColor: ko.Observable<string>; nodeColorKey: ko.Observable<string>; // map property to node color. Takes precedence over nodeColor unless undefined linkColor: ko.Observable<string>; showNeighborType: ko.Observable<ViewModels.NeighborType>; nodeCaption: ko.Observable<string>; nodeSize: ko.Observable<number>; linkWidth: ko.Observable<number>; nodeIconKey: ko.Observable<string>; iconsMap: ko.Observable<GraphIconMap>; } export interface IGraphConfig { nodeColor: string; nodeColorKey: string; linkColor: string; showNeighborType: ViewModels.NeighborType; nodeCaption: string; nodeSize: number; linkWidth: number; nodeIconKey: string; iconsMap: GraphIconMap; } interface GraphTabOptions extends ViewModels.TabOptions { account: DatabaseAccount; masterKey: string; collectionId: string; databaseId: string; collectionPartitionKeyProperty: string; } // export default class GraphTab extends React.Component<GraphTabProps, GraphTabStates> { export default class GraphTab extends TabsBase { // Graph default configuration public static readonly DEFAULT_NODE_CAPTION = "id"; private static readonly LINK_COLOR = "#aaa"; private static readonly NODE_SIZE = 10; private static readonly NODE_COLOR = "orange"; private static readonly LINK_WIDTH = 1; private graphExplorerProps: GraphExplorerProps; private isNewVertexDisabled: ko.Observable<boolean>; private isPropertyEditing: ko.Observable<boolean>; private isGraphDisplayed: ko.Observable<boolean>; private graphAccessor: GraphAccessor; private igraphConfig: IGraphConfig; private igraphConfigUiData: ViewModels.IGraphConfigUiData; private isFilterQueryLoading: ko.Observable<boolean>; private isValidQuery: ko.Observable<boolean>; private collectionPartitionKeyProperty: string; public graphExplorer: GraphExplorer; public options: GraphTabOptions; constructor(options: GraphTabOptions) { super(options); this.collectionPartitionKeyProperty = options.collectionPartitionKeyProperty; this.isNewVertexDisabled = ko.observable(false); this.isPropertyEditing = ko.observable(false); this.isGraphDisplayed = ko.observable(false); this.graphAccessor = undefined; this.igraphConfig = GraphTab.createIGraphConfig(); this.igraphConfigUiData = GraphTab.createIGraphConfigUiData(this.igraphConfig); this.graphExplorerProps = { onGraphAccessorCreated: (instance: GraphAccessor): void => { this.graphAccessor = instance; }, onIsNewVertexDisabledChange: (isDisabled: boolean): void => { this.isNewVertexDisabled(isDisabled); this.updateNavbarWithTabsButtons(); }, onIsPropertyEditing: (isEditing: boolean) => { this.isPropertyEditing(isEditing); this.updateNavbarWithTabsButtons(); }, onIsGraphDisplayed: (isDisplayed: boolean) => { this.isGraphDisplayed(isDisplayed); this.updateNavbarWithTabsButtons(); }, onResetDefaultGraphConfigValues: () => this.setDefaultIGraphConfigValues(), igraphConfig: this.igraphConfig, igraphConfigUiData: this.igraphConfigUiData, onIsFilterQueryLoadingChange: (isFilterQueryLoading: boolean): void => this.isFilterQueryLoading(isFilterQueryLoading), onIsValidQueryChange: (isValidQuery: boolean): void => this.isValidQuery(isValidQuery), collectionPartitionKeyProperty: options.collectionPartitionKeyProperty, graphBackendEndpoint: GraphTab.getGremlinEndpoint(options.account), databaseId: options.databaseId, collectionId: options.collectionId, masterKey: options.masterKey, onLoadStartKey: options.onLoadStartKey, onLoadStartKeyChange: (onLoadStartKey: number): void => { if (onLoadStartKey === undefined) { this.onLoadStartKey = undefined; } }, resourceId: options.account.id, setIConfigUiData: this.setIGraphConfigUiData, }; this.isFilterQueryLoading = ko.observable(false); this.isValidQuery = ko.observable(true); // this.setCaption = this.setCaption.bind(this); } public static getGremlinEndpoint(account: DatabaseAccount): string { return account.properties.gremlinEndpoint ? GraphTab.sanitizeHost(account.properties.gremlinEndpoint) : `${account.name}.graphs.azure.com:443/`; } public render(): JSX.Element { return ( <div className="graphExplorerContainer" role="tabpanel" id={this.tabId}> <GraphExplorer {...this.graphExplorerProps} /> </div> ); } public onTabClick(): void { super.onTabClick(); this.collection.selectedSubnodeKind(ViewModels.CollectionTabKind.Graph); } /** * Removing leading http|https and remove trailing / * @param url * @return */ private static sanitizeHost(url: string): string { if (!url) { return url; } return url.replace(/^(http|https):\/\//, "").replace(/\/$/, ""); } /* Command bar */ private showNewVertexEditor(): void { useSidePanel.getState().openSidePanel( "New Vertex", <NewVertexPanel partitionKeyPropertyProp={this.collectionPartitionKeyProperty} onSubmit={( result: ViewModels.NewVertexData, onError: (errorMessage: string) => void, onSuccess: () => void ): void => { this.graphAccessor.addVertex(result).then( () => { onSuccess(); useSidePanel.getState().closeSidePanel(); }, (error: GraphExplorerError) => { onError(error.title); } ); }} /> ); } public openStyling(): void { useSidePanel.getState().openSidePanel( "Graph Style", <GraphStylingPanel igraphConfigUiData={this.igraphConfigUiData} igraphConfig={this.igraphConfig} getValues={(igraphConfig?: IGraphConfig): void => { this.igraphConfig = igraphConfig; this.graphAccessor.shareIGraphConfig(igraphConfig); }} /> ); } setIGraphConfigUiData = (val: string[]): void => { if (val.length > 0) { this.igraphConfigUiData = { showNeighborType: ViewModels.NeighborType.TARGETS_ONLY, nodeProperties: val, nodePropertiesWithNone: [GraphExplorer.NONE_CHOICE].concat(val), nodeCaptionChoice: this.igraphConfig.nodeCaption, nodeColorKeyChoice: "None", nodeIconChoice: "Node", nodeIconSet: "", }; } }; public static createIGraphConfig(): IGraphConfig { return { nodeColor: GraphTab.NODE_COLOR, nodeColorKey: "None", linkColor: GraphTab.LINK_COLOR, showNeighborType: ViewModels.NeighborType.TARGETS_ONLY, nodeCaption: GraphTab.DEFAULT_NODE_CAPTION, nodeSize: GraphTab.NODE_SIZE, linkWidth: GraphTab.LINK_WIDTH, nodeIconKey: undefined, iconsMap: {}, }; } public static createIGraphConfigUiData(igraphConfig: IGraphConfig): ViewModels.IGraphConfigUiData { return { showNeighborType: igraphConfig.showNeighborType, nodeProperties: [], nodePropertiesWithNone: [], nodeCaptionChoice: igraphConfig.nodeCaption, nodeColorKeyChoice: igraphConfig.nodeIconKey, nodeIconChoice: igraphConfig.nodeIconKey, nodeIconSet: undefined, }; } private setDefaultIGraphConfigValues() { // Assign default values if undefined if (this.igraphConfigUiData.nodeCaptionChoice === undefined && this.igraphConfigUiData.nodeProperties.length > 1) { this.igraphConfigUiData.nodeCaptionChoice = this.igraphConfigUiData.nodeProperties[0]; } if ( this.igraphConfigUiData.nodeColorKeyChoice === undefined && this.igraphConfigUiData.nodePropertiesWithNone.length > 1 ) { this.igraphConfigUiData.nodeColorKeyChoice = this.igraphConfigUiData.nodePropertiesWithNone[0]; } if ( this.igraphConfigUiData.nodeIconChoice === undefined && this.igraphConfigUiData.nodePropertiesWithNone.length > 1 ) { this.igraphConfigUiData.nodeIconChoice = this.igraphConfigUiData.nodePropertiesWithNone[0]; } } protected getTabsButtons(): CommandButtonComponentProps[] { const label = "New Vertex"; const buttons: CommandButtonComponentProps[] = [ { iconSrc: NewVertexIcon, iconAlt: label, onCommandClick: () => this.showNewVertexEditor(), commandButtonLabel: label, ariaLabel: label, hasPopup: false, disabled: this.isNewVertexDisabled(), }, ]; buttons.push(); if (this.isGraphDisplayed()) { const label = "Style"; buttons.push({ iconSrc: StyleIcon, iconAlt: label, onCommandClick: () => this.openStyling(), commandButtonLabel: label, ariaLabel: label, hasPopup: false, disabled: this.isPropertyEditing(), }); } return buttons; } protected buildCommandBarOptions(): void { ko.computed(() => ko.toJSON([this.isNewVertexDisabled])).subscribe(() => this.updateNavbarWithTabsButtons()); this.updateNavbarWithTabsButtons(); } }
the_stack
import type { DMMF } from '@prisma/client/runtime' import dedent from 'dindist' import { chain } from 'lodash' import * as Nexus from 'nexus' import { NexusEnumTypeConfig, NexusListDef, NexusNonNullDef, NexusNullDef } from 'nexus/dist/core' import { MaybePromise, RecordUnknown, Resolver } from '../../helpers/utils' import { PrismaDmmf } from '../../lib/prisma-dmmf' import { PrismaDocumentation } from '../../lib/prisma-documentation' import { PrismaUtils } from '../../lib/prisma-utils' import { Gentime } from '../gentime/settingsSingleton' import { createWhereUniqueInput } from '../../lib/prisma-utils/whereUniqueInput' import { Runtime } from '../runtime/settingsSingleton' import { ModuleSpec } from '../types' import { fieldTypeToGraphQLType } from './declaration' type PrismaEnumName = string type PrismaModelName = string type PrismaModelOrEnumName = string type PrismaFieldName = string type PrismaModelFieldNameOrMetadataFieldName = string type NexusTypeDefConfigurations = Record< PrismaModelOrEnumName, NexusObjectTypeDefConfiguration | NexusEnumTypeDefConfiguration > export type Settings = { runtime: Runtime.Settings gentime: Gentime.SettingsData } /** * Create the module specification for the JavaScript runtime. */ export function createModuleSpec(params: { /** * Resolved generator settings (whatever user supplied merged with defaults). */ gentimeSettings: Gentime.Settings /** * Should the module be generated using ESM instead of CJS? */ esm: boolean /** * Detailed data about the Prisma Schema contents and available operations over its models. */ dmmf: DMMF.Document }): ModuleSpec { const { esm, gentimeSettings, dmmf } = params const esmModelExports = dmmf.datamodel.models .map((model) => { return dedent` export const ${model.name} = models['${model.name}'] ` }) .join('\n') || `// N/A -- You have not defined any models in your Prisma Schema.` const esmEnumExports = dmmf.datamodel.enums .map((enum_) => { return dedent` export const ${enum_.name} = models['${enum_.name}'] ` }) .join('\n') || `// N/A -- You have not defined any enums in your Prisma Schema.` const exports = esm ? dedent` // // Exports // // Static API Exports export const $settings = Runtime.settings.change // Reflected Model Exports ${esmModelExports} // Reflected Enum Exports ${esmEnumExports} ` : dedent` module.exports = { $settings: Runtime.settings.change, ...models, } ` const importSpecifierToNexusPrismaSourceDirectory = gentimeSettings.data.output.directory === 'default' ? `..` : esm ? `nexus-prisma/dist-esm` : `nexus-prisma/dist-cjs` const imports = esm ? dedent` import { getPrismaClientDmmf } from '${importSpecifierToNexusPrismaSourceDirectory}/helpers/prisma' import * as ModelsGenerator from '${importSpecifierToNexusPrismaSourceDirectory}/generator/models/index' import { Runtime } from '${importSpecifierToNexusPrismaSourceDirectory}/generator/runtime/settingsSingleton' ` : dedent` const { getPrismaClientDmmf } = require('${importSpecifierToNexusPrismaSourceDirectory}/helpers/prisma') const ModelsGenerator = require('${importSpecifierToNexusPrismaSourceDirectory}/generator/models/index') const { Runtime } = require('${importSpecifierToNexusPrismaSourceDirectory}/generator/runtime/settingsSingleton') ` return { // TODO this is no longer used, just return content fileName: 'index.js', content: dedent` ${imports} const gentimeSettings = ${JSON.stringify(gentimeSettings.data, null, 2)} const dmmf = getPrismaClientDmmf({ // JSON stringify the values to ensure proper escaping // Details: https://github.com/prisma/nexus-prisma/issues/143 // TODO test that fails without this code require: () => require(${JSON.stringify(gentimeSettings.data.prismaClientImportId)}), importId: gentimeSettings.prismaClientImportId, importIdResolved: require.resolve(${JSON.stringify(gentimeSettings.data.prismaClientImportId)}) }) const models = ModelsGenerator.JS.createNexusTypeDefConfigurations(dmmf, { runtime: Runtime.settings, gentime: gentimeSettings, }) ${exports} `, } } export function createNexusTypeDefConfigurations( dmmf: DMMF.Document, settings: Settings ): NexusTypeDefConfigurations { return { ...createNexusObjectTypeDefConfigurations(dmmf, settings), ...createNexusEnumTypeDefConfigurations(dmmf, settings), } } type NexusObjectTypeDefConfigurations = Record<PrismaModelName, NexusObjectTypeDefConfiguration> type NexusObjectTypeDefConfiguration = Record< PrismaModelFieldNameOrMetadataFieldName, | { name: PrismaFieldName type: NexusNonNullDef<string> | NexusListDef<string> | NexusNullDef<string> description: string } // Metadata fields can be any of these | string | undefined > /** * Create Nexus object type definition configurations for Prisma models found in the given DMMF. */ function createNexusObjectTypeDefConfigurations( dmmf: DMMF.Document, settings: Settings ): NexusObjectTypeDefConfigurations { return chain(dmmf.datamodel.models) .map((model) => { return { $name: model.name, $description: prismaNodeDocumentationToDescription({ settings, node: model }), ...chain(model.fields) .map((field) => { return { name: field.name, type: prismaFieldToNexusType(field, settings), description: prismaNodeDocumentationToDescription({ settings, node: field }), resolve: nexusResolverFromPrismaField(model, field, settings), } }) .keyBy('name') .value(), } }) .keyBy('$name') .value() } const prismaNodeDocumentationToDescription = (params: { settings: Settings node: PrismaDmmf.DocumentableNode }): string | undefined => { return params.settings.gentime.docPropagation.GraphQLDocs && params.node.documentation ? PrismaDocumentation.format(params.node.documentation) : undefined } // Complex return type I don't really understand how to easily work with manually. // eslint-disable-next-line export function prismaFieldToNexusType(field: DMMF.Field, settings: Settings) { const graphqlType = fieldTypeToGraphQLType(field, settings.gentime) if (field.isList) { return Nexus.nonNull(Nexus.list(Nexus.nonNull(graphqlType))) } else if (field.isRequired) { return Nexus.nonNull(graphqlType) } else { return Nexus.nullable(graphqlType) } } /** * Create a GraphQL resolver for the given Prisma field. If the Prisma field is a scalar then no resolver is * returned and instead the Nexus default is relied upon. * * @remarks Allow Nexus default resolver to handle resolving scalars. * * By using Nexus default we also affect its generated types, assuming there are not explicit * source types setup which actually for Nexus Prisma projects there usually will be (the Prisma * model types). Still, using the Nexus default is a bit more idiomatic and provides the better * _default_ type generation experience of scalars being expected to come down from the source * type (aka. parent). * * So: * * ```ts ... * t.field(M1.Foo.bar) * ``` * * where `bar` is a scalar prisma field would have NO resolve generated and thus default Nexus * as mentioned would think that `bar` field WILL be present on the source type. This is, again, * mostly moot since most Nexus Prisma users WILL setup the Prisma source types e.g.: * * ```ts ... * sourceTypes: { modules: [{ module: '.prisma/client', alias: 'PrismaClient' }]}, * ``` * * but this is overall the better way to handle this detail it seems. */ export function nexusResolverFromPrismaField( model: DMMF.Model, field: DMMF.Field, settings: Settings ): undefined | Resolver { if (field.kind !== 'object') { return undefined } return (source: RecordUnknown, _args: RecordUnknown, ctx: RecordUnknown): MaybePromise<unknown> => { const whereUnique = createWhereUniqueInput(source, model) // eslint-disable-next-line const PrismaClientPackage = require(settings.gentime.prismaClientImportId) // eslint-disable-next-line if (!(ctx[settings.runtime.data.prismaClientContextField] instanceof PrismaClientPackage.PrismaClient)) { // TODO rich errors throw new Error( `The GraphQL context.${settings.runtime.data.prismaClientContextField} value is not an instance of the Prisma Client (class reference for check imported from ${settings.gentime.prismaClientImportId}).` ) } // eslint-disable-next-line @typescript-eslint/no-explicit-any const prisma: any = ctx[settings.runtime.data.prismaClientContextField] // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access const prismaModel = prisma[PrismaUtils.typeScriptOrmModelPropertyNameFromModelName(model.name)] // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access if (typeof prismaModel.findUnique !== 'function') { // TODO rich errors throw new Error(`The prisma model ${model.name} does not have a findUnique method available.`) } // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access const findUnique = prismaModel.findUnique as (query: unknown) => MaybePromise<unknown> const result: unknown = findUnique({ where: whereUnique, /** * * The user might have configured Prisma Client globally to rejectOnNotFound. * In the context of this Nexus Prisma managed resolver, we don't want that setting to * be a behavioral factor. Instead, Nexus Prisma has its own documented rules about the logic * it uses to project nullability from the database to the api. * * More details about this design can be found in the README. * * References: * * - https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#rejectonnotfound */ rejectOnNotFound: false, }) // @ts-expect-error Only known at runtime // eslint-disable-next-line return result[field.name]() } } type AnyNexusEnumTypeConfig = NexusEnumTypeConfig<string> type NexusEnumTypeDefConfigurations = Record<PrismaEnumName, NexusEnumTypeDefConfiguration> type NexusEnumTypeDefConfiguration = AnyNexusEnumTypeConfig /** * Create Nexus enum type definition configurations for Prisma enums found in the given DMMF. */ function createNexusEnumTypeDefConfigurations( dmmf: DMMF.Document, settings: Settings ): NexusEnumTypeDefConfigurations { return chain(dmmf.datamodel.enums) .map((enum_): AnyNexusEnumTypeConfig => { return { name: enum_.name, description: prismaNodeDocumentationToDescription({ settings, node: enum_ }), members: enum_.values.map((val) => val.name), } }) .keyBy('name') .value() }
the_stack
declare var highlightedDates: string[]; declare var weekStart: number; namespace Home { declare var bulmaCalendar: any; declare var InlineEditor: any; declare var BulmaTagsInput: any; interface GetDayReponse extends Result { data: DayData; } interface DayData { date: string; content: string; mood: MoodEnum; version: number; tags: string[]; } enum MoodEnum { terrible = -2, unhappy = -1, neutral = 0, happy = 1, joyous = 2 } interface API { getDay(day: string): Promise<GetDayReponse>; postDay(day: DayData): Promise<Result>; deleteDay(day: string): Promise<Result>; } class DocumentStorageAPI implements API { public async getDay(day: string): Promise<GetDayReponse> { let json = localStorage.getItem('entry_' + day); console.log('local storage read entry_' + day); let dayData: DayData; if (typeof json === "undefined" || json === "" || json === null) { dayData = { content: "", date: day, mood: MoodEnum.neutral, version: 1, tags: [] } } else { dayData = JSON.parse(json); } return { success: true, data: dayData }; } public async postDay(day: DayData): Promise<Result> { let json = JSON.stringify(day); console.log("setting item " + json); console.log('local storage write entry_' + day.date); const oldjson = localStorage.getItem('entry_' + day.date); let dayData: DayData; if (typeof oldjson === "undefined" || oldjson === "" || oldjson === null) { } else { dayData = JSON.parse(oldjson); if (dayData.version >= day.version) throw new Error("Entry is out of date"); } localStorage.setItem('entry_' + day.date, json); return { success: true }; } public async deleteDay(day: string): Promise<Result> { localStorage.removeItem('entry_' + day); return { success: true, }; } } class RestAPI implements API { public async getDay(day: string): Promise<GetDayReponse> { return this.get<GetDayReponse>("api/day", { day: day }); } public async postDay(day: DayData): Promise<Result> { return this.post<Result>("api/day", day); } public async deleteDay(day: string): Promise<Result> { return this.post<Result>("api/day", day, "DELETE"); } private async get<T extends Result>(path: string, data?: any): Promise<T> { return new Promise<T>((then, reject) => { $.ajax(path, { cache: false, method: "GET", data: data, success: (data: Result) => { if (data === null || typeof (data) === "undefined") reject("No content"); if (data.success) then(<T>data); else reject(data.message); }, error: (e) => { reject(e.statusText + " - " + e.responseText); } }); }); } private async post<T extends Result>(path: string, data?: any, method:string = "POST"): Promise<T> { return new Promise<T>((then, reject) => { $.ajax(path, { cache: false, method: method, data: JSON.stringify(data), contentType: "application/json; charset=utf-8", success: (data: Result) => { if (data == null || typeof (data) === "undefined") reject("No content"); if (data.success) then(<T>data); else reject(data.message); }, error: (e) => { reject(e.statusText + " - " + e.responseText); } }); }); } } let editor: any = null; let calendars: any[]; let isSettingDataToControls: boolean = false; let isDirty: boolean = false; let loadedSuccessfully = false; let currentDate: string; let currentVersion: number; let tmrAutoSave: number = -1; // use local storage if it's loaded from github.io const api: API = window.location.host.indexOf("github") == -1 ? new RestAPI() : new DocumentStorageAPI(); async function run() { // Initialize all input of type date // TODO once bulma calendar fixes the highlighted dates thing, fetch the dates and highlight them //let highlightDates = [new Date("2020-07-14")]; /*for (let i:number = 0; i < 1000; i++) { highlightDates.push(new Date(new Date("2020-07-12").getTime()-24*3600*1000*i*2)); }*/ let desktopCalendars = bulmaCalendar.attach('#cal', { displayMode: "inline", startDate: new Date(), weekStart: weekStart, showClearButton: false, dateFormat: 'YYYY-MM-DD', // disabledDates: [ new Date(new Date().getTime()-24*3600*1000) ], highlightedDates: highlightedDates.map(d => getDateFromDateString(d)) }); let mobileCalendars = bulmaCalendar.attach('#calMobile', { //displayMode: "inline", startDate: new Date(), weekStart: weekStart, showClearButton: false, dateFormat: 'YYYY-MM-DD', // disabledDates: [ new Date(new Date().getTime()-24*3600*1000) ], highlightedDates: highlightedDates.map(d => getDateFromDateString(d)) }); calendars = [desktopCalendars[0], mobileCalendars[0]]; await initEditor(); for (let calendar of calendars) { calendar.datePicker.on('select', async (date: Date) => { console.log("selected"); if (isSettingDataToControls) return; if (loadedSuccessfully && isDirty) { const success = await saveDay(); if (!success) { alert("Not saved and attempt to save failed"); window.setTimeout(() => { console.log("reverting date to " + currentDate); isSettingDataToControls = true; calendar.value(getDateFromDateString(currentDate)); calendar.refresh(); calendar.datePicker.refresh(); isSettingDataToControls = false; }, 1); return; } } console.log("loading " + calendar.date.start); await loadDay(getDateString(calendar.date.start)); }); } let isSaving = false; $("#pnlUnsaved").click(async () => { if (isSaving) return; isSaving = true; await saveDay(); isSaving = false; }); $("input[name=optMood]").change(() => { updateMoodLabelCheckState(); onControlChange(); }); $("#tags").change(() => { onControlChange(); }); $("#lnkDelete").click(async function () { if (confirm("Are you sure?")) { const result = await api.deleteDay(currentDate); if (result.success) { isDirty = false; document.location.reload(true); } else { alert("Delete failed: " + result.message); } } }); new BulmaTagsInput(document.getElementById("tags"), { freeInput: true, allowDuplicates: false, caseSensitive: false, // itemValue: "value", // itemText: "name", //noResultsLabel: "No results, <a class='lnkAddCurrentTag'>add current search text</a>", // source: [{ name: "work", value: "work" }, { name: "trans", value: "trans" }, { name: "school", value: "school" }] }); /* $(document).on("click", ".lnkAddCurrentTag", null, () => { var tags = <any>$("#tags").get(0); var searchText = tags.BulmaTagsInput().input.value; tags.BulmaTagsInput().add({ name: searchText, value: searchText }); $(tags.BulmaTagsInput().container).removeClass("is-active"); tags.BulmaTagsInput().input.value = ""; }); */ window.addEventListener("beforeunload", function (e) { if (!isDirty) { return undefined; } var confirmationMessage = 'It looks like you have been editing something. ' + 'If you leave before saving, your changes will be lost.'; (e || window.event).returnValue = confirmationMessage; //Gecko + IE return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc. }); const urlParams = new URLSearchParams(window.location.search); let date = urlParams.get('date'); if (date !== null) date = getDateString(new Date(date)); else date = getDateString(new Date()); await loadDay(date); subscribeToEvents(); } function getDateString(date: Date) { date.setHours(23); // damnit timezones return date.toISOString().split("T")[0]; } function getDateFromDateString(dateStr: string) { const date = new Date(dateStr); date.setHours(23); // fix for wrongly interpreted timezone return date; } function subscribeToEvents() { let wsPrefix = document.location.protocol == "https:" ? "wss://" : "ws://"; const ws = new WebSocket(wsPrefix + document.location.host + "/events"); ws.onmessage = function onmessage(ev: MessageEvent) { //console.log("Data received: " + ev.data); var event = <PhotoRequest>JSON.parse(ev.data); handlePhoto(event.Photo); }; ws.onopen = function open() { console.log("open"); }; ws.onerror = function error(ev: Event) { console.log("error " + ev); }; ws.onclose = function close(ev: CloseEvent) { console.log("close " + ev.reason); }; } function handlePhoto(payload: string) { // insert image into editor editor.setData(editor.getData() + payload); // scroll to the bottom $("#editor").get(0).scrollTop = $("#editor").get(0).scrollHeight; } async function initEditor() { if (editor !== null) editor.destroy(); editor = await InlineEditor.create(document.querySelector('#editor'), { toolbar: { items: [ 'heading', 'fontSize', 'fontColor', '|', 'bold', 'italic', 'underline', 'strikethrough', '|', 'indent', 'outdent', '|', 'bulletedList', 'numberedList', 'todoList', '|', 'code', 'blockQuote', 'codeBlock', '|', 'horizontalLine', '|', 'link', 'imageUpload', 'insertTable', 'mediaEmbed', '|', 'undo', 'redo' ] }, language: 'en', image: { toolbar: [ 'imageTextAlternative', 'imageStyle:full', 'imageStyle:side' ] }, table: { contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells' ] }, licenseKey: '', }); //editor = await InlineEditor.create(document.querySelector('#editor')); editor.model.document.on('change:data', () => { onControlChange(); }); } function onControlChange() { if (isSettingDataToControls) return; if (loadedSuccessfully) { setDirty(true); scheduleSave(); } } function setDirty(dirty: boolean) { isDirty = dirty; if (isDirty) { $("#pnlUnsaved").show(); $("#pnlSaved").hide(); } else { $("#pnlUnsaved").hide(); $("#pnlSaved").show(); } } function setAutoSaveError(error: boolean, msg?: string) { if (error) $("#pnlUnsaved").addClass("is-error").attr("title", msg); else $("#pnlUnsaved").removeClass("is-error").attr("title", ""); } function setLoadedSuccessfully(success: boolean) { loadedSuccessfully = success; if (success) { $("#editorContainer").removeClass("is-error"); editor.isReadOnly = false; $("input[name=optMood]").prop("disabled", false); $("#tabs").prop("disabled", false); } else { $("#editorContainer").addClass("is-error"); editor.isReadOnly = true; $("input[name=optMood]").prop("disabled", true); $("#tabs").prop("disabled", true); } } async function loadDay(date: string) { try { const dayData: DayData = (await api.getDay(date)).data; await setDayDataToControls(dayData); setLoadedSuccessfully(true); } catch (err) { alert("Error loading: " + err); setLoadedSuccessfully(false); } // force clear autosave if (tmrAutoSave !== -1) window.clearTimeout(tmrAutoSave); } async function saveDay() { // force clear autosave if (tmrAutoSave !== -1) window.clearTimeout(tmrAutoSave); console.log("Saving"); // increment version currentVersion++; const dayData = getDayDataFromControls(); console.log(JSON.stringify(dayData)); try { const data = await api.postDay(dayData) if (data.success) { // do save call and check if success setDirty(false); setAutoSaveError(false, ""); // add current day to highlight for (let calendar of calendars) { if (calendar.options.highlightedDates.indexOf(currentDate) == -1) calendar.options.highlightedDates.push(currentDate); } } else { // revert increment of version currentVersion--; setAutoSaveError(true, data.message); } return true; } catch (err) { // revert increment of version currentVersion--; setAutoSaveError(true, err); return false; } } function scheduleSave() { if (tmrAutoSave !== -1) window.clearTimeout(tmrAutoSave); tmrAutoSave = window.setTimeout(async () => { await saveDay(); }, 5000); } function updateMoodLabelCheckState() { $(".mood").attr("data-checked", "false"); $("input[name='optMood']:checked").parent().attr("data-checked", "true"); } async function setDayDataToControls(data: DayData) { isSettingDataToControls = true; try { for (let calendar of calendars) { calendar.value(getDateFromDateString(data.date)); calendar.refresh(); calendar.datePicker.refresh(); } currentDate = data.date; currentVersion = data.version; (<any>$("#tags").get(0)).BulmaTagsInput().value = data.tags.join(","); var url = new URL(document.location.toString()); url.searchParams.set("date", data.date); window.history.replaceState({}, "", url.toString()); window.document.title = "Journal " + data.date; // await initEditor(); editor.setData(data.content); setDirty(false); $(`input[name=optMood][value=${data.mood}]`).prop("checked", true); updateMoodLabelCheckState(); } finally { isSettingDataToControls = false; } } function getDayDataFromControls(): DayData { return { date: currentDate, version: currentVersion, content: editor.getData(), mood: parseInt(<string>$("input[name=optMood]:checked").val()), tags: (<any>$("#tags").get(0)).BulmaTagsInput().value.split(",") }; } interface PhotoRequest { Photo: string; } interface Result { success: boolean; message?: string; } run().then(editor => { }).catch(err => { console.error(err); }); }
the_stack
import { IIcon, ImageryVisualizer, IVisualizerEntity, IVisualizersConfig, VisualizerInteractions, VisualizersConfig } from '@ansyn/imagery'; import { cloneDeep as _cloneDeep } from 'lodash'; import Feature from 'ol/Feature'; import Style from 'ol/style/Style'; import Point from 'ol/geom/Point'; import * as condition from 'ol/events/condition'; import Select from 'ol/interaction/Select'; import { Inject } from '@angular/core'; import { Observable } from 'rxjs'; import { Store, select } from '@ngrx/store'; import { MultiLineString } from 'geojson'; import { distinctUntilChanged, pluck, tap } from 'rxjs/operators'; import { AutoSubscription } from 'auto-subscriptions'; import { OpenLayersMap } from '@ansyn/ol'; import { BaseFootprintsVisualizer } from './base-footprints-visualizer'; import { DisplayOverlayFromStoreAction, SetMarkUp } from '../../../../../overlays/actions/overlays.actions'; import { IMarkUpData, IOverlaysState, MarkUpClass, overlaysStateSelector } from '../../../../../overlays/reducers/overlays.reducer'; import { ExtendMap } from '../../../../../overlays/reducers/extendedMap.class'; import { OverlaysService } from '../../../../../overlays/services/overlays.service'; import { getIconSvg } from './arrow-svg'; import { selectOverlaysFootprintActiveByMapId } from '@ansyn/map-facade'; @ImageryVisualizer({ supported: [OpenLayersMap], deps: [Store, VisualizersConfig, OverlaysService], layerClassName: 'footprint-layer' }) export class FootprintPolylineVisualizer extends BaseFootprintsVisualizer { markups: ExtendMap<MarkUpClass, IMarkUpData>; overlaysState$: Observable<IOverlaysState> = this.store.select(overlaysStateSelector); @AutoSubscription dropsMarkUp$: Observable<ExtendMap<MarkUpClass, IMarkUpData>> = this.overlaysState$.pipe( pluck<IOverlaysState, ExtendMap<MarkUpClass, IMarkUpData>>('dropsMarkUp'), distinctUntilChanged(), tap((markups) => this.markups = markups) ); protected disableCache = true; ghostId: string; constructor(public store: Store<any>, @Inject(VisualizersConfig) public config: IVisualizersConfig, public overlaysService: OverlaysService ) { super(store, overlaysService, config.FootprintPolylineVisualizer); this.updateStyle({ opacity: 0.5, initial: { zIndex: this.getZIndex.bind(this), fill: this.getFillColor.bind(this), stroke: this.getStrokeColor.bind(this), 'stroke-width': this.getStrokeWidth.bind(this), 'stroke-opacity': this.getStrokeOpacity.bind(this), shadow: this.getShadow.bind(this), circle: this.getRadius.bind(this), icon: this.getImage.bind(this), geometry: this.getGeometry.bind(this) } }); } selectVisualizerActive = () => this.store.pipe( select(selectOverlaysFootprintActiveByMapId(this.mapId)), ); addOrUpdateEntities(logicalEntities: IVisualizerEntity[]): Observable<boolean> { const conversion = this.convertPolygonToPolyline(logicalEntities); return super.addOrUpdateEntities(conversion); } createPointerMoveInteraction() { const pointerMove = new Select({ condition: condition.pointerMove, style: () => new Style(), layers: [this.vector] }); pointerMove.on('select', this.onSelectFeature.bind(this)); return pointerMove; } onDoubleClickFeature($event) { this.purgeCache(); if ($event.selected.length > 0) { const feature = $event.selected[0]; const id = feature.getId(); this.store.dispatch(new DisplayOverlayFromStoreAction({ id })); } } createDoubleClickInteraction() { const doubleClick = new Select({ condition: condition.doubleClick, style: () => new Style({}), layers: [this.vector] }); doubleClick.on('select', this.onDoubleClickFeature.bind(this)); return doubleClick; } onDispose(): void { this.removeInteraction(VisualizerInteractions.doubleClick); this.removeInteraction(VisualizerInteractions.pointerMove); } /** * Explanation: * 1. This is a callback function, which may get either a select event or an unselect event * 2. Our features are clipped to the extent. But we get events also from outside the extent, * so we need to handle those. * 3. If we get a select event, we check whether it comes from within the extent. If yes, we * fire an action to update the store. If not, we just assign the feature's id to an internal var, ghostId. * 4. If we get an unselect event, we check whether the associated feature's id is equal to ghostId. If yes, * it means that a "ghost" feature outside the extent was unselected. In that case, we just clear the ghostId var. * Otherwise, we fire an action to update the store. * 5. Note that, in the case of an unselect event, we should not check whether it comes from within the * extent or not. Because we may can a real (not ghost) unselect event simply by moving the mouse from the extent * outside. In that case the location of the event will be outside the extent, but it will be a unselect event of * a feature which is inside the extent. */ onSelectFeature($event) { if ($event.selected.length > 0) { const id = $event.selected[0].getId(); if (this.isMouseEventInExtent($event)) { this.store.dispatch(new SetMarkUp({ classToSet: MarkUpClass.hover, dataToSet: { overlaysIds: [id] } })); } else { this.ghostId = id; } } else { if (this.ghostId) { this.ghostId = undefined; } else { this.store.dispatch(new SetMarkUp({ classToSet: MarkUpClass.hover, dataToSet: { overlaysIds: [] } })); } } } public purgeCache(feature?: Feature) { if (feature) { delete (<any>feature).styleCache; } else if (this.source) { let features = this.source.getFeatures(); features.forEach(f => this.purgeCache(f)); } } protected resetInteractions(): void { this.removeInteraction(VisualizerInteractions.doubleClick); this.removeInteraction(VisualizerInteractions.pointerMove); this.addInteraction(VisualizerInteractions.pointerMove, this.createPointerMoveInteraction()); this.addInteraction(VisualizerInteractions.doubleClick, this.createDoubleClickInteraction()); } private propsByFeature(feature: Feature) { const classes = this.markups.findKeysByValue(<string>feature.getId(), 'overlaysIds'); const isFavorites = classes.includes(MarkUpClass.favorites); const isActive = classes.includes(MarkUpClass.active); const isDisplayed = classes.includes(MarkUpClass.displayed); return { isFavorites, isActive, isDisplayed }; } private getFeatureType(feature: Feature): 'MultiLineString' | 'Point' | 'LineString' | 'MultiPolygon' { const type = feature && feature.getGeometry().getType(); if (type && !['MultiLineString', 'Point', 'LineString', 'MultiPolygon'].includes(type)) { console.warn(`polyline-visualizer.ts getFeatureType - unsupported type ${ type }`); } return type; } private getRadius(feature: Feature, hover = false) { if (this.getFeatureType(feature) === 'Point') { return hover ? 8 : 7; } return undefined; } private getZIndex(feature: Feature) { const { isActive, isFavorites, isDisplayed } = this.propsByFeature(feature); return isActive ? 4 : isFavorites ? 3 : isDisplayed ? 2 : 1; } private getFillColor(feature: Feature, hover = false) { const { active, display, favorite, inactive } = this.visualizerStyle.colors; const { isActive, isFavorites, isDisplayed } = this.propsByFeature(feature); switch (this.getFeatureType(feature)) { case 'MultiLineString': case 'MultiPolygon': return hover ? 'white' : 'transparent'; case 'Point' : return isFavorites ? favorite : isActive ? active : !isDisplayed ? inactive : display; case 'LineString': return undefined; } } private getStrokeColor(feature: Feature, hover = false) { const { active, display, favorite, inactive } = this.visualizerStyle.colors; const { isActive, isDisplayed, isFavorites } = this.propsByFeature(feature); switch (this.getFeatureType(feature)) { case 'MultiLineString': case 'MultiPolygon': case 'LineString': return isFavorites ? favorite : isDisplayed ? display : isActive ? active : inactive; case 'Point' : return display; } } private getStrokeOpacity(feature: Feature, hover = false) { return 1; } private getStrokeWidth(feature: Feature, hover = false) { const { isActive, isDisplayed, isFavorites } = this.propsByFeature(feature); switch (feature.getGeometry().getType()) { case 'MultiLineString': case 'MultiPolygon': return isFavorites ? 4 : (isActive || isDisplayed || hover) ? 5 : 3; case 'Point' : return undefined; case 'LineString': return hover ? 7 : 5; } } private getImage(feature, hover = false): IIcon | undefined { if (this.getFeatureType(feature) === 'LineString') { const coordinates = feature.getGeometry().getCoordinates(); const rotation = this.calcArrowAngle(coordinates[0], coordinates[1]); const color = this.getStrokeColor(feature); return { src: getIconSvg(hover ? this.colorWithAlpha(color, 0.5) : color), anchor: [0.5, 0.5], scale: 0.15, rotation, rotateWithView: true } } return undefined; } private getGeometry(feature: Feature) { if (this.getFeatureType(feature) === 'LineString') { const coordinates = feature.getGeometry().getCoordinates(); return new Point(coordinates[0]) } return undefined; } private calcArrowAngle(previousPoint: [number, number], currentPoint: [number, number]): number { const dx = currentPoint[0] - previousPoint[0]; const dy = currentPoint[1] - previousPoint[1]; return Math.atan2(dx, dy); } private getShadow(feature: Feature) { const { isFavorites } = this.propsByFeature(feature); if (!isFavorites) { return; } return { 'stroke-width': 5, stroke: this.visualizerStyle.colors.favorite }; } private convertPolygonToPolyline(logicalEntities: IVisualizerEntity[]): IVisualizerEntity[] { const clonedLogicalEntities = _cloneDeep(logicalEntities); clonedLogicalEntities .filter((entity: IVisualizerEntity) => entity.featureJson.geometry.type === 'MultiPolygon') .forEach((entity: IVisualizerEntity) => { let geometry: MultiLineString = entity.featureJson.geometry; geometry.type = 'MultiLineString'; geometry.coordinates = <any>geometry.coordinates[0]; }); return clonedLogicalEntities; } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {WaiterConfiguration} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class Amp extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Amp.Types.ClientConfiguration) config: Config & Amp.Types.ClientConfiguration; /** * Create an alert manager definition. */ createAlertManagerDefinition(params: Amp.Types.CreateAlertManagerDefinitionRequest, callback?: (err: AWSError, data: Amp.Types.CreateAlertManagerDefinitionResponse) => void): Request<Amp.Types.CreateAlertManagerDefinitionResponse, AWSError>; /** * Create an alert manager definition. */ createAlertManagerDefinition(callback?: (err: AWSError, data: Amp.Types.CreateAlertManagerDefinitionResponse) => void): Request<Amp.Types.CreateAlertManagerDefinitionResponse, AWSError>; /** * Create a rule group namespace. */ createRuleGroupsNamespace(params: Amp.Types.CreateRuleGroupsNamespaceRequest, callback?: (err: AWSError, data: Amp.Types.CreateRuleGroupsNamespaceResponse) => void): Request<Amp.Types.CreateRuleGroupsNamespaceResponse, AWSError>; /** * Create a rule group namespace. */ createRuleGroupsNamespace(callback?: (err: AWSError, data: Amp.Types.CreateRuleGroupsNamespaceResponse) => void): Request<Amp.Types.CreateRuleGroupsNamespaceResponse, AWSError>; /** * Creates a new AMP workspace. */ createWorkspace(params: Amp.Types.CreateWorkspaceRequest, callback?: (err: AWSError, data: Amp.Types.CreateWorkspaceResponse) => void): Request<Amp.Types.CreateWorkspaceResponse, AWSError>; /** * Creates a new AMP workspace. */ createWorkspace(callback?: (err: AWSError, data: Amp.Types.CreateWorkspaceResponse) => void): Request<Amp.Types.CreateWorkspaceResponse, AWSError>; /** * Deletes an alert manager definition. */ deleteAlertManagerDefinition(params: Amp.Types.DeleteAlertManagerDefinitionRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an alert manager definition. */ deleteAlertManagerDefinition(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Delete a rule groups namespace. */ deleteRuleGroupsNamespace(params: Amp.Types.DeleteRuleGroupsNamespaceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Delete a rule groups namespace. */ deleteRuleGroupsNamespace(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an AMP workspace. */ deleteWorkspace(params: Amp.Types.DeleteWorkspaceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an AMP workspace. */ deleteWorkspace(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Describes an alert manager definition. */ describeAlertManagerDefinition(params: Amp.Types.DescribeAlertManagerDefinitionRequest, callback?: (err: AWSError, data: Amp.Types.DescribeAlertManagerDefinitionResponse) => void): Request<Amp.Types.DescribeAlertManagerDefinitionResponse, AWSError>; /** * Describes an alert manager definition. */ describeAlertManagerDefinition(callback?: (err: AWSError, data: Amp.Types.DescribeAlertManagerDefinitionResponse) => void): Request<Amp.Types.DescribeAlertManagerDefinitionResponse, AWSError>; /** * Describe a rule groups namespace. */ describeRuleGroupsNamespace(params: Amp.Types.DescribeRuleGroupsNamespaceRequest, callback?: (err: AWSError, data: Amp.Types.DescribeRuleGroupsNamespaceResponse) => void): Request<Amp.Types.DescribeRuleGroupsNamespaceResponse, AWSError>; /** * Describe a rule groups namespace. */ describeRuleGroupsNamespace(callback?: (err: AWSError, data: Amp.Types.DescribeRuleGroupsNamespaceResponse) => void): Request<Amp.Types.DescribeRuleGroupsNamespaceResponse, AWSError>; /** * Describes an existing AMP workspace. */ describeWorkspace(params: Amp.Types.DescribeWorkspaceRequest, callback?: (err: AWSError, data: Amp.Types.DescribeWorkspaceResponse) => void): Request<Amp.Types.DescribeWorkspaceResponse, AWSError>; /** * Describes an existing AMP workspace. */ describeWorkspace(callback?: (err: AWSError, data: Amp.Types.DescribeWorkspaceResponse) => void): Request<Amp.Types.DescribeWorkspaceResponse, AWSError>; /** * Lists rule groups namespaces. */ listRuleGroupsNamespaces(params: Amp.Types.ListRuleGroupsNamespacesRequest, callback?: (err: AWSError, data: Amp.Types.ListRuleGroupsNamespacesResponse) => void): Request<Amp.Types.ListRuleGroupsNamespacesResponse, AWSError>; /** * Lists rule groups namespaces. */ listRuleGroupsNamespaces(callback?: (err: AWSError, data: Amp.Types.ListRuleGroupsNamespacesResponse) => void): Request<Amp.Types.ListRuleGroupsNamespacesResponse, AWSError>; /** * Lists the tags you have assigned to the resource. */ listTagsForResource(params: Amp.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Amp.Types.ListTagsForResourceResponse) => void): Request<Amp.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags you have assigned to the resource. */ listTagsForResource(callback?: (err: AWSError, data: Amp.Types.ListTagsForResourceResponse) => void): Request<Amp.Types.ListTagsForResourceResponse, AWSError>; /** * Lists all AMP workspaces, including workspaces being created or deleted. */ listWorkspaces(params: Amp.Types.ListWorkspacesRequest, callback?: (err: AWSError, data: Amp.Types.ListWorkspacesResponse) => void): Request<Amp.Types.ListWorkspacesResponse, AWSError>; /** * Lists all AMP workspaces, including workspaces being created or deleted. */ listWorkspaces(callback?: (err: AWSError, data: Amp.Types.ListWorkspacesResponse) => void): Request<Amp.Types.ListWorkspacesResponse, AWSError>; /** * Update an alert manager definition. */ putAlertManagerDefinition(params: Amp.Types.PutAlertManagerDefinitionRequest, callback?: (err: AWSError, data: Amp.Types.PutAlertManagerDefinitionResponse) => void): Request<Amp.Types.PutAlertManagerDefinitionResponse, AWSError>; /** * Update an alert manager definition. */ putAlertManagerDefinition(callback?: (err: AWSError, data: Amp.Types.PutAlertManagerDefinitionResponse) => void): Request<Amp.Types.PutAlertManagerDefinitionResponse, AWSError>; /** * Update a rule groups namespace. */ putRuleGroupsNamespace(params: Amp.Types.PutRuleGroupsNamespaceRequest, callback?: (err: AWSError, data: Amp.Types.PutRuleGroupsNamespaceResponse) => void): Request<Amp.Types.PutRuleGroupsNamespaceResponse, AWSError>; /** * Update a rule groups namespace. */ putRuleGroupsNamespace(callback?: (err: AWSError, data: Amp.Types.PutRuleGroupsNamespaceResponse) => void): Request<Amp.Types.PutRuleGroupsNamespaceResponse, AWSError>; /** * Creates tags for the specified resource. */ tagResource(params: Amp.Types.TagResourceRequest, callback?: (err: AWSError, data: Amp.Types.TagResourceResponse) => void): Request<Amp.Types.TagResourceResponse, AWSError>; /** * Creates tags for the specified resource. */ tagResource(callback?: (err: AWSError, data: Amp.Types.TagResourceResponse) => void): Request<Amp.Types.TagResourceResponse, AWSError>; /** * Deletes tags from the specified resource. */ untagResource(params: Amp.Types.UntagResourceRequest, callback?: (err: AWSError, data: Amp.Types.UntagResourceResponse) => void): Request<Amp.Types.UntagResourceResponse, AWSError>; /** * Deletes tags from the specified resource. */ untagResource(callback?: (err: AWSError, data: Amp.Types.UntagResourceResponse) => void): Request<Amp.Types.UntagResourceResponse, AWSError>; /** * Updates an AMP workspace alias. */ updateWorkspaceAlias(params: Amp.Types.UpdateWorkspaceAliasRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates an AMP workspace alias. */ updateWorkspaceAlias(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Waits for the workspaceActive state by periodically calling the underlying Amp.describeWorkspaceoperation every 2 seconds (at most 60 times). Wait until a workspace reaches ACTIVE status */ waitFor(state: "workspaceActive", params: Amp.Types.DescribeWorkspaceRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Amp.Types.DescribeWorkspaceResponse) => void): Request<Amp.Types.DescribeWorkspaceResponse, AWSError>; /** * Waits for the workspaceActive state by periodically calling the underlying Amp.describeWorkspaceoperation every 2 seconds (at most 60 times). Wait until a workspace reaches ACTIVE status */ waitFor(state: "workspaceActive", callback?: (err: AWSError, data: Amp.Types.DescribeWorkspaceResponse) => void): Request<Amp.Types.DescribeWorkspaceResponse, AWSError>; /** * Waits for the workspaceDeleted state by periodically calling the underlying Amp.describeWorkspaceoperation every 2 seconds (at most 60 times). Wait until a workspace reaches DELETED status */ waitFor(state: "workspaceDeleted", params: Amp.Types.DescribeWorkspaceRequest & {$waiter?: WaiterConfiguration}, callback?: (err: AWSError, data: Amp.Types.DescribeWorkspaceResponse) => void): Request<Amp.Types.DescribeWorkspaceResponse, AWSError>; /** * Waits for the workspaceDeleted state by periodically calling the underlying Amp.describeWorkspaceoperation every 2 seconds (at most 60 times). Wait until a workspace reaches DELETED status */ waitFor(state: "workspaceDeleted", callback?: (err: AWSError, data: Amp.Types.DescribeWorkspaceResponse) => void): Request<Amp.Types.DescribeWorkspaceResponse, AWSError>; } declare namespace Amp { export type AlertManagerDefinitionData = Buffer|Uint8Array|Blob|string; export interface AlertManagerDefinitionDescription { /** * The time when the alert manager definition was created. */ createdAt: Timestamp; /** * The alert manager definition. */ data: AlertManagerDefinitionData; /** * The time when the alert manager definition was modified. */ modifiedAt: Timestamp; /** * The status of alert manager definition. */ status: AlertManagerDefinitionStatus; } export interface AlertManagerDefinitionStatus { /** * Status code of this definition. */ statusCode: AlertManagerDefinitionStatusCode; /** * The reason for failure if any. */ statusReason?: String; } export type AlertManagerDefinitionStatusCode = "CREATING"|"ACTIVE"|"UPDATING"|"DELETING"|"CREATION_FAILED"|"UPDATE_FAILED"|string; export interface CreateAlertManagerDefinitionRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The alert manager definition data. */ data: AlertManagerDefinitionData; /** * The ID of the workspace in which to create the alert manager definition. */ workspaceId: WorkspaceId; } export interface CreateAlertManagerDefinitionResponse { /** * The status of alert manager definition. */ status: AlertManagerDefinitionStatus; } export interface CreateRuleGroupsNamespaceRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The namespace data that define the rule groups. */ data: RuleGroupsNamespaceData; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * Optional, user-provided tags for this rule groups namespace. */ tags?: TagMap; /** * The ID of the workspace in which to create the rule group namespace. */ workspaceId: WorkspaceId; } export interface CreateRuleGroupsNamespaceResponse { /** * The Amazon Resource Name (ARN) of this rule groups namespace. */ arn: RuleGroupsNamespaceArn; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * The status of rule groups namespace. */ status: RuleGroupsNamespaceStatus; /** * The tags of this rule groups namespace. */ tags?: TagMap; } export interface CreateWorkspaceRequest { /** * An optional user-assigned alias for this workspace. This alias is for user reference and does not need to be unique. */ alias?: WorkspaceAlias; /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * Optional, user-provided tags for this workspace. */ tags?: TagMap; } export interface CreateWorkspaceResponse { /** * The ARN of the workspace that was just created. */ arn: WorkspaceArn; /** * The status of the workspace that was just created (usually CREATING). */ status: WorkspaceStatus; /** * The tags of this workspace. */ tags?: TagMap; /** * The generated ID of the workspace that was just created. */ workspaceId: WorkspaceId; } export interface DeleteAlertManagerDefinitionRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The ID of the workspace in which to delete the alert manager definition. */ workspaceId: WorkspaceId; } export interface DeleteRuleGroupsNamespaceRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * The ID of the workspace to delete rule group definition. */ workspaceId: WorkspaceId; } export interface DeleteWorkspaceRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The ID of the workspace to delete. */ workspaceId: WorkspaceId; } export interface DescribeAlertManagerDefinitionRequest { /** * The ID of the workspace to describe. */ workspaceId: WorkspaceId; } export interface DescribeAlertManagerDefinitionResponse { /** * The properties of the selected workspace's alert manager definition. */ alertManagerDefinition: AlertManagerDefinitionDescription; } export interface DescribeRuleGroupsNamespaceRequest { /** * The rule groups namespace. */ name: RuleGroupsNamespaceName; /** * The ID of the workspace to describe. */ workspaceId: WorkspaceId; } export interface DescribeRuleGroupsNamespaceResponse { /** * The selected rule groups namespace. */ ruleGroupsNamespace: RuleGroupsNamespaceDescription; } export interface DescribeWorkspaceRequest { /** * The ID of the workspace to describe. */ workspaceId: WorkspaceId; } export interface DescribeWorkspaceResponse { /** * The properties of the selected workspace. */ workspace: WorkspaceDescription; } export type IdempotencyToken = string; export interface ListRuleGroupsNamespacesRequest { /** * Maximum results to return in response (default=100, maximum=1000). */ maxResults?: ListRuleGroupsNamespacesRequestMaxResultsInteger; /** * Optional filter for rule groups namespace name. Only the rule groups namespace that begin with this value will be returned. */ name?: RuleGroupsNamespaceName; /** * Pagination token to request the next page in a paginated list. This token is obtained from the output of the previous ListRuleGroupsNamespaces request. */ nextToken?: PaginationToken; /** * The ID of the workspace. */ workspaceId: WorkspaceId; } export type ListRuleGroupsNamespacesRequestMaxResultsInteger = number; export interface ListRuleGroupsNamespacesResponse { /** * Pagination token to use when requesting the next page in this list. */ nextToken?: PaginationToken; /** * The list of the selected rule groups namespaces. */ ruleGroupsNamespaces: RuleGroupsNamespaceSummaryList; } export interface ListTagsForResourceRequest { /** * The ARN of the resource. */ resourceArn: String; } export interface ListTagsForResourceResponse { tags?: TagMap; } export interface ListWorkspacesRequest { /** * Optional filter for workspace alias. Only the workspaces with aliases that begin with this value will be returned. */ alias?: WorkspaceAlias; /** * Maximum results to return in response (default=100, maximum=1000). */ maxResults?: ListWorkspacesRequestMaxResultsInteger; /** * Pagination token to request the next page in a paginated list. This token is obtained from the output of the previous ListWorkspaces request. */ nextToken?: PaginationToken; } export type ListWorkspacesRequestMaxResultsInteger = number; export interface ListWorkspacesResponse { /** * Pagination token to use when requesting the next page in this list. */ nextToken?: PaginationToken; /** * The list of existing workspaces, including those undergoing creation or deletion. */ workspaces: WorkspaceSummaryList; } export type PaginationToken = string; export interface PutAlertManagerDefinitionRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The alert manager definition data. */ data: AlertManagerDefinitionData; /** * The ID of the workspace in which to update the alert manager definition. */ workspaceId: WorkspaceId; } export interface PutAlertManagerDefinitionResponse { /** * The status of alert manager definition. */ status: AlertManagerDefinitionStatus; } export interface PutRuleGroupsNamespaceRequest { /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The namespace data that define the rule groups. */ data: RuleGroupsNamespaceData; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * The ID of the workspace in which to update the rule group namespace. */ workspaceId: WorkspaceId; } export interface PutRuleGroupsNamespaceResponse { /** * The Amazon Resource Name (ARN) of this rule groups namespace. */ arn: RuleGroupsNamespaceArn; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * The status of rule groups namespace. */ status: RuleGroupsNamespaceStatus; /** * The tags of this rule groups namespace. */ tags?: TagMap; } export type RuleGroupsNamespaceArn = string; export type RuleGroupsNamespaceData = Buffer|Uint8Array|Blob|string; export interface RuleGroupsNamespaceDescription { /** * The Amazon Resource Name (ARN) of this rule groups namespace. */ arn: RuleGroupsNamespaceArn; /** * The time when the rule groups namespace was created. */ createdAt: Timestamp; /** * The rule groups namespace data. */ data: RuleGroupsNamespaceData; /** * The time when the rule groups namespace was modified. */ modifiedAt: Timestamp; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * The status of rule groups namespace. */ status: RuleGroupsNamespaceStatus; /** * The tags of this rule groups namespace. */ tags?: TagMap; } export type RuleGroupsNamespaceName = string; export interface RuleGroupsNamespaceStatus { /** * Status code of this namespace. */ statusCode: RuleGroupsNamespaceStatusCode; /** * The reason for failure if any. */ statusReason?: String; } export type RuleGroupsNamespaceStatusCode = "CREATING"|"ACTIVE"|"UPDATING"|"DELETING"|"CREATION_FAILED"|"UPDATE_FAILED"|string; export interface RuleGroupsNamespaceSummary { /** * The Amazon Resource Name (ARN) of this rule groups namespace. */ arn: RuleGroupsNamespaceArn; /** * The time when the rule groups namespace was created. */ createdAt: Timestamp; /** * The time when the rule groups namespace was modified. */ modifiedAt: Timestamp; /** * The rule groups namespace name. */ name: RuleGroupsNamespaceName; /** * The status of rule groups namespace. */ status: RuleGroupsNamespaceStatus; /** * The tags of this rule groups namespace. */ tags?: TagMap; } export type RuleGroupsNamespaceSummaryList = RuleGroupsNamespaceSummary[]; export type String = string; export type TagKey = string; export type TagKeys = TagKey[]; export type TagMap = {[key: string]: TagValue}; export interface TagResourceRequest { /** * The ARN of the resource. */ resourceArn: String; tags: TagMap; } export interface TagResourceResponse { } export type TagValue = string; export type Timestamp = Date; export interface UntagResourceRequest { /** * The ARN of the resource. */ resourceArn: String; /** * One or more tag keys */ tagKeys: TagKeys; } export interface UntagResourceResponse { } export interface UpdateWorkspaceAliasRequest { /** * The new alias of the workspace. */ alias?: WorkspaceAlias; /** * Optional, unique, case-sensitive, user-provided identifier to ensure the idempotency of the request. */ clientToken?: IdempotencyToken; /** * The ID of the workspace being updated. */ workspaceId: WorkspaceId; } export type Uri = string; export type WorkspaceAlias = string; export type WorkspaceArn = string; export interface WorkspaceDescription { /** * Alias of this workspace. */ alias?: WorkspaceAlias; /** * The Amazon Resource Name (ARN) of this workspace. */ arn: WorkspaceArn; /** * The time when the workspace was created. */ createdAt: Timestamp; /** * Prometheus endpoint URI. */ prometheusEndpoint?: Uri; /** * The status of this workspace. */ status: WorkspaceStatus; /** * The tags of this workspace. */ tags?: TagMap; /** * Unique string identifying this workspace. */ workspaceId: WorkspaceId; } export type WorkspaceId = string; export interface WorkspaceStatus { /** * Status code of this workspace. */ statusCode: WorkspaceStatusCode; } export type WorkspaceStatusCode = "CREATING"|"ACTIVE"|"UPDATING"|"DELETING"|"CREATION_FAILED"|string; export interface WorkspaceSummary { /** * Alias of this workspace. */ alias?: WorkspaceAlias; /** * The AmazonResourceName of this workspace. */ arn: WorkspaceArn; /** * The time when the workspace was created. */ createdAt: Timestamp; /** * The status of this workspace. */ status: WorkspaceStatus; /** * The tags of this workspace. */ tags?: TagMap; /** * Unique string identifying this workspace. */ workspaceId: WorkspaceId; } export type WorkspaceSummaryList = WorkspaceSummary[]; /** * 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 = "2020-08-01"|"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 Amp client. */ export import Types = Amp; } export = Amp;
the_stack