text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { format as dateFormat } from 'date-fns'; import { promises as fs } from 'fs'; import { EOL } from 'os'; import environments from '../libs/environments'; import http from '../libs/http'; import { HttpCall } from '../libs/models'; import routes from '../libs/routes'; import utils from '../libs/utils'; const testSuites: { name: string; tests: HttpCall[] }[] = [ { name: 'Body helper: text/plain Content-Type (incompatible with path search)', tests: [ { description: 'Body path, default value', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{"property1":"stringcontent"}', testedResponse: { status: 200, body: 'defaultvalue' } }, { description: 'Body path, no default value', path: '/bodyjson-rootlvl-nodefault', method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{"property1":"stringcontent"}', testedResponse: { status: 200, body: '' } }, { description: 'Full body, no path param provided', path: '/bodyjson-full-noparam', method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{"property1":"stringcontent"}', testedResponse: { status: 200, body: '{"property1":"stringcontent"}' } }, { description: 'Full body, empty path param', path: '/bodyjson-full-emptyparam', method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{"property1":"stringcontent"}', testedResponse: { status: 200, body: '{"property1":"stringcontent"}' } } ] }, { name: 'Body helper: Request body application/json', tests: [ { description: 'Empty body', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, testedResponse: { status: 200, body: 'defaultvalue' } }, { description: 'Empty body, no default value', path: '/bodyjson-rootlvl-nodefault', method: 'POST', headers: { 'Content-Type': 'application/json' }, testedResponse: { status: 200, body: '' } }, { description: 'Invalid body', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"test":"invalid}', testedResponse: { status: 200, body: 'defaultvalue' } }, { description: 'Invalid body, no default value', path: '/bodyjson-rootlvl-nodefault', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"test":"invalid}', testedResponse: { status: 200, body: '' } }, { description: 'Full body, no path parameter provided', path: '/bodyjson-full-noparam', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"test": "testcontent"}', testedResponse: { status: 200, body: '{"test": "testcontent"}' } }, { description: 'Full body, empty path parameter', path: '/bodyjson-full-emptyparam', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{"test": "testcontent"}', testedResponse: { status: 200, body: '{"test": "testcontent"}' } }, { description: 'Root level string', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: 'stringcontent' }, testedResponse: { status: 200, body: 'stringcontent' } }, { description: 'Root level number', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: 10 }, testedResponse: { status: 200, body: '10' } }, { description: 'Root level boolean', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: false }, testedResponse: { status: 200, body: 'false' } }, { description: 'Root level null', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: null }, testedResponse: { status: 200, body: 'null' } }, { description: 'Root level object', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: { teststring: 'stringcontent', testboolean: true, testnumber: 5, testnull: null } }, testedResponse: { status: 200, body: '{"teststring":"stringcontent","testboolean":true,"testnumber":5,"testnull":null}' } }, { description: 'Root level default value (path not found)', path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { anotherproperty: 'test' }, testedResponse: { status: 200, body: 'defaultvalue' } }, { description: 'Non-root level string', path: '/bodyjson', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: 'stringcontent' }, testedResponse: { status: 200, body: '{ "response": stringcontent }' } }, { description: 'Non-root level number', path: '/bodyjson', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: 10 }, testedResponse: { status: 200, body: '{ "response": 10 }' } }, { description: 'Non-root level boolean', path: '/bodyjson', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: false }, testedResponse: { status: 200, body: '{ "response": false }' } }, { description: 'Non-root level null', path: '/bodyjson', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: null }, testedResponse: { status: 200, body: '{ "response": null }' } }, { description: 'Non-root level object', path: '/bodyjson', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { property1: { teststring: 'stringcontent', testboolean: true, testnumber: 5, testnull: null } }, testedResponse: { status: 200, body: '{ "response": {"teststring":"stringcontent","testboolean":true,"testnumber":5,"testnull":null} }' } }, { description: 'Non-root level default value (path not found)', path: '/bodyjson', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { anotherproperty: 'test' }, testedResponse: { status: 200, body: '{ "response": defaultvalue }' } }, { description: 'Non-root level complex path', path: '/bodyjson-path', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: { root: { array: [{}, {}, { property1: 'test1' }] } }, testedResponse: { status: 200, body: '{ "response": "test1" }' } } ] }, { /** * Reference form: * <form method="post"> * <input type="email" name="email" value="john@example.com" /> * <input type="text" name="name" value="john" /> * <input type="checkbox" name="areyousure" checked> * <input type="radio" name="choice" value="choice1"> * <input type="radio" name="choice" value="choice2" checked> * <input type="radio" name="choice" value="choice3"> * <input type="text" name="comments" value="comment1"> * <input type="text" name="comments" value="comment2"> * <input type="text" name="comments" value="comment3"> * <input type="text" name="moreinfo[part1]" value="moreinfo1"> * <input type="text" name="moreinfo[part2]" value="moreinfo2"> * <input type="submit" value="submit" /> * </form> * * Produces: * email=john%40example.com&name=john&areyousure=on&choice=choice2&comments=comment1& comments=comment2&comments=comment3&moreinfo%5Bpart1%5D=moreinfo1& moreinfo%5Bpart2%5D=moreinfo2 */ name: 'Body helper: Request body application/x-www-form-urlencoded', tests: [ { description: 'Empty body', path: '/bodyform-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, testedResponse: { status: 200, body: 'defaultvalue' } }, { description: 'Empty body, no default value', path: '/bodyform-rootlvl-nodefault', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, testedResponse: { status: 200, body: '' } }, { description: 'Full body, no path parameter provided', path: '/bodyform-full-noparam', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1=stringcontent', testedResponse: { status: 200, body: 'param1=stringcontent' } }, { description: 'Full body, empty path parameter', path: '/bodyform-full-emptyparam', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1=stringcontent', testedResponse: { status: 200, body: 'param1=stringcontent' } }, { description: 'Root level string', path: '/bodyform-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1=stringcontent', testedResponse: { status: 200, body: 'stringcontent' } }, { description: 'Root level array', path: '/bodyform-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1=content1&param1=content2&param1=content3', testedResponse: { status: 200, body: '["content1","content2","content3"]' } }, { description: 'Root level array (with array notation)', path: '/bodyform-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1%5B%5D=content1&param1%5B%5D=content2&param1%5B%5D=content3', testedResponse: { status: 200, body: '["content1","content2","content3"]' } }, { description: 'Root level object', path: '/bodyform-rootlvl', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1%5Bpart1%5D=content1&param1%5Bpart2%5D=content2', testedResponse: { status: 200, body: '{"part1":"content1","part2":"content2"}' } }, { description: 'Non-root level string', path: '/bodyform', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1=stringcontent', testedResponse: { status: 200, body: '{ "response": stringcontent }' } }, { description: 'Non-root level array', path: '/bodyform', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1=content1&param1=content2&param1=content3', testedResponse: { status: 200, body: '{ "response": ["content1","content2","content3"] }' } }, { description: 'Non-root level array (with array notation)', path: '/bodyform', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1%5B%5D=content1&param1%5B%5D=content2&param1%5B%5D=content3', testedResponse: { status: 200, body: '{ "response": ["content1","content2","content3"] }' } }, { description: 'Non-root level object', path: '/bodyform', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1%5Bpart1%5D=content1&param1%5Bpart2%5D=content2', testedResponse: { status: 200, body: '{ "response": {"part1":"content1","part2":"content2"} }' } }, { description: 'Non-root level object path', path: '/bodyform-path', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: 'param1%5Bpart1%5D=content1&param1%5Bpart2%5D=content2', testedResponse: { status: 200, body: '{ "response": content1 }' } } ] }, { name: 'Helper in file path', tests: [ { description: 'Relative unix-like path with body helper', path: '/filepath', method: 'GET', headers: { 'Content-Type': 'application/json' }, body: { test: 'file' }, testedResponse: { status: 200, body: 'filebody' } }, { description: 'Relative windows-like path with body helper', path: '/filepath-windows', method: 'GET', headers: { 'Content-Type': 'application/json' }, body: { test: 'file' }, testedResponse: { status: 200, body: 'filebody' } } ] }, { name: 'Helper in file content', tests: [ { description: 'Body helper', path: '/file-templating', method: 'GET', headers: { 'Content-Type': 'application/json' }, body: { test: 'bodycontent' }, testedResponse: { status: 200, body: 'startbodycontentend' } } ] }, { name: 'Other helpers', tests: [ { description: 'Helper: urlParam', path: '/urlparam/testurlparam1', method: 'GET', testedResponse: { status: 200, body: 'testurlparam1' } }, { description: 'Helper: queryParam, empty, no default value', path: '/queryparam-rootlvl-nodefault', method: 'GET', testedResponse: { status: 200, body: '' } }, { description: 'Helper: queryParam, empty, with default value', path: '/queryparam-rootlvl', method: 'GET', testedResponse: { status: 200, body: 'defaultqueryparam' } }, { description: 'Helper: queryParam property, root level', path: '/queryparam-rootlvl?param1=testqueryparam1', method: 'GET', testedResponse: { status: 200, body: 'testqueryparam1' } }, { description: 'Helper: queryParam missing property, root level (default value)', path: '/queryparam-rootlvl?param2=testqueryparam2', method: 'GET', testedResponse: { status: 200, body: 'defaultqueryparam' } }, { description: 'Helper: queryParam item in array, root level', path: '/queryparam-rootlvl-arrayitem?paramarray[]=test1&paramarray[]=test2', method: 'GET', testedResponse: { status: 200, body: 'test2' } }, { description: 'Helper: queryParam property in object, root level', path: '/queryparam-rootlvl-objectproperty?paramobj[prop1]=testprop1&paramobj[prop2]=testprop2', method: 'GET', testedResponse: { status: 200, body: 'testprop2' } }, { description: 'Helper: queryParam sub array, root level', path: '/queryparam-rootlvl-array?paramarray[]=test1&paramarray[]=test2', method: 'GET', testedResponse: { status: 200, body: '["test1","test2"]' } }, { description: 'Helper: queryParam sub object, root level', path: '/queryparam-rootlvl-object?paramobj[prop1]=testprop1&paramobj[prop2]=testprop2', method: 'GET', testedResponse: { status: 200, body: '{"prop1":"testprop1","prop2":"testprop2"}' } }, { description: 'Helper: queryParam multiple fetch, deep level', path: '/queryparam-multiple?param1=param1value&paramarray[]=test1&paramarray[]=test2&paramobj[prop1]=testprop1&paramobj[prop2]=testprop2', method: 'GET', testedResponse: { status: 200, body: '{ "param1": "param1value","arrayitem": "test2","objprop": "testprop2","fullarray": ["test1","test2"],"fullobj": {"prop1":"testprop1","prop2":"testprop2"} }' } }, { description: 'Helper: queryParam full object with empty path param', path: '/queryparam-full-emptypath?param1=param1value&paramarray[]=test1&paramarray[]=test2&paramobj[prop1]=testprop1&paramobj[prop2]=testprop2', method: 'GET', testedResponse: { status: 200, body: '{"param1":"param1value","paramarray":["test1","test2"],"paramobj":{"prop1":"testprop1","prop2":"testprop2"}}' } }, { description: 'Helper: queryParam full object with no path param', path: '/queryparam-full-nopath?param1=param1value&paramarray[]=test1&paramarray[]=test2&paramobj[prop1]=testprop1&paramobj[prop2]=testprop2', method: 'GET', testedResponse: { status: 200, body: '{"param1":"param1value","paramarray":["test1","test2"],"paramobj":{"prop1":"testprop1","prop2":"testprop2"}}' } }, { description: 'Helper: header', path: '/header', headers: { header1: 'testheader1' }, method: 'GET', testedResponse: { status: 200, body: 'testheader1' } }, { description: 'Helper: header (default value)', path: '/header', headers: { header2: 'testheader2' }, method: 'GET', testedResponse: { status: 200, body: 'defaultheader' } }, { description: 'Helper: cookie', path: '/cookie', method: 'GET', cookie: 'cookie1=testcookie1', testedResponse: { status: 200, body: 'testcookie1' } }, { description: 'Helper: cookie (default value)', path: '/cookie', method: 'GET', cookie: 'cookie2=testcookie2', testedResponse: { status: 200, body: 'defaultcookie' } }, { description: 'Helper: hostname', path: '/hostname', method: 'GET', testedResponse: { status: 200, body: 'localhost' } }, { description: 'Helper: ip', path: '/ip', method: 'GET', testedResponse: { status: 200, body: '127.0.0.1' } }, { description: 'Helper: method', path: '/method', method: 'GET', testedResponse: { status: 200, body: 'GET' } }, { description: 'Helper: oneOf', path: '/oneof', method: 'GET', testedResponse: { status: 200, body: 'testitem1' } }, { description: 'Helper: someOf', path: '/someof', method: 'GET', testedResponse: { status: 200, body: 'testitem,testitem' } }, { description: 'Helper: someOf (as array)', path: '/someofarray', method: 'GET', testedResponse: { status: 200, body: '[&quot;testitem&quot;,&quot;testitem&quot;]' } }, { description: 'Helper: now', path: '/now', method: 'GET', testedResponse: { status: 200, body: dateFormat(new Date(), 'yyyy-MM-dd', { useAdditionalWeekYearTokens: true, useAdditionalDayOfYearTokens: true }) } }, { description: 'Helper: newline', path: '/newline', method: 'GET', testedResponse: { status: 200, body: '\n' } }, { description: 'Helper: random objectId', path: '/objectid_1', method: 'GET', testedResponse: { status: 200, body: /^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i } }, { description: 'Helper: objectId based on time', path: '/objectid_2', method: 'GET', testedResponse: { status: 200, body: '54495ad94c934721ede76d90' } }, { description: 'Helper: base64 (inline + block helper)', path: '/base64', method: 'GET', body: 'test', testedResponse: { status: 200, body: 'dGVzdA==dGVzdHRlc3R0ZXN0dGVzdHRlc3R0ZXN0dGVzdHRlc3R0ZXN0dGVzdA==' } }, { description: 'Bad helper name', path: '/bad-helper', method: 'GET', testedResponse: { status: 200, body: 'startend' } } ] }, { name: 'Templating syntax Errors', tests: [ { description: 'Templating syntax error in body', path: '/templating-syntax-error-body', method: 'GET', testedResponse: { status: 200, body: { contains: "Error while serving the content: Parse error on line 1:\nstart{{body 'test'}}}end" } } }, { description: 'Templating syntax error in header', path: '/templating-syntax-error-header', method: 'GET', testedResponse: { status: 200, body: 'body', headers: { 'test-header': '-- Parsing error. Check logs for more information --' } } }, { description: 'Templating syntax error in file path', path: '/templating-syntax-error-filepath', method: 'GET', testedResponse: { status: 200, body: { contains: "Error while serving the content: Parse error on line 1:\n...:/test/{{body 'test'}}}.txt" } } }, { description: 'Templating syntax error in file', path: '/templating-syntax-error-file', method: 'GET', headers: { 'Content-Type': 'application/json' }, body: { test: 'bodycontent' }, testedResponse: { status: 200, body: { contains: "Error while serving the file content: Parse error on line 1:\n{{body 'test'}}}" } } } ] }, { name: 'Old Dummy JSON helpers', tests: [ { description: 'Helper: repeat', path: '/old.repeat', method: 'GET', testedResponse: { status: 200, body: `test,${EOL}test,${EOL}test,${EOL}test,${EOL}test${EOL}` } }, { description: 'Helper: repeat with invalid syntax', path: '/old.repeat.invalid', method: 'GET', testedResponse: { status: 200, body: { contains: 'The repeat helper requires a numeric param' } } }, { description: 'Helper: switch from urlParam, string case value', path: '/old.switch.urlParam/1', method: 'GET', testedResponse: { status: 200, body: 'casecontent1' } }, { description: 'Helper: switch from urlParam, default', path: '/old.switch.urlParam/11', method: 'GET', testedResponse: { status: 200, body: 'defaultcontent' } }, { description: 'Helper: switch from urlParam with inner helper', path: '/old.switch.urlParam.helper/1', method: 'GET', testedResponse: { status: 200, body: 'GET' } }, { description: 'Helper: switch from urlParam with inner helper, default', path: '/old.switch.urlParam.helper/11', method: 'GET', testedResponse: { status: 200, body: 'defaultcontentGET' } }, { description: 'Helper: multiple switches from urlParam', path: '/old.switch.urlParam.multi/1/2', method: 'GET', testedResponse: { status: 200, body: 'switch1casecontent1switch2casecontent2' } }, { description: 'Helper: switch from queryParam, string case value', path: '/old.switch.queryParam?qp=1', method: 'GET', testedResponse: { status: 200, body: 'casecontent1' } }, { description: 'Helper: switch from queryParam, default', path: '/old.switch.queryParam?qp=11', method: 'GET', testedResponse: { status: 200, body: 'defaultcontent' } }, { description: 'Helper: switch from body, string case value', path: '/old.switch.body', method: 'GET', headers: { 'Content-Type': 'application/json' }, body: '{ "prop": 1 }', testedResponse: { status: 200, body: 'casecontent1' } }, { description: 'Helper: switch from body, default', path: '/old.switch.body', method: 'GET', headers: { 'Content-Type': 'application/json' }, body: { prop: 'nothing' }, testedResponse: { status: 200, body: 'defaultcontent' } } ] } ]; describe('Templating', () => { describe('Helpers', () => { before(async () => { await fs.copyFile( './test/data/res/file-templating-error.txt', './tmp/storage/file-templating-error.txt' ); await fs.copyFile( './test/data/res/file-templating.txt', './tmp/storage/file-templating.txt' ); await fs.copyFile('./test/data/res/file.txt', './tmp/storage/file.txt'); }); it('should open and start the environment', async () => { await environments.open('templating'); await environments.start(); }); testSuites.forEach((testSuite) => { describe(testSuite.name, () => { testSuite.tests.forEach((testCase) => { it(testCase.description, async () => { await http.assertCall(testCase); }); }); }); }); }); describe('Disable route response templating', () => { it('should get body content with disabled templating', async () => { await routes.select(1); await routes.switchTab('SETTINGS'); await routes.toggleDisableTemplating(); await utils.waitForAutosave(); await http.assertCall({ path: '/bodyjson-rootlvl', method: 'POST', headers: { 'Content-Type': 'text/plain' }, testedResponse: { status: 200, body: "{{body 'property1' 'defaultvalue'}}" } }); }); it('should get file content with disabled templating', async () => { await routes.select(20); await routes.switchTab('SETTINGS'); await routes.toggleDisableTemplating(); await utils.waitForAutosave(); await http.assertCall({ path: '/file-templating', method: 'GET', headers: { 'Content-Type': 'text/plain' }, testedResponse: { status: 200, body: "start{{body 'test'}}end" } }); }); }); });
the_stack
import { Injectable, NotFoundException, UnauthorizedException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { InputJsonValue, JsonValue, Prisma } from '@prisma/client'; import { ApiKey } from '@prisma/client'; import QuickLRU from 'quick-lru'; import { API_KEY_NOT_FOUND, UNAUTHORIZED_RESOURCE, USER_NOT_FOUND, } from '../../errors/errors.constants'; import { groupOwnerScopes, userScopes } from '../../helpers/scopes'; import { ElasticSearchService } from '../../providers/elasticsearch/elasticsearch.service'; import { Expose } from '../../providers/prisma/prisma.interface'; import { PrismaService } from '../../providers/prisma/prisma.service'; import { TokensService } from '../../providers/tokens/tokens.service'; @Injectable() export class ApiKeysService { private lru = new QuickLRU<string, ApiKey>({ maxSize: this.configService.get<number>('caching.apiKeyLruSize') ?? 100, }); constructor( private prisma: PrismaService, private tokensService: TokensService, private configService: ConfigService, private elasticSearchService: ElasticSearchService, ) {} async createApiKeyForGroup( groupId: number, data: Omit<Omit<Prisma.ApiKeyCreateInput, 'apiKey'>, 'group'>, ): Promise<ApiKey> { const apiKey = await this.tokensService.generateRandomString(); data.scopes = await this.cleanScopesForGroup(groupId, data.scopes); return this.prisma.apiKey.create({ data: { ...data, apiKey, group: { connect: { id: groupId } } }, }); } async createApiKeyForUser( userId: number, data: Omit<Omit<Prisma.ApiKeyCreateInput, 'apiKey'>, 'user'>, ): Promise<ApiKey> { const apiKey = await this.tokensService.generateRandomString(); data.scopes = await this.cleanScopesForUser(userId, data.scopes); return this.prisma.apiKey.create({ data: { ...data, apiKey, user: { connect: { id: userId } } }, }); } async getApiKeysForGroup( groupId: number, params: { skip?: number; take?: number; cursor?: Prisma.ApiKeyWhereUniqueInput; where?: Prisma.ApiKeyWhereInput; orderBy?: Prisma.ApiKeyOrderByInput; }, ): Promise<Expose<ApiKey>[]> { const { skip, take, cursor, where, orderBy } = params; try { const apiKey = await this.prisma.apiKey.findMany({ skip, take, cursor, where: { ...where, group: { id: groupId } }, orderBy, }); return apiKey.map((group) => this.prisma.expose<ApiKey>(group)); } catch (error) { return []; } } async getApiKeysForUser( userId: number, params: { skip?: number; take?: number; cursor?: Prisma.ApiKeyWhereUniqueInput; where?: Prisma.ApiKeyWhereInput; orderBy?: Prisma.ApiKeyOrderByInput; }, ): Promise<Expose<ApiKey>[]> { const { skip, take, cursor, where, orderBy } = params; try { const apiKey = await this.prisma.apiKey.findMany({ skip, take, cursor, where: { ...where, user: { id: userId } }, orderBy, }); return apiKey.map((user) => this.prisma.expose<ApiKey>(user)); } catch (error) { return []; } } async getApiKeyForGroup( groupId: number, id: number, ): Promise<Expose<ApiKey>> { const apiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!apiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (apiKey.groupId !== groupId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); return this.prisma.expose<ApiKey>(apiKey); } async getApiKeyForUser(userId: number, id: number): Promise<Expose<ApiKey>> { const apiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!apiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (apiKey.userId !== userId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); return this.prisma.expose<ApiKey>(apiKey); } async getApiKeyFromKey(key: string): Promise<Expose<ApiKey>> { if (this.lru.has(key)) return this.lru.get(key); const apiKey = await this.prisma.apiKey.findFirst({ where: { apiKey: key }, }); if (!apiKey) throw new NotFoundException(API_KEY_NOT_FOUND); this.lru.set(key, apiKey); return this.prisma.expose<ApiKey>(apiKey); } async updateApiKeyForGroup( groupId: number, id: number, data: Prisma.ApiKeyUpdateInput, ): Promise<Expose<ApiKey>> { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.groupId !== groupId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); data.scopes = await this.cleanScopesForGroup(groupId, data.scopes); const apiKey = await this.prisma.apiKey.update({ where: { id }, data, }); this.lru.delete(testApiKey.apiKey); return this.prisma.expose<ApiKey>(apiKey); } async updateApiKeyForUser( userId: number, id: number, data: Prisma.ApiKeyUpdateInput, ): Promise<Expose<ApiKey>> { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.userId !== userId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); data.scopes = await this.cleanScopesForUser(userId, data.scopes); const apiKey = await this.prisma.apiKey.update({ where: { id }, data, }); this.lru.delete(testApiKey.apiKey); return this.prisma.expose<ApiKey>(apiKey); } async replaceApiKeyForGroup( groupId: number, id: number, data: Prisma.ApiKeyCreateInput, ): Promise<Expose<ApiKey>> { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.groupId !== groupId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); data.scopes = await this.cleanScopesForGroup(groupId, data.scopes); const apiKey = await this.prisma.apiKey.update({ where: { id }, data, }); this.lru.delete(testApiKey.apiKey); return this.prisma.expose<ApiKey>(apiKey); } async replaceApiKeyForUser( userId: number, id: number, data: Prisma.ApiKeyCreateInput, ): Promise<Expose<ApiKey>> { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.userId !== userId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); data.scopes = await this.cleanScopesForUser(userId, data.scopes); const apiKey = await this.prisma.apiKey.update({ where: { id }, data, }); this.lru.delete(testApiKey.apiKey); return this.prisma.expose<ApiKey>(apiKey); } async deleteApiKeyForGroup( groupId: number, id: number, ): Promise<Expose<ApiKey>> { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.groupId !== groupId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); const apiKey = await this.prisma.apiKey.delete({ where: { id }, }); this.lru.delete(testApiKey.apiKey); return this.prisma.expose<ApiKey>(apiKey); } async deleteApiKeyForUser( userId: number, id: number, ): Promise<Expose<ApiKey>> { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.userId !== userId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); const apiKey = await this.prisma.apiKey.delete({ where: { id }, }); this.lru.delete(testApiKey.apiKey); return this.prisma.expose<ApiKey>(apiKey); } async getApiKeyLogsForGroup( groupId: number, id: number, params: { take?: number; cursor?: { id?: number }; where?: { after?: string }; }, ) { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.groupId !== groupId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); return this.getApiLogsFromKey(testApiKey.apiKey, params); } async getApiKeyLogsForUser( userId: number, id: number, params: { take?: number; cursor?: { id?: number }; where?: { after?: string }; }, ) { const testApiKey = await this.prisma.apiKey.findUnique({ where: { id }, }); if (!testApiKey) throw new NotFoundException(API_KEY_NOT_FOUND); if (testApiKey.userId !== userId) throw new UnauthorizedException(UNAUTHORIZED_RESOURCE); return this.getApiLogsFromKey(testApiKey.apiKey, params); } /** * Remove any unauthorized scopes in an API key for a user * This should run when a user's permissions have changed, for example * if they are removed from a group; this will remove any API scopes * they don't have access to anymore from that API key */ async removeUnauthorizedScopesForUser(userId: number): Promise<void> { const userApiKeys = await this.prisma.apiKey.findMany({ where: { user: { id: userId } }, }); if (!userApiKeys.length) return; const scopesAllowed = await this.getApiKeyScopesForUser(userId); for await (const apiKey of userApiKeys) { const currentScopes = (apiKey.scopes ?? []) as string[]; const newScopes = currentScopes.filter((i) => Object.keys(scopesAllowed).includes(i), ); if (currentScopes.length !== newScopes.length) this.prisma.apiKey.update({ where: { id: apiKey.id }, data: { scopes: newScopes }, }); } } private async getApiLogsFromKey( apiKey: string, params: { take?: number; cursor?: { id?: number }; where?: { after?: string }; }, ): Promise<Record<string, any>[]> { const now = new Date(); now.setDate( now.getDate() - this.configService.get<number>('tracking.deleteOldLogsDays'), ); const result = await this.elasticSearchService.search({ index: this.configService.get<string>('tracking.index'), from: params.cursor?.id, body: { query: { bool: { must: [ { match: { authorization: apiKey, }, }, { range: { date: { gte: params.where?.after ? new Date( new Date().getTime() - new Date(params.where?.after).getTime(), ) : now, }, }, }, ], }, }, sort: [ { date: { order: 'desc' }, }, ], size: params.take ?? 100, }, }); try { return result.body.hits.hits.map( (item: { _index: string; _type: '_doc'; _id: string; _score: any; _source: Record<string, any>; }) => ({ ...item._source, id: item._id }), ); } catch (error) {} return []; } private async cleanScopesForGroup( groupId: number, scopes: InputJsonValue, ): Promise<JsonValue[]> { if (!Array.isArray(scopes)) return []; return (scopes as string[]).filter((i) => Object.keys( Object.keys(groupOwnerScopes).map((i) => i.replace('{groupId}', groupId.toString()), ), ).includes(i), ); } private async cleanScopesForUser( userId: number, scopes: InputJsonValue, allowedScopes?: Record<string, string>, ): Promise<JsonValue[]> { if (!Array.isArray(scopes)) return []; if (!allowedScopes) allowedScopes = await this.getApiKeyScopesForUser(userId); return (scopes as string[]).filter((i) => Object.keys(allowedScopes).includes(i), ); } /** * Clean all API keys for a user, i.e., make sure they don't have * any scopes they're not allowed to have */ async cleanAllApiKeysForUser(userId: number): Promise<void> { const apiKeys = await this.prisma.apiKey.findMany({ where: { user: { id: userId } }, select: { id: true, scopes: true }, }); if (!apiKeys.length) return; const allowedScopes = await this.getApiKeyScopesForUser(userId); for await (const apiKey of apiKeys) await this.prisma.apiKey.update({ where: { id: apiKey.id }, data: { scopes: await this.cleanScopesForUser( userId, apiKey.scopes, allowedScopes, ), }, }); } getApiKeyScopesForGroup(groupId: number): Record<string, string> { const scopes: Record<string, string> = {}; Object.keys(groupOwnerScopes).forEach( (key) => (scopes[key.replace('{groupId}', groupId.toString())] = groupOwnerScopes[key]), ); return scopes; } async getApiKeyScopesForUser( userId: number, ): Promise<Record<string, string>> { const user = await this.prisma.user.findUnique({ where: { id: userId }, select: { role: true }, }); if (!userId) throw new NotFoundException(USER_NOT_FOUND); const scopes: Record<string, string> = {}; if (user.role === 'SUDO') { scopes['*'] = 'Do everything (USE WITH CAUTION)'; scopes['user-*:*'] = 'CRUD users'; scopes['group-*:*'] = 'CRUD groups'; } Object.keys(userScopes).forEach( (key) => (scopes[key.replace('{userId}', userId.toString())] = userScopes[key]), ); return scopes; } }
the_stack
import faker from "faker"; import { PluginContext, TelemetryReporter, LogProvider, AppStudioTokenProvider, GraphTokenProvider, UserInteraction, LogLevel, PermissionRequestProvider, Result, FxError, ok, LocalSettings, ConfigMap, } from "@microsoft/teamsfx-api"; import sinon from "sinon"; import { ConfigKeys, ConfigKeysOfOtherPlugin, Plugins, } from "../../../../src/plugins/resource/aad/constants"; import jwt_decode from "jwt-decode"; import { Utils } from "../../../../src/plugins/resource/aad/utils/common"; import { MockUserInteraction } from "../../../core/utils"; import { DEFAULT_PERMISSION_REQUEST } from "../../../../src/plugins/solution/fx-solution/constants"; import { newEnvInfo } from "../../../../src"; import { IUserList } from "../../../../src/plugins/resource/appstudio/interfaces/IAppDefinition"; import { ARM_TEMPLATE_OUTPUT } from "../../../../src/plugins/solution/fx-solution/constants"; import { SOLUTION } from "../../../../src/plugins/resource/appstudio/constants"; import { LocalSettingsBotKeys, LocalSettingsFrontendKeys, } from "../../../../src/common/localSettingsConstants"; import { EnvConfig } from "@microsoft/teamsfx-api"; const permissions = '[{"resource": "Microsoft Graph","delegated": ["User.Read"],"application":[]}]'; const permissionsWrong = '[{"resource": "Microsoft Graph","delegated": ["User.ReadData"],"application":[]}]'; const mockPermissionRequestProvider: PermissionRequestProvider = { async checkPermissionRequest(): Promise<Result<undefined, FxError>> { return ok(undefined); }, async getPermissionRequest(): Promise<Result<string, FxError>> { return ok(JSON.stringify(DEFAULT_PERMISSION_REQUEST)); }, }; const mockLogProvider: LogProvider = { async log(logLevel: LogLevel, message: string): Promise<boolean> { console.log("Log log"); console.log(message); return true; }, async info(message: string | Array<any>): Promise<boolean> { console.log("Log info"); console.log(message); return true; }, async debug(message: string): Promise<boolean> { console.log("Log debug"); console.log(message); return true; }, async error(message: string): Promise<boolean> { console.log("Log error"); console.error(message); return true; }, async trace(message: string): Promise<boolean> { console.log("Log trace"); console.log(message); return true; }, async warning(message: string): Promise<boolean> { console.log("Log warning"); console.log(message); return true; }, async fatal(message: string): Promise<boolean> { console.log("Log fatal"); console.log(message); return true; }, }; const mockUI: UserInteraction = new MockUserInteraction(); const mockTelemetryReporter: TelemetryReporter = { async sendTelemetryEvent( eventName: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number } ) { console.log("Telemetry event"); console.log(eventName); console.log(properties); }, async sendTelemetryErrorEvent( eventName: string, properties?: { [key: string]: string }, measurements?: { [key: string]: number } ) { console.log("Telemetry Error"); console.log(eventName); console.log(properties); }, async sendTelemetryException( error: Error, properties?: { [key: string]: string }, measurements?: { [key: string]: number } ) { console.log("Telemetry Exception"); console.log(error.message); console.log(properties); }, }; const userList: IUserList = { tenantId: faker.datatype.uuid(), aadId: faker.datatype.uuid(), displayName: "displayName", userPrincipalName: "userPrincipalName", isAdministrator: true, }; export class TestHelper { // TODO: update type static async pluginContext( // eslint-disable-next-line @typescript-eslint/ban-types config?: object, frontend = true, bot = true, isLocalDebug = false ) { let domain: string | undefined = undefined; let endpoint: string | undefined = undefined; if (frontend) { domain = faker.internet.domainName(); endpoint = "https://" + domain; } let botId: string | undefined = undefined; let botEndpoint: string | undefined = undefined; if (bot) { botId = faker.datatype.uuid(); botEndpoint = "https://botendpoint" + botId + ".test"; } const configOfOtherPlugins = isLocalDebug ? mockConfigOfOtherPluginsLocalDebug(domain, endpoint, botEndpoint, botId) : mockConfigOfOtherPluginsProvision(domain, endpoint, botEndpoint, botId); const pluginContext: PluginContext = { logProvider: mockLogProvider, ui: mockUI, telemetryReporter: mockTelemetryReporter, config: config, envInfo: newEnvInfo(undefined, undefined, configOfOtherPlugins), projectSettings: { appName: "aad-plugin-unit-test", }, permissionRequestProvider: mockPermissionRequestProvider, } as unknown as PluginContext; const localSettings: LocalSettings = { teamsApp: new ConfigMap(), auth: new ConfigMap(), }; if (frontend) { localSettings.frontend = new ConfigMap([ [LocalSettingsFrontendKeys.TabDomain, domain], [LocalSettingsFrontendKeys.TabEndpoint, endpoint], ]); } if (bot) { localSettings.bot = new ConfigMap([ [LocalSettingsBotKeys.BotEndpoint, botEndpoint], [LocalSettingsBotKeys.BotId, botId], ]); } pluginContext.localSettings = localSettings; return pluginContext; } } function mockConfigOfOtherPluginsProvision( domain: string | undefined, endpoint: string | undefined, botEndpoint: string | undefined, botId: string | undefined ) { return new Map([ [ Plugins.solution, new Map([ [ConfigKeysOfOtherPlugin.remoteTeamsAppId, faker.datatype.uuid()], [ConfigKeysOfOtherPlugin.solutionUserInfo, JSON.stringify(userList)], ]), ], [ Plugins.frontendHosting, new Map([ [ConfigKeysOfOtherPlugin.frontendHostingDomain, domain], [ConfigKeysOfOtherPlugin.frontendHostingEndpoint, endpoint], ]), ], [ Plugins.teamsBot, new Map([ [ConfigKeysOfOtherPlugin.teamsBotEndpoint, botEndpoint], [ConfigKeysOfOtherPlugin.teamsBotId, botId], ]), ], ]); } function mockConfigOfOtherPluginsLocalDebug( domain: string | undefined, endpoint: string | undefined, botEndpoint: string | undefined, botId: string | undefined ) { const result = new Map([ [ Plugins.solution, new Map([[ConfigKeysOfOtherPlugin.remoteTeamsAppId, faker.datatype.uuid()]]), ], [Plugins.teamsBot, new Map([[ConfigKeysOfOtherPlugin.teamsBotIdLocal, botId]])], ]); // local debug config is stored in localSettings in multi-env const localDebugConfig = new Map([ [ConfigKeysOfOtherPlugin.localDebugTabDomain, domain], [ConfigKeysOfOtherPlugin.localDebugTabEndpoint, endpoint], [ConfigKeysOfOtherPlugin.localDebugBotEndpoint, botEndpoint], ]); result.set(Plugins.localDebug, localDebugConfig); return result; } export function mockProvisionResult( context: PluginContext, isLocalDebug = false, hasFrontend = true ) { context.config.set( Utils.addLocalDebugPrefix(isLocalDebug, ConfigKeys.clientId), faker.datatype.uuid() ); context.config.set( Utils.addLocalDebugPrefix(isLocalDebug, ConfigKeys.objectId), faker.datatype.uuid() ); context.config.set( Utils.addLocalDebugPrefix(isLocalDebug, ConfigKeys.clientSecret), faker.datatype.uuid() ); if (!isLocalDebug) { // set context.envInfo.state.get(SOLUTION)[ARM_TEMPLATE_OUTPUT]["domain"] = some fake value const solutionProfile = context.envInfo.state.get(SOLUTION) ?? new Map(); const armOutput = solutionProfile[ARM_TEMPLATE_OUTPUT] ?? {}; const aadProfile = context.envInfo.state.get(Plugins.pluginNameComplex) ?? new Map(); aadProfile.set(ConfigKeys.clientId, faker.datatype.uuid()); aadProfile.set(ConfigKeys.objectId, faker.datatype.uuid()); aadProfile.set(ConfigKeys.clientSecret, faker.datatype.uuid()); if (hasFrontend) { armOutput["frontendHostingOutput"] = { type: "Object", value: { teamsFxPluginId: "fx-resource-frontend-hosting", storageResourceId: `/subscriptions/test_subscription_id/resourceGroups/test_resource_group_name/providers/Microsoft.Storage/storageAccounts/test_storage_name`, endpoint: `https://test_storage_name.z13.web.core.windows.net`, domain: `test_storage_name.z13.web.core.windows.net`, }, }; } solutionProfile.set(ARM_TEMPLATE_OUTPUT, armOutput); context.envInfo.state.set(SOLUTION, solutionProfile); context.envInfo.state.set(Plugins.pluginNameComplex, aadProfile); } else { const aadInfo = new ConfigMap(); aadInfo.set(ConfigKeys.clientId, faker.datatype.uuid()); aadInfo.set(ConfigKeys.objectId, faker.datatype.uuid()); aadInfo.set(ConfigKeys.clientSecret, faker.datatype.uuid()); aadInfo.set(ConfigKeys.oauth2PermissionScopeId, faker.datatype.uuid()); const frontendInfo = new ConfigMap(); frontendInfo.set("tabDomain", "fake.storage.domain.test"); frontendInfo.set("tabEndpoint", "https://fake.storage.domain.test"); const localSettings: LocalSettings = { teamsApp: new ConfigMap(), auth: aadInfo, frontend: frontendInfo, }; context.localSettings = localSettings; } } export function mockSkipFlag(context: PluginContext, isLocalDebug = false) { if (isLocalDebug) { const aadInfo = new ConfigMap(); aadInfo.set(ConfigKeys.clientId, faker.datatype.uuid()); aadInfo.set(ConfigKeys.objectId, faker.datatype.uuid()); aadInfo.set(ConfigKeys.clientSecret, faker.datatype.uuid()); aadInfo.set(ConfigKeys.oauth2PermissionScopeId, faker.datatype.uuid()); const localSettings: LocalSettings = { teamsApp: new ConfigMap(), auth: aadInfo, }; context.localSettings = localSettings; } else { const config: EnvConfig = { auth: { clientId: faker.datatype.uuid(), objectId: faker.datatype.uuid(), clientSecret: faker.datatype.uuid(), accessAsUserScopeId: faker.datatype.uuid(), }, manifest: { appName: { short: "appName", }, }, }; context.envInfo.config = config; context.envInfo.state.set(Plugins.pluginNameComplex, new Map()); } } export function mockTokenProvider(): AppStudioTokenProvider { const provider = <AppStudioTokenProvider>{}; const mockTokenObject = { tid: faker.datatype.uuid(), }; provider.getAccessToken = sinon.stub().returns("token"); provider.getJsonObject = sinon.stub().returns(mockTokenObject); return provider; } export function mockTokenProviderGraph(): GraphTokenProvider { const provider = <GraphTokenProvider>{}; const mockTokenObject = { tid: faker.datatype.uuid(), }; provider.getAccessToken = sinon.stub().returns("token"); provider.getJsonObject = sinon.stub().returns(mockTokenObject); return provider; } export function mockTokenProviderAzure(token: string): AppStudioTokenProvider { const provider = <AppStudioTokenProvider>{}; const tokenObject = jwt_decode(token); provider.getAccessToken = sinon.stub().returns(token); provider.getJsonObject = sinon.stub().returns(tokenObject); return provider; } export function mockTokenProviderAzureGraph(token: string): GraphTokenProvider { const provider = <GraphTokenProvider>{}; const tokenObject = jwt_decode(token); provider.getAccessToken = sinon.stub().returns(token); provider.getJsonObject = sinon.stub().returns(tokenObject); return provider; }
the_stack
import {WebPlugin} from '@capacitor/core'; import type {OAuth2AuthenticateOptions, OAuth2ClientPlugin, OAuth2RefreshTokenOptions} from "./definitions"; import {WebOptions, WebUtils} from "./web-utils"; export class OAuth2ClientPluginWeb extends WebPlugin implements OAuth2ClientPlugin { private webOptions: WebOptions; private windowHandle: Window | null; private intervalId: number; private loopCount = 2000; private intervalLength = 100; private windowClosedByPlugin: boolean; /** * Get a new access token using an existing refresh token. */ async refreshToken(_options: OAuth2RefreshTokenOptions): Promise<any> { return new Promise<any>((_resolve, reject) => { reject(new Error("Functionality not implemented for PWAs yet")); }); } async authenticate(options: OAuth2AuthenticateOptions): Promise<any> { this.webOptions = await WebUtils.buildWebOptions(options); return new Promise<any>((resolve, reject) => { // validate if (!this.webOptions.appId || this.webOptions.appId.length == 0) { reject(new Error("ERR_PARAM_NO_APP_ID")); } else if (!this.webOptions.authorizationBaseUrl || this.webOptions.authorizationBaseUrl.length == 0) { reject(new Error("ERR_PARAM_NO_AUTHORIZATION_BASE_URL")); } else if (!this.webOptions.redirectUrl || this.webOptions.redirectUrl.length == 0) { reject(new Error("ERR_PARAM_NO_REDIRECT_URL")); } else if (!this.webOptions.responseType || this.webOptions.responseType.length == 0) { reject(new Error("ERR_PARAM_NO_RESPONSE_TYPE")); } else { // init internal control params let loopCount = this.loopCount; this.windowClosedByPlugin = false; // open window const authorizationUrl = WebUtils.getAuthorizationUrl(this.webOptions); if (this.webOptions.logsEnabled) { this.doLog("Authorization url: " + authorizationUrl); } this.windowHandle = window.open( authorizationUrl, this.webOptions.windowTarget, this.webOptions.windowOptions, this.webOptions.windowReplace); // wait for redirect and resolve the this.intervalId = window.setInterval(() => { if (loopCount-- < 0) { this.closeWindow(); } else if (this.windowHandle?.closed && !this.windowClosedByPlugin) { window.clearInterval(this.intervalId); reject(new Error("USER_CANCELLED")); } else { let href: string = undefined!; try { href = this.windowHandle?.location.href!; } catch (ignore) { // ignore DOMException: Blocked a frame with origin "http://localhost:4200" from accessing a cross-origin frame. } if (href != null && href.indexOf(this.webOptions.redirectUrl) >= 0) { if (this.webOptions.logsEnabled) { this.doLog("Url from Provider: " + href); } let authorizationRedirectUrlParamObj = WebUtils.getUrlParams(href); if (authorizationRedirectUrlParamObj) { if (this.webOptions.logsEnabled) { this.doLog("Authorization response:", authorizationRedirectUrlParamObj); } window.clearInterval(this.intervalId); // check state if (authorizationRedirectUrlParamObj.state === this.webOptions.state) { if (this.webOptions.accessTokenEndpoint) { const self = this; let authorizationCode = authorizationRedirectUrlParamObj.code; if (authorizationCode) { const tokenRequest = new XMLHttpRequest(); tokenRequest.onload = function () { if (this.status === 200) { let accessTokenResponse = JSON.parse(this.response); if (self.webOptions.logsEnabled) { self.doLog("Access token response:", accessTokenResponse); } self.requestResource(accessTokenResponse.access_token, resolve, reject, authorizationRedirectUrlParamObj, accessTokenResponse); } }; tokenRequest.onerror = function () { // always log error because of CORS hint self.doLog("ERR_GENERAL: See client logs. It might be CORS. Status text: " + this.statusText); reject(new Error("ERR_GENERAL")); }; tokenRequest.open("POST", this.webOptions.accessTokenEndpoint, true); tokenRequest.setRequestHeader('accept', 'application/json'); tokenRequest.setRequestHeader('cache-control', 'no-cache'); tokenRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); tokenRequest.send(WebUtils.getTokenEndpointData(this.webOptions, authorizationCode)); } else { reject(new Error("ERR_NO_AUTHORIZATION_CODE")); } this.closeWindow(); } else { // if no accessTokenEndpoint exists request the resource this.requestResource(authorizationRedirectUrlParamObj.access_token, resolve, reject, authorizationRedirectUrlParamObj); } } else { if (this.webOptions.logsEnabled) { this.doLog("State from web options: " + this.webOptions.state); this.doLog("State returned from provider: " + authorizationRedirectUrlParamObj.state); } reject(new Error("ERR_STATES_NOT_MATCH")); this.closeWindow(); } } // this is no error no else clause required } } }, this.intervalLength); } }); } private readonly MSG_RETURNED_TO_JS = "Returned to JS:"; private requestResource(accessToken: string, resolve: any, reject: (reason?: any) => void, authorizationResponse: any, accessTokenResponse: any = null) { if (this.webOptions.resourceUrl) { const logsEnabled = this.webOptions.logsEnabled; if (logsEnabled) { this.doLog("Resource url: " + this.webOptions.resourceUrl); } if (accessToken) { if (logsEnabled) { this.doLog("Access token:", accessToken); } const self = this; const request = new XMLHttpRequest(); request.onload = function () { if (this.status === 200) { let resp = JSON.parse(this.response); if (logsEnabled) { self.doLog("Resource response:", resp); } if (resp) { self.assignResponses(resp, accessToken, authorizationResponse, accessTokenResponse); } if (logsEnabled) { self.doLog(self.MSG_RETURNED_TO_JS, resp); } resolve(resp); } else { reject(new Error(this.statusText)); } self.closeWindow(); }; request.onerror = function () { if (logsEnabled) { self.doLog("ERR_GENERAL: " + this.statusText); } reject(new Error("ERR_GENERAL")); self.closeWindow(); }; request.open("GET", this.webOptions.resourceUrl, true); request.setRequestHeader('Authorization', `Bearer ${accessToken}`); if (this.webOptions.additionalResourceHeaders) { for (const key in this.webOptions.additionalResourceHeaders) { request.setRequestHeader(key, this.webOptions.additionalResourceHeaders[key]); } } request.send(); } else { if (logsEnabled) { this.doLog("No accessToken was provided although you configured a resourceUrl. Remove the resourceUrl from the config."); } reject(new Error("ERR_NO_ACCESS_TOKEN")); this.closeWindow(); } } else { // if no resource url exists just return the accessToken response const resp = {}; this.assignResponses(resp, accessToken, authorizationResponse, accessTokenResponse); if (this.webOptions.logsEnabled) { this.doLog(this.MSG_RETURNED_TO_JS, resp); } resolve(resp); this.closeWindow(); } } assignResponses(resp: any, accessToken: string, authorizationResponse: any, accessTokenResponse: any = null): void { // #154 if (authorizationResponse) { resp["authorization_response"] = authorizationResponse; } if (accessTokenResponse) { resp["access_token_response"] = accessTokenResponse; } resp["access_token"] = accessToken; } async logout(options: OAuth2AuthenticateOptions): Promise<boolean> { return new Promise<any>((resolve, _reject) => { localStorage.removeItem(WebUtils.getAppId(options)); resolve(true); }); } private closeWindow() { window.clearInterval(this.intervalId); // #164 if the provider's login page is opened in the same tab or window it must not be closed // if (this.webOptions.windowTarget !== "_self") { // this.windowHandle?.close(); // } this.windowHandle?.close(); this.windowClosedByPlugin = true; } private doLog(msg: string, obj: any = null) { console.log("I/Capacitor/OAuth2ClientPlugin: " + msg, obj); } }
the_stack
import React, { useState } from 'react'; import { v4 as uuid } from 'uuid'; // Give composer access to both business Redux store slice and all actions import { useDispatch } from 'react-redux'; import * as actions from '../../../features/business/businessSlice'; import * as uiactions from '../../../features/ui/uiSlice'; // Import controllers import connectionController from '../../../controllers/reqResController'; import historyController from '../../../controllers/historyController'; // Import local components import Http2EndpointForm from './Http2EndpointForm'; import Http2MetaData from './Http2MetaData'; // TODO: refactor all of the below components to use MUI, place them in a new "components" folder import RestMethodAndEndpointEntryForm from '../new-request/RestMethodAndEndpointEntryForm'; import HeaderEntryForm from '../new-request/HeaderEntryForm'; import CookieEntryForm from '../new-request/CookieEntryForm'; import SendRequestButton from '../new-request/SendRequestButton'; import NewRequestButton from '../new-request/NewRequestButton'; import BodyEntryForm from '../new-request/BodyEntryForm'; import TestEntryForm from '../new-request/TestEntryForm'; // Import MUI components import { Box, Typography } from '@mui/material'; import { BooleanValueNode } from 'graphql'; // Translated from RestContainer.jsx export default function Http2Composer(props) { interface Parameter { id: string; key: string; value: string; toggle: boolean; } interface Header { id: string; key: string; value: string; toggle: boolean; } interface Cookie { id: string; key: string; value: string; toggle: BooleanValueNode; } const [parameters, setParameters] = useState<Parameter[]>([]) const [headers, setHeaders] = useState<Header[]>([]) const [cookies, setCookies] = useState<Cookie[]>([]) const [http2Method, setHttp2Method] = useState('GET') const [http2Uri, setHttp2Uri] = useState('') const dispatch = useDispatch(); // Destructuring business store props. const { currentTab, newRequestFields, newRequestHeaders, newRequestBody, newRequestCookies, newRequestStreams, newRequestSSE, warningMessage, } = props; // console.log(newRequestBody) const { gRPC, url, method, graphQL, restUrl, wsUrl, webrtc, gqlUrl, grpcUrl, network, testContent, } = newRequestFields; const { JSONFormatted, rawType, bodyContent, bodyVariables, bodyType, } = newRequestBody; // Destructuring dispatch props. const { setNewRequestFields, resetComposerFields, setNewRequestBody, setNewTestContent, setNewRequestHeaders, setNewRequestCookies, setNewRequestStreams, setNewRequestSSE, setComposerWarningMessage, setWorkspaceActiveTab, reqResAdd } = props; const { protoPath } = newRequestSSE; const { headersArr } = newRequestHeaders; const { cookiesArr } = newRequestCookies; const { isSSE } = newRequestSSE; /** * Validates the request before it is sent. * @returns ValidationMessage */ const requestValidationCheck = () => { interface ValidationMessage { uri?: string; json?: string; }; const validationMessage: ValidationMessage = {} // Error conditions... if (/https?:\/\/$|wss?:\/\/$/.test(url)) { //if url is only http/https/ws/wss:// validationMessage.uri = 'Enter a valid URI'; } if (!/(https?:\/\/)|(wss?:\/\/)/.test(url)) { //if url doesn't have http/https/ws/wss:// validationMessage.uri = 'Enter a valid URI'; } if (!JSONFormatted && rawType === 'application/json') { validationMessage.json = 'Please fix JSON body formatting errors'; } return validationMessage; }; // TODO: what does this function do? const sendNewRequest = () => { const warnings = requestValidationCheck(); if (Object.keys(warnings).length > 0) { setComposerWarningMessage(warnings); return; } let reqRes; const protocol = url.match(/(https?:\/\/)|(wss?:\/\/)/)[0]; // HTTP && GRAPHQL QUERY & MUTATION REQUESTS if (!/wss?:\/\//.test(protocol) && !gRPC) { const URIWithoutProtocol = `${url.split(protocol)[1]}/`; URIWithoutProtocol; // deleteable ??? const host = protocol + URIWithoutProtocol.split('/')[0]; let path = `/${URIWithoutProtocol.split('/') .splice(1) .join('/') .replace(/\/{2,}/g, '/')}`; if (path.charAt(path.length - 1) === '/' && path.length > 1) { path = path.substring(0, path.length - 1); } path = path.replace(/https?:\//g, 'http://'); reqRes = { id: uuid(), createdAt: new Date(), protocol: url.match(/https?:\/\//)[0], host, path, url, webrtc, graphQL, gRPC, timeSent: null, timeReceived: null, connection: 'uninitialized', connectionType: null, checkSelected: false, protoPath, request: { method, headers: headersArr.filter((header) => header.active && !!header.key), cookies: cookiesArr.filter((cookie) => cookie.active && !!cookie.key), body: bodyContent || '', bodyType, bodyVariables: bodyVariables || '', rawType, isSSE, network, restUrl, testContent: testContent || '', wsUrl, gqlUrl, grpcUrl, }, response: { headers: null, events: null, }, checked: false, minimized: false, tab: currentTab, }; } // add request to history historyController.addHistoryToIndexedDb(reqRes); reqResAdd(reqRes); // dispatch(actions.scheduledReqResUpdate(reqRes)); //reset for next request resetComposerFields(); // dispatch(actions.setResponsePaneActiveTab('events')); // dispatch(actions.setSidebarActiveTab('composer')); connectionController.openReqRes(reqRes.id); dispatch( actions.saveCurrentResponseData( reqRes, 'singleReqResContainercomponentSendHandler' ) ); }; // TODO: what does this function do? const addNewRequest = () => { const warnings = requestValidationCheck(); if (Object.keys(warnings).length > 0) { setComposerWarningMessage(warnings); return; } let reqRes; const protocol = url.match(/(https?:\/\/)|(wss?:\/\/)/)[0]; // HTTP && GRAPHQL QUERY & MUTATION REQUESTS if (!/wss?:\/\//.test(protocol) && !gRPC) { const URIWithoutProtocol = `${url.split(protocol)[1]}/`; URIWithoutProtocol; // deleteable ??? const host = protocol + URIWithoutProtocol.split('/')[0]; let path = `/${URIWithoutProtocol.split('/') .splice(1) .join('/') .replace(/\/{2,}/g, '/')}`; if (path.charAt(path.length - 1) === '/' && path.length > 1) { path = path.substring(0, path.length - 1); } path = path.replace(/https?:\//g, 'http://'); reqRes = { id: uuid(), createdAt: new Date(), protocol: url.match(/https?:\/\//)[0], host, path, url, webrtc, graphQL, gRPC, timeSent: null, timeReceived: null, connection: 'uninitialized', connectionType: null, checkSelected: false, protoPath, request: { method, headers: headersArr.filter((header) => header.active && !!header.key), cookies: cookiesArr.filter((cookie) => cookie.active && !!cookie.key), body: bodyContent || '', bodyType, bodyVariables: bodyVariables || '', rawType, isSSE, network, restUrl, testContent: testContent || '', wsUrl, gqlUrl, grpcUrl, }, response: { headers: null, events: null, }, checked: false, minimized: false, tab: currentTab, }; } // add request to history historyController.addHistoryToIndexedDb(reqRes); reqResAdd(reqRes); //reset for next request resetComposerFields(); setWorkspaceActiveTab('workspace'); }; const handleSSEPayload = (e) => { setNewRequestSSE(e.target.checked); }; return( <Box className="is-flex-grow-3 add-vertical-scroll" sx={{ height: '40%', px: 1, overflowX: 'scroll', overflowY: 'scroll', }} id = "composer-http2" > {/* <Typography align='center'> HTTP/2 </Typography> */} {/** * TODO: * The two commented components are our attempt to port the entire app to use MaterialUI for consistency. * The first one... * ... is an HTTP2Enpoint form with a (1) method select (2) endpoint form (3) send button. * The second one... * ... is all of the metadata you would need for an HTTP2 request (parameters, headers, body, cookies) * These are not tied to the Redux store currently, and thus do not interact with the app yet. * They are just standalone components that need to be integrated with the logic of the app. */} {/* <Http2EndpointForm http2Method={http2Method} setHttp2Method={setHttp2Method} http2Uri={http2Uri} setHttp2Uri={setHttp2Uri} /> <Http2MetaData parameters={parameters} setParameters={setParameters} headers={headers} setHeaders={setHeaders} cookies={cookies} setCookies={setCookies} http2Method={http2Method} /> */} <RestMethodAndEndpointEntryForm newRequestFields={newRequestFields} newRequestBody={newRequestBody} setNewTestContent={setNewTestContent} setNewRequestFields={setNewRequestFields} setNewRequestBody={setNewRequestBody} warningMessage={warningMessage} setComposerWarningMessage={setComposerWarningMessage} /> <span className="inputs"> <div> <HeaderEntryForm newRequestHeaders={newRequestHeaders} newRequestStreams={newRequestStreams} newRequestBody={newRequestBody} newRequestFields={newRequestFields} setNewRequestHeaders={setNewRequestHeaders} setNewRequestStreams={setNewRequestStreams} /> <CookieEntryForm newRequestCookies={newRequestCookies} newRequestBody={newRequestBody} setNewRequestCookies={setNewRequestCookies} /> </div> <div className="is-3rem-footer is-clickable restReqBtns"> <SendRequestButton onClick={sendNewRequest} /> <p> --- or --- </p> <NewRequestButton onClick={addNewRequest} /> </div> </span> {/* SSE TOGGLE SWITCH */} <div className="field mt-2"> <span className="composer-section-title mr-3"> Server Sent Events </span> <input id="SSEswitch" type="checkbox" className="switch is-outlined is-warning" onChange={(e) => { handleSSEPayload(e); }} checked={isSSE} /> <label htmlFor="SSEswitch" /> </div> {method !== 'GET' && ( <BodyEntryForm warningMessage={warningMessage} newRequestBody={newRequestBody} setNewRequestBody={setNewRequestBody} newRequestHeaders={newRequestHeaders} setNewRequestHeaders={setNewRequestHeaders} /> )} <TestEntryForm setNewTestContent={setNewTestContent} testContent={testContent} /> </Box> ) }
the_stack
import { Component } from 'vue-property-decorator'; import { select } from 'd3-selection'; import { line, curveBasis } from 'd3-shape'; import _ from 'lodash'; import $ from 'jquery'; import template from './line-chart.html'; import { DEFAULT_PLOT_MARGINS, drawBrushBox, getScale, injectVisualizationTemplate, PlotMargins, Scale, Visualization, drawAxis, multiplyVisuals, AnyScale, getBrushBox, isPointInBox, } from '@/components/visualization'; import ColumnSelect from '@/components/column-select/column-select'; import { VisualProperties } from '@/data/visuals'; import { SELECTED_COLOR, INDEX_COLUMN } from '@/common/constants'; import { getColumnSelectOptions, valueComparator } from '@/data/util'; import { getTransform, fadeOut } from '@/common/util'; import * as history from './history'; const DOMAIN_MARGIN = .1; const LABEL_OFFSET_PX = 5; const LEGEND_X_OFFSET_PX = 10; const LEGEND_Y_OFFSET_PX = 15; const LEGEND_LABEL_X_OFFSET_PX = 15; const LEGEND_LABEL_Y_OFFSET_PX = 10; const DEFAULT_ITEM_VISUALS: VisualProperties = { color: '#333', border: 'black', size: 3, width: 1.5, opacity: 1, }; const SELECTED_ITEM_VISUALS: VisualProperties = { color: 'white', border: SELECTED_COLOR, }; const SELECTED_LINE_VISUALS: VisualProperties = { color: SELECTED_COLOR, width: 2, }; interface LineChartSave { seriesColumn: number | null; valueColumn: number | null; groupByColumn: number | null; arePointsVisible: boolean; isCurveDrawing: boolean; areLegendsVisible: boolean; areXAxisTicksVisible: boolean; areYAxisTicksVisible: boolean; } interface LineChartLineProps { lineIndex: number; itemIndices: number[]; points: Array<[number | string, number | string]>; visuals: VisualProperties; hasVisuals: boolean; selected: boolean; label: string; } interface LineChartItemProps { index: number; x: number | string; y: number | string; hasVisuals: boolean; visuals: VisualProperties; selected: boolean; } @Component({ template: injectVisualizationTemplate(template), components: { ColumnSelect, }, }) export default class LineChart extends Visualization { protected NODE_TYPE = 'line-chart'; protected DEFAULT_WIDTH = 400; protected DEFAULT_HEIGHT = 250; private seriesColumn: number | null = null; private valueColumn: number | null = null; private groupByColumn: number | null = null; private arePointsVisible = false; private isCurveDrawing = false; private areLegendsVisible = true; private areXAxisTicksVisible = true; private areYAxisTicksVisible = true; private areSeriesValuesDuplicated = false; private margins: PlotMargins = _.extend({}, DEFAULT_PLOT_MARGINS, { bottom: 25 }); private xScale!: Scale; private yScale!: Scale; private itemProps: LineChartItemProps[] = []; private lineProps: LineChartLineProps[] = []; get columnSelectOptionsWithIndexColumn(): SelectOption[] { return [{ label: '[index]', value: INDEX_COLUMN } as SelectOption] .concat(getColumnSelectOptions(this.dataset)); } public setSeriesColumn(column: number | null) { this.seriesColumn = column; this.draw(); } public setValueColumn(column: number | null) { this.valueColumn = column; this.draw(); } public setGroupByColumn(column: number | null) { this.groupByColumn = column; this.draw(); } public setPointsVisible(value: boolean) { this.arePointsVisible = value; this.draw(); } public setCurveDrawing(value: boolean) { this.isCurveDrawing = value; this.draw(); } public setLegendsVisible(value: boolean) { this.areLegendsVisible = value; this.draw(); } public setXAxisTicksVisible(value: boolean) { this.areXAxisTicksVisible = value; this.draw(); } public setYAxisTicksVisible(value: boolean) { this.areYAxisTicksVisible = value; this.draw(); } public applyColumns(columns: number[]) { if (columns.length === 0) { this.findDefaultColumns(); return; } if (columns.length >= 1) { this.valueColumn = columns[0]; } if (columns.length >= 2) { this.seriesColumn = columns[1]; } if (columns.length >= 3) { this.groupByColumn = columns[2]; } this.draw(); } protected created() { this.serializationChain.push((): LineChartSave => ({ seriesColumn: this.seriesColumn, valueColumn: this.valueColumn, groupByColumn: this.groupByColumn, arePointsVisible: this.arePointsVisible, isCurveDrawing: this.isCurveDrawing, areLegendsVisible: this.areLegendsVisible, areXAxisTicksVisible: this.areXAxisTicksVisible, areYAxisTicksVisible: this.areYAxisTicksVisible, })); } protected findDefaultColumns() { if (!this.dataset) { return; } this.seriesColumn = this.updateColumnOnDatasetChange(this.seriesColumn); this.valueColumn = this.updateColumnOnDatasetChange(this.valueColumn); this.groupByColumn = this.updateColumnOnDatasetChange(this.groupByColumn); } protected draw() { if (this.seriesColumn === null) { this.coverText = 'Please select series column'; return; } if (this.valueColumn === null) { this.coverText = 'Please select value column'; return; } this.coverText = ''; this.computeScales(); this.computeItemProps(); this.computeLineProps(); this.updateLeftMargin(); this.updateBottomMargin(); this.drawXAxis(); this.drawYAxis(); this.drawLegends(); this.drawLines(); this.drawPoints(); this.moveSelectedLinesToFront(); } protected brushed(brushPoints: Point[], isBrushStop?: boolean) { if (isBrushStop) { this.computeBrushedItems(brushPoints); this.computeSelection(); this.computeItemProps(); this.computeLineProps(); this.drawLines(); this.drawPoints(); this.drawLegends(); this.propagateSelection(); } drawBrushBox(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []); } private computeBrushedItems(brushPoints: Point[]) { if (!this.isShiftPressed || !brushPoints.length) { this.selection.clear(); // reset selection if shift key is not down if (!brushPoints.length) { return; } } const box = getBrushBox(brushPoints); // Mapping from item to group index. const itemLineIndex: { [itemIndex: number]: number } = {}; this.lineProps.forEach(props => { props.itemIndices.forEach(itemIndex => itemLineIndex[itemIndex] = props.lineIndex); }); const pkg = this.inputPortMap.in.getSubsetPackage(); const dataset = this.getDataset(); const selectedLineIndices: Set<number> = new Set(); const itemIndices = pkg.getItemIndices(); itemIndices.forEach(itemIndex => { if (this.selection.hasItem(itemIndex)) { selectedLineIndices.add(itemLineIndex[itemIndex]); } }); for (const itemIndex of itemIndices) { const lineIndex = itemLineIndex[itemIndex]; if (selectedLineIndices.has(lineIndex)) { continue; } const point = { x: this.xScale(this.seriesColumn === INDEX_COLUMN ? itemIndex : dataset.getCellForScale(itemIndex, this.seriesColumn as number)), y: this.yScale(dataset.getCellForScale(itemIndex, this.valueColumn as number)), }; if (isPointInBox(point, box)) { selectedLineIndices.add(itemLineIndex[itemIndex]); } } for (const itemIndex of itemIndices) { if (selectedLineIndices.has(itemLineIndex[itemIndex])) { this.selection.addItem(itemIndex); } } } private moveSelectedLinesToFront() { const $lines = $(this.$refs.lines as SVGGElement); $lines.children('path[has-visuals=true]').appendTo(this.$refs.lines as SVGGElement); $lines.children('path[is-selected=true]').appendTo(this.$refs.lines as SVGGElement); } private computeScales() { const pkg = this.inputPortMap.in.getSubsetPackage(); const dataset = this.getDataset(); this.yScale = getScale( dataset.getColumnType(this.valueColumn as number), dataset.getDomain(this.valueColumn as number, pkg.getItemIndices()), [this.svgHeight - this.margins.bottom, this.margins.top], ); this.xScale = getScale( dataset.getColumnType(this.seriesColumn as number), dataset.getDomain(this.seriesColumn as number, pkg.getItemIndices()), [this.margins.left, this.svgWidth - this.margins.right], ); } private computeItemProps() { const pkg = this.inputPortMap.in.getSubsetPackage(); const dataset = this.getDataset(); this.itemProps = pkg.getItems().map(item => { const props: LineChartItemProps = { index: item.index, x: this.seriesColumn === INDEX_COLUMN ? item.index : dataset.getCellForScale(item, this.seriesColumn as number), y: dataset.getCellForScale(item, this.valueColumn as number), visuals: _.extend({}, DEFAULT_ITEM_VISUALS, item.visuals), hasVisuals: !_.isEmpty(item.visuals), selected: this.selection.hasItem(item.index), }; if (props.selected) { _.extend(props, SELECTED_ITEM_VISUALS); multiplyVisuals(props.visuals); } return props; }); } private computeLineProps() { const pkg = this.inputPortMap.in.getSubsetPackage(); const dataset = this.getDataset(); const itemGroups = pkg.groupItems(this.groupByColumn); this.sortItems(itemGroups); this.lineProps = itemGroups.map((itemIndices, groupIndex) => { const props: LineChartLineProps = { lineIndex: groupIndex, itemIndices, points: [], label: this.groupByColumn === INDEX_COLUMN || this.groupByColumn === null ? '' : dataset.getCell(itemIndices[0], this.groupByColumn as number).toString(), visuals: _.clone(DEFAULT_ITEM_VISUALS), hasVisuals: false, selected: false, }; let groupSelected = false; itemIndices.forEach(itemIndex => { const item = pkg.getItem(itemIndex); _.extend(props.visuals, item.visuals); props.points.push([ this.seriesColumn === INDEX_COLUMN ? itemIndex : dataset.getCellForScale(itemIndex, this.seriesColumn as number), dataset.getCellForScale(itemIndex, this.valueColumn as number), ]); props.hasVisuals = props.hasVisuals || !_.isEmpty(item.visuals); groupSelected = groupSelected || this.selection.hasItem(itemIndex); }); if (groupSelected) { props.selected = true; _.extend(props.visuals, SELECTED_LINE_VISUALS); multiplyVisuals(props.visuals); } return props; }); } /** * Sorts data items in each group based on seriesColumn. */ private sortItems(itemGroups: number[][]) { const dataset = this.getDataset(); let seriesCollided = false; const seriesColumn = this.seriesColumn as number; const isIndexColumn = seriesColumn === INDEX_COLUMN; const columnType = dataset.getColumnType(seriesColumn); const comparator = valueComparator(columnType); itemGroups.forEach(itemIndices => { itemIndices.sort((a, b) => isIndexColumn ? a - b : comparator(dataset.getCell(a, seriesColumn), dataset.getCell(b, seriesColumn))); for (let i = 1; !seriesCollided && i < itemIndices.length; i++) { const itemIndex = itemIndices[i]; const prevIndex = itemIndices[i - 1]; const curValue = isIndexColumn ? itemIndex : dataset.getCell(itemIndex, seriesColumn); const prevValue = isIndexColumn ? itemIndex : dataset.getCell(prevIndex, seriesColumn); if (comparator(curValue, prevValue) === 0) { seriesCollided = true; } } }); this.areSeriesValuesDuplicated = seriesCollided; } private updateLeftMargin() { this.drawYAxis(); if (this.areLegendsVisible) { this.drawLegends(); } this.updateMargins(() => { const maxTickWidth = _.max($(this.$refs.yAxis as SVGGElement) .find('.y > .tick > text') .map((index: number, element: SVGGraphicsElement) => element.getBBox().width)) || 0; this.margins.left = DEFAULT_PLOT_MARGINS.left + maxTickWidth; if (this.areLegendsVisible) { const maxLegendWidth = _.max($(this.$refs.legends as SVGGElement) .find('> g') .map((index: number, element: SVGGraphicsElement) => element.getBBox().width)) || 0; this.margins.left += maxLegendWidth + LEGEND_LABEL_X_OFFSET_PX + LEGEND_X_OFFSET_PX; } (this.xScale as AnyScale).range([this.margins.left, this.svgWidth - this.margins.right]); }); } private updateBottomMargin() { this.drawXAxis(); this.updateMargins(() => { const maxTickHeight = _.max($(this.$refs.xAxis as SVGGElement) .find('.x > .tick > text') .map((index: number, element: SVGGraphicsElement) => element.getBBox().height)) || 0; this.margins.bottom = DEFAULT_PLOT_MARGINS.bottom + maxTickHeight; (this.yScale as AnyScale).range([this.svgHeight - this.margins.bottom, this.margins.top]); }); } private drawLines() { // const points: { [index: number]: { x: string | number, y: string | number } } = {}; const l = line<[number | string, number | string]>() .x(point => this.xScale(point[0])) .y(point => this.yScale(point[1])); if (this.isCurveDrawing) { l.curve(curveBasis); } // this.itemProps.forEach(props => points[props.index] = { x: props.x, y: props.y }); let lines = select(this.$refs.lines as SVGGElement).selectAll<SVGPathElement, LineChartLineProps>('path') .data(this.lineProps, d => d.lineIndex.toString()); fadeOut(lines.exit()); lines = lines.enter().append<SVGPathElement>('path') .attr('id', d => d.lineIndex) .merge(lines) .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected); const updatedLines = this.isTransitionFeasible(this.itemProps.length) ? lines.transition() : lines; updatedLines .style('stroke', d => d.visuals.color as string) .style('stroke-width', d => d.visuals.width + 'px') .style('opacity', d => d.visuals.opacity as number) .attr('d', d => l(d.points)); } private drawPoints() { if (!this.arePointsVisible) { fadeOut(select(this.$refs.points as SVGGElement).selectAll('*')); return; } let points = select(this.$refs.points as SVGGElement).selectAll<SVGCircleElement, LineChartItemProps>('circle') .data(this.itemProps, d => d.index.toString()); fadeOut(points.exit()); points = points.enter().append<SVGCircleElement>('circle') .merge(points) .attr('cx', d => this.xScale(d.x)) .attr('cy', d => this.yScale(d.y)) .attr('r', d => d.visuals.size as number) .attr('has-visuals', d => d.hasVisuals) .attr('is-selected', d => d.selected); const updatedPoints = this.isTransitionFeasible(this.itemProps.length) ? points.transition() : points; updatedPoints .style('fill', d => d.visuals.color as string) .style('stroke', d => d.visuals.border as string) .style('stroke-width', d => d.visuals.width + 'px') .style('opacity', d => d.visuals.opacity as number); } private drawXAxis() { drawAxis(this.$refs.xAxis as SVGElement, this.xScale, { classes: 'x', orient: 'bottom', ticks: !this.areXAxisTicksVisible ? 0 : undefined, transform: getTransform([0, this.svgHeight - this.margins.bottom]), label: { text: this.getDataset().getColumnName(this.seriesColumn as number), transform: getTransform([this.svgWidth - this.margins.right, -LABEL_OFFSET_PX]), }, }); } private drawYAxis() { drawAxis(this.$refs.yAxis as SVGElement, this.yScale, { classes: 'y', orient: 'left', ticks: !this.areYAxisTicksVisible ? 0 : undefined, transform: getTransform([this.margins.left, 0]), label: { text: this.getDataset().getColumnName(this.valueColumn as number), transform: getTransform([LABEL_OFFSET_PX, this.margins.top], 1, 90), }, }); } private drawLegends() { const svgLegends = select(this.$refs.legends as SVGGElement); if (!this.areLegendsVisible || this.groupByColumn === INDEX_COLUMN || this.groupByColumn === null) { fadeOut(svgLegends.selectAll('*')); return; } const boxes = svgLegends.selectAll<SVGGElement, LineChartLineProps>('g').data(this.lineProps); fadeOut(boxes.exit()); const enteredBoxes = boxes.enter().append<SVGGElement>('g') .attr('transform', (props, index) => getTransform([LEGEND_X_OFFSET_PX, (index + 1) * LEGEND_Y_OFFSET_PX])); const labelTransform = getTransform([LEGEND_LABEL_X_OFFSET_PX, LEGEND_LABEL_Y_OFFSET_PX]); enteredBoxes.append('rect'); // color box enteredBoxes.append('text'); // label const updatedBoxes = enteredBoxes.merge(boxes); updatedBoxes.select('rect') .style('fill', d => d.visuals.color as string); updatedBoxes.select('text') .attr('transform', labelTransform) .text(d => d.label); } private onInputSeriesColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectSeriesColumnEvent(this, column, prevColumn)); this.setSeriesColumn(column); } private onInputValueColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectValueColumnEvent(this, column, prevColumn)); this.setValueColumn(column); } private onInputGroupByColumn(column: number | null, prevColumn: number | null) { this.commitHistory(history.selectGroupByColumnEvent(this, column, prevColumn)); this.setGroupByColumn(column); } private onTogglePointsVisible(value: boolean) { this.commitHistory(history.togglePointsVisibleEvent(this, value)); this.setPointsVisible(value); } private onToggleCurveDrawing(value: boolean) { this.commitHistory(history.toggleCurveDrawingEvent(this, value)); this.setCurveDrawing(value); } private onToggleLegendsVisible(value: boolean) { this.commitHistory(history.toggleLegendsVisibleEvent(this, value)); this.setLegendsVisible(value); } private onToggleXAxisTicksVisible(value: boolean) { this.commitHistory(history.toggleXAxisTicksVisibleEvent(this, value)); this.setXAxisTicksVisible(value); } private onToggleYAxisTicksVisible(value: boolean) { this.commitHistory(history.toggleYAxisTicksVisibleEvent(this, value)); this.setYAxisTicksVisible(value); } }
the_stack
import Connection from '../../../src/lib/connection'; import * as mediasoupMixer from '../../../src/lib/media-soup/mediasoup-mixer'; import { Participant } from '../../../src/lib/participant'; import { MEDIA_CAN_SHARE_AUDIO, MEDIA_CAN_SHARE_WEBCAM, Permission } from '../../../src/lib/permissions'; import Room from '../../../src/lib/rooms/room'; import { ConferenceRepository } from '../../../src/lib/synchronization/conference-repository'; import { ConferenceInfo, ProducerLink } from '../../../src/lib/types'; import fromEntries from 'object.fromentries'; const createConferenceRepoMock = (conference: ConferenceInfo): ConferenceRepository => { return { getConference: jest.fn().mockReturnValue(conference) } as any; }; const createMediasoupMixerMock = () => { const removeReceiveTransport = jest.fn(); const addReceiveTransport = jest.fn(); const removeProducer = jest.fn(); const addProducer = jest.fn(); const instance = { removeReceiveTransport, addReceiveTransport, removeProducer, addProducer }; jest.spyOn(mediasoupMixer, 'MediasoupMixer').mockReturnValue(instance as any); return instance; }; const createConn = (connectionId: string) => ({ connectionId } as Connection); const createProducer = (id: string) => ({ producer: { id } } as any as ProducerLink); const conferenceWithPermissions = (participantId: string, ...permissions: Permission<boolean>[]): ConferenceInfo => ({ ...emptyConference, participantPermissions: new Map().set(participantId, fromEntries(permissions.map((x) => [x.key, true]))), }); const emptyConference: ConferenceInfo = { participantPermissions: new Map(), participantToRoom: new Map() }; const roomId = '123'; const conferenceId = '1'; test('join() | active receive connection without permissions | add to mixer', async () => { const conferenceRepo = createConferenceRepoMock(emptyConference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant = { connections: [], participantId: '1', producers: {}, receiveConnection: createConn('34'), }; await room.join(participant); expect(room.getIsParticipantJoined(participant.participantId)).toEqual(true); expect(mixer.addReceiveTransport.mock.calls.length).toEqual(1); expect(mixer.addReceiveTransport.mock.calls[0][0]).toEqual(participant.receiveConnection); }); test('join() | active producer but no permissions | dont add producer to mixer', async () => { const conferenceRepo = createConferenceRepoMock(emptyConference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); expect(room.getIsParticipantJoined(participant.participantId)).toEqual(true); expect(mixer.addProducer.mock.calls.length).toEqual(0); }); test('join() | active producer with permissions | add producer to mixer', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); expect(room.getIsParticipantJoined(participant.participantId)).toEqual(true); expect(mixer.addProducer.mock.calls.length).toEqual(1); expect(mixer.addProducer.mock.calls[0][0]).toEqual({ participantId: participant.participantId, producer: participant.producers.mic?.producer, }); }); test('updateParticipant() | equal participant | do nothing', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); await room.updateParticipant(participant); expect(room.getIsParticipantJoined(participant.participantId)).toEqual(true); expect(mixer.addProducer.mock.calls.length).toEqual(1); expect(mixer.removeProducer.mock.calls.length).toEqual(0); }); test('updateParticipant() | new producer | add producer to mixer', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO, MEDIA_CAN_SHARE_WEBCAM); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic', 'webcam']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); const webcamProducer = createProducer('6'); await room.updateParticipant({ ...participant, producers: { ...participant.producers, webcam: webcamProducer, }, }); expect(room.getIsParticipantJoined(participant.participantId)).toEqual(true); expect(mixer.addProducer.mock.calls.length).toEqual(2); expect(mixer.addProducer.mock.calls[1][0]).toEqual({ participantId: participant.participantId, producer: webcamProducer.producer, }); }); test('updateParticipant() | new producer but no permissions | dont add producer to mixer', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic', 'webcam']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); const webcamProducer = createProducer('6'); await room.updateParticipant({ ...participant, producers: { ...participant.producers, webcam: webcamProducer, }, }); expect(mixer.addProducer.mock.calls.length).toEqual(1); }); test('updateParticipant() | removed producer | remove producer from mixer', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); await room.updateParticipant({ ...participant, producers: {}, }); expect(mixer.addProducer.mock.calls.length).toEqual(1); expect(mixer.removeProducer.mock.calls.length).toEqual(1); expect(mixer.removeProducer.mock.calls[0][0]).toEqual(participant.producers.mic!.producer.id); }); test('updateParticipant() | removed permissions | remove producer from mixer', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); const conferenceWithoutPermissions = conferenceWithPermissions('1'); (conferenceRepo.getConference as any).mockReturnValueOnce(conferenceWithoutPermissions); await room.updateParticipant(participant); expect(mixer.removeProducer.mock.calls.length).toEqual(1); expect(mixer.removeProducer.mock.calls[0][0]).toEqual(participant.producers.mic!.producer.id); }); test('updateParticipant() | added permissions | add to mixer', async () => { const conference = conferenceWithPermissions('1'); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: undefined, }; await room.join(participant); expect(mixer.addProducer.mock.calls.length).toEqual(0); const newConferenceInfo = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); (conferenceRepo.getConference as any).mockReturnValueOnce(newConferenceInfo); await room.updateParticipant(participant); expect(mixer.addProducer.mock.calls.length).toEqual(1); }); test('updateParticipant() | new receive transport | update old transport and subscribe new one', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('5'), }, receiveConnection: createConn('old'), }; await room.join(participant); const newParticipant: Participant = { ...participant, receiveConnection: createConn('receiveConn'), }; await room.updateParticipant(newParticipant); expect(mixer.addReceiveTransport.mock.calls.length).toEqual(2); expect(mixer.removeReceiveTransport.mock.calls.length).toEqual(1); expect(mixer.addReceiveTransport.mock.calls[0][0]).toEqual(participant.receiveConnection); expect(mixer.addReceiveTransport.mock.calls[1][0]).toEqual(newParticipant.receiveConnection); expect(mixer.removeReceiveTransport.mock.calls[0][0]).toEqual('old'); }); test('leave() | not joined | no error', async () => { const conferenceRepo = createConferenceRepoMock(emptyConference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: {}, receiveConnection: undefined, }; await room.leave(participant); }); test('leave() | joined with receive connection | remove receive connection', async () => { const conferenceRepo = createConferenceRepoMock(emptyConference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: {}, receiveConnection: createConn('receiveConnId'), }; await room.join(participant); await room.leave(participant); expect(mixer.removeReceiveTransport.mock.calls[0][0]).toEqual('receiveConnId'); }); test('leave() | joined with producer | remove producer', async () => { const conference = conferenceWithPermissions('1', MEDIA_CAN_SHARE_AUDIO); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('producerId'), }, receiveConnection: undefined, }; await room.join(participant); await room.leave(participant); expect(mixer.removeProducer.mock.calls[0][0]).toEqual('producerId'); }); test('leave() | has producer but not activated | dont remove producer', async () => { const conference = conferenceWithPermissions('1'); const conferenceRepo = createConferenceRepoMock(conference); const mixer = createMediasoupMixerMock(); const room = new Room(roomId, undefined as any, undefined as any, conferenceRepo, conferenceId, ['mic']); const participant: Participant = { connections: [], participantId: '1', producers: { mic: createProducer('producerId'), }, receiveConnection: undefined, }; await room.join(participant); await room.leave(participant); expect(mixer.removeProducer.mock.calls.length).toEqual(0); }); // test('getIsParticipantJoined() should return false if participant is not joined', () => { // const conferenceRepo = createConferenceRepoMock(emptyConference); // const mixer = createMediasoupMixerMock(); // const room = new Room('123', undefined as any, undefined as any, conferenceRepo as any, '123', ['mic']); // expect(room.getIsParticipantJoined('123')).toEqual(false); // });
the_stack
import { expect } from "chai"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ContentSpecificationTypes, KeySet, RelationshipDirection, Ruleset, RuleTypes } from "@itwin/presentation-common"; import { Presentation } from "@itwin/presentation-frontend"; import { initialize, terminate } from "../../../IntegrationTests"; import { printRuleset } from "../../Utils"; describe("Learning Snippets", () => { let imodel: IModelConnection; beforeEach(async () => { await initialize(); imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim"); }); afterEach(async () => { await imodel.close(); await terminate(); }); describe("Content Rules", () => { describe("ContentRule", () => { it("uses `SelectedNode` symbol in rule condition", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentRule.Condition.SelectedNodeSymbol // The ruleset has two content rules: // - the one for `bis.Element` returns content for input instances // - the one for `bis.Model` returns content for input model's contained elements const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, condition: `SelectedNode.IsOfClass("Element", "BisCore")`, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, }], }, { ruleType: RuleTypes.Content, condition: `SelectedNode.IsOfClass("Model", "BisCore")`, specifications: [{ specType: ContentSpecificationTypes.ContentRelatedInstances, relationshipPaths: [{ relationship: { schemaName: "BisCore", className: "ModelContainsElements" }, direction: RelationshipDirection.Forward, }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Expect element content when providing `bis.Element` input const elementContent = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "Generic:PhysicalObject", id: "0x74" }]), descriptor: {}, }); expect(elementContent!.contentSet.length).to.eq(1); expect(elementContent!.contentSet[0].primaryKeys).to.deep.eq([{ className: "Generic:PhysicalObject", id: "0x74" }]); const modelContent = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:PhysicalModel", id: "0x1c" }]), descriptor: {}, }); expect(modelContent!.contentSet.length).to.eq(62); }); it("uses ruleset variables in rule condition", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentRule.Condition.RulesetVariables.Ruleset // The ruleset has two content rules that return content for `bis.SpatialCategory` and `bis.GeometricModel` instances. Both // rules can be enabled or disabled with a ruleset variable. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, condition: `GetVariableBoolValue("DISPLAY_CATEGORIES")`, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialCategory"] }, handleInstancesPolymorphically: true, }], }, { ruleType: RuleTypes.Content, condition: `GetVariableBoolValue("DISPLAY_MODELS")`, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricModel"] }, handleInstancesPolymorphically: true, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // No variables set - no content let content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content).to.be.undefined; // Set DISPLAY_CATEGORIES to get content of all Category instances in the imodel await Presentation.presentation.vars(ruleset.id).setBool("DISPLAY_CATEGORIES", true); content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet).to.containSubset([{ primaryKeys: [{ className: "BisCore:SpatialCategory", id: "0x17" }], }]).and.to.have.lengthOf(1); // Set DISPLAY_MODELS to also get geometric model instances' content await Presentation.presentation.vars(ruleset.id).setBool("DISPLAY_MODELS", true); content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet).to.containSubset([{ primaryKeys: [{ className: "BisCore:SpatialCategory", id: "0x17" }], }, { primaryKeys: [{ className: "BisCore:PhysicalModel", id: "0x1c" }], }]).and.to.have.lengthOf(2); }); it("uses `requiredSchemas` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentRule.RequiredSchemas.Ruleset // The ruleset has one content rule that returns content of `bis.ExternalSourceAspect` instances. The // ECClass was introduced in BisCore version 1.0.2, so the rule needs a `requiredSchemas` attribute // to only use the rule if the version meets the requirement. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, requiredSchemas: [{ name: "BisCore", minVersion: "1.0.2" }], specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["ExternalSourceAspect"], }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // The iModel uses BisCore older than 1.0.2 - no content should be returned const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content).to.be.undefined; }); it("uses `priority` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentRule.Priority.Ruleset // The ruleset has two content rules that return content for `bis.SpatialCategory` and // `bis.GeometricModel` respectively. The rules have different priorities and higher priority // rule is handled first - it's content appears first. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, priority: 1, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialCategory"] }, handleInstancesPolymorphically: true, }], }, { ruleType: RuleTypes.Content, priority: 2, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricModel"] }, handleInstancesPolymorphically: true, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Expect GeometricModel record to be first even though category rule was defined first const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet).to.containSubset([{ primaryKeys: [{ className: "BisCore:PhysicalModel", id: "0x1c" }], }, { primaryKeys: [{ className: "BisCore:SpatialCategory", id: "0x17" }], }]).and.to.have.lengthOf(2); }); it("uses `onlyIfNotHandled` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.ContentRule.OnlyIfNotHandled.Ruleset // The ruleset has two root node rules that return content for `bis.SpatialCategory` and // `bis.GeometricModel` respectively. The `bis.SpatialCategory` rule has lower priority and `onlyIfNotHandled` // attribute, which allows it to be overriden by higher priority rules. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, priority: 1, onlyIfNotHandled: true, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["SpatialCategory"] }, handleInstancesPolymorphically: true, }], }, { ruleType: RuleTypes.Content, priority: 2, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricModel"] }, handleInstancesPolymorphically: true, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Expect only `GeometricModel` record, as the rule for `SpatialCategory` is skipped due to `onlyIfNotHandled` attribute const content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {}, }); expect(content!.contentSet).to.containSubset([{ primaryKeys: [{ className: "BisCore:PhysicalModel", id: "0x1c" }], }]).and.to.have.lengthOf(1); }); }); }); });
the_stack
import * as React from 'react'; import { Animated, StyleSheet, Text, TextStyle, View, ViewStyle, } from 'react-native'; import { steps as theme } from '../../_styles/themes/default.components'; import MDIcon from '../icon'; export interface IMDStepsItem { title: string; brief?: string; } type MDStepsDirection = 'horizontal' | 'vertical'; type MDStepStatus = 'current' | 'reached' | 'unreached'; export type MDStepsRenderFunc = ( status: MDStepStatus, index: number ) => React.ReactNode; export interface IMDStepsProps { styles?: IMDStepsStyle; steps: IMDStepsItem[]; current?: number; direction?: MDStepsDirection; transition?: boolean; iconRender?: MDStepsRenderFunc; titleRender?: MDStepsRenderFunc; briefRender?: MDStepsRenderFunc; } export interface IMDStepsState { current: number; } const BAR_SIZE = 1; const VERTICAL_LEFT = 40; const HORIZONTAL_TOP = 24; const VERTICAL_GAP = 24; const BAR_WRAPPER_WIDTH = 16; const BAR_VERTICAL_HEIGHT = 100; const TRANSITION_DURATION = 1000; const isDecimal = (num: number = 0): boolean => num.toString().indexOf('.') >= 0; export interface IMDStepsStyle { wrapper?: ViewStyle; backgroundBar?: ViewStyle; nodeWrapper?: ViewStyle; defaultIconWrapper?: ViewStyle; defaultIcon?: ViewStyle; title?: TextStyle; brief?: TextStyle; unactive?: ViewStyle; active?: ViewStyle; } export const MDStepsStyles: IMDStepsStyle = { wrapper: { alignItems: 'flex-start', alignSelf: 'flex-start', paddingTop: 20, paddingLeft: 50, paddingRight: 50, paddingBottom: 50, width: '100%', }, backgroundBar: { position: 'relative', flex: 1, alignItems: 'center', backgroundColor: 'transparent', }, nodeWrapper: { justifyContent: 'center', }, defaultIconWrapper: { width: BAR_WRAPPER_WIDTH, height: BAR_WRAPPER_WIDTH, backgroundColor: 'transparent', borderRadius: BAR_WRAPPER_WIDTH / 2, justifyContent: 'center', alignItems: 'center', }, defaultIcon: { height: 3, width: 3, borderRadius: 3, }, title: { position: 'absolute', fontSize: 16, color: theme.textColor, }, brief: { position: 'absolute', fontSize: 13, color: theme.descColor, }, unactive: { backgroundColor: theme.color, }, active: { backgroundColor: theme.colorActive, }, }; const defaultStyles = StyleSheet.create<IMDStepsStyle>(MDStepsStyles); export default class MDSteps extends React.Component< IMDStepsProps, IMDStepsState > { public static defaultProps = { styles: defaultStyles, current: 0, direction: 'horizontal', transition: false, }; constructor (props: IMDStepsProps) { super(props); for (let i = 0; i < props.steps.length - 1; i++) { this.animatedValues.push(new Animated.Value(0)); } this.state = { current: 0, }; } private animatedValues: Animated.Value[] = []; public componentDidMount () { const { steps, transition, direction, current } = this.props; this.startAnimByIndex( this.state.current, !!transition, direction, current, steps.length ); } public componentWillReceiveProps (nextProps: IMDStepsProps) { const { transition, direction, steps } = this.props; const current: number = this.props.current as number; const nextCurrent: number = nextProps.current as number; if (nextCurrent !== current) { this.startAnimByIndex( this.state.current, !!transition, direction, nextCurrent, steps.length, nextCurrent > current ); } } public render () { const { steps } = this.props; const _styles = this.props.styles || {}; const _steps = steps.map((item, index) => { const _bar = index !== steps.length - 1 ? this.renderBar(index) : null; return ( <React.Fragment key={index}> <View style={[ _styles.nodeWrapper, { alignItems: this.isVertical() ? 'flex-start' : 'center' }, ]} > {this.renderIcon(index)} {this.renderTitle(index, item.title)} {this.renderBrief(index, item.brief)} </View> {_bar} </React.Fragment> ); }); return ( <View style={[ _styles.wrapper, { flexDirection: this.isVertical() ? 'column' : 'row' }, ]} > {_steps} </View> ); } private startAnimByIndex ( index: number, transition: boolean, direction: MDStepsDirection = 'horizontal', current: number = 0, length: number, isAddStep = true ) { const toValue = direction === 'vertical' ? BAR_VERTICAL_HEIGHT : 100; const _index = isAddStep ? Math.floor(index) : Math.ceil(index); let diff = isAddStep ? 1 : 0; const _current = isAddStep ? _index : _index - 1; const next = isAddStep ? _index + 1 : _index - 1; if (isAddStep) { if (isDecimal(current) && current < _index) { // 在 步进 的情况下,目标 current 为小数,且小于想要去变化的 index,如:2.4 < 3,则不做处理 return; } // 如果 index 是个小数(一般出现在,前一个props为小数情况下),则在下一个步进动画完成后, // 再设置 current 来触发渲染 icon !isDecimal(index) && this.setState({ current: _current, }); if (!isDecimal(current) && (length - 1 <= _index || current <= _index)) { // 在 步进 的情况下,目标 current 为整数,且小于等于想要去变化的 index,或 index 大于等于 步进 的长度,则不继续处理 return; } if (isDecimal(current) && current < _index + 1 && current > _index) { diff = +(+current.toFixed(2) - _index).toFixed(2); this.setState({ current, }); } } else { if (current >= _index || _index < 0) { // 在 步减 的情况下,目标 current 为整数,且大于等于想要去变化的 index,或 index 小于 0 的长度,则不继续处理 return; } this.setState({ current: _current, }); if (isDecimal(current) && current < _index && current > _index - 1) { diff = 1 - +(_index - +current.toFixed(2)).toFixed(2); this.setState({ current, }); } } Animated.timing(this.animatedValues[_current], { toValue: toValue * diff, duration: !transition || !isAddStep ? 0 : TRANSITION_DURATION, }).start(() => { this.startAnimByIndex( next, transition, direction, current, length, isAddStep ); }); } private _getStatus (index: number, current: number = 0): MDStepStatus { return current === index ? 'current' : index < current ? 'reached' : 'unreached'; } private renderBar (index: number): React.ReactNode { const { current = 0 } = this.props; const animatedVales = this.animatedValues; const _v = this.isVertical(); const _barWrapperStyle = this.genBarWrapperStyle(); const size = _v ? { height: animatedVales[index] } : { width: animatedVales[index].interpolate({ inputRange: [0, 100], outputRange: ['0%', '100%'], }), }; return ( <View style={_barWrapperStyle}> <View style={[ this.genBarStyle(false), _v ? { height: BAR_VERTICAL_HEIGHT } : { width: '100%' }, ]} /> <Animated.View style={[ this.genBarStyle(index < current), size, { position: 'absolute' }, ]} /> </View> ); } private genBarWrapperStyle () { const _styles = this.props.styles || {}; const _v = this.isVertical(); return StyleSheet.flatten([ _styles.backgroundBar, { flexDirection: _v ? 'column' : 'row' }, _v ? { width: BAR_WRAPPER_WIDTH } : { height: BAR_WRAPPER_WIDTH }, ]); } private genBarStyle (actived: boolean) { const _styles = this.props.styles || {}; const _v = this.isVertical(); return StyleSheet.flatten([ _v ? { width: BAR_SIZE } : { height: BAR_SIZE }, actived ? _styles.active : _styles.unactive, ]); } private renderIcon (index: number): React.ReactNode { const { iconRender } = this.props; const { current } = this.state; const _styles = this.props.styles || {}; const status: MDStepStatus = this._getStatus(index, current); const margin = this.isVertical() ? { marginVertical: 5 } : { marginHorizontal: 5 }; if (iconRender) { const icon: React.ReactNode = iconRender(status, index); if (icon) { return <View style={margin}>{icon}</View>; } } if (status === 'current') { return ( <MDIcon style={margin} size={BAR_WRAPPER_WIDTH} name='checked' color={theme.colorActive} /> ); } return ( <View style={[_styles.defaultIconWrapper, margin]}> <View style={[ _styles.defaultIcon, status === 'reached' ? _styles.active : _styles.unactive, ]} /> </View> ); } private renderTitle (index: number, title: string): React.ReactNode { const { titleRender } = this.props; const { current } = this.state; const _isVertical = this.isVertical(); if (titleRender) { const ele: React.ReactNode = titleRender(this._getStatus(index, current), index); if (ele && React.isValidElement(ele)) { const _flatStyle = Object.assign( { position: 'absolute' }, !_isVertical ? { top: HORIZONTAL_TOP } : null, _isVertical ? { left: VERTICAL_LEFT } : null ); return <View style={_flatStyle}>{ele}</View>; } } const _titleStyle = this.genTitleStyle(index); return title ? <Text style={_titleStyle}>{title}</Text> : null; } private genTitleStyle (index: number) { const { current } = this.state; const _styles = this.props.styles || {}; const _v = this.isVertical(); const _c = index === current; return StyleSheet.flatten([ _styles.title, _c ? { color: theme.colorActive } : null, { textAlign: _v ? 'left' : 'center' }, { width: _v ? 200 : 120 }, _v ? { left: VERTICAL_LEFT } : { top: HORIZONTAL_TOP }, ]); } private renderBrief (index: number, brief?: string): React.ReactNode { const { briefRender } = this.props; const { current } = this.state; const _isVertical = this.isVertical(); if (briefRender) { const ele: React.ReactNode = briefRender(this._getStatus(index, current), index); if (ele && React.isValidElement(ele)) { const _flatStyle = Object.assign( { position: 'absolute', top: _isVertical ? VERTICAL_GAP : VERTICAL_GAP + HORIZONTAL_TOP, }, _isVertical ? { left: VERTICAL_LEFT } : null ); return <View style={_flatStyle}>{ele}</View>; } } return brief ? <Text style={this.genBriefStyle()}>{brief}</Text> : null; } private genBriefStyle (): TextStyle { const _styles = this.props.styles || {}; const _v = this.isVertical(); return StyleSheet.flatten([ _styles.brief, { textAlign: !_v ? 'center' : 'left', }, { width: !_v ? 120 : 200 }, { top: _v ? VERTICAL_GAP : HORIZONTAL_TOP + VERTICAL_GAP }, _v ? { left: VERTICAL_LEFT } : null, ]); } private isVertical () { return this.props.direction === 'vertical'; } }
the_stack
import * as Clutter from "@gi-types/clutter"; import * as Cogl from "@gi-types/cogl"; import * as CoglPango from "@gi-types/coglpango"; import * as Atk from "@gi-types/atk"; import * as GObject from "@gi-types/gobject"; export function accessibility_init(): boolean; export function get_cally_initialized(): boolean; export type ActionCallback = (cally_actor: Actor) => void; export type ActionFunc = (cally_actor: Actor) => void; export module Actor { export interface ConstructorProperties extends Atk.GObjectAccessible.ConstructorProperties { [key: string]: any; } } export class Actor extends Atk.GObjectAccessible implements Atk.Action, Atk.Component { static $gtype: GObject.GType<Actor>; constructor(properties?: Partial<Actor.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Actor.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](actor: Clutter.Actor): Actor; // Members add_action( action_name: string, action_description: string, action_keybinding: string, callback: ActionCallback ): number; remove_action(action_id: number): boolean; remove_action_by_name(action_name: string): boolean; // Implemented Members do_action(i: number): boolean; get_description(i: number): string | null; get_description(...args: never[]): never; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; get_name(...args: never[]): never; set_description(i: number, desc: string): boolean; set_description(...args: never[]): never; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_description(...args: never[]): never; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_get_name(...args: never[]): never; vfunc_set_description(i: number, desc: string): boolean; vfunc_set_description(...args: never[]): never; contains(x: number, y: number, coord_type: Atk.CoordType): boolean; get_alpha(): number; get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Atk.Layer; get_mdi_zorder(): number; get_position(coord_type: Atk.CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: Atk.ScrollType): boolean; scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Atk.Rectangle): void; vfunc_contains(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Atk.Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: Atk.CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: Atk.ScrollType): boolean; vfunc_scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; } export module Clone { export interface ConstructorProperties extends Actor.ConstructorProperties { [key: string]: any; } } export class Clone extends Actor implements Atk.Action, Atk.Component { static $gtype: GObject.GType<Clone>; constructor(properties?: Partial<Clone.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Clone.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](actor: Clutter.Actor): Clone; // Implemented Members do_action(i: number): boolean; get_description(i: number): string | null; get_description(...args: never[]): never; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; get_name(...args: never[]): never; set_description(i: number, desc: string): boolean; set_description(...args: never[]): never; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_description(...args: never[]): never; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_get_name(...args: never[]): never; vfunc_set_description(i: number, desc: string): boolean; vfunc_set_description(...args: never[]): never; contains(x: number, y: number, coord_type: Atk.CoordType): boolean; get_alpha(): number; get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Atk.Layer; get_mdi_zorder(): number; get_position(coord_type: Atk.CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: Atk.ScrollType): boolean; scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Atk.Rectangle): void; vfunc_contains(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Atk.Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: Atk.CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: Atk.ScrollType): boolean; vfunc_scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; } export module Root { export interface ConstructorProperties extends Atk.GObjectAccessible.ConstructorProperties { [key: string]: any; } } export class Root extends Atk.GObjectAccessible { static $gtype: GObject.GType<Root>; constructor(properties?: Partial<Root.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Root.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Root; } export module Stage { export interface ConstructorProperties extends Actor.ConstructorProperties { [key: string]: any; } } export class Stage extends Actor implements Atk.Action, Atk.Component, Atk.Window { static $gtype: GObject.GType<Stage>; constructor(properties?: Partial<Stage.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Stage.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](actor: Clutter.Actor): Stage; // Implemented Members do_action(i: number): boolean; get_description(i: number): string | null; get_description(...args: never[]): never; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; get_name(...args: never[]): never; set_description(i: number, desc: string): boolean; set_description(...args: never[]): never; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_description(...args: never[]): never; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_get_name(...args: never[]): never; vfunc_set_description(i: number, desc: string): boolean; vfunc_set_description(...args: never[]): never; contains(x: number, y: number, coord_type: Atk.CoordType): boolean; get_alpha(): number; get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Atk.Layer; get_mdi_zorder(): number; get_position(coord_type: Atk.CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: Atk.ScrollType): boolean; scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Atk.Rectangle): void; vfunc_contains(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Atk.Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: Atk.CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: Atk.ScrollType): boolean; vfunc_scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; } export module Text { export interface ConstructorProperties extends Actor.ConstructorProperties { [key: string]: any; } } export class Text extends Actor implements Atk.Action, Atk.Component, Atk.EditableText, Atk.Text { static $gtype: GObject.GType<Text>; constructor(properties?: Partial<Text.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Text.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](actor: Clutter.Actor): Text; // Implemented Members do_action(i: number): boolean; get_description(i: number): string | null; get_description(...args: never[]): never; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; get_name(...args: never[]): never; set_description(i: number, desc: string): boolean; set_description(...args: never[]): never; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_description(...args: never[]): never; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_get_name(...args: never[]): never; vfunc_set_description(i: number, desc: string): boolean; vfunc_set_description(...args: never[]): never; contains(x: number, y: number, coord_type: Atk.CoordType): boolean; get_alpha(): number; get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Atk.Layer; get_mdi_zorder(): number; get_position(coord_type: Atk.CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: Atk.ScrollType): boolean; scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Atk.Rectangle): void; vfunc_contains(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: Atk.CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Atk.Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: Atk.CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: Atk.CoordType): Atk.Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: Atk.ScrollType): boolean; vfunc_scroll_to_point(coords: Atk.CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: Atk.CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: Atk.CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; copy_text(start_pos: number, end_pos: number): void; cut_text(start_pos: number, end_pos: number): void; delete_text(start_pos: number, end_pos: number): void; insert_text(string: string, length: number, position: number): void; paste_text(position: number): void; set_run_attributes(attrib_set: Atk.AttributeSet, start_offset: number, end_offset: number): boolean; set_text_contents(string: string): void; vfunc_copy_text(start_pos: number, end_pos: number): void; vfunc_cut_text(start_pos: number, end_pos: number): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_insert_text(string: string, length: number, position: number): void; vfunc_paste_text(position: number): void; vfunc_set_run_attributes(attrib_set: Atk.AttributeSet, start_offset: number, end_offset: number): boolean; vfunc_set_text_contents(string: string): void; add_selection(start_offset: number, end_offset: number): boolean; get_bounded_ranges( rect: Atk.TextRectangle, coord_type: Atk.CoordType, x_clip_type: Atk.TextClipType, y_clip_type: Atk.TextClipType ): Atk.TextRange[]; get_caret_offset(): number; get_character_at_offset(offset: number): number; get_character_count(): number; get_character_extents( offset: number, coords: Atk.CoordType ): [number | null, number | null, number | null, number | null]; get_default_attributes(): Atk.AttributeSet; get_n_selections(): number; get_offset_at_point(x: number, y: number, coords: Atk.CoordType): number; get_range_extents(start_offset: number, end_offset: number, coord_type: Atk.CoordType): Atk.TextRectangle; get_run_attributes(offset: number): [Atk.AttributeSet, number, number]; get_selection(selection_num: number): [string, number, number]; get_string_at_offset(offset: number, granularity: Atk.TextGranularity): [string | null, number, number]; get_text(start_offset: number, end_offset: number): string; get_text_after_offset(offset: number, boundary_type: Atk.TextBoundary): [string, number, number]; get_text_at_offset(offset: number, boundary_type: Atk.TextBoundary): [string, number, number]; get_text_before_offset(offset: number, boundary_type: Atk.TextBoundary): [string, number, number]; remove_selection(selection_num: number): boolean; scroll_substring_to(start_offset: number, end_offset: number, type: Atk.ScrollType): boolean; scroll_substring_to_point( start_offset: number, end_offset: number, coords: Atk.CoordType, x: number, y: number ): boolean; set_caret_offset(offset: number): boolean; set_selection(selection_num: number, start_offset: number, end_offset: number): boolean; vfunc_add_selection(start_offset: number, end_offset: number): boolean; vfunc_get_bounded_ranges( rect: Atk.TextRectangle, coord_type: Atk.CoordType, x_clip_type: Atk.TextClipType, y_clip_type: Atk.TextClipType ): Atk.TextRange[]; vfunc_get_caret_offset(): number; vfunc_get_character_at_offset(offset: number): number; vfunc_get_character_count(): number; vfunc_get_character_extents( offset: number, coords: Atk.CoordType ): [number | null, number | null, number | null, number | null]; vfunc_get_default_attributes(): Atk.AttributeSet; vfunc_get_n_selections(): number; vfunc_get_offset_at_point(x: number, y: number, coords: Atk.CoordType): number; vfunc_get_range_extents(start_offset: number, end_offset: number, coord_type: Atk.CoordType): Atk.TextRectangle; vfunc_get_run_attributes(offset: number): [Atk.AttributeSet, number, number]; vfunc_get_selection(selection_num: number): [string, number, number]; vfunc_get_string_at_offset(offset: number, granularity: Atk.TextGranularity): [string | null, number, number]; vfunc_get_text(start_offset: number, end_offset: number): string; vfunc_get_text_after_offset(offset: number, boundary_type: Atk.TextBoundary): [string, number, number]; vfunc_get_text_at_offset(offset: number, boundary_type: Atk.TextBoundary): [string, number, number]; vfunc_get_text_before_offset(offset: number, boundary_type: Atk.TextBoundary): [string, number, number]; vfunc_remove_selection(selection_num: number): boolean; vfunc_scroll_substring_to(start_offset: number, end_offset: number, type: Atk.ScrollType): boolean; vfunc_scroll_substring_to_point( start_offset: number, end_offset: number, coords: Atk.CoordType, x: number, y: number ): boolean; vfunc_set_caret_offset(offset: number): boolean; vfunc_set_selection(selection_num: number, start_offset: number, end_offset: number): boolean; vfunc_text_attributes_changed(): void; vfunc_text_caret_moved(location: number): void; vfunc_text_changed(position: number, length: number): void; vfunc_text_selection_changed(): void; } export module Util { export interface ConstructorProperties extends Atk.Util.ConstructorProperties { [key: string]: any; } } export class Util extends Atk.Util { static $gtype: GObject.GType<Util>; constructor(properties?: Partial<Util.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Util.ConstructorProperties>, ...args: any[]): void; } export class ActorPrivate { static $gtype: GObject.GType<ActorPrivate>; constructor(copy: ActorPrivate); } export class ClonePrivate { static $gtype: GObject.GType<ClonePrivate>; constructor(copy: ClonePrivate); } export class RootPrivate { static $gtype: GObject.GType<RootPrivate>; constructor(copy: RootPrivate); } export class StagePrivate { static $gtype: GObject.GType<StagePrivate>; constructor(copy: StagePrivate); } export class TextPrivate { static $gtype: GObject.GType<TextPrivate>; constructor(copy: TextPrivate); } export class UtilPrivate { static $gtype: GObject.GType<UtilPrivate>; constructor(copy: UtilPrivate); }
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/dscCompilationJobOperationsMappers"; import * as Parameters from "../models/parameters"; import { AutomationClientContext } from "../automationClientContext"; /** Class representing a DscCompilationJobOperations. */ export class DscCompilationJobOperations { private readonly client: AutomationClientContext; /** * Create a DscCompilationJobOperations. * @param {AutomationClientContext} client Reference to the service client. */ constructor(client: AutomationClientContext) { this.client = client; } /** * Creates the Dsc compilation job of the configuration. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param compilationJobName The the DSC configuration Id. * @param parameters The parameters supplied to the create compilation job operation. * @param [options] The optional parameters * @returns Promise<Models.DscCompilationJobCreateResponse> */ create(resourceGroupName: string, automationAccountName: string, compilationJobName: string, parameters: Models.DscCompilationJobCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.DscCompilationJobCreateResponse> { return this.beginCreate(resourceGroupName,automationAccountName,compilationJobName,parameters,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.DscCompilationJobCreateResponse>; } /** * Retrieve the Dsc configuration compilation job identified by job id. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param compilationJobName The the DSC configuration Id. * @param [options] The optional parameters * @returns Promise<Models.DscCompilationJobGetResponse> */ get(resourceGroupName: string, automationAccountName: string, compilationJobName: string, options?: msRest.RequestOptionsBase): Promise<Models.DscCompilationJobGetResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param compilationJobName The the DSC configuration Id. * @param callback The callback */ get(resourceGroupName: string, automationAccountName: string, compilationJobName: string, callback: msRest.ServiceCallback<Models.DscCompilationJob>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param compilationJobName The the DSC configuration Id. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, automationAccountName: string, compilationJobName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DscCompilationJob>): void; get(resourceGroupName: string, automationAccountName: string, compilationJobName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DscCompilationJob>, callback?: msRest.ServiceCallback<Models.DscCompilationJob>): Promise<Models.DscCompilationJobGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, compilationJobName, options }, getOperationSpec, callback) as Promise<Models.DscCompilationJobGetResponse>; } /** * Retrieve a list of dsc compilation jobs. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param [options] The optional parameters * @returns Promise<Models.DscCompilationJobListByAutomationAccountResponse> */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options?: Models.DscCompilationJobListByAutomationAccountOptionalParams): Promise<Models.DscCompilationJobListByAutomationAccountResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param callback The callback */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, callback: msRest.ServiceCallback<Models.DscCompilationJobListResult>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param options The optional parameters * @param callback The callback */ listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options: Models.DscCompilationJobListByAutomationAccountOptionalParams, callback: msRest.ServiceCallback<Models.DscCompilationJobListResult>): void; listByAutomationAccount(resourceGroupName: string, automationAccountName: string, options?: Models.DscCompilationJobListByAutomationAccountOptionalParams | msRest.ServiceCallback<Models.DscCompilationJobListResult>, callback?: msRest.ServiceCallback<Models.DscCompilationJobListResult>): Promise<Models.DscCompilationJobListByAutomationAccountResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, options }, listByAutomationAccountOperationSpec, callback) as Promise<Models.DscCompilationJobListByAutomationAccountResponse>; } /** * Retrieve the job stream identified by job stream id. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param jobId The job id. * @param jobStreamId The job stream id. * @param [options] The optional parameters * @returns Promise<Models.DscCompilationJobGetStreamResponse> */ getStream(resourceGroupName: string, automationAccountName: string, jobId: string, jobStreamId: string, options?: msRest.RequestOptionsBase): Promise<Models.DscCompilationJobGetStreamResponse>; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param jobId The job id. * @param jobStreamId The job stream id. * @param callback The callback */ getStream(resourceGroupName: string, automationAccountName: string, jobId: string, jobStreamId: string, callback: msRest.ServiceCallback<Models.JobStream>): void; /** * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param jobId The job id. * @param jobStreamId The job stream id. * @param options The optional parameters * @param callback The callback */ getStream(resourceGroupName: string, automationAccountName: string, jobId: string, jobStreamId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.JobStream>): void; getStream(resourceGroupName: string, automationAccountName: string, jobId: string, jobStreamId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.JobStream>, callback?: msRest.ServiceCallback<Models.JobStream>): Promise<Models.DscCompilationJobGetStreamResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationAccountName, jobId, jobStreamId, options }, getStreamOperationSpec, callback) as Promise<Models.DscCompilationJobGetStreamResponse>; } /** * Creates the Dsc compilation job of the configuration. * @param resourceGroupName Name of an Azure Resource group. * @param automationAccountName The name of the automation account. * @param compilationJobName The the DSC configuration Id. * @param parameters The parameters supplied to the create compilation job operation. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(resourceGroupName: string, automationAccountName: string, compilationJobName: string, parameters: Models.DscCompilationJobCreateParameters, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, automationAccountName, compilationJobName, parameters, options }, beginCreateOperationSpec, options); } /** * Retrieve a list of dsc compilation jobs. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.DscCompilationJobListByAutomationAccountNextResponse> */ listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DscCompilationJobListByAutomationAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByAutomationAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DscCompilationJobListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByAutomationAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DscCompilationJobListResult>): void; listByAutomationAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DscCompilationJobListResult>, callback?: msRest.ServiceCallback<Models.DscCompilationJobListResult>): Promise<Models.DscCompilationJobListByAutomationAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByAutomationAccountNextOperationSpec, callback) as Promise<Models.DscCompilationJobListByAutomationAccountNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs/{compilationJobName}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.compilationJobName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DscCompilationJob }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAutomationAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.subscriptionId ], queryParameters: [ Parameters.filter, Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DscCompilationJobListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getStreamOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs/{jobId}/streams/{jobStreamId}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.jobId, Parameters.jobStreamId, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.JobStream }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/compilationjobs/{compilationJobName}", urlParameters: [ Parameters.resourceGroupName, Parameters.automationAccountName, Parameters.compilationJobName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion2 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.DscCompilationJobCreateParameters, required: true } }, responses: { 201: { bodyMapper: Mappers.DscCompilationJob }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByAutomationAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.DscCompilationJobListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
export interface ApplicationData { /** Application product details. */ applicationProductDetails?: Array<ApplicationProductDetail>; /** Schema for storing measurement reading and unit. */ avgMaterial?: Measure; /** Schema for storing measurement reading and unit. */ totalMaterial?: Measure; /** Schema for storing measurement reading and unit. */ area?: Measure; /** Source of the operation data. */ source?: string; /** * Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. * Note: this will be specified by the source provider itself. */ operationModifiedDateTime?: Date | string; /** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationStartDateTime?: Date | string; /** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationEndDateTime?: Date | string; /** Link for attachments. */ attachmentsLink?: string; /** Optional boundary ID of the field for which operation was applied. */ associatedBoundaryId?: string; /** Optional boundary ID of the actual area for which operation was applied inside the specified field. */ operationBoundaryId?: string; /** Farmer ID which belongs to the operation data. */ farmerId?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface ApplicationProductDetail { /** Name of the product applied. */ productName?: string; /** A flag indicating whether product is a carrier for a tank mix. */ isCarrier?: boolean; /** Schema for storing measurement reading and unit. */ avgMaterial?: Measure; /** Schema for storing measurement reading and unit. */ totalMaterial?: Measure; } export interface Measure { /** Data unit. */ unit?: string; /** Data value. */ value?: number; } export interface Boundary { /** Farmer ID. */ farmerId?: string; /** ID of the parent(field or seasonalField) it belongs to. */ parentId?: string; /** GeoJSON abstract class. */ geometry?: GeoJsonObject; /** Is the boundary primary. */ isPrimary?: boolean; /** Boundary area in acres. */ acreage?: number; /** Type of the parent it belongs to. */ parentType?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface GeoJsonObjectBase { type: "MultiPolygon" | "Point" | "Polygon"; } export interface SearchBoundaryQuery { /** Ids of the resource. */ ids?: Array<string>; /** Names of the resource. */ names?: Array<string>; /** * Filters on key-value pairs within the Properties object. * eg. "{testKey} eq {testValue}". */ propertyFilters?: Array<string>; /** Statuses of the resource. */ statuses?: Array<string>; /** Minimum creation date of resource (inclusive). */ minCreatedDateTime?: Date | string; /** Maximum creation date of resource (inclusive). */ maxCreatedDateTime?: Date | string; /** Minimum last modified date of resource (inclusive). */ minLastModifiedDateTime?: Date | string; /** Maximum last modified date of resource (inclusive). */ maxLastModifiedDateTime?: Date | string; /** * Maximum number of items needed (inclusive). * Minimum = 10, Maximum = 1000, Default value = 50. */ $maxPageSize?: number; /** Skip token for getting next set of results. */ $skipToken?: string; /** Is the boundary primary. */ isPrimary?: boolean; /** Type of the parent it belongs to. */ parentType?: string; /** Parent Ids of the resource. */ parentIds?: Array<string>; /** Minimum acreage of the boundary (inclusive). */ minAcreage?: number; /** Maximum acreage of the boundary (inclusive). */ maxAcreage?: number; /** GeoJSON abstract class. */ intersectsWithGeometry?: GeoJsonObject; } export interface Crop { /** Crop phenotype. */ phenotype?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface CropVariety { /** ID of the crop it belongs to. */ cropId?: string; /** CropVariety Brand. */ brand?: string; /** CropVariety product. */ product?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface Farmer { /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface FarmOperationDataIngestionJob { /** Farmer ID. */ farmerId: string; /** Authentication provider ID. */ authProviderId: string; /** List of operation types for which data needs to be downloaded. Available values: AllOperations, Application, Planting, Harvest, Tillage. */ operations?: Array<string>; /** Start Year (Minimum = 2000, Maximum = CurrentYear). */ startYear: number; /** Unique job id. */ id?: string; /** * Status of the job. * Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'. */ status?: string; /** Duration of the job in seconds. */ durationInSeconds?: number; /** Status message to capture more details of the job. */ message?: string; /** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ lastActionDateTime?: Date | string; /** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ startTime?: Date | string; /** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ endTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface Farm { /** Farmer ID. */ farmerId?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface Field { /** ID of the associated Farm. */ farmId?: string; /** Farmer ID. */ farmerId?: string; /** Primary boundary id. */ primaryBoundaryId?: string; /** Boundary Ids. */ boundaryIds?: Array<string>; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface HarvestData { /** Schema for storing measurement reading and unit. */ totalYield?: Measure; /** Schema for storing measurement reading and unit. */ avgYield?: Measure; /** Schema for storing measurement reading and unit. */ totalWetMass?: Measure; /** Schema for storing measurement reading and unit. */ avgWetMass?: Measure; /** Schema for storing measurement reading and unit. */ avgMoisture?: Measure; /** Schema for storing measurement reading and unit. */ avgSpeed?: Measure; /** Harvest product details. */ harvestProductDetails?: Array<HarvestProductDetail>; /** Schema for storing measurement reading and unit. */ area?: Measure; /** Source of the operation data. */ source?: string; /** * Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. * Note: this will be specified by the source provider itself. */ operationModifiedDateTime?: Date | string; /** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationStartDateTime?: Date | string; /** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationEndDateTime?: Date | string; /** Link for attachments. */ attachmentsLink?: string; /** Optional boundary ID of the field for which operation was applied. */ associatedBoundaryId?: string; /** Optional boundary ID of the actual area for which operation was applied inside the specified field. */ operationBoundaryId?: string; /** Farmer ID which belongs to the operation data. */ farmerId?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface HarvestProductDetail { /** Name of the product. */ productName?: string; /** Schema for storing measurement reading and unit. */ area?: Measure; /** Schema for storing measurement reading and unit. */ totalYield?: Measure; /** Schema for storing measurement reading and unit. */ avgYield?: Measure; /** Schema for storing measurement reading and unit. */ avgMoisture?: Measure; /** Schema for storing measurement reading and unit. */ totalWetMass?: Measure; /** Schema for storing measurement reading and unit. */ avgWetMass?: Measure; } export interface ImageProcessingRasterizeJob { /** Farmer ID. */ farmerId: string; /** Shapefile attachment ID. */ shapefileAttachmentId: string; /** List of shapefile column names to create raster attachments. */ shapefileColumnNames: Array<string>; /** Unique job id. */ id?: string; /** * Status of the job. * Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'. */ status?: string; /** Duration of the job in seconds. */ durationInSeconds?: number; /** Status message to capture more details of the job. */ message?: string; /** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ lastActionDateTime?: Date | string; /** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ startTime?: Date | string; /** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ endTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface OAuthProvider { /** OAuth App ID for given OAuth Provider. */ appId?: string; /** * OAuth App secret for given Provider. * Note: Won't be sent in response. */ appSecret?: string; /** * OAuth Api key for given Provider. * Note: currently Applicable to Climate provider. Won't be sent in response. */ apiKey?: string; /** * An optional flag to determine if the App is ready to be used for Production scenarios in the provider side or not. (Default value: false) * Note: Currently applicable for JohnDeere. */ isProductionApp?: boolean; /** Unique OAuth provider ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface OAuthConnectRequest { /** ID of the farmer. */ farmerId: string; /** ID of the OAuthProvider. */ oAuthProviderId: string; /** Link to redirect the user to, at the end of the oauth flow. */ userRedirectLink: string; /** State to provide back when redirecting the user, at the end of the oauth flow. */ userRedirectState?: string; } export interface PlantingData { /** Schema for storing measurement reading and unit. */ avgPlantingRate?: Measure; /** Schema for storing measurement reading and unit. */ totalMaterial?: Measure; /** Schema for storing measurement reading and unit. */ avgMaterial?: Measure; /** Planting product details. */ plantingProductDetails?: Array<PlantingProductDetail>; /** Schema for storing measurement reading and unit. */ area?: Measure; /** Source of the operation data. */ source?: string; /** * Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. * Note: this will be specified by the source provider itself. */ operationModifiedDateTime?: Date | string; /** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationStartDateTime?: Date | string; /** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationEndDateTime?: Date | string; /** Link for attachments. */ attachmentsLink?: string; /** Optional boundary ID of the field for which operation was applied. */ associatedBoundaryId?: string; /** Optional boundary ID of the actual area for which operation was applied inside the specified field. */ operationBoundaryId?: string; /** Farmer ID which belongs to the operation data. */ farmerId?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface PlantingProductDetail { /** Name of the product. */ productName?: string; /** Schema for storing measurement reading and unit. */ area?: Measure; /** Schema for storing measurement reading and unit. */ totalMaterial?: Measure; /** Schema for storing measurement reading and unit. */ avgMaterial?: Measure; } export interface SatelliteDataIngestionJob { /** Farmer ID. */ farmerId: string; /** The id of the boundary object for which satellite data is being fetched. */ boundaryId: string; /** Start Date. */ startDateTime: Date | string; /** End Date. */ endDateTime: Date | string; /** Provider of satellite data. */ provider?: "Microsoft"; /** Source of satellite data. */ source?: "Sentinel_2_L2A"; /** Data Model for SatelliteIngestionJobRequest. */ data?: SatelliteData; /** Unique job id. */ id?: string; /** * Status of the job. * Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'. */ status?: string; /** Duration of the job in seconds. */ durationInSeconds?: number; /** Status message to capture more details of the job. */ message?: string; /** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ lastActionDateTime?: Date | string; /** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ startTime?: Date | string; /** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ endTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface SatelliteData { /** List of ImageNames. */ imageNames?: Array<string>; /** List of ImageFormats. Available value: TIF. */ imageFormats?: Array<string>; /** List of ImageResolutions in meters. Available values: 10, 20, 60. */ imageResolutions?: Array<number>; } export interface SeasonalField { /** Farmer ID. */ farmerId?: string; /** Primary boundary id. */ primaryBoundaryId?: string; /** Boundary Ids. */ boundaryIds?: Array<string>; /** ID of the associated Farm. */ farmId?: string; /** ID of the associated Field. */ fieldId?: string; /** ID of the season it belongs to. */ seasonId?: string; /** CropVariety ids. */ cropVarietyIds?: Array<string>; /** ID of the crop it belongs to. */ cropId?: string; /** Average yield value of the seasonal field. */ avgYieldValue?: number; /** Unit of the average yield value attribute. */ avgYieldUnit?: string; /** Average seed population value of the seasonal field. */ avgSeedPopulationValue?: number; /** Unit of average seed population value attribute. */ avgSeedPopulationUnit?: string; /** Planting datetime, sample format: yyyy-MM-ddTHH:mm:ssZ. */ plantingDateTime?: Date | string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface Season { /** Season start datetime, sample format: yyyy-MM-ddTHH:mm:ssZ. */ startDateTime?: Date | string; /** Season end datetime, sample format: yyyy-MM-ddTHH:mm:ssZ. */ endDateTime?: Date | string; /** Season year. */ year?: number; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface TillageData { /** Schema for storing measurement reading and unit. */ tillageDepth?: Measure; /** Schema for storing measurement reading and unit. */ tillagePressure?: Measure; /** Schema for storing measurement reading and unit. */ area?: Measure; /** Source of the operation data. */ source?: string; /** * Modified date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. * Note: this will be specified by the source provider itself. */ operationModifiedDateTime?: Date | string; /** Start date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationStartDateTime?: Date | string; /** End date-time of the operation data, sample format: yyyy-MM-ddTHH:mm:ssZ. */ operationEndDateTime?: Date | string; /** Link for attachments. */ attachmentsLink?: string; /** Optional boundary ID of the field for which operation was applied. */ associatedBoundaryId?: string; /** Optional boundary ID of the actual area for which operation was applied inside the specified field. */ operationBoundaryId?: string; /** Farmer ID which belongs to the operation data. */ farmerId?: string; /** Unique resource ID. */ id?: string; /** The ETag value to implement optimistic concurrency. */ eTag?: string; /** Status of the resource. */ status?: string; /** Date-time when resource was created, sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Date-time when resource was last modified, sample format: yyyy-MM-ddTHH:mm:ssZ. */ modifiedDateTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface WeatherDataIngestionJob { /** The id of the boundary object for which weather data is being fetched. */ boundaryId: string; /** The id of the farmer object for which weather data is being fetched. */ farmerId: string; /** ID of the extension to be used for the providerInput. eg. DTN.ClearAg. */ extensionId: string; /** Extension api name to which request is to be made. */ extensionApiName: string; /** Extension api input dictionary which would be used to feed request query/body/parameter information. */ extensionApiInput: Record<string, Record<string, unknown>>; /** App id of the weather data provider. */ extensionDataProviderAppId?: string; /** Api key of the weather data provider. */ extensionDataProviderApiKey?: string; /** Unique job id. */ id?: string; /** * Status of the job. * Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'. */ status?: string; /** Duration of the job in seconds. */ durationInSeconds?: number; /** Status message to capture more details of the job. */ message?: string; /** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ lastActionDateTime?: Date | string; /** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ startTime?: Date | string; /** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ endTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface WeatherDataDeleteJob { /** ID of the extension to be used for the providerInput. eg. DTN.ClearAg. */ extensionId: string; /** The id of the farmer object for which weather data is being fetched. */ farmerId: string; /** The id of the boundary object for which weather data is being fetched. */ boundaryId: string; /** Type of weather data. Possible values include: 'forecast' , 'historical'. */ weatherDataType?: string; /** Granularity of weather data. Possible values include: 'daily' , 'hourly'. */ granularity?: string; /** Weather data start UTC date-time (inclusive), sample format: yyyy-MM-ddTHH:mm:ssZ. */ startDateTime?: Date | string; /** Weather data end UTC date-time (inclusive), sample format: yyyy-MM-ddTHH:mm:ssZ. */ endDateTime?: Date | string; /** Unique job id. */ id?: string; /** * Status of the job. * Possible values: 'Waiting', 'Running', 'Succeeded', 'Failed', 'Cancelled'. */ status?: string; /** Duration of the job in seconds. */ durationInSeconds?: number; /** Status message to capture more details of the job. */ message?: string; /** Job created at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ createdDateTime?: Date | string; /** Job was last acted upon at dateTime. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ lastActionDateTime?: Date | string; /** Job start time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ startTime?: Date | string; /** Job end time when available. Sample format: yyyy-MM-ddTHH:mm:ssZ. */ endTime?: Date | string; /** Name to identify resource. */ name?: string; /** Textual description of the resource. */ description?: string; /** * A collection of key value pairs that belongs to the resource. * Each pair must not have a key greater than 50 characters * and must not have a value greater than 150 characters. * Note: A maximum of 25 key value pairs can be provided for a resource and only string and numeral values are supported. */ properties?: Record<string, Record<string, unknown>>; } export interface MultiPolygon extends GeoJsonObjectBase, MultiPolygonCoordinates { type: "MultiPolygon"; } export interface MultiPolygonCoordinates { /** * Gets or sets Coordinates of GeoJSON Object. * It must be an array of polygons, each polygon contains list of linear rings. * For Polygons with more than one of these rings, the first MUST be the exterior ring, * and any others MUST be interior rings. */ coordinates: Array<Array<Array<Array<number>>>>; } export interface Point extends GeoJsonObjectBase, PointCoordinates { type: "Point"; } export interface PointCoordinates { /** * Gets or sets the coordinate of this point. * It must be an array of 2 or 3 elements for a 2D or 3D system. */ coordinates: Array<number>; } export interface Polygon extends GeoJsonObjectBase, PolygonCoordinates { type: "Polygon"; } export interface PolygonCoordinates { /** * Gets or sets type of the GeoJSON Object. * It must be an array of linear ring coordinate arrays. * For Polygons with more than one of these rings, the first MUST be the exterior ring, * and any others MUST be interior rings. */ coordinates: Array<Array<Array<number>>>; } export type GeoJsonObject = MultiPolygon | Point | Polygon;
the_stack
import { Headers, Response } from 'node-fetch'; import * as WebSocket from 'ws'; import fetch from 'node-fetch'; import { HttpgdPlot, IHttpgdViewerApi, PlotId } from './httpgdTypes'; /** * State of the graphics device. * For details see: * https://github.com/nx10/httpgd/blob/master/docs/api-documentation.md */ interface HttpgdState { upid: number, hsize: number, active: boolean } interface PlotsIdResponse { id: PlotId } interface PlotsResponse { state: HttpgdState, plots: PlotsIdResponse[] } /** * Light wrapper for httpgd API calls. */ class HttpgdApi { private readonly host: string; private readonly http: string; private readonly ws: string; private readonly httpSVG: string; private readonly httpState: string; private readonly httpRemove: string; private readonly httpClear: string; private readonly httpPlots: string; private readonly httpHeaders: Headers = new Headers(); private readonly useToken: boolean; private readonly token: string; public constructor(host: string, token?: string) { this.host = host; this.http = 'http://' + host; this.ws = 'ws://' + host; this.httpSVG = this.http + '/svg'; this.httpState = this.http + '/state'; this.httpClear = this.http + '/clear'; this.httpRemove = this.http + '/remove'; this.httpPlots = this.http + '/plots'; if (token) { this.useToken = true; this.token = token; this.httpHeaders.set('X-HTTPGD-TOKEN', this.token); } else { this.useToken = false; this.token = ''; } } public svg_index(index: number, width?: number, height?: number, c?: string): URL { const url = this.svg_ext(width, height, c); url.searchParams.append('index', index.toString()); return url; } public svg_id(id: PlotId, width?: number, height?: number, c?: string): URL { const url = this.svg_ext(width, height, c); url.searchParams.append('id', id); return url; } private svg_ext(width?: number, height?: number, c?: string): URL { const url = new URL(this.httpSVG); if (width) {url.searchParams.append('width', Math.round(width).toString());} if (height) {url.searchParams.append('height', Math.round(height).toString());} // Token needs to be included in query params because request headers can't be set // when setting image.src // upid is included to avoid caching if (this.useToken) {url.searchParams.append('token', this.token);} if (c) {url.searchParams.append('c', c);} return url; } private remove_index(index: number): URL { const url = new URL(this.httpRemove); url.searchParams.append('index', index.toString()); return url; } public async get_remove_index(index: number): Promise<Response> { const res = await fetch(this.remove_index(index).href, { headers: this.httpHeaders }); return res; } private remove_id(id: PlotId): URL { const url = new URL(this.httpRemove); url.searchParams.append('id', id); return url; } public async get_remove_id(id: PlotId): Promise<Response> { const res = await fetch(this.remove_id(id).href, { headers: this.httpHeaders }); return res; } public async get_plots(): Promise<PlotsResponse> { const res = await fetch(this.httpPlots, { headers: this.httpHeaders }); return await (res.json() as Promise<PlotsResponse>); } public async get_plot_contents_all(): Promise<HttpgdPlot[]> { const plotIds = await this.get_plots(); const plots = plotIds.plots.map(async idRes => { return await this.get_plot_contents(idRes.id); }); return await Promise.all(plots); } public async get_plot_contents(id: PlotId, width?: number, height?: number, c?: string): Promise<HttpgdPlot> { const url = this.svg_id(id, width, height, c).toString(); const plot = fetch(url).then(res => res.text()).then(res => { return { url: url, host: this.host, id: id, svg: res, height: height, width: width, }; }); return plot; } public async get_clear(): Promise<Response> { const res = await fetch(this.httpClear, { headers: this.httpHeaders }); return res; } public async get_state(): Promise<HttpgdState> { const res = await fetch(this.httpState, { headers: this.httpHeaders }); return await (res.json() as Promise<HttpgdState>); } public new_websocket(): WebSocket { return new WebSocket(this.ws); } } const enum HttpgdConnectionMode { NONE, POLL, SLOWPOLL, WEBSOCKET } /** * Handles HTTP polling / WebSocket connection. * This handles falling back to HTTP polling when WebSockets are not available, * and automatically reconnects if the server is temporarily unavailable. */ class HttpgdConnection { private static readonly INTERVAL_POLL: number = 500; private static readonly INTERVAL_POLL_SLOW: number = 5000; public api: HttpgdApi; private mode: HttpgdConnectionMode = HttpgdConnectionMode.NONE; private allowWebsockets: boolean; private socket?: WebSocket; private pollHandle?: ReturnType<typeof setInterval>; private pausePoll: boolean = false; private disconnected: boolean = true; private lastState?: HttpgdState; public remoteStateChanged?: (newState: HttpgdState) => void; public connectionChanged?: (disconnected: boolean) => void; public constructor(host: string, token?: string, allowWebsockets?: boolean) { this.api = new HttpgdApi(host, token); this.allowWebsockets = allowWebsockets ? allowWebsockets : false; } public open(): void { if (this.mode !== HttpgdConnectionMode.NONE) {return;} this.start(HttpgdConnectionMode.WEBSOCKET); } public close(): void { if (this.mode === HttpgdConnectionMode.NONE) {return;} this.start(HttpgdConnectionMode.NONE); } private start(targetMode: HttpgdConnectionMode): void { if (this.mode === targetMode) {return;} switch (targetMode) { case HttpgdConnectionMode.POLL: console.log('Start POLL'); this.clearWebsocket(); this.clearPoll(); this.pollHandle = setInterval(() => this.poll(), HttpgdConnection.INTERVAL_POLL); this.mode = targetMode; break; case HttpgdConnectionMode.SLOWPOLL: console.log('Start SLOWPOLL'); this.clearWebsocket(); this.clearPoll(); this.pollHandle = setInterval(() => this.poll(), HttpgdConnection.INTERVAL_POLL_SLOW); this.mode = targetMode; break; case HttpgdConnectionMode.WEBSOCKET: if (!this.allowWebsockets) { this.start(HttpgdConnectionMode.POLL); break; } console.log('Start WEBSOCKET'); this.clearPoll(); this.clearWebsocket(); this.socket = this.api.new_websocket(); this.socket.onmessage = (ev) => this.onWsMessage(ev.data.toString()); this.socket.onopen = () => this.onWsOpen(); this.socket.onclose = () => this.onWsClose(); this.socket.onerror = () => console.log('Websocket error'); this.mode = targetMode; this.poll(); // get initial state break; case HttpgdConnectionMode.NONE: this.clearWebsocket(); this.clearPoll(); this.mode = targetMode; break; default: break; } } private clearPoll() { if (this.pollHandle) { clearInterval(this.pollHandle); } } private clearWebsocket() { if (this.socket) { this.socket.onclose = () => { /* ignore? */ }; this.socket.close(); } } private poll(): void { if (this.pausePoll) {return;} this.api.get_state().then((remoteState: HttpgdState) => { this.setDisconnected(false); if (this.mode === HttpgdConnectionMode.SLOWPOLL) {this.start(HttpgdConnectionMode.WEBSOCKET);} // reconnect if (this.pausePoll) {return;} this.checkState(remoteState); }).catch((e) => { console.warn(e); this.setDisconnected(true); }); } private onWsMessage(message: string): void { if (message.startsWith('{')) { const remoteState = JSON.parse(message) as HttpgdState; this.checkState(remoteState); } else { console.log('Unknown WS message: ' + message); } } private onWsClose(): void { console.log('Websocket closed'); this.setDisconnected(true); } private onWsOpen(): void { console.log('Websocket opened'); this.setDisconnected(false); } private setDisconnected(disconnected: boolean): void { if (this.disconnected !== disconnected) { this.disconnected = disconnected; if (this.disconnected) { this.start(HttpgdConnectionMode.SLOWPOLL); } else { this.start(HttpgdConnectionMode.WEBSOCKET); } this.connectionChanged?.(disconnected); } } private checkState(remoteState: HttpgdState): void { if ( (!this.lastState) || (this.lastState.active !== remoteState.active) || (this.lastState.hsize !== remoteState.hsize) || (this.lastState.upid !== remoteState.upid) ) { this.lastState = remoteState; this.remoteStateChanged?.(remoteState); } } } /** * Public API for communicating with a httpgd server. */ export class Httpgd implements IHttpgdViewerApi { private connection: HttpgdConnection; // Constructor is called by the viewer: public constructor(host: string, token?: string) { this.connection = new HttpgdConnection(host, token, true); } // Opens the connection to the server public start(): void { this.connection.open(); } // api calls: // general state info: public getState(): Promise<HttpgdState> { return this.connection.api.get_state(); } // get list of plot Ids: public getPlotIds(): Promise<PlotId[]> { return this.connection.api.get_plots().then(res => res.plots.map(r => r.id)); } // get content of a single plot. Use sensible defaults if no height/width given: public getPlotContent(id: PlotId, height?: number, width?: number, c?: string): Promise<HttpgdPlot> { return this.connection.api.get_plot_contents(id, width, height, c); } // get content of multiple plots: // Use sensible defaults if no height/width given. // Return all plots if no ids given. public getPlotContents(ids?: PlotId[], height?: number, width?: number): Promise<HttpgdPlot[]> { if (!ids) { return this.connection.api.get_plot_contents_all(); } const plots = ids.map(async id => { return await this.connection.api.get_plot_contents(id, width, height); }); return Promise.all(plots); } // close/remove plot public async closePlot(id: PlotId): Promise<void> { await this.connection.api.get_remove_id(id); } // Listen to connection changes of the httpgd server // Todo: Expand to fill observer pattern with multiple listeners (?) public onConnectionChange(listener: (disconnected: boolean) => void): void { this.connection.connectionChanged = listener; } // Listen to plot changes of the httpgd server // Todo: Expand to fill observer pattern with multiple listeners (?) public onPlotsChange(listener: () => void): void { this.connection.remoteStateChanged = listener; } // Dispose-function to clean up when vscode closes public dispose(): void { this.connection.close(); } }
the_stack
import * as ChessJS from 'chess.js'; import { Chess } from 'chess.js'; // 2nd line is a hack to full rollup that will remove the line: import * as ChessJS from 'chess.js'; // unless we add the 2nd line. import { Injectable, EventEmitter } from '@angular/core'; import { Block, BaseBlock, Piece, PieceColor, PieceType, MoveType, ChessMove, GAME_STATE, ChessEngine } from 'ngx-chess'; import { util } from './util'; function indexOfByBoard(piece: Piece, pArr: Piece[]): number { for (let i = 0, len = pArr.length; i < len; i++) { if (piece.block === pArr[i].block) return i; } return -1; } /** * A Chess game controller using the chess.js game controller. */ @Injectable() export class ChessJSGame extends ChessEngine { public blocks: Block[]; public pieces: Piece[]; public capturedPieces: Piece[]; public state: GAME_STATE = GAME_STATE.IDLE; get rowCount(): number { return 8; } get colCount(): number { return 8; } /** * True if the game is running. * Readonly. */ get inGame(): boolean { switch (this.state) { case GAME_STATE.ACTIVE: case GAME_STATE.CHECK: return true; default: return false; } } /** * Fired when the game state has changed, usually after a move. * @type {EventEmitter<GAME_STATE>} */ public stateChanged: EventEmitter<GAME_STATE> = new EventEmitter<GAME_STATE>(true); /** * Fired when the board was synced with the engine, usually after a move. * Most moves (a move to an empty block or a simple capture ) will not trigger a board/engine sync * however, special moves will (promotions, en passant and casteling) * @type {EventEmitter} */ public boardSynced: EventEmitter<void> = new EventEmitter<void>(true); protected chess: Chess; constructor() { super(); this.initBoard(); } init(): Promise<void> { return Promise.resolve(); } newGame(): Promise<void> { // we always usee ChessJS and not Chess, see comment on the top. this.chess = ChessJS ? new (<any>ChessJS)() : new Chess(); this.pieces = this.createPieces(); this.capturedPieces = []; this.changeState(GAME_STATE.ACTIVE); this.boardSynced.emit(null); return Promise.resolve(); } isPromotionMove(piece: Piece, toBlock: Block): boolean { if (piece.type === PieceType.PAWN) { // TODO: row/col are inverted for some reason... fix and change here to row. if (piece.color === PieceColor.BLACK && toBlock.col === this.rowCount - 1) { return true; } if (piece.color === PieceColor.WHITE && toBlock.col === 0) { return true; } } return false; } move(piece: Piece, toBlock: Block, promotion?: PieceType): ChessMove { if (this.state !== GAME_STATE.ACTIVE && this.state !== GAME_STATE.CHECK) { return null; } const move = util.move.factory(this.chess.move({ from: piece.block.pos, to: toBlock.pos, promotion: util.piece.to(promotion) })); // if it was a kill, remove the piece from the board. if (!move.invalid) { move.effected = this.updateMove(move, piece, toBlock); this.checkState(); } return move; } undo(): ChessMove { if (this.state !== GAME_STATE.ACTIVE && this.state !== GAME_STATE.CHECK) { return util.move.factory(null); } const move = util.move.factory(this.chess.undo()); if (!move.invalid) { const piece = this.getPiece(move.to), toBlock = this.getBlock(move.from); // move.from = move.to; // move.to = toBlock.pos; move.effected = this.updateMove(move, piece, toBlock, true); this.checkState(); } return move; } turn(): PieceColor { return util.color.from(this.chess.turn()); } winner(): PieceColor { if (this.state === GAME_STATE.CHECKMATE) { return this.turn() === PieceColor.BLACK ? PieceColor.WHITE : PieceColor.BLACK; } else { return PieceColor.UNKNOWN; } } /** * Query a block/square on the board and returns the piece on it. * Returns null if block is empty. * @param pos * @returns {Piece} */ getBlock(pos: string): Block { return this.blocks[ BaseBlock.posToIndex(pos, this.rowCount) ]; } /** * Query a block/square on the board and returns the piece on it. * Returns null if block is empty. * @param pos * @returns {Piece} */ getPiece(pos: string): Piece { // TODO: Maybe hold a hash for direct access? // this will also speed up other operations in updateBpoard() and syncBoard() // consider that there are max of 32 items in the array, not sure worth the trade off. for (let i = 0, len = this.pieces.length; i < len; i++) { if (this.pieces[i].block.pos === pos) { return this.pieces[i]; } } } /** * Get block piece index. * Return the index of a piece on a specific block/square, if a piece occupiy the block. * @param { Block | string } blockOrPosition A Block instance or a position in file/rank format (e8) * @returns { number } The index of the piece in the pieces array or -1 if not found. */ getBPI(blockOrPosition: Block| string): number { if (typeof blockOrPosition !== 'string') { blockOrPosition = (blockOrPosition as Block).pos; } for (let i = 0, len = this.pieces.length; i < len; i++) { if (this.pieces[i].block.pos === blockOrPosition as string) { return i; } } return -1; } moves(piece: Piece): Block[] { return (this.chess.moves({square: piece.block.pos}) as string[]) .map(move => this.blocks[BaseBlock.sanToIndex(move, piece.block.pos)]); } /** * Preforms a sync between the chess engine and the current piece collection so the * piece collection will represent the actual board state. * This call does not change the pieces array, it just modify it (i.e: reference is the same) * This call is not used but since every move is updated per changes, but its here if needed. */ public syncBoard() { // generate a new piece collection representing the current board state. // We want to avoid a redraw of all of the pieces so we will work on the existing collection // and update it, this will minimize DOM operations as most pieces are the same. // For every block on the board we have 5 options // 1) Didn't Have a piece and still doesn't (nothing changed) // 2) Had a piece and it didn't change. (nothing changed) // 3) Had a piece but now it doesn't. // 4) Had a piece but now the color and/or type had changed. // 5) Didn't Have a piece but now it does. // Since a piece refer to a block, we will create a collection of pieces representing // the new state, #1 is automatically resolved this way const pieces = this.createPieces(); for (let i = 0, len = this.pieces.length; i < len; i++) { const idx = indexOfByBoard(this.pieces[i], pieces); if (idx === -1) { // #3 this piece is on a block no longer occupied, remove it. // TODO: some removed pieces are capture and should be stored in the captured collection // some just moved to a new location so we need to handle that. this.pieces.splice(i, 1); len--; i--; } else { // #2&4 found a matching block, match piece (event is its the same, who cares) let newPiece = pieces.splice(idx, 1)[0]; // remove to have only "new" locations left this.pieces[i].color = newPiece.color; this.pieces[i].type = newPiece.type; } } // now our new piece collection holds only pieces moved to new blocks, blocks that were // empty before, we will handle that. this.pieces.splice(this.pieces.length, 0, ...pieces); this.boardSynced.emit(null); } destroy(): void { super.destroy(); this.stateChanged.complete(); this.boardSynced.complete(); } /** * Update the board after a move so pieces reflect the new state of the board. * @param move * @param piece * @param newBlock * @returns A collection of all pieces effected by this move. */ private updateMove(move: ChessMove, piece: Piece, newBlock: Block, revert: boolean = false): Piece[] { const effected: Piece[] = [piece]; if (move.isPromotionMove()) { piece.type = revert ? move.piece : move.promotion; } if (move.isCaptureMove()) { // Handling captures: Standard capture, Promotion capture or en passant. // we point to the index (block array) of the block to remove the piece on, newBlock by default. // The only case where default is invalid is when an En Passant happen since the captured // piece is not on the block the acting piece landed on, in such case we will add the offset // to the index so we will point to the right kill block. if (revert) { const p = this.capturedPieces.pop(); this.pieces.push(p); p.block = piece.block; p.captured = false; effected.push(p); } else { let killIndex = newBlock.index; if (move.type === MoveType.EnPassant) { // TODO: row/col are inverted for some reason... fix and change here to row. killIndex += (newBlock.col > piece.block.col ? -1 : 1); } const p = this.getPiece(this.blocks[killIndex].pos); p.capture(); this.pieces.splice(this.pieces.indexOf(p), 1); this.capturedPieces.push(p); effected.push(p); } } // can be else if... if (move.isCastlingMove()) { // in castling we have to also take into consideration the Rook which moves next to the king. // king side castling: kings lands 1 block from the rook and we need to move it to the other side // queen side castling: kings lands 2 blocks from the rook and we need to move it to the other next. if (revert) { let matrix = piece.block.row > newBlock.row ? [1, -1] : [-2, 1], rookSrcIndex = piece.block.index + this.rowCount * matrix[0], rookDstIndex = piece.block.index + this.rowCount * matrix[1]; const p = this.getPiece(this.blocks[rookDstIndex].pos); p.block = this.blocks[rookSrcIndex]; effected.push(p); } else { let matrix = newBlock.row > piece.block.row ? [1, -1] : [-2, 1], rookSrcIndex = newBlock.index + this.rowCount * matrix[0], rookDstIndex = newBlock.index + this.rowCount * matrix[1]; // find the rook piece and set it's block to our "after castling" block. const p = this.getPiece(this.blocks[rookSrcIndex].pos); p.block = this.blocks[rookDstIndex]; effected.push(p); } } // in any case, our acting piece should now reflect the block it moved to. piece.block = newBlock; return effected; } private checkState() { if (this.chess.game_over()) { if (this.chess.in_checkmate()) { this.changeState(GAME_STATE.CHECKMATE); } else if (this.chess.in_draw()) { this.changeState(GAME_STATE.DRAW); } else if (this.chess.in_stalemate()) { this.changeState(GAME_STATE.STALEMATE); } else if (this.chess.in_threefold_repetition()) { this.changeState(GAME_STATE.THREEFOLD_REPETITION); } else if (this.chess.insufficient_material()) { this.changeState(GAME_STATE.INSUFFICIENT_MATERIAL); } else { throw new Error('Unknown game state'); // TODO: What to do? } } else if (this.chess.in_check()) { this.changeState(GAME_STATE.CHECK); } else if (this.state === GAME_STATE.CHECK) { this.changeState(GAME_STATE.ACTIVE); } } private changeState(newState: GAME_STATE): void { if (this.state === newState) return; this.state = newState; this.stateChanged.emit(newState); } private initBoard(): void { this.pieces = undefined; this.capturedPieces = undefined; this.blocks = this.createBlocks(); } private createBlocks(): Block[] { const ChessBlock = BaseBlock.factory({ rowCount: this.rowCount, colCount: this.colCount }); const blocks: Block[] = []; for (let i = 0, len = this.rowCount * this.colCount; i < len; i++) { blocks.push(new ChessBlock(i)); } return blocks; } private createPieces(): Piece[] { const pieces = []; this.blocks.forEach( block => { let csPiece: Chess.Piece; if (csPiece = this.chess.get(block.pos)) { pieces.push(util.piece.factory(block, csPiece)); } }); return pieces; } }
the_stack
import Page = require('../../../base/Page'); import Response = require('../../../http/response'); import V1 = require('../V1'); import { ParticipantList } from './room/participant'; import { ParticipantListInstance } from './room/participant'; import { SerializableClass } from '../../../interfaces'; type RoomCodec = 'VP8'|'H264'|'VP9'; type RoomCreatedMethod = 'sdk'|'ad_hoc'|'api'; type RoomEdgeLocation = 'ashburn'|'dublin'|'frankfurt'|'singapore'|'sydney'|'sao_paulo'|'roaming'|'umatilla'|'tokyo'; type RoomEndReason = 'room_ended_via_api'|'timeout'; type RoomProcessingState = 'complete'|'in_progress'; type RoomRoomStatus = 'in_progress'|'completed'; type RoomRoomType = 'go'|'peer_to_peer'|'group'|'group_small'; type RoomTwilioRealm = 'us1'|'us2'|'au1'|'br1'|'ie1'|'jp1'|'sg1'|'in1'|'de1'|'gll'; /** * Initialize the RoomList * * PLEASE NOTE that this class contains beta products that are subject to change. * Use them with caution. * * @param version - Version of the resource */ declare function RoomList(version: V1): RoomListInstance; interface RoomListInstance { /** * @param sid - sid of instance */ (sid: string): RoomContext; /** * Streams RoomInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Function to process each record */ each(callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; /** * Streams RoomInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Function to process each record */ each(opts?: RoomListInstanceEachOptions, callback?: (item: RoomInstance, done: (err?: Error) => void) => void): void; /** * Constructs a room * * @param roomSid - The SID of the Room resource. */ get(roomSid: string): RoomContext; /** * Retrieve a single target page of RoomInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ getPage(callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; /** * Retrieve a single target page of RoomInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param targetUrl - API-generated URL for the requested results page * @param callback - Callback to handle list of records */ getPage(targetUrl?: string, callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; /** * Lists RoomInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ list(callback?: (error: Error | null, items: RoomInstance[]) => any): Promise<RoomInstance[]>; /** * Lists RoomInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ list(opts?: RoomListInstanceOptions, callback?: (error: Error | null, items: RoomInstance[]) => any): Promise<RoomInstance[]>; /** * Retrieve a single page of RoomInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param callback - Callback to handle list of records */ page(callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; /** * Retrieve a single page of RoomInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @param opts - Options for request * @param callback - Callback to handle list of records */ page(opts?: RoomListInstancePageOptions, callback?: (error: Error | null, items: RoomPage) => any): Promise<RoomPage>; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to each * * @property callback - * Function to process each record. If this and a positional * callback are passed, this one will be used * @property codec - Codecs used by participants in the room. * @property createdAfter - Only read rooms that started on or after this ISO 8601 timestamp. * @property createdBefore - Only read rooms that started before this ISO 8601 timestamp. * @property done - Function to be called upon completion of streaming * @property limit - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @property roomName - Room friendly name. * @property roomType - Type of room. */ interface RoomListInstanceEachOptions { callback?: (item: RoomInstance, done: (err?: Error) => void) => void; codec?: RoomCodec | RoomCodec[]; createdAfter?: Date; createdBefore?: Date; done?: Function; limit?: number; pageSize?: number; roomName?: string; roomType?: RoomRoomType | RoomRoomType[]; } /** * Options to pass to list * * @property codec - Codecs used by participants in the room. * @property createdAfter - Only read rooms that started on or after this ISO 8601 timestamp. * @property createdBefore - Only read rooms that started before this ISO 8601 timestamp. * @property limit - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @property pageSize - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @property roomName - Room friendly name. * @property roomType - Type of room. */ interface RoomListInstanceOptions { codec?: RoomCodec | RoomCodec[]; createdAfter?: Date; createdBefore?: Date; limit?: number; pageSize?: number; roomName?: string; roomType?: RoomRoomType | RoomRoomType[]; } /** * Options to pass to page * * @property codec - Codecs used by participants in the room. * @property createdAfter - Only read rooms that started on or after this ISO 8601 timestamp. * @property createdBefore - Only read rooms that started before this ISO 8601 timestamp. * @property pageNumber - Page Number, this value is simply for client state * @property pageSize - Number of records to return, defaults to 50 * @property pageToken - PageToken provided by the API * @property roomName - Room friendly name. * @property roomType - Type of room. */ interface RoomListInstancePageOptions { codec?: RoomCodec | RoomCodec[]; createdAfter?: Date; createdBefore?: Date; pageNumber?: number; pageSize?: number; pageToken?: string; roomName?: string; roomType?: RoomRoomType | RoomRoomType[]; } interface RoomPayload extends RoomResource, Page.TwilioResponsePayload { } interface RoomResource { account_sid: string; codecs: RoomCodec[]; concurrent_participants: number; create_time: Date; created_method: RoomCreatedMethod; duration_sec: number; edge_location: RoomEdgeLocation; end_reason: RoomEndReason; end_time: Date; links: string; max_concurrent_participants: number; max_participants: number; media_region: RoomTwilioRealm; processing_state: RoomProcessingState; recording_enabled: boolean; room_name: string; room_sid: string; room_status: RoomRoomStatus; room_type: RoomRoomType; status_callback: string; status_callback_method: string; total_participant_duration_sec: number; total_recording_duration_sec: number; unique_participant_identities: number; unique_participants: number; url: string; } interface RoomSolution { } declare class RoomContext { /** * Initialize the RoomContext * * PLEASE NOTE that this class contains beta products that are subject to change. * Use them with caution. * * @param version - Version of the resource * @param roomSid - The SID of the Room resource. */ constructor(version: V1, roomSid: string); /** * fetch a RoomInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: RoomInstance) => any): Promise<RoomInstance>; participants: ParticipantListInstance; /** * Provide a user-friendly representation */ toJSON(): any; } declare class RoomInstance extends SerializableClass { /** * Initialize the RoomContext * * PLEASE NOTE that this class contains beta products that are subject to change. * Use them with caution. * * @param version - Version of the resource * @param payload - The instance payload * @param roomSid - The SID of the Room resource. */ constructor(version: V1, payload: RoomPayload, roomSid: string); private _proxy: RoomContext; accountSid: string; codecs: RoomCodec[]; concurrentParticipants: number; createTime: Date; createdMethod: RoomCreatedMethod; durationSec: number; edgeLocation: RoomEdgeLocation; endReason: RoomEndReason; endTime: Date; /** * fetch a RoomInstance * * @param callback - Callback to handle processed record */ fetch(callback?: (error: Error | null, items: RoomInstance) => any): Promise<RoomInstance>; links: string; maxConcurrentParticipants: number; maxParticipants: number; mediaRegion: RoomTwilioRealm; /** * Access the participants */ participants(): ParticipantListInstance; processingState: RoomProcessingState; recordingEnabled: boolean; roomName: string; roomSid: string; roomStatus: RoomRoomStatus; roomType: RoomRoomType; statusCallback: string; statusCallbackMethod: string; /** * Provide a user-friendly representation */ toJSON(): any; totalParticipantDurationSec: number; totalRecordingDurationSec: number; uniqueParticipantIdentities: number; uniqueParticipants: number; url: string; } declare class RoomPage extends Page<V1, RoomPayload, RoomResource, RoomInstance> { /** * Initialize the RoomPage * * PLEASE NOTE that this class contains beta products that are subject to change. * Use them with caution. * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V1, response: Response<string>, solution: RoomSolution); /** * Build an instance of RoomInstance * * @param payload - Payload response from the API */ getInstance(payload: RoomPayload): RoomInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { RoomCodec, RoomContext, RoomCreatedMethod, RoomEdgeLocation, RoomEndReason, RoomInstance, RoomList, RoomListInstance, RoomListInstanceEachOptions, RoomListInstanceOptions, RoomListInstancePageOptions, RoomPage, RoomPayload, RoomProcessingState, RoomResource, RoomRoomStatus, RoomRoomType, RoomSolution, RoomTwilioRealm }
the_stack
declare namespace MusicKit { /** * This class represents the Apple Music API. */ interface API { /** * An instance of the Cloud library. */ library: Library; /** * The storefront used for making calls to the API. */ storefrontId: string; /** * Fetch one or more activities using their identifiers. * * @param ids An array of activity identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ activities( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch an activity using its identifier. * * @param id An activity identifier. * @param parameters A query params object that is serialized and passed * directly to the Apple Music API. */ activity( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Add a catalog resource to a user's library. */ addToLibrary(parameters?: AddToLibraryParameters): Promise<void>; /** * Fetch an album using its identifier. * * @param id An album identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ album( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Album>; /** * Fetch one or more albums using their identifiers. * * @param ids An array of album identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ albums( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch an Apple curator using its identifier. * * @param id An Apple curator identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ appleCurator( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Fetch one or more Apple curators using their identifiers. * * @param ids An array of Apple curator identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ appleCurators( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch an artist using its identifier. * * @param id An artist identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ artist( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Artist>; /** Stub type */ artistRelationship( id: string, relationship: string ): Promise<AppleMusicApi.Album[]>; /** * Fetch one or more artists using their identifiers. * * @param ids An array of artist identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ artists( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Artist[]>; /** * Fetch one or more charts. * * @param types An array of chart types. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ charts( types: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a curator using its identifier. * * @param id A curator identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ curator( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Fetch one or more curators using their identifiers. * * @param ids An array of curator identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ curators( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a genre using its identifier. * * @param id An array of * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ genre( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Genre>; /** * Fetch one or more genres using their identifiers. * * @param ids An array of genre identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ genres( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Genre[]>; /** * Fetch the resources in heavy rotation for the user. * * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ historyHeavyRotation( parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a music video using its identifier. * * @param id An array of video identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ musicVideo( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Fetch one or more music videos using their identifiers. * * @param ids An array of music video identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ musicVideos( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a playlist using its identifier. * * @param id A playlist identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ playlist( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Playlist>; /** * Fetch one or more playlists using their identifiers. * * @param ids An array of playlist identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ playlists( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Playlist[]>; /** * Fetch the recently played resources for the user. * * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ recentPlayed( parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a recommendation using its identifier. * * @param id A recommendation identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ recommendation( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Fetch one or more recommendations using their identifiers. * * @param ids An array of recommendation identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ recommendations( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Search the catalog using a query. * * @param term The term to search. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ search( term: string, parameters?: QueryParameters ): Promise< Record< AppleMusicApi.Resource['type'], AppleMusicApi.Relationship< | AppleMusicApi.Artist | AppleMusicApi.Album | AppleMusicApi.Playlist | AppleMusicApi.Song > > >; /** * Fetch the search term results for a hint. * * @param term The term to search. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ searchHints( term: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a song using its identifier. * * @param ids An array of identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ song(id: string, parameters?: QueryParameters): Promise<AppleMusicApi.Song>; /** * Fetch one or more songs using their identifiers. * * @param ids An array of song identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ songs( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Song[]>; /** * Fetch a station using its identifier. * * @param id A station identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ station( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Fetch one or more stations using their identifiers. * * @param ids An array of station identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ stations( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; /** * Fetch a storefront using its identifier. * * @param id A storefront identifier. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ storefront( id: string, parameters?: QueryParameters ): Promise<AppleMusicApi.Resource>; /** * Fetch one or more storefronts using their identifiers. * * @param ids An array of storefront identifiers. * @param parameters A query parameters object that is serialized and passed * directly to the Apple Music API. */ storefronts( ids: string[], parameters?: QueryParameters ): Promise<AppleMusicApi.Resource[]>; } type AddToLibraryParameters = any; interface QueryParameters { [key: string]: any; } /** * An object that represents artwork. */ interface Artwork { bgColor: string; height: number; width: number; textColor1: string; textColor2: string; textColor3: string; textColor4: string; url: string; } }
the_stack
import os from 'os'; import convict from 'convict'; import { DataEncoding, dataEncodings, flatten, getField, getTypeOf, hasOwn, isNotNil, isNumber, isPlainObject, isString, } from '@terascope/utils'; import { Context } from './interfaces'; const cpuCount = os.cpus().length; const workers = cpuCount < 5 ? cpuCount : 5; /** * This schema is for a Teraslice Job definition. * @param context Teraslice context object * @returns Complete convict schema for the Teraslice Job */ export function jobSchema(context: Context): convict.Schema<any> { const schemas: convict.Schema<any> = { active: { default: true, doc: 'A convenience property that allows the user to indicate whether the job' + ' is in active use. This is just a marker, Teraslice does not use it.', format: Boolean }, analytics: { default: true, doc: [ 'logs the time it took in milliseconds for each action,', 'as well as the number of docs it receives', ].join(' '), format: Boolean, }, performance_metrics: { default: false, doc: 'logs performance metrics, including gc, loop and usage metrics for nodejs', format: Boolean, }, assets: { default: null, doc: 'An array of actions to execute, typically the first is a reader ' + 'and the last is a sender with any number of processing function in-between', format(arr: any) { if (arr != null) { if (!Array.isArray(arr)) { throw new Error('assets need to be of type array'); } if (!arr.every(isString)) { throw new Error('assets needs to be an array of strings'); } } }, }, autorecover: { default: false, doc: 'Automatically recover pending slices from the last stopped/completed execution. ' + 'The last state will always be passed to the slicer', format: Boolean, }, lifecycle: { default: 'once', doc: 'Job lifecycle behavior, determines if it should exit on completion or remain active', format: ['once', 'persistent'], }, max_retries: { default: 3, doc: [ 'the number of times a worker will attempt to process', 'the same slice after a error has occurred', ].join(' '), format: 'nat', // integer >=0 (natural number) }, name: { default: 'Custom Job', doc: 'Name for specific job', format: 'required_String', }, operations: { default: [], doc: 'An array of actions to execute, typically the first is a reader ' + 'and the last is a sender with ' + 'any number of processing function in-between', format(arr: any) { if (!(Array.isArray(arr) && arr.length >= 2)) { throw new Error('Operations need to be of type array with at least two operations in it'); } const connectorsObject = getField(context.sysconfig.terafoundation, 'connectors', {}); const connectors = Object.values(connectorsObject); const connections = flatten(connectors.map((conn) => Object.keys(conn))); for (const op of arr) { if (!op || !isPlainObject(op)) { throw new Error(`Invalid Operation config in operations, got ${getTypeOf(op)}`); } if (op.connection && !connections.includes(op.connection)) { throw new Error(`Operation ${op._op} refers to connection "${op.connection}" which is unavailable`); } } }, }, apis: { default: [], doc: `An array of apis to load and any configurations they require. Validated similar to operations, with the exception of no apis are required. The _name property is required, and it is required to be unique but can be suffixed with a identifier by using the format "example:0", anything after the ":" is stripped out when searching for the file or folder.`, format(arr: any[]) { if (!Array.isArray(arr)) { throw new Error('APIs is required to be an array'); } const connectorsObject = getField(context.sysconfig.terafoundation, 'connectors', {}); const connectors = Object.values(connectorsObject); const connections = flatten(connectors.map((conn) => Object.keys(conn))); const names: string[] = []; for (const api of arr) { if (!api || !isPlainObject(api)) { throw new Error(`Invalid API config in apis, got ${getTypeOf(api)}`); } if (!api._name) { throw new Error('API requires an _name'); } if (names.includes(api._name)) { throw new Error(`Duplicate API configurations for ${api._name} found`); } names.push(api._name); if (api.connection && !connections.includes(api.connection)) { throw new Error(`API ${api._name} refers to connection "${api.connection}" which is unavailable`); } } }, }, probation_window: { default: 300000, doc: 'time in ms that the execution controller checks for failed slices, ' + 'if there are none then it updates the state of the execution to running ' + '(this is only when lifecycle is set to persistent)', format: 'duration', }, slicers: { default: 1, doc: 'how many parallel slicer contexts that will run within the slicer', format: 'positive_int' }, workers: { default: workers, doc: 'the number of workers dedicated for the job', format: 'positive_int' }, labels: { default: null, doc: 'An array of arrays containing key value pairs used to label kubernetes resources.', // TODO: Refactor this out as format, copied from env_vars format(obj: any[]) { if (obj != null) { if (!isPlainObject(obj)) { throw new Error('must be object'); } Object.entries(obj).forEach(([key, val]) => { if (key == null || key === '') { throw new Error('key must be not empty'); } if (val == null || val === '') { throw new Error(`value for key "${key}" must be not empty`); } }); } }, }, env_vars: { default: {}, doc: 'environment variables to set on each the teraslice worker, in the format, { "EXAMPLE": "test" }', format(obj: any[]) { if (!isPlainObject(obj)) { throw new Error('must be object'); } Object.entries(obj).forEach(([key, val]) => { if (key == null || key === '') { throw new Error('key must be not empty'); } if (val == null || val === '') { throw new Error(`value for key "${key}" must be not empty`); } }); }, } }; const clusteringType = context.sysconfig.teraslice.cluster_manager_type; if (clusteringType === 'kubernetes') { schemas.targets = { default: [], doc: 'array of key/value labels used for targeting teraslice jobs to nodes', format(arr: any[]) { if (!Array.isArray(arr)) { throw new Error('must be array'); } arr.forEach((label) => { if (label.key == null) { throw new Error(`needs to have a key: ${label}`); } if (label.value == null) { throw new Error(`needs to have a value: ${label}`); } }); }, }; schemas.cpu = { doc: 'number of cpus to reserve per teraslice worker in kubernetes', default: undefined, format: 'Number', }; schemas.cpu_execution_controller = { doc: 'number of cpus to reserve per teraslice execution controller in kubernetes', default: undefined, format: 'Number', }; schemas.ephemeral_storage = { doc: 'Add ephemeral storage volume to worker and execution controller pods', default: false, format: Boolean }; schemas.external_ports = { doc: 'A numerical array of ports that should be exposed as external ports on the pods', default: undefined, format(arr) { // TODO: What should we really do to validate this? It can be // omitted, an empty array, or an array with numbers. It can't // contain anything other than numbers. Processors should be able // to have reserved ports. That is, if a job has port X but a // processor requires port X this code should throw an error. if (arr != null) { if (!Array.isArray(arr)) { throw new Error('external_ports is required to be an array of numbers or objects like {name: \'myJob\', port: 9000}.'); } for (const portValue of arr) { if (isNumber(portValue)) { if (portValue === 45680) { throw new Error('Port 45680 cannot be included in external_ports, it is reserved by Teraslice.'); } } else if (isPlainObject(portValue)) { Object.entries(portValue).forEach(([key, val]) => { if (key == null || key === '') { throw new Error('key must be not empty'); } if (val == null || val === '') { throw new Error(`value for key "${key}" must be not empty`); } if (hasOwn(portValue, 'name') && hasOwn(portValue, 'port')) { if (!isNumber(portValue.port)) { throw new Error('The port set on an external_ports object must be a number.'); } if (portValue.name === '' || !isString(portValue.name)) { throw new Error('The name set on an external ports object must be a non empty string.'); } } else { throw new Error('An external_ports entry must be an object like {name: \'myJob\', port: 9000} or a number.'); } }); } else { throw new Error('An external_ports entry must be a number or an object like {name: \'myJob\', port: 9000}.'); } } } } }; schemas.memory = { doc: 'memory, in bytes, to reserve per teraslice worker in Kubernetes', default: undefined, format: 'Number', }; schemas.memory_execution_controller = { doc: 'memory, in bytes, to reserve per teraslice execution controller in kubernetes', default: undefined, format: 'Number', }; schemas.volumes = { default: [], doc: 'array of volumes to be mounted by job workers', format(arr: any[]) { if (!Array.isArray(arr)) { throw new Error('must be array'); } arr.forEach((volume) => { if (volume.name == null) { throw new Error(`needs to have a name: ${volume}`); } if (volume.path == null) { throw new Error(`needs to have a path: ${volume}`); } }); }, }; schemas.kubernetes_image = { doc: 'Specify a custom image name for kubernetes, this only applies to kubernetes systems', default: undefined, format: 'optional_String', }; } return schemas; } export const makeJobSchema = jobSchema; /** * This is the schema for a Teraslice Operation. */ export const opSchema: convict.Schema<any> = { _op: { default: '', doc: 'Name of operation, , it must reflect the name of the file or folder', format: 'required_String', }, _encoding: { doc: 'Used for specifying the data encoding type when using `DataEntity.fromBuffer`. Defaults to `json`.', default: DataEncoding.JSON, format: dataEncodings, }, _dead_letter_action: { doc: [ 'This action will specify what to do when failing to parse or transform a record.', 'The following builtin actions are supported:', ' - "throw": throw the original error​​', ' - "log": log the error and the data​​', ' - "none": (default) skip the error entirely', 'If none of the actions are specified it will try and use a registered Dead Letter Queue API under that name.', 'The API must be already be created by a operation before it can used.' ].join('\n'), default: 'throw', format: 'optional_String', }, }; /** * This is the schema for a Teraslice API. */ export const apiSchema: convict.Schema<any> = { _name: { default: '', doc: `The _name property is required, and it is required to be unique but can be suffixed with a identifier by using the format "example:0", anything after the ":" is stripped out when searching for the file or folder.`, format: 'required_String', }, _encoding: { doc: 'Used for specifying the data encoding type when using `DataEntity.fromBuffer`. Defaults to `json`.', default: undefined, format: (val: unknown): void => { if (isNotNil(val)) { if (isString(val)) { if (!dataEncodings.includes(val as any)) throw new Error(`Invalid parameter _encoding, expected values ${dataEncodings.join(' , ')}, was given ${val}`); } else { throw new Error(`Invalid parameter _encoding, expect type string, was given ${getTypeOf(val)}`); } } }, }, _dead_letter_action: { doc: [ 'This action will specify what to do when failing to parse or transform a record.', 'The following builtin actions are supported:', ' - "throw": throw the original error​​', ' - "log": log the error and the data​​', ' - "none": (default) skip the error entirely', 'If none of the actions are specified it will try and use a registered Dead Letter Queue API under that name.', 'The API must be already be created by a operation before it can used.' ].join('\n'), default: 'throw', format: 'optional_String', }, };
the_stack
import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { FailedPredicateException } from "antlr4ts/FailedPredicateException"; import { NotNull } from "antlr4ts/Decorators"; import { NoViableAltException } from "antlr4ts/NoViableAltException"; import { Override } from "antlr4ts/Decorators"; import { Parser } from "antlr4ts/Parser"; import { ParserRuleContext } from "antlr4ts/ParserRuleContext"; import { ParserATNSimulator } from "antlr4ts/atn/ParserATNSimulator"; import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor"; import { RecognitionException } from "antlr4ts/RecognitionException"; import { RuleContext } from "antlr4ts/RuleContext"; //import { RuleVersion } from "antlr4ts/RuleVersion"; import { TerminalNode } from "antlr4ts/tree/TerminalNode"; import { Token } from "antlr4ts/Token"; import { TokenStream } from "antlr4ts/TokenStream"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; import { GenericSqlListener } from "./GenericSqlListener"; import { GenericSqlVisitor } from "./GenericSqlVisitor"; export class GenericSqlParser extends Parser { public static readonly T__0 = 1; public static readonly T__1 = 2; public static readonly T__2 = 3; public static readonly T__3 = 4; public static readonly SELECT = 5; public static readonly ASTERISK = 6; public static readonly FROM = 7; public static readonly WHERE = 8; public static readonly AND = 9; public static readonly OR = 10; public static readonly NOT = 11; public static readonly AS = 12; public static readonly LT = 13; public static readonly LTE = 14; public static readonly GT = 15; public static readonly GTE = 16; public static readonly EQUALS = 17; public static readonly NOT_EQUALS = 18; public static readonly IS = 19; public static readonly NULL = 20; public static readonly CAST = 21; public static readonly INDEXED_PARAM = 22; public static readonly ID = 23; public static readonly DIGIT = 24; public static readonly QUOTED_ID = 25; public static readonly STRING = 26; public static readonly WHITESPACE = 27; public static readonly RULE_statement = 0; public static readonly RULE_query = 1; public static readonly RULE_fromTables = 2; public static readonly RULE_selectFields = 3; public static readonly RULE_field = 4; public static readonly RULE_aliasField = 5; public static readonly RULE_boolExp = 6; public static readonly RULE_exp = 7; public static readonly RULE_numeric = 8; public static readonly RULE_binaryOperator = 9; public static readonly RULE_unaryOperator = 10; public static readonly RULE_idPath = 11; public static readonly RULE_identifier = 12; // tslint:disable:no-trailing-whitespace public static readonly ruleNames: string[] = [ "statement", "query", "fromTables", "selectFields", "field", "aliasField", "boolExp", "exp", "numeric", "binaryOperator", "unaryOperator", "idPath", "identifier", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, "'('", "')'", "','", "'.'", "'SELECT'", "'*'", "'FROM'", "'WHERE'", "'AND'", "'OR'", "'NOT'", "'AS'", "'<'", "'<='", "'>'", "'>='", "'='", undefined, "'IS'", "'NULL'", "'CAST'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, undefined, undefined, "SELECT", "ASTERISK", "FROM", "WHERE", "AND", "OR", "NOT", "AS", "LT", "LTE", "GT", "GTE", "EQUALS", "NOT_EQUALS", "IS", "NULL", "CAST", "INDEXED_PARAM", "ID", "DIGIT", "QUOTED_ID", "STRING", "WHITESPACE", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(GenericSqlParser._LITERAL_NAMES, GenericSqlParser._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return GenericSqlParser.VOCABULARY; } // tslint:enable:no-trailing-whitespace // @Override public get grammarFileName(): string { return "GenericSql.g4"; } // @Override public get ruleNames(): string[] { return GenericSqlParser.ruleNames; } // @Override public get serializedATN(): string { return GenericSqlParser._serializedATN; } protected createFailedPredicateException(predicate?: string, message?: string): FailedPredicateException { return new FailedPredicateException(this, predicate, message); } constructor(input: TokenStream) { super(input); this._interp = new ParserATNSimulator(GenericSqlParser._ATN, this); } // @RuleVersion(0) public statement(): StatementContext { let _localctx: StatementContext = new StatementContext(this._ctx, this.state); this.enterRule(_localctx, 0, GenericSqlParser.RULE_statement); try { this.state = 34; this._errHandler.sync(this); switch (this._input.LA(1)) { case GenericSqlParser.SELECT: this.enterOuterAlt(_localctx, 1); { this.state = 26; this.query(); this.state = 27; this.match(GenericSqlParser.EOF); } break; case GenericSqlParser.T__0: this.enterOuterAlt(_localctx, 2); { this.state = 29; this.match(GenericSqlParser.T__0); this.state = 30; this.query(); this.state = 31; this.match(GenericSqlParser.T__1); this.state = 32; this.match(GenericSqlParser.EOF); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public query(): QueryContext { let _localctx: QueryContext = new QueryContext(this._ctx, this.state); this.enterRule(_localctx, 2, GenericSqlParser.RULE_query); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 36; this.match(GenericSqlParser.SELECT); this.state = 37; this.selectFields(); this.state = 38; this.match(GenericSqlParser.FROM); this.state = 39; _localctx._from = this.fromTables(); this.state = 42; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === GenericSqlParser.WHERE) { { this.state = 40; this.match(GenericSqlParser.WHERE); this.state = 41; _localctx._where = this.boolExp(0); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public fromTables(): FromTablesContext { let _localctx: FromTablesContext = new FromTablesContext(this._ctx, this.state); this.enterRule(_localctx, 4, GenericSqlParser.RULE_fromTables); try { this.enterOuterAlt(_localctx, 1); { this.state = 44; this.aliasField(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public selectFields(): SelectFieldsContext { let _localctx: SelectFieldsContext = new SelectFieldsContext(this._ctx, this.state); this.enterRule(_localctx, 6, GenericSqlParser.RULE_selectFields); let _la: number; try { this.enterOuterAlt(_localctx, 1); { { this.state = 46; this.field(); this.state = 51; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === GenericSqlParser.T__2) { { { this.state = 47; this.match(GenericSqlParser.T__2); this.state = 48; this.field(); } } this.state = 53; this._errHandler.sync(this); _la = this._input.LA(1); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public field(): FieldContext { let _localctx: FieldContext = new FieldContext(this._ctx, this.state); this.enterRule(_localctx, 8, GenericSqlParser.RULE_field); try { this.state = 56; this._errHandler.sync(this); switch (this._input.LA(1)) { case GenericSqlParser.ID: case GenericSqlParser.QUOTED_ID: this.enterOuterAlt(_localctx, 1); { this.state = 54; this.aliasField(); } break; case GenericSqlParser.ASTERISK: this.enterOuterAlt(_localctx, 2); { this.state = 55; this.match(GenericSqlParser.ASTERISK); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public aliasField(): AliasFieldContext { let _localctx: AliasFieldContext = new AliasFieldContext(this._ctx, this.state); this.enterRule(_localctx, 10, GenericSqlParser.RULE_aliasField); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 58; this.idPath(); this.state = 63; this._errHandler.sync(this); _la = this._input.LA(1); if ((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << GenericSqlParser.AS) | (1 << GenericSqlParser.ID) | (1 << GenericSqlParser.QUOTED_ID))) !== 0)) { { this.state = 60; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === GenericSqlParser.AS) { { this.state = 59; this.match(GenericSqlParser.AS); } } this.state = 62; this.identifier(); } } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } public boolExp(): BoolExpContext; public boolExp(_p: number): BoolExpContext; // @RuleVersion(0) public boolExp(_p?: number): BoolExpContext { if (_p === undefined) { _p = 0; } let _parentctx: ParserRuleContext = this._ctx; let _parentState: number = this.state; let _localctx: BoolExpContext = new BoolExpContext(this._ctx, _parentState); let _prevctx: BoolExpContext = _localctx; let _startState: number = 12; this.enterRecursionRule(_localctx, 12, GenericSqlParser.RULE_boolExp, _p); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 69; this._errHandler.sync(this); switch (this._input.LA(1)) { case GenericSqlParser.T__0: case GenericSqlParser.T__3: case GenericSqlParser.CAST: case GenericSqlParser.INDEXED_PARAM: case GenericSqlParser.ID: case GenericSqlParser.DIGIT: case GenericSqlParser.QUOTED_ID: case GenericSqlParser.STRING: { this.state = 66; this.exp(0); } break; case GenericSqlParser.NOT: { this.state = 67; this.match(GenericSqlParser.NOT); this.state = 68; this.boolExp(1); } break; default: throw new NoViableAltException(this); } this._ctx._stop = this._input.tryLT(-1); this.state = 79; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { if (this._parseListeners != null) { this.triggerExitRuleEvent(); } _prevctx = _localctx; { this.state = 77; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 7, this._ctx) ) { case 1: { _localctx = new BoolExpContext(_parentctx, _parentState); this.pushNewRecursionContext(_localctx, _startState, GenericSqlParser.RULE_boolExp); this.state = 71; if (!(this.precpred(this._ctx, 3))) { throw this.createFailedPredicateException("this.precpred(this._ctx, 3)"); } this.state = 72; this.match(GenericSqlParser.AND); this.state = 73; this.boolExp(4); } break; case 2: { _localctx = new BoolExpContext(_parentctx, _parentState); this.pushNewRecursionContext(_localctx, _startState, GenericSqlParser.RULE_boolExp); this.state = 74; if (!(this.precpred(this._ctx, 2))) { throw this.createFailedPredicateException("this.precpred(this._ctx, 2)"); } this.state = 75; this.match(GenericSqlParser.OR); this.state = 76; this.boolExp(3); } break; } } } this.state = 81; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 8, this._ctx); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.unrollRecursionContexts(_parentctx); } return _localctx; } public exp(): ExpContext; public exp(_p: number): ExpContext; // @RuleVersion(0) public exp(_p?: number): ExpContext { if (_p === undefined) { _p = 0; } let _parentctx: ParserRuleContext = this._ctx; let _parentState: number = this.state; let _localctx: ExpContext = new ExpContext(this._ctx, _parentState); let _prevctx: ExpContext = _localctx; let _startState: number = 14; this.enterRecursionRule(_localctx, 14, GenericSqlParser.RULE_exp, _p); let _la: number; try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 111; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 10, this._ctx) ) { case 1: { this.state = 83; this.idPath(); } break; case 2: { this.state = 84; this.identifier(); this.state = 85; this.match(GenericSqlParser.T__0); { this.state = 86; this.exp(0); this.state = 91; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === GenericSqlParser.T__2) { { { this.state = 87; this.match(GenericSqlParser.T__2); this.state = 88; this.exp(0); } } this.state = 93; this._errHandler.sync(this); _la = this._input.LA(1); } } this.state = 94; this.match(GenericSqlParser.T__1); } break; case 3: { this.state = 96; this.match(GenericSqlParser.CAST); this.state = 97; this.match(GenericSqlParser.T__0); this.state = 98; this.exp(0); this.state = 99; this.match(GenericSqlParser.AS); this.state = 100; this.identifier(); this.state = 101; this.match(GenericSqlParser.T__1); } break; case 4: { this.state = 103; this.match(GenericSqlParser.STRING); } break; case 5: { this.state = 104; this.numeric(); } break; case 6: { this.state = 105; this.identifier(); } break; case 7: { this.state = 106; this.match(GenericSqlParser.INDEXED_PARAM); } break; case 8: { this.state = 107; this.match(GenericSqlParser.T__0); this.state = 108; this.exp(0); this.state = 109; this.match(GenericSqlParser.T__1); } break; } this._ctx._stop = this._input.tryLT(-1); this.state = 121; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { if (this._parseListeners != null) { this.triggerExitRuleEvent(); } _prevctx = _localctx; { this.state = 119; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 11, this._ctx) ) { case 1: { _localctx = new ExpContext(_parentctx, _parentState); this.pushNewRecursionContext(_localctx, _startState, GenericSqlParser.RULE_exp); this.state = 113; if (!(this.precpred(this._ctx, 10))) { throw this.createFailedPredicateException("this.precpred(this._ctx, 10)"); } this.state = 114; this.binaryOperator(); this.state = 115; this.exp(11); } break; case 2: { _localctx = new ExpContext(_parentctx, _parentState); this.pushNewRecursionContext(_localctx, _startState, GenericSqlParser.RULE_exp); this.state = 117; if (!(this.precpred(this._ctx, 9))) { throw this.createFailedPredicateException("this.precpred(this._ctx, 9)"); } this.state = 118; this.unaryOperator(); } break; } } } this.state = 123; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 12, this._ctx); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.unrollRecursionContexts(_parentctx); } return _localctx; } // @RuleVersion(0) public numeric(): NumericContext { let _localctx: NumericContext = new NumericContext(this._ctx, this.state); this.enterRule(_localctx, 16, GenericSqlParser.RULE_numeric); try { let _alt: number; this.state = 143; this._errHandler.sync(this); switch (this._input.LA(1)) { case GenericSqlParser.DIGIT: this.enterOuterAlt(_localctx, 1); { this.state = 125; this._errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { this.state = 124; this.match(GenericSqlParser.DIGIT); } } break; default: throw new NoViableAltException(this); } this.state = 127; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 13, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); this.state = 135; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 15, this._ctx) ) { case 1: { this.state = 129; this.match(GenericSqlParser.T__3); this.state = 131; this._errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { this.state = 130; this.match(GenericSqlParser.DIGIT); } } break; default: throw new NoViableAltException(this); } this.state = 133; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 14, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); } break; } } break; case GenericSqlParser.T__3: this.enterOuterAlt(_localctx, 2); { this.state = 137; this.match(GenericSqlParser.T__3); this.state = 139; this._errHandler.sync(this); _alt = 1; do { switch (_alt) { case 1: { { this.state = 138; this.match(GenericSqlParser.DIGIT); } } break; default: throw new NoViableAltException(this); } this.state = 141; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 16, this._ctx); } while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public binaryOperator(): BinaryOperatorContext { let _localctx: BinaryOperatorContext = new BinaryOperatorContext(this._ctx, this.state); this.enterRule(_localctx, 18, GenericSqlParser.RULE_binaryOperator); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 145; _la = this._input.LA(1); if (!((((_la) & ~0x1F) === 0 && ((1 << _la) & ((1 << GenericSqlParser.LT) | (1 << GenericSqlParser.LTE) | (1 << GenericSqlParser.GT) | (1 << GenericSqlParser.GTE) | (1 << GenericSqlParser.EQUALS) | (1 << GenericSqlParser.NOT_EQUALS))) !== 0))) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public unaryOperator(): UnaryOperatorContext { let _localctx: UnaryOperatorContext = new UnaryOperatorContext(this._ctx, this.state); this.enterRule(_localctx, 20, GenericSqlParser.RULE_unaryOperator); try { this.state = 152; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 18, this._ctx) ) { case 1: this.enterOuterAlt(_localctx, 1); { this.state = 147; this.match(GenericSqlParser.IS); this.state = 148; this.match(GenericSqlParser.NULL); } break; case 2: this.enterOuterAlt(_localctx, 2); { this.state = 149; this.match(GenericSqlParser.IS); this.state = 150; this.match(GenericSqlParser.NOT); this.state = 151; this.match(GenericSqlParser.NULL); } break; } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public idPath(): IdPathContext { let _localctx: IdPathContext = new IdPathContext(this._ctx, this.state); this.enterRule(_localctx, 22, GenericSqlParser.RULE_idPath); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 154; this.identifier(); this.state = 159; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 19, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { this.state = 155; this.match(GenericSqlParser.T__3); this.state = 156; this.identifier(); } } } this.state = 161; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 19, this._ctx); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public identifier(): IdentifierContext { let _localctx: IdentifierContext = new IdentifierContext(this._ctx, this.state); this.enterRule(_localctx, 24, GenericSqlParser.RULE_identifier); let _la: number; try { this.enterOuterAlt(_localctx, 1); { this.state = 162; _la = this._input.LA(1); if (!(_la === GenericSqlParser.ID || _la === GenericSqlParser.QUOTED_ID)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { switch (ruleIndex) { case 6: return this.boolExp_sempred(_localctx as BoolExpContext, predIndex); case 7: return this.exp_sempred(_localctx as ExpContext, predIndex); } return true; } private boolExp_sempred(_localctx: BoolExpContext, predIndex: number): boolean { switch (predIndex) { case 0: return this.precpred(this._ctx, 3); case 1: return this.precpred(this._ctx, 2); } return true; } private exp_sempred(_localctx: ExpContext, predIndex: number): boolean { switch (predIndex) { case 2: return this.precpred(this._ctx, 10); case 3: return this.precpred(this._ctx, 9); } return true; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x1D\xA7\x04\x02" + "\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" + "\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r\t\r\x04" + "\x0E\t\x0E\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03\x02\x03" + "\x02\x05\x02%\n\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x05" + "\x03-\n\x03\x03\x04\x03\x04\x03\x05\x03\x05\x03\x05\x07\x054\n\x05\f\x05" + "\x0E\x057\v\x05\x03\x06\x03\x06\x05\x06;\n\x06\x03\x07\x03\x07\x05\x07" + "?\n\x07\x03\x07\x05\x07B\n\x07\x03\b\x03\b\x03\b\x03\b\x05\bH\n\b\x03" + "\b\x03\b\x03\b\x03\b\x03\b\x03\b\x07\bP\n\b\f\b\x0E\bS\v\b\x03\t\x03\t" + "\x03\t\x03\t\x03\t\x03\t\x03\t\x07\t\\\n\t\f\t\x0E\t_\v\t\x03\t\x03\t" + "\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03" + "\t\x03\t\x03\t\x03\t\x05\tr\n\t\x03\t\x03\t\x03\t\x03\t\x03\t\x03\t\x07" + "\tz\n\t\f\t\x0E\t}\v\t\x03\n\x06\n\x80\n\n\r\n\x0E\n\x81\x03\n\x03\n\x06" + "\n\x86\n\n\r\n\x0E\n\x87\x05\n\x8A\n\n\x03\n\x03\n\x06\n\x8E\n\n\r\n\x0E" + "\n\x8F\x05\n\x92\n\n\x03\v\x03\v\x03\f\x03\f\x03\f\x03\f\x03\f\x05\f\x9B" + "\n\f\x03\r\x03\r\x03\r\x07\r\xA0\n\r\f\r\x0E\r\xA3\v\r\x03\x0E\x03\x0E" + "\x03\x0E\x02\x02\x04\x0E\x10\x0F\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f" + "\x02\x0E\x02\x10\x02\x12\x02\x14\x02\x16\x02\x18\x02\x1A\x02\x02\x04\x03" + "\x02\x0F\x14\x04\x02\x19\x19\x1B\x1B\x02\xB3\x02$\x03\x02\x02\x02\x04" + "&\x03\x02\x02\x02\x06.\x03\x02\x02\x02\b0\x03\x02\x02\x02\n:\x03\x02\x02" + "\x02\f<\x03\x02\x02\x02\x0EG\x03\x02\x02\x02\x10q\x03\x02\x02\x02\x12" + "\x91\x03\x02\x02\x02\x14\x93\x03\x02\x02\x02\x16\x9A\x03\x02\x02\x02\x18" + "\x9C\x03\x02\x02\x02\x1A\xA4\x03\x02\x02\x02\x1C\x1D\x05\x04\x03\x02\x1D" + "\x1E\x07\x02\x02\x03\x1E%\x03\x02\x02\x02\x1F \x07\x03\x02\x02 !\x05\x04" + "\x03\x02!\"\x07\x04\x02\x02\"#\x07\x02\x02\x03#%\x03\x02\x02\x02$\x1C" + "\x03\x02\x02\x02$\x1F\x03\x02\x02\x02%\x03\x03\x02\x02\x02&\'\x07\x07" + "\x02\x02\'(\x05\b\x05\x02()\x07\t\x02\x02),\x05\x06\x04\x02*+\x07\n\x02" + "\x02+-\x05\x0E\b\x02,*\x03\x02\x02\x02,-\x03\x02\x02\x02-\x05\x03\x02" + "\x02\x02./\x05\f\x07\x02/\x07\x03\x02\x02\x0205\x05\n\x06\x0212\x07\x05" + "\x02\x0224\x05\n\x06\x0231\x03\x02\x02\x0247\x03\x02\x02\x0253\x03\x02" + "\x02\x0256\x03\x02\x02\x026\t\x03\x02\x02\x0275\x03\x02\x02\x028;\x05" + "\f\x07\x029;\x07\b\x02\x02:8\x03\x02\x02\x02:9\x03\x02\x02\x02;\v\x03" + "\x02\x02\x02<A\x05\x18\r\x02=?\x07\x0E\x02\x02>=\x03\x02\x02\x02>?\x03" + "\x02\x02\x02?@\x03\x02\x02\x02@B\x05\x1A\x0E\x02A>\x03\x02\x02\x02AB\x03" + "\x02\x02\x02B\r\x03\x02\x02\x02CD\b\b\x01\x02DH\x05\x10\t\x02EF\x07\r" + "\x02\x02FH\x05\x0E\b\x03GC\x03\x02\x02\x02GE\x03\x02\x02\x02HQ\x03\x02" + "\x02\x02IJ\f\x05\x02\x02JK\x07\v\x02\x02KP\x05\x0E\b\x06LM\f\x04\x02\x02" + "MN\x07\f\x02\x02NP\x05\x0E\b\x05OI\x03\x02\x02\x02OL\x03\x02\x02\x02P" + "S\x03\x02\x02\x02QO\x03\x02\x02\x02QR\x03\x02\x02\x02R\x0F\x03\x02\x02" + "\x02SQ\x03\x02\x02\x02TU\b\t\x01\x02Ur\x05\x18\r\x02VW\x05\x1A\x0E\x02" + "WX\x07\x03\x02\x02X]\x05\x10\t\x02YZ\x07\x05\x02\x02Z\\\x05\x10\t\x02" + "[Y\x03\x02\x02\x02\\_\x03\x02\x02\x02][\x03\x02\x02\x02]^\x03\x02\x02" + "\x02^`\x03\x02\x02\x02_]\x03\x02\x02\x02`a\x07\x04\x02\x02ar\x03\x02\x02" + "\x02bc\x07\x17\x02\x02cd\x07\x03\x02\x02de\x05\x10\t\x02ef\x07\x0E\x02" + "\x02fg\x05\x1A\x0E\x02gh\x07\x04\x02\x02hr\x03\x02\x02\x02ir\x07\x1C\x02" + "\x02jr\x05\x12\n\x02kr\x05\x1A\x0E\x02lr\x07\x18\x02\x02mn\x07\x03\x02" + "\x02no\x05\x10\t\x02op\x07\x04\x02\x02pr\x03\x02\x02\x02qT\x03\x02\x02" + "\x02qV\x03\x02\x02\x02qb\x03\x02\x02\x02qi\x03\x02\x02\x02qj\x03\x02\x02" + "\x02qk\x03\x02\x02\x02ql\x03\x02\x02\x02qm\x03\x02\x02\x02r{\x03\x02\x02" + "\x02st\f\f\x02\x02tu\x05\x14\v\x02uv\x05\x10\t\rvz\x03\x02\x02\x02wx\f" + "\v\x02\x02xz\x05\x16\f\x02ys\x03\x02\x02\x02yw\x03\x02\x02\x02z}\x03\x02" + "\x02\x02{y\x03\x02\x02\x02{|\x03\x02\x02\x02|\x11\x03\x02\x02\x02}{\x03" + "\x02\x02\x02~\x80\x07\x1A\x02\x02\x7F~\x03\x02\x02\x02\x80\x81\x03\x02" + "\x02\x02\x81\x7F\x03\x02\x02\x02\x81\x82\x03\x02\x02\x02\x82\x89\x03\x02" + "\x02\x02\x83\x85\x07\x06\x02\x02\x84\x86\x07\x1A\x02\x02\x85\x84\x03\x02" + "\x02\x02\x86\x87\x03\x02\x02\x02\x87\x85\x03\x02\x02\x02\x87\x88\x03\x02" + "\x02\x02\x88\x8A\x03\x02\x02\x02\x89\x83\x03\x02\x02\x02\x89\x8A\x03\x02" + "\x02\x02\x8A\x92\x03\x02\x02\x02\x8B\x8D\x07\x06\x02\x02\x8C\x8E\x07\x1A" + "\x02\x02\x8D\x8C\x03\x02\x02\x02\x8E\x8F\x03\x02\x02\x02\x8F\x8D\x03\x02" + "\x02\x02\x8F\x90\x03\x02\x02\x02\x90\x92\x03\x02\x02\x02\x91\x7F\x03\x02" + "\x02\x02\x91\x8B\x03\x02\x02\x02\x92\x13\x03\x02\x02\x02\x93\x94\t\x02" + "\x02\x02\x94\x15\x03\x02\x02\x02\x95\x96\x07\x15\x02\x02\x96\x9B\x07\x16" + "\x02\x02\x97\x98\x07\x15\x02\x02\x98\x99\x07\r\x02\x02\x99\x9B\x07\x16" + "\x02\x02\x9A\x95\x03\x02\x02\x02\x9A\x97\x03\x02\x02\x02\x9B\x17\x03\x02" + "\x02\x02\x9C\xA1\x05\x1A\x0E\x02\x9D\x9E\x07\x06\x02\x02\x9E\xA0\x05\x1A" + "\x0E\x02\x9F\x9D\x03\x02\x02\x02\xA0\xA3\x03\x02\x02\x02\xA1\x9F\x03\x02" + "\x02\x02\xA1\xA2\x03\x02\x02\x02\xA2\x19\x03\x02\x02\x02\xA3\xA1\x03\x02" + "\x02\x02\xA4\xA5\t\x03\x02\x02\xA5\x1B\x03\x02\x02\x02\x16$,5:>AGOQ]q" + "y{\x81\x87\x89\x8F\x91\x9A\xA1"; public static __ATN: ATN; public static get _ATN(): ATN { if (!GenericSqlParser.__ATN) { GenericSqlParser.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(GenericSqlParser._serializedATN)); } return GenericSqlParser.__ATN; } } export class StatementContext extends ParserRuleContext { public query(): QueryContext { return this.getRuleContext(0, QueryContext); } public EOF(): TerminalNode { return this.getToken(GenericSqlParser.EOF, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_statement; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterStatement) { listener.enterStatement(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitStatement) { listener.exitStatement(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitStatement) { return visitor.visitStatement(this); } else { return visitor.visitChildren(this); } } } export class QueryContext extends ParserRuleContext { public _from!: FromTablesContext; public _where!: BoolExpContext; public SELECT(): TerminalNode { return this.getToken(GenericSqlParser.SELECT, 0); } public selectFields(): SelectFieldsContext { return this.getRuleContext(0, SelectFieldsContext); } public FROM(): TerminalNode { return this.getToken(GenericSqlParser.FROM, 0); } public fromTables(): FromTablesContext { return this.getRuleContext(0, FromTablesContext); } public WHERE(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.WHERE, 0); } public boolExp(): BoolExpContext | undefined { return this.tryGetRuleContext(0, BoolExpContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_query; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterQuery) { listener.enterQuery(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitQuery) { listener.exitQuery(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitQuery) { return visitor.visitQuery(this); } else { return visitor.visitChildren(this); } } } export class FromTablesContext extends ParserRuleContext { public aliasField(): AliasFieldContext { return this.getRuleContext(0, AliasFieldContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_fromTables; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterFromTables) { listener.enterFromTables(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitFromTables) { listener.exitFromTables(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitFromTables) { return visitor.visitFromTables(this); } else { return visitor.visitChildren(this); } } } export class SelectFieldsContext extends ParserRuleContext { public field(): FieldContext[]; public field(i: number): FieldContext; public field(i?: number): FieldContext | FieldContext[] { if (i === undefined) { return this.getRuleContexts(FieldContext); } else { return this.getRuleContext(i, FieldContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_selectFields; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterSelectFields) { listener.enterSelectFields(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitSelectFields) { listener.exitSelectFields(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitSelectFields) { return visitor.visitSelectFields(this); } else { return visitor.visitChildren(this); } } } export class FieldContext extends ParserRuleContext { public aliasField(): AliasFieldContext | undefined { return this.tryGetRuleContext(0, AliasFieldContext); } public ASTERISK(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.ASTERISK, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_field; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterField) { listener.enterField(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitField) { listener.exitField(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitField) { return visitor.visitField(this); } else { return visitor.visitChildren(this); } } } export class AliasFieldContext extends ParserRuleContext { public idPath(): IdPathContext { return this.getRuleContext(0, IdPathContext); } public identifier(): IdentifierContext | undefined { return this.tryGetRuleContext(0, IdentifierContext); } public AS(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.AS, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_aliasField; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterAliasField) { listener.enterAliasField(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitAliasField) { listener.exitAliasField(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitAliasField) { return visitor.visitAliasField(this); } else { return visitor.visitChildren(this); } } } export class BoolExpContext extends ParserRuleContext { public exp(): ExpContext | undefined { return this.tryGetRuleContext(0, ExpContext); } public boolExp(): BoolExpContext[]; public boolExp(i: number): BoolExpContext; public boolExp(i?: number): BoolExpContext | BoolExpContext[] { if (i === undefined) { return this.getRuleContexts(BoolExpContext); } else { return this.getRuleContext(i, BoolExpContext); } } public AND(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.AND, 0); } public OR(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.OR, 0); } public NOT(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.NOT, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_boolExp; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterBoolExp) { listener.enterBoolExp(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitBoolExp) { listener.exitBoolExp(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitBoolExp) { return visitor.visitBoolExp(this); } else { return visitor.visitChildren(this); } } } export class ExpContext extends ParserRuleContext { public exp(): ExpContext[]; public exp(i: number): ExpContext; public exp(i?: number): ExpContext | ExpContext[] { if (i === undefined) { return this.getRuleContexts(ExpContext); } else { return this.getRuleContext(i, ExpContext); } } public binaryOperator(): BinaryOperatorContext | undefined { return this.tryGetRuleContext(0, BinaryOperatorContext); } public unaryOperator(): UnaryOperatorContext | undefined { return this.tryGetRuleContext(0, UnaryOperatorContext); } public idPath(): IdPathContext | undefined { return this.tryGetRuleContext(0, IdPathContext); } public identifier(): IdentifierContext | undefined { return this.tryGetRuleContext(0, IdentifierContext); } public CAST(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.CAST, 0); } public AS(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.AS, 0); } public STRING(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.STRING, 0); } public numeric(): NumericContext | undefined { return this.tryGetRuleContext(0, NumericContext); } public INDEXED_PARAM(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.INDEXED_PARAM, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_exp; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterExp) { listener.enterExp(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitExp) { listener.exitExp(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitExp) { return visitor.visitExp(this); } else { return visitor.visitChildren(this); } } } export class NumericContext extends ParserRuleContext { public DIGIT(): TerminalNode[]; public DIGIT(i: number): TerminalNode; public DIGIT(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(GenericSqlParser.DIGIT); } else { return this.getToken(GenericSqlParser.DIGIT, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_numeric; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterNumeric) { listener.enterNumeric(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitNumeric) { listener.exitNumeric(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitNumeric) { return visitor.visitNumeric(this); } else { return visitor.visitChildren(this); } } } export class BinaryOperatorContext extends ParserRuleContext { public LT(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.LT, 0); } public LTE(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.LTE, 0); } public GT(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.GT, 0); } public GTE(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.GTE, 0); } public EQUALS(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.EQUALS, 0); } public NOT_EQUALS(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.NOT_EQUALS, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_binaryOperator; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterBinaryOperator) { listener.enterBinaryOperator(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitBinaryOperator) { listener.exitBinaryOperator(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitBinaryOperator) { return visitor.visitBinaryOperator(this); } else { return visitor.visitChildren(this); } } } export class UnaryOperatorContext extends ParserRuleContext { public IS(): TerminalNode { return this.getToken(GenericSqlParser.IS, 0); } public NULL(): TerminalNode { return this.getToken(GenericSqlParser.NULL, 0); } public NOT(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.NOT, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_unaryOperator; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterUnaryOperator) { listener.enterUnaryOperator(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitUnaryOperator) { listener.exitUnaryOperator(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitUnaryOperator) { return visitor.visitUnaryOperator(this); } else { return visitor.visitChildren(this); } } } export class IdPathContext extends ParserRuleContext { public identifier(): IdentifierContext[]; public identifier(i: number): IdentifierContext; public identifier(i?: number): IdentifierContext | IdentifierContext[] { if (i === undefined) { return this.getRuleContexts(IdentifierContext); } else { return this.getRuleContext(i, IdentifierContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_idPath; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterIdPath) { listener.enterIdPath(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitIdPath) { listener.exitIdPath(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitIdPath) { return visitor.visitIdPath(this); } else { return visitor.visitChildren(this); } } } export class IdentifierContext extends ParserRuleContext { public ID(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.ID, 0); } public QUOTED_ID(): TerminalNode | undefined { return this.tryGetToken(GenericSqlParser.QUOTED_ID, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return GenericSqlParser.RULE_identifier; } // @Override public enterRule(listener: GenericSqlListener): void { if (listener.enterIdentifier) { listener.enterIdentifier(this); } } // @Override public exitRule(listener: GenericSqlListener): void { if (listener.exitIdentifier) { listener.exitIdentifier(this); } } // @Override public accept<Result>(visitor: GenericSqlVisitor<Result>): Result { if (visitor.visitIdentifier) { return visitor.visitIdentifier(this); } else { return visitor.visitChildren(this); } } }
the_stack
import {Callback, Id, IdOrNull, Ids, ParameterizedCallback} from '../common.d'; import { Cell, CellIdsListener, CellListener, MapCell, Row, RowIdsListener, RowListener, Store, Table, TableIdsListener, TableListener, Tables, TablesListener, } from '../store.d'; import { CheckpointIds, CheckpointIdsListener, CheckpointListener, Checkpoints, } from '../checkpoints.d'; import { CheckpointsOrCheckpointsId, IndexesOrIndexesId, MetricsOrMetricsId, RelationshipsOrRelationshipsId, StoreOrStoreId, UndoOrRedoInformation, useAddRowCallback as useAddRowCallbackDecl, useCell as useCellDecl, useCellIds as useCellIdsDecl, useCellIdsListener as useCellIdsListenerDecl, useCellListener as useCellListenerDecl, useCheckpoint as useCheckpointDecl, useCheckpointIds as useCheckpointIdsDecl, useCheckpointIdsListener as useCheckpointIdsListenerDecl, useCheckpointListener as useCheckpointListenerDecl, useCreateCheckpoints as useCreateCheckpointsDecl, useCreateIndexes as useCreateIndexesDecl, useCreateMetrics as useCreateMetricsDecl, useCreatePersister as useCreatePersisterDecl, useCreateRelationships as useCreateRelationshipsDecl, useCreateStore as useCreateStoreDecl, useDelCellCallback as useDelCellCallbackDecl, useDelRowCallback as useDelRowCallbackDecl, useDelTableCallback as useDelTableCallbackDecl, useDelTablesCallback as useDelTablesCallbackDecl, useGoBackwardCallback as useGoBackwardCallbackDecl, useGoForwardCallback as useGoForwardCallbackDecl, useGoToCallback as useGoToCallbackDecl, useLinkedRowIds as useLinkedRowIdsDecl, useLinkedRowIdsListener as useLinkedRowIdsListenerDecl, useLocalRowIds as useLocalRowIdsDecl, useLocalRowIdsListener as useLocalRowIdsListenerDecl, useMetric as useMetricDecl, useMetricListener as useMetricListenerDecl, useRedoInformation as useRedoInformationDecl, useRemoteRowId as useRemoteRowIdDecl, useRemoteRowIdListener as useRemoteRowIdListenerDecl, useRow as useRowDecl, useRowIds as useRowIdsDecl, useRowIdsListener as useRowIdsListenerDecl, useRowListener as useRowListenerDecl, useSetCellCallback as useSetCellCallbackDecl, useSetCheckpointCallback as useSetCheckpointCallbackDecl, useSetPartialRowCallback as useSetPartialRowCallbackDecl, useSetRowCallback as useSetRowCallbackDecl, useSetTableCallback as useSetTableCallbackDecl, useSetTablesCallback as useSetTablesCallbackDecl, useSliceIds as useSliceIdsDecl, useSliceIdsListener as useSliceIdsListenerDecl, useSliceRowIds as useSliceRowIdsDecl, useSliceRowIdsListener as useSliceRowIdsListenerDecl, useTable as useTableDecl, useTableIds as useTableIdsDecl, useTableIdsListener as useTableIdsListenerDecl, useTableListener as useTableListenerDecl, useTables as useTablesDecl, useTablesListener as useTablesListenerDecl, useUndoInformation as useUndoInformationDecl, } from '../ui-react.d'; import {Indexes, SliceIdsListener, SliceRowIdsListener} from '../indexes.d'; import { LinkedRowIdsListener, LocalRowIdsListener, Relationships, RemoteRowIdListener, } from '../relationships.d'; import {MetricListener, Metrics} from '../metrics.d'; import {getUndefined, ifNotUndefined, isUndefined} from '../common/other'; import { useCheckpointsOrCheckpointsId, useIndexesOrIndexesId, useMetricsOrMetricsId, useRelationshipsOrRelationshipsId, useStoreOrStoreId, } from './common'; import {Persister} from '../persisters.d'; import React from 'react'; import {arrayIsEmpty} from '../common/array'; export { useCheckpoints, useIndexes, useMetrics, useRelationships, useStore, } from './common'; const {useCallback, useEffect, useMemo, useState} = React; const useCreate = ( store: Store, create: (store: Store) => any, createDeps: React.DependencyList = [], ) => { const thing = useMemo( () => create(store), // eslint-disable-next-line react-hooks/exhaustive-deps [store, ...createDeps], ); useEffect(() => () => thing.destroy(), [thing]); return thing; }; const useListenable = ( listenable: string, thing: any, defaulted: any, ...args: any[] ): any => { const getListenable = thing?.['get' + listenable] ?? (() => defaulted); const immediateListenable = getListenable(...args); const [, setListenable] = useState(immediateListenable); useEffect(() => { const listenerId = thing?.[`add${listenable}Listener`]?.( ...args, () => setListenable(getListenable(...args)), false, ); return () => thing?.delListener(listenerId); // eslint-disable-next-line react-hooks/exhaustive-deps }, [thing, listenable, setListenable, getListenable, ...args]); return immediateListenable; }; const useListener = ( listenable: string, thing: any, listener: (...args: any[]) => void, listenerDeps: React.DependencyList = [], mutator?: boolean, ...args: IdOrNull[] ): void => { useEffect(() => { const listenerId = thing?.[`add${listenable}Listener`]?.( ...args, listener, mutator, ); return () => thing?.delListener(listenerId); // eslint-disable-next-line react-hooks/exhaustive-deps }, [thing, listenable, ...listenerDeps, mutator, ...args]); }; const useSetCallback = <Parameter, Value>( storeOrStoreId: StoreOrStoreId | undefined, settable: string, get: (parameter: Parameter, store: Store) => Value, getDeps: React.DependencyList = [], then: (store: Store, value: Value) => void = getUndefined, thenDeps: React.DependencyList = [], ...args: Ids ): ParameterizedCallback<Parameter> => { const store = useStoreOrStoreId(storeOrStoreId); return useCallback( (parameter) => ifNotUndefined(store, (store: any) => ifNotUndefined(get(parameter as any, store), (value: Value) => then(store['set' + settable](...args, value), value), ), ), // eslint-disable-next-line react-hooks/exhaustive-deps [store, settable, ...getDeps, ...thenDeps, ...args], ); }; const useDel = ( storeOrStoreId: StoreOrStoreId | undefined, deletable: string, then: (store: Store) => void = getUndefined, thenDeps: React.DependencyList = [], ...args: (Id | boolean | undefined)[] ) => { const store: any = useStoreOrStoreId(storeOrStoreId); return useCallback( () => then(store?.['del' + deletable](...args)), // eslint-disable-next-line react-hooks/exhaustive-deps [store, deletable, ...thenDeps, ...args], ); }; const useCheckpointAction = ( checkpointsOrCheckpointsId: CheckpointsOrCheckpointsId | undefined, action: string, arg?: string, ) => { const checkpoints: any = useCheckpointsOrCheckpointsId( checkpointsOrCheckpointsId, ); return useCallback( () => checkpoints?.[action](arg), // eslint-disable-next-line react-hooks/exhaustive-deps [checkpoints, action, arg], ); }; export const useCreateStore: typeof useCreateStoreDecl = ( create: () => Store, createDeps: React.DependencyList = [], // eslint-disable-next-line react-hooks/exhaustive-deps ): Store => useMemo(create, createDeps); export const useTables: typeof useTablesDecl = ( storeOrStoreId?: StoreOrStoreId, ): Tables => useListenable('Tables', useStoreOrStoreId(storeOrStoreId), {}); export const useTableIds: typeof useTableIdsDecl = ( storeOrStoreId?: StoreOrStoreId, ): Ids => useListenable('TableIds', useStoreOrStoreId(storeOrStoreId), []); export const useTable: typeof useTableDecl = ( tableId: Id, storeOrStoreId?: StoreOrStoreId, ): Table => useListenable('Table', useStoreOrStoreId(storeOrStoreId), {}, tableId); export const useRowIds: typeof useRowIdsDecl = ( tableId: Id, storeOrStoreId?: StoreOrStoreId, ): Ids => useListenable('RowIds', useStoreOrStoreId(storeOrStoreId), [], tableId); export const useRow: typeof useRowDecl = ( tableId: Id, rowId: Id, storeOrStoreId?: StoreOrStoreId, ): Row => useListenable('Row', useStoreOrStoreId(storeOrStoreId), {}, tableId, rowId); export const useCellIds: typeof useCellIdsDecl = ( tableId: Id, rowId: Id, storeOrStoreId?: StoreOrStoreId, ): Ids => useListenable( 'CellIds', useStoreOrStoreId(storeOrStoreId), [], tableId, rowId, ); export const useCell: typeof useCellDecl = ( tableId: Id, rowId: Id, cellId: Id, storeOrStoreId?: StoreOrStoreId, ): Cell | undefined => useListenable( 'Cell', useStoreOrStoreId(storeOrStoreId), undefined, tableId, rowId, cellId, ); export const useSetTablesCallback: typeof useSetTablesCallbackDecl = < Parameter, >( getTables: (parameter: Parameter, store: Store) => Tables, getTablesDeps?: React.DependencyList, storeOrStoreId?: StoreOrStoreId, then?: (store: Store, tables: Tables) => void, thenDeps?: React.DependencyList, ): ParameterizedCallback<Parameter> => useSetCallback( storeOrStoreId, 'Tables', getTables, getTablesDeps, then, thenDeps, ); export const useSetTableCallback: typeof useSetTableCallbackDecl = <Parameter>( tableId: Id, getTable: (parameter: Parameter, store: Store) => Table, getTableDeps?: React.DependencyList, storeOrStoreId?: StoreOrStoreId, then?: (store: Store, table: Table) => void, thenDeps?: React.DependencyList, ): ParameterizedCallback<Parameter> => useSetCallback( storeOrStoreId, 'Table', getTable, getTableDeps, then, thenDeps, tableId, ); export const useSetRowCallback: typeof useSetRowCallbackDecl = <Parameter>( tableId: Id, rowId: Id, getRow: (parameter: Parameter, store: Store) => Row, getRowDeps?: React.DependencyList, storeOrStoreId?: StoreOrStoreId, then?: (store: Store, row: Row) => void, thenDeps?: React.DependencyList, ): ParameterizedCallback<Parameter> => useSetCallback( storeOrStoreId, 'Row', getRow, getRowDeps, then, thenDeps, tableId, rowId, ); export const useAddRowCallback: typeof useAddRowCallbackDecl = <Parameter>( tableId: Id, getRow: (parameter: Parameter, store: Store) => Row, getRowDeps: React.DependencyList = [], storeOrStoreId?: StoreOrStoreId, then: (rowId: Id | undefined, store: Store, row: Row) => void = getUndefined, thenDeps: React.DependencyList = [], ): ParameterizedCallback<Parameter> => { const store = useStoreOrStoreId(storeOrStoreId); return useCallback( (parameter) => ifNotUndefined(store, (store) => ifNotUndefined(getRow(parameter as any, store), (row: Row) => then(store.addRow(tableId, row), store, row), ), ), // eslint-disable-next-line react-hooks/exhaustive-deps [store, tableId, ...getRowDeps, ...thenDeps], ); }; export const useSetPartialRowCallback: typeof useSetPartialRowCallbackDecl = < Parameter, >( tableId: Id, rowId: Id, getPartialRow: (parameter: Parameter, store: Store) => Row, getPartialRowDeps?: React.DependencyList, storeOrStoreId?: StoreOrStoreId, then?: (store: Store, partialRow: Row) => void, thenDeps?: React.DependencyList, ): ParameterizedCallback<Parameter> => useSetCallback( storeOrStoreId, 'PartialRow', getPartialRow, getPartialRowDeps, then, thenDeps, tableId, rowId, ); export const useSetCellCallback: typeof useSetCellCallbackDecl = <Parameter>( tableId: Id, rowId: Id, cellId: Id, getCell: (parameter: Parameter, store: Store) => Cell | MapCell, getCellDeps?: React.DependencyList, storeOrStoreId?: StoreOrStoreId, then?: (store: Store, cell: Cell | MapCell) => void, thenDeps?: React.DependencyList, ): ParameterizedCallback<Parameter> => useSetCallback( storeOrStoreId, 'Cell', getCell, getCellDeps, then, thenDeps, tableId, rowId, cellId, ); export const useDelTablesCallback: typeof useDelTablesCallbackDecl = ( storeOrStoreId?: StoreOrStoreId, then?: (store: Store) => void, thenDeps?: React.DependencyList, ): Callback => useDel(storeOrStoreId, 'Tables', then, thenDeps); export const useDelTableCallback: typeof useDelTableCallbackDecl = ( tableId: Id, storeOrStoreId?: StoreOrStoreId, then?: (store: Store) => void, thenDeps?: React.DependencyList, ): Callback => useDel(storeOrStoreId, 'Table', then, thenDeps, tableId); export const useDelRowCallback: typeof useDelRowCallbackDecl = ( tableId: Id, rowId: Id, storeOrStoreId?: StoreOrStoreId, then?: (store: Store) => void, thenDeps?: React.DependencyList, ): Callback => useDel(storeOrStoreId, 'Row', then, thenDeps, tableId, rowId); export const useDelCellCallback: typeof useDelCellCallbackDecl = ( tableId: Id, rowId: Id, cellId: Id, forceDel?: boolean, storeOrStoreId?: StoreOrStoreId, then?: (store: Store) => void, thenDeps?: React.DependencyList, ): Callback => useDel( storeOrStoreId, 'Cell', then, thenDeps, tableId, rowId, cellId, forceDel, ); export const useTablesListener: typeof useTablesListenerDecl = ( listener: TablesListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'Tables', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, ); export const useTableIdsListener: typeof useTableIdsListenerDecl = ( listener: TableIdsListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'TableIds', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, ); export const useTableListener: typeof useTableListenerDecl = ( tableId: IdOrNull, listener: TableListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'Table', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, tableId, ); export const useRowIdsListener: typeof useRowIdsListenerDecl = ( tableId: IdOrNull, listener: RowIdsListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'RowIds', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, tableId, ); export const useRowListener: typeof useRowListenerDecl = ( tableId: IdOrNull, rowId: IdOrNull, listener: RowListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'Row', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, tableId, rowId, ); export const useCellIdsListener: typeof useCellIdsListenerDecl = ( tableId: IdOrNull, rowId: IdOrNull, listener: CellIdsListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'CellIds', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, tableId, rowId, ); export const useCellListener: typeof useCellListenerDecl = ( tableId: IdOrNull, rowId: IdOrNull, cellId: IdOrNull, listener: CellListener, listenerDeps?: React.DependencyList, mutator?: boolean, storeOrStoreId?: StoreOrStoreId, ): void => useListener( 'Cell', useStoreOrStoreId(storeOrStoreId), listener, listenerDeps, mutator, tableId, rowId, cellId, ); export const useCreateMetrics: typeof useCreateMetricsDecl = ( store: Store, create: (store: Store) => Metrics, createDeps?: React.DependencyList, ): Metrics => useCreate(store, create, createDeps); export const useMetric: typeof useMetricDecl = ( metricId: Id, metricsOrMetricsId?: MetricsOrMetricsId, ): number | undefined => useListenable( 'Metric', useMetricsOrMetricsId(metricsOrMetricsId), undefined, metricId, ); export const useMetricListener: typeof useMetricListenerDecl = ( metricId: IdOrNull, listener: MetricListener, listenerDeps?: React.DependencyList, metricsOrMetricsId?: MetricsOrMetricsId, ): void => useListener( 'Metric', useMetricsOrMetricsId(metricsOrMetricsId), listener, listenerDeps, undefined, metricId, ); export const useCreateIndexes: typeof useCreateIndexesDecl = ( store: Store, create: (store: Store) => Indexes, createDeps?: React.DependencyList, ): Indexes => useCreate(store, create, createDeps); export const useSliceIds: typeof useSliceIdsDecl = ( indexId: Id, indexesOrIndexesId?: IndexesOrIndexesId, ): Ids => useListenable( 'SliceIds', useIndexesOrIndexesId(indexesOrIndexesId), [], indexId, ); export const useSliceRowIds: typeof useSliceRowIdsDecl = ( indexId: Id, sliceId: Id, indexesOrIndexesId?: IndexesOrIndexesId, ): Ids => useListenable( 'SliceRowIds', useIndexesOrIndexesId(indexesOrIndexesId), [], indexId, sliceId, ); export const useSliceIdsListener: typeof useSliceIdsListenerDecl = ( indexId: IdOrNull, listener: SliceIdsListener, listenerDeps?: React.DependencyList, indexesOrIndexesId?: IndexesOrIndexesId, ): void => useListener( 'SliceIds', useIndexesOrIndexesId(indexesOrIndexesId), listener, listenerDeps, undefined, indexId, ); export const useSliceRowIdsListener: typeof useSliceRowIdsListenerDecl = ( indexId: IdOrNull, sliceId: IdOrNull, listener: SliceRowIdsListener, listenerDeps?: React.DependencyList, indexesOrIndexesId?: IndexesOrIndexesId, ): void => useListener( 'SliceRowIds', useIndexesOrIndexesId(indexesOrIndexesId), listener, listenerDeps, undefined, indexId, sliceId, ); export const useCreateRelationships: typeof useCreateRelationshipsDecl = ( store: Store, create: (store: Store) => Relationships, createDeps?: React.DependencyList, ): Relationships => useCreate(store, create, createDeps); export const useRemoteRowId: typeof useRemoteRowIdDecl = ( relationshipId: Id, localRowId: Id, relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId, ): Id | undefined => useListenable( 'RemoteRowId', useRelationshipsOrRelationshipsId(relationshipsOrRelationshipsId), undefined, relationshipId, localRowId, ); export const useLocalRowIds: typeof useLocalRowIdsDecl = ( relationshipId: Id, remoteRowId: Id, relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId, ): Ids => useListenable( 'LocalRowIds', useRelationshipsOrRelationshipsId(relationshipsOrRelationshipsId), [], relationshipId, remoteRowId, ); export const useLinkedRowIds: typeof useLinkedRowIdsDecl = ( relationshipId: Id, firstRowId: Id, relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId, ): Ids => useListenable( 'LinkedRowIds', useRelationshipsOrRelationshipsId(relationshipsOrRelationshipsId), [], relationshipId, firstRowId, ); export const useRemoteRowIdListener: typeof useRemoteRowIdListenerDecl = ( relationshipId: IdOrNull, localRowId: IdOrNull, listener: RemoteRowIdListener, listenerDeps?: React.DependencyList, relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId, ): void => useListener( 'RemoteRowId', useRelationshipsOrRelationshipsId(relationshipsOrRelationshipsId), listener, listenerDeps, undefined, relationshipId, localRowId, ); export const useLocalRowIdsListener: typeof useLocalRowIdsListenerDecl = ( relationshipId: IdOrNull, remoteRowId: IdOrNull, listener: LocalRowIdsListener, listenerDeps?: React.DependencyList, relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId, ): void => useListener( 'LocalRowIds', useRelationshipsOrRelationshipsId(relationshipsOrRelationshipsId), listener, listenerDeps, undefined, relationshipId, remoteRowId, ); export const useLinkedRowIdsListener: typeof useLinkedRowIdsListenerDecl = ( relationshipId: Id, firstRowId: Id, listener: LinkedRowIdsListener, listenerDeps?: React.DependencyList, relationshipsOrRelationshipsId?: RelationshipsOrRelationshipsId, ): void => useListener( 'LinkedRowIds', useRelationshipsOrRelationshipsId(relationshipsOrRelationshipsId), listener, listenerDeps, undefined, relationshipId, firstRowId, ); export const useCreateCheckpoints: typeof useCreateCheckpointsDecl = ( store: Store, create: (store: Store) => Checkpoints, createDeps?: React.DependencyList, ): Checkpoints => useCreate(store, create, createDeps); export const useCheckpointIds: typeof useCheckpointIdsDecl = ( checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): CheckpointIds => useListenable( 'CheckpointIds', useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId), [[], undefined, []], ); export const useCheckpoint: typeof useCheckpointDecl = ( checkpointId: Id, checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): string | undefined => useListenable( 'Checkpoint', useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId), undefined, checkpointId, ); export const useSetCheckpointCallback: typeof useSetCheckpointCallbackDecl = < Parameter, >( getCheckpoint: (parameter: Parameter) => string | undefined = getUndefined, getCheckpointDeps: React.DependencyList = [], checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, then: ( checkpointId: Id, checkpoints: Checkpoints, label?: string, ) => void = getUndefined, thenDeps: React.DependencyList = [], ): ParameterizedCallback<Parameter> => { const checkpoints = useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId); return useCallback( (parameter) => ifNotUndefined(checkpoints, (checkpoints) => { const label = getCheckpoint(parameter as any); then(checkpoints.addCheckpoint(label), checkpoints, label); }), // eslint-disable-next-line react-hooks/exhaustive-deps [checkpoints, ...getCheckpointDeps, ...thenDeps], ); }; export const useGoBackwardCallback: typeof useGoBackwardCallbackDecl = ( checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): Callback => useCheckpointAction(checkpointsOrCheckpointsId, 'goBackward'); export const useGoForwardCallback: typeof useGoForwardCallbackDecl = ( checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): Callback => useCheckpointAction(checkpointsOrCheckpointsId, 'goForward'); export const useGoToCallback: typeof useGoToCallbackDecl = <Parameter>( getCheckpointId: (parameter: Parameter) => Id, getCheckpointIdDeps: React.DependencyList = [], checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, then: (checkpoints: Checkpoints, checkpointId: Id) => void = getUndefined, thenDeps: React.DependencyList = [], ): ParameterizedCallback<Parameter> => { const checkpoints = useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId); return useCallback( (parameter) => ifNotUndefined(checkpoints, (checkpoints) => ifNotUndefined(getCheckpointId(parameter as any), (checkpointId: Id) => then(checkpoints.goTo(checkpointId), checkpointId), ), ), // eslint-disable-next-line react-hooks/exhaustive-deps [checkpoints, ...getCheckpointIdDeps, ...thenDeps], ); }; export const useUndoInformation: typeof useUndoInformationDecl = ( checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): UndoOrRedoInformation => { const checkpoints = useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId); const [backwardIds, currentId] = useCheckpointIds(checkpoints); return [ !arrayIsEmpty(backwardIds), useGoBackwardCallback(checkpoints), currentId, ifNotUndefined(currentId, (id) => checkpoints?.getCheckpoint(id)) ?? '', ]; }; export const useRedoInformation: typeof useRedoInformationDecl = ( checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): UndoOrRedoInformation => { const checkpoints = useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId); const [, , [forwardId]] = useCheckpointIds(checkpoints); return [ !isUndefined(forwardId), useGoForwardCallback(checkpoints), forwardId, ifNotUndefined(forwardId, (id) => checkpoints?.getCheckpoint(id)) ?? '', ]; }; export const useCheckpointIdsListener: typeof useCheckpointIdsListenerDecl = ( listener: CheckpointIdsListener, listenerDeps?: React.DependencyList, checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): void => useListener( 'CheckpointIds', useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId), listener, listenerDeps, ); export const useCheckpointListener: typeof useCheckpointListenerDecl = ( checkpointId: IdOrNull, listener: CheckpointListener, listenerDeps?: React.DependencyList, checkpointsOrCheckpointsId?: CheckpointsOrCheckpointsId, ): void => useListener( 'Checkpoint', useCheckpointsOrCheckpointsId(checkpointsOrCheckpointsId), listener, listenerDeps, undefined, checkpointId, ); export const useCreatePersister: typeof useCreatePersisterDecl = ( store: Store, create: (store: Store) => Persister, createDeps: React.DependencyList = [], then?: (persister: Persister) => Promise<void>, thenDeps: React.DependencyList = [], ): Persister => { const [, setDone] = useState<1>(); const persister = useMemo( () => create(store), // eslint-disable-next-line react-hooks/exhaustive-deps [store, ...createDeps], ); useEffect( () => { (async () => { await then?.(persister); setDone(1); return; })(); return () => { persister.destroy(); }; }, // eslint-disable-next-line react-hooks/exhaustive-deps [persister, ...thenDeps], ); return persister; };
the_stack
import { deepSet, Dict } from '@orbit/utils'; import { Orbit, Assertion } from '@orbit/core'; import { RecordSchema, RecordKeyMap, InitializedRecord, RecordIdentity, RecordOperation, ModelDefinition } from '@orbit/records'; import { Serializer, SerializerForFn, StringSerializer, buildSerializerSettingsFor } from '@orbit/serializers'; import { Resource, ResourceDocument, ResourceIdentity, ResourceRelationship } from './resource-document'; import { ResourceAtomicOperation, RecordOperationsDocument } from './resource-operations'; import { ResourceAtomicOperationsDocument } from './resource-operations'; import { RecordDocument } from './record-document'; import { JSONAPIResourceSerializer } from './serializers/jsonapi-resource-serializer'; import { JSONAPIResourceIdentitySerializer } from './serializers/jsonapi-resource-identity-serializer'; import { buildJSONAPISerializerFor } from './serializers/jsonapi-serializer-builder'; import { JSONAPISerializers } from './serializers/jsonapi-serializers'; import { JSONAPIAtomicOperationSerializer } from './serializers/jsonapi-atomic-operation-serializer'; import { JSONAPIResourceFieldSerializer } from './serializers/jsonapi-resource-field-serializer'; const { deprecate } = Orbit; export interface JSONAPISerializationOptions { primaryRecord?: InitializedRecord; primaryRecords?: InitializedRecord[]; } export interface JSONAPISerializerSettings { schema: RecordSchema; keyMap?: RecordKeyMap; serializers?: Dict<Serializer>; } /** * @deprecated since v0.17, remove in v0.18 */ export class JSONAPISerializer implements Serializer< RecordDocument, ResourceDocument, JSONAPISerializationOptions, JSONAPISerializationOptions > { protected _schema: RecordSchema; protected _keyMap?: RecordKeyMap; protected _serializerFor: SerializerForFn; constructor(settings: JSONAPISerializerSettings) { deprecate( "The 'JSONAPISerializer' class has deprecated. Use 'serializerFor' instead." ); const { schema, keyMap, serializers } = settings; let serializerFor: SerializerForFn | undefined; if (serializers) { serializerFor = (type: string) => serializers[type]; } const serializerSettingsFor = buildSerializerSettingsFor({ settingsByType: { [JSONAPISerializers.ResourceField]: { serializationOptions: { inflectors: ['dasherize'] } }, [JSONAPISerializers.ResourceType]: { serializationOptions: { inflectors: ['pluralize', 'dasherize'] } } } }); this._schema = schema; this._keyMap = keyMap; this._serializerFor = buildJSONAPISerializerFor({ schema, keyMap, serializerFor, serializerSettingsFor }); } get schema(): RecordSchema { return this._schema; } get keyMap(): RecordKeyMap | undefined { return this._keyMap; } get serializerFor(): SerializerForFn { return this._serializerFor; } /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ resourceKey(type: string): string { return 'id'; } resourceType(type: string): string { return this.typeSerializer.serialize(type) as string; } resourceRelationship(type: string | undefined, relationship: string): string { return this.fieldSerializer.serialize(relationship, { type }) as string; } resourceAttribute(type: string | undefined, attr: string): string { return this.fieldSerializer.serialize(attr, { type }) as string; } resourceIdentity(identity: RecordIdentity): Resource { return { type: this.resourceType(identity.type), id: this.resourceId(identity.type, identity.id) }; } resourceIds(type: string, ids: string[]): (string | undefined)[] { return ids.map((id) => this.resourceId(type, id)); } resourceId(type: string, id: string): string | undefined { let resourceKey = this.resourceKey(type); if (resourceKey === 'id') { return id; } else if (this.keyMap) { return this.keyMap.idToKey(type, resourceKey, id); } else { throw new Assertion( `A keyMap is required to determine an id from the key '${resourceKey}'` ); } } recordId(type: string, resourceId: string): string { let resourceKey = this.resourceKey(type); if (resourceKey === 'id') { return resourceId; } let existingId; if (this.keyMap) { existingId = this.keyMap.keyToId(type, resourceKey, resourceId); if (existingId) { return existingId; } } else { throw new Assertion( `A keyMap is required to determine an id from the key '${resourceKey}'` ); } return this._generateNewId(type, resourceKey, resourceId); } recordType(resourceType: string): string { return this.typeSerializer.deserialize(resourceType) as string; } recordIdentity(resourceIdentity: ResourceIdentity): RecordIdentity { let type = this.recordType(resourceIdentity.type); let id = this.recordId(type, resourceIdentity.id); return { type, id }; } recordAttribute(type: string, resourceAttribute: string): string { return this.fieldSerializer.deserialize(resourceAttribute) as string; } recordRelationship(type: string, resourceRelationship: string): string { return this.fieldSerializer.deserialize(resourceRelationship) as string; } serialize(document: RecordDocument): ResourceDocument { let data = document.data; return { data: Array.isArray(data) ? this.serializeRecords(data as InitializedRecord[]) : this.serializeRecord(data as InitializedRecord) }; } serializeAtomicOperationsDocument( document: RecordOperationsDocument ): ResourceAtomicOperationsDocument { return { 'atomic:operations': this.serializeAtomicOperations(document.operations) }; } serializeAtomicOperations( operations: RecordOperation[] ): ResourceAtomicOperation[] { return operations.map((operation) => this.serializeAtomicOperation(operation) ); } serializeAtomicOperation( operation: RecordOperation ): ResourceAtomicOperation { return this.atomicOperationSerializer.serialize(operation); } serializeRecords(records: InitializedRecord[]): Resource[] { return records.map((record) => this.serializeRecord(record)); } serializeRecord(record: InitializedRecord): Resource { const resource: Resource = { type: this.resourceType(record.type) }; const model: ModelDefinition = this._schema.getModel(record.type); this.serializeId(resource, record, model); this.serializeAttributes(resource, record, model); this.serializeRelationships(resource, record, model); return resource; } serializeIdentity(record: InitializedRecord): Resource { return { type: this.resourceType(record.type), id: this.resourceId(record.type, record.id) }; } serializeId( resource: Resource, record: RecordIdentity, /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ model: ModelDefinition ): void { let value = this.resourceId(record.type, record.id); if (value !== undefined) { resource.id = value; } } serializeAttributes( resource: Resource, record: InitializedRecord, model: ModelDefinition ): void { if (record.attributes) { Object.keys(record.attributes).forEach((attr) => { this.serializeAttribute(resource, record, attr, model); }); } } serializeAttribute( resource: Resource, record: InitializedRecord, attr: string, model: ModelDefinition ): void { let value: any = record.attributes?.[attr]; if (value === undefined) { return; } const attrOptions = model.attributes?.[attr]; if (attrOptions === undefined) { return; } const serializer = this.serializerFor(attrOptions.type || 'unknown'); if (serializer) { const serializationOptions = attrOptions.serialization ?? (attrOptions as any).serializationOptions; if ((attrOptions as any).serializationOptions !== undefined) { deprecate( `The attribute '${attr}' for '${record.type}' has been assigned \`serializationOptions\` in the schema. Use \`serialization\` instead.` ); } value = value === null ? null : serializer.serialize(value, serializationOptions); } deepSet( resource, ['attributes', this.resourceAttribute(record.type, attr)], value ); } serializeRelationships( resource: Resource, record: InitializedRecord, model: ModelDefinition ): void { if (record.relationships) { Object.keys(record.relationships).forEach((relationship) => { this.serializeRelationship(resource, record, relationship, model); }); } } serializeRelationship( resource: Resource, record: InitializedRecord, relationship: string, model: ModelDefinition ): void { const value = record.relationships?.[relationship].data; if (value === undefined) { return; } if (model.relationships?.[relationship] === undefined) { return; } let data; if (Array.isArray(value)) { data = (value as RecordIdentity[]).map((id) => this.resourceIdentity(id)); } else if (value !== null) { data = this.resourceIdentity(value as RecordIdentity); } else { data = null; } const resourceRelationship = this.resourceRelationship( record.type, relationship ); deepSet(resource, ['relationships', resourceRelationship, 'data'], data); } deserialize( document: ResourceDocument, options?: JSONAPISerializationOptions ): RecordDocument { let result: RecordDocument; let data; if (Array.isArray(document.data)) { let primaryRecords = options?.primaryRecords; if (primaryRecords) { data = (document.data as Resource[]).map((entry, i) => { return this.deserializeResource(entry, primaryRecords?.[i]); }); } else { data = (document.data as Resource[]).map((entry) => this.deserializeResource(entry) ); } } else if (document.data !== null) { let primaryRecord = options && options.primaryRecord; if (primaryRecord) { data = this.deserializeResource( document.data as Resource, primaryRecord ); } else { data = this.deserializeResource(document.data as Resource); } } else { data = null; } result = { data }; if (document.included) { result.included = document.included.map((e) => this.deserializeResource(e) ); } if (document.links) { result.links = document.links; } if (document.meta) { result.meta = document.meta; } return result; } deserializeAtomicOperationsDocument( document: ResourceAtomicOperationsDocument ): RecordOperationsDocument { const result: RecordOperationsDocument = { operations: this.deserializeAtomicOperations( document['atomic:operations'] ) }; if (document.links) { result.links = document.links; } if (document.meta) { result.meta = document.meta; } return result; } deserializeAtomicOperations( operations: ResourceAtomicOperation[] ): RecordOperation[] { return operations.map((operation) => this.deserializeAtomicOperation(operation) ); } deserializeAtomicOperation( operation: ResourceAtomicOperation ): RecordOperation { return this.atomicOperationSerializer.deserialize(operation); } deserializeResourceIdentity( resource: Resource, primaryRecord?: InitializedRecord ): InitializedRecord { let record: InitializedRecord; const type: string = this.recordType(resource.type); const resourceKey = this.resourceKey(type); if (resourceKey === 'id') { if (resource.id) { record = { type, id: resource.id }; } else { throw new Assertion(`A resource has been enountered without an id`); } } else if (this.keyMap) { let id: string; let keys: Dict<string> | undefined; if (resource.id) { keys = { [resourceKey]: resource.id }; id = (primaryRecord && primaryRecord.id) || this.keyMap.idFromKeys(type, keys) || this.schema.generateId(type); } else { id = (primaryRecord && primaryRecord.id) || this.schema.generateId(type); } record = { type, id }; if (keys) { record.keys = keys; } } else { throw new Assertion( `A keyMap is required to determine an id from the key '${resourceKey}'` ); } if (this.keyMap) { this.keyMap.pushRecord(record); } return record; } deserializeResource( resource: Resource, primaryRecord?: InitializedRecord ): InitializedRecord { const record = this.deserializeResourceIdentity(resource, primaryRecord); const model: ModelDefinition = this._schema.getModel(record.type); this.deserializeAttributes(record, resource, model); this.deserializeRelationships(record, resource, model); this.deserializeLinks(record, resource, model); this.deserializeMeta(record, resource, model); return record; } deserializeAttributes( record: InitializedRecord, resource: Resource, model: ModelDefinition ): void { if (resource.attributes) { Object.keys(resource.attributes).forEach((resourceAttribute) => { let attribute = this.recordAttribute(record.type, resourceAttribute); if (this.schema.hasAttribute(record.type, attribute)) { let value = resource.attributes?.[resourceAttribute]; if (value !== undefined) { this.deserializeAttribute(record, attribute, value, model); } } }); } } deserializeAttribute( record: InitializedRecord, attr: string, value: unknown, model: ModelDefinition ): void { record.attributes = record.attributes || {}; if (value !== undefined && value !== null) { const attrOptions = model.attributes?.[attr]; if (attrOptions === undefined) { return; } const serializer = this.serializerFor(attrOptions?.type || 'unknown'); if (serializer) { const deserializationOptions = attrOptions.deserialization ?? (attrOptions as any).deserializationOptions; if ((attrOptions as any).deserializationOptions !== undefined) { deprecate( `The attribute '${attr}' for '${record.type}' has been assigned \`deserializationOptions\` in the schema. Use \`deserialization\` instead.` ); } value = serializer.deserialize(value, deserializationOptions); } } record.attributes[attr] = value; } deserializeRelationships( record: InitializedRecord, resource: Resource, model: ModelDefinition ): void { if (resource.relationships) { Object.keys(resource.relationships).forEach((resourceRel) => { let relationship = this.recordRelationship(record.type, resourceRel); if (this.schema.hasRelationship(record.type, relationship)) { let value = resource.relationships?.[resourceRel]; if (value !== undefined) { this.deserializeRelationship(record, relationship, value, model); } } }); } } deserializeRelationship( record: InitializedRecord, relationship: string, value: ResourceRelationship, /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ model: ModelDefinition ): void { let resourceData = value.data; if (resourceData !== undefined) { let data; if (resourceData === null) { data = null; } else if (Array.isArray(resourceData)) { data = (resourceData as ResourceIdentity[]).map((resourceIdentity) => this.recordIdentity(resourceIdentity) ); } else { data = this.recordIdentity(resourceData as ResourceIdentity); } deepSet(record, ['relationships', relationship, 'data'], data); } let { links, meta } = value; if (links !== undefined) { deepSet(record, ['relationships', relationship, 'links'], links); } if (meta !== undefined) { deepSet(record, ['relationships', relationship, 'meta'], meta); } } deserializeLinks( record: InitializedRecord, resource: Resource, /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ model: ModelDefinition ): void { if (resource.links) { record.links = resource.links; } } deserializeMeta( record: InitializedRecord, resource: Resource, /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ model: ModelDefinition ): void { if (resource.meta) { record.meta = resource.meta; } } // Protected / Private protected get resourceSerializer(): JSONAPIResourceSerializer { return this.serializerFor( JSONAPISerializers.Resource ) as JSONAPIResourceSerializer; } protected get identitySerializer(): JSONAPIResourceIdentitySerializer { return this.serializerFor( JSONAPISerializers.ResourceIdentity ) as JSONAPIResourceIdentitySerializer; } protected get typeSerializer(): StringSerializer { return this.serializerFor( JSONAPISerializers.ResourceType ) as StringSerializer; } protected get fieldSerializer(): JSONAPIResourceFieldSerializer { return this.serializerFor( JSONAPISerializers.ResourceField ) as JSONAPIResourceFieldSerializer; } protected get atomicOperationSerializer(): JSONAPIAtomicOperationSerializer { return this.serializerFor( JSONAPISerializers.ResourceAtomicOperation ) as JSONAPIAtomicOperationSerializer; } protected _generateNewId( type: string, keyName: string, keyValue: string ): string { let id = this.schema.generateId(type); if (this.keyMap) { this.keyMap.pushRecord({ type, id, keys: { [keyName]: keyValue } }); } else { throw new Assertion( `A keyMap is required to generate ids for resource type '${type}'` ); } return id; } }
the_stack
import { Injectable } from '@angular/core'; import { IgxTree, IgxTreeNode, IgxTreeSelectionType, ITreeNodeSelectionEvent } from './common'; /** A collection containing the nodes affected in the selection as well as their direct parents */ interface CascadeSelectionNodeCollection { nodes: Set<IgxTreeNode<any>>; parents: Set<IgxTreeNode<any>>; }; /** @hidden @internal */ @Injectable() export class IgxTreeSelectionService { private tree: IgxTree; private nodeSelection: Set<IgxTreeNode<any>> = new Set<IgxTreeNode<any>>(); private indeterminateNodes: Set<IgxTreeNode<any>> = new Set<IgxTreeNode<any>>(); private nodesToBeSelected: Set<IgxTreeNode<any>>; private nodesToBeIndeterminate: Set<IgxTreeNode<any>>; public register(tree: IgxTree) { this.tree = tree; } /** Select range from last selected node to the current specified node. */ public selectMultipleNodes(node: IgxTreeNode<any>, event?: Event): void { if (!this.nodeSelection.size) { this.selectNode(node); return; } const lastSelectedNodeIndex = this.tree.nodes.toArray().indexOf(this.getSelectedNodes()[this.nodeSelection.size - 1]); const currentNodeIndex = this.tree.nodes.toArray().indexOf(node); const nodes = this.tree.nodes.toArray().slice(Math.min(currentNodeIndex, lastSelectedNodeIndex), Math.max(currentNodeIndex, lastSelectedNodeIndex) + 1); const added = nodes.filter(_node => !this.isNodeSelected(_node)); const newSelection = this.getSelectedNodes().concat(added); this.emitNodeSelectionEvent(newSelection, added, [], event); } /** Select the specified node and emit event. */ public selectNode(node: IgxTreeNode<any>, event?: Event): void { if (this.tree.selection === IgxTreeSelectionType.None) { return; } this.emitNodeSelectionEvent([...this.getSelectedNodes(), node], [node], [], event); } /** Deselect the specified node and emit event. */ public deselectNode(node: IgxTreeNode<any>, event?: Event): void { const newSelection = this.getSelectedNodes().filter(r => r !== node); this.emitNodeSelectionEvent(newSelection, [], [node], event); } /** Clears node selection */ public clearNodesSelection(): void { this.nodeSelection.clear(); this.indeterminateNodes.clear(); } public isNodeSelected(node: IgxTreeNode<any>): boolean { return this.nodeSelection.has(node); } public isNodeIndeterminate(node: IgxTreeNode<any>): boolean { return this.indeterminateNodes.has(node); } /** Select specified nodes. No event is emitted. */ public selectNodesWithNoEvent(nodes: IgxTreeNode<any>[], clearPrevSelection = false, shouldEmit = true): void { if (this.tree && this.tree.selection === IgxTreeSelectionType.Cascading) { this.cascadeSelectNodesWithNoEvent(nodes, clearPrevSelection); return; } const oldSelection = this.getSelectedNodes(); if (clearPrevSelection) { this.nodeSelection.clear(); } nodes.forEach(node => this.nodeSelection.add(node)); if (shouldEmit) { this.emitSelectedChangeEvent(oldSelection); } } /** Deselect specified nodes. No event is emitted. */ public deselectNodesWithNoEvent(nodes?: IgxTreeNode<any>[], shouldEmit = true): void { const oldSelection = this.getSelectedNodes(); if (!nodes) { this.nodeSelection.clear(); } else if (this.tree && this.tree.selection === IgxTreeSelectionType.Cascading) { this.cascadeDeselectNodesWithNoEvent(nodes); } else { nodes.forEach(node => this.nodeSelection.delete(node)); } if (shouldEmit) { this.emitSelectedChangeEvent(oldSelection); } } /** Called on `node.ngOnDestroy` to ensure state is correct after node is removed */ public ensureStateOnNodeDelete(node: IgxTreeNode<any>): void { if (this.tree?.selection !== IgxTreeSelectionType.Cascading) { return; } requestAnimationFrame(() => { if (this.isNodeSelected(node)) { // node is destroyed, do not emit event this.deselectNodesWithNoEvent([node], false); } else { if (!node.parentNode) { return; } const assitantLeafNode = node.parentNode?.allChildren.find(e => !e._children?.length); if (!assitantLeafNode) { return; } this.retriggerNodeState(assitantLeafNode); } }); } /** Retriggers a node's selection state */ private retriggerNodeState(node: IgxTreeNode<any>): void { if (node.selected) { this.nodeSelection.delete(node); this.selectNodesWithNoEvent([node], false, false); } else { this.nodeSelection.add(node); this.deselectNodesWithNoEvent([node], false); } } /** Returns array of the selected nodes. */ private getSelectedNodes(): IgxTreeNode<any>[] { return this.nodeSelection.size ? Array.from(this.nodeSelection) : []; } /** Returns array of the nodes in indeterminate state. */ private getIndeterminateNodes(): IgxTreeNode<any>[] { return this.indeterminateNodes.size ? Array.from(this.indeterminateNodes) : []; } private emitNodeSelectionEvent( newSelection: IgxTreeNode<any>[], added: IgxTreeNode<any>[], removed: IgxTreeNode<any>[], event: Event ): boolean { if (this.tree.selection === IgxTreeSelectionType.Cascading) { this.emitCascadeNodeSelectionEvent(newSelection, added, removed, event); return; } const currSelection = this.getSelectedNodes(); if (this.areEqualCollections(currSelection, newSelection)) { return; } const args: ITreeNodeSelectionEvent = { oldSelection: currSelection, newSelection, added, removed, event, cancel: false, owner: this.tree }; this.tree.nodeSelection.emit(args); if (args.cancel) { return; } this.selectNodesWithNoEvent(args.newSelection, true); } private areEqualCollections(first: IgxTreeNode<any>[], second: IgxTreeNode<any>[]): boolean { return first.length === second.length && new Set(first.concat(second)).size === first.length; } private cascadeSelectNodesWithNoEvent(nodes?: IgxTreeNode<any>[], clearPrevSelection = false): void { const oldSelection = this.getSelectedNodes(); if (clearPrevSelection) { this.indeterminateNodes.clear(); this.nodeSelection.clear(); this.calculateNodesNewSelectionState({ added: nodes, removed: [] }); } else { const newSelection = [...oldSelection, ...nodes]; const args: Partial<ITreeNodeSelectionEvent> = { oldSelection, newSelection }; // retrieve only the rows without their parents/children which has to be added to the selection this.populateAddRemoveArgs(args); this.calculateNodesNewSelectionState(args); } this.nodeSelection = new Set(this.nodesToBeSelected); this.indeterminateNodes = new Set(this.nodesToBeIndeterminate); this.emitSelectedChangeEvent(oldSelection); } private cascadeDeselectNodesWithNoEvent(nodes: IgxTreeNode<any>[]): void { const args = { added: [], removed: nodes }; this.calculateNodesNewSelectionState(args); this.nodeSelection = new Set<IgxTreeNode<any>>(this.nodesToBeSelected); this.indeterminateNodes = new Set<IgxTreeNode<any>>(this.nodesToBeIndeterminate); } /** * populates the nodesToBeSelected and nodesToBeIndeterminate sets * with the nodes which will be eventually in selected/indeterminate state */ private calculateNodesNewSelectionState(args: Partial<ITreeNodeSelectionEvent>): void { this.nodesToBeSelected = new Set<IgxTreeNode<any>>(args.oldSelection ? args.oldSelection : this.getSelectedNodes()); this.nodesToBeIndeterminate = new Set<IgxTreeNode<any>>(this.getIndeterminateNodes()); this.cascadeSelectionState(args.removed, false); this.cascadeSelectionState(args.added, true); } /** Ensures proper selection state for all predescessors and descendants during a selection event */ private cascadeSelectionState(nodes: IgxTreeNode<any>[], selected: boolean): void { if (!nodes || nodes.length === 0) { return; } if (nodes && nodes.length > 0) { const nodeCollection: CascadeSelectionNodeCollection = this.getCascadingNodeCollection(nodes); nodeCollection.nodes.forEach(node => { if (selected) { this.nodesToBeSelected.add(node); } else { this.nodesToBeSelected.delete(node); } this.nodesToBeIndeterminate.delete(node); }); Array.from(nodeCollection.parents).forEach((parent) => { this.handleParentSelectionState(parent); }); } } private emitCascadeNodeSelectionEvent(newSelection, added, removed, event?): boolean { const currSelection = this.getSelectedNodes(); if (this.areEqualCollections(currSelection, newSelection)) { return; } const args: ITreeNodeSelectionEvent = { oldSelection: currSelection, newSelection, added, removed, event, cancel: false, owner: this.tree }; this.calculateNodesNewSelectionState(args); args.newSelection = Array.from(this.nodesToBeSelected); // retrieve nodes/parents/children which has been added/removed from the selection this.populateAddRemoveArgs(args); this.tree.nodeSelection.emit(args); if (args.cancel) { return; } // if args.newSelection hasn't been modified if (this.areEqualCollections(Array.from(this.nodesToBeSelected), args.newSelection)) { this.nodeSelection = new Set<IgxTreeNode<any>>(this.nodesToBeSelected); this.indeterminateNodes = new Set(this.nodesToBeIndeterminate); this.emitSelectedChangeEvent(currSelection); } else { // select the nodes within the modified args.newSelection with no event this.cascadeSelectNodesWithNoEvent(args.newSelection, true); } } /** * recursively handle the selection state of the direct and indirect parents */ private handleParentSelectionState(node: IgxTreeNode<any>) { if (!node) { return; } this.handleNodeSelectionState(node); if (node.parentNode) { this.handleParentSelectionState(node.parentNode); } } /** * Handle the selection state of a given node based the selection states of its direct children */ private handleNodeSelectionState(node: IgxTreeNode<any>) { const nodesArray = (node && node._children) ? node._children.toArray() : []; if (nodesArray.length) { if (nodesArray.every(n => this.nodesToBeSelected.has(n))) { this.nodesToBeSelected.add(node); this.nodesToBeIndeterminate.delete(node); } else if (nodesArray.some(n => this.nodesToBeSelected.has(n) || this.nodesToBeIndeterminate.has(n))) { this.nodesToBeIndeterminate.add(node); this.nodesToBeSelected.delete(node); } else { this.nodesToBeIndeterminate.delete(node); this.nodesToBeSelected.delete(node); } } else { // if the children of the node has been deleted and the node was selected do not change its state if (this.isNodeSelected(node)) { this.nodesToBeSelected.add(node); } else { this.nodesToBeSelected.delete(node); } this.nodesToBeIndeterminate.delete(node); } } /** * Get a collection of all nodes affected by the change event * * @param nodesToBeProcessed set of the nodes to be selected/deselected * @returns a collection of all affected nodes and all their parents */ private getCascadingNodeCollection(nodes: IgxTreeNode<any>[]): CascadeSelectionNodeCollection { const collection: CascadeSelectionNodeCollection = { parents: new Set<IgxTreeNode<any>>(), nodes: new Set<IgxTreeNode<any>>(nodes) }; Array.from(collection.nodes).forEach((node) => { const nodeAndAllChildren = node.allChildren?.toArray() || []; nodeAndAllChildren.forEach(n => { collection.nodes.add(n); }); if (node && node.parentNode) { collection.parents.add(node.parentNode); } }); return collection; } /** * retrieve the nodes which should be added/removed to/from the old selection */ private populateAddRemoveArgs(args: Partial<ITreeNodeSelectionEvent>): void { args.removed = args.oldSelection.filter(x => args.newSelection.indexOf(x) < 0); args.added = args.newSelection.filter(x => args.oldSelection.indexOf(x) < 0); } /** Emits the `selectedChange` event for each node affected by the selection */ private emitSelectedChangeEvent(oldSelection: IgxTreeNode<any>[]): void { this.getSelectedNodes().forEach(n => { if (oldSelection.indexOf(n) < 0) { n.selectedChange.emit(true); } }); oldSelection.forEach(n => { if (!this.nodeSelection.has(n)) { n.selectedChange.emit(false); } }); } }
the_stack
import React, { Fragment, useCallback, useEffect, useState } from "react"; import { BaseEditor, Editor as StaticEditor, Range, Transforms, Element as SlateElement, Descendant, } from "slate"; import { ReactEditor, useSlateStatic } from "slate-react"; import { Icon } from "./editor/core/navbar/Icon"; import { ParaStyleDropDown } from "./editor/core/navbar/ParaStyleDropdown"; import { MdOutlineDelete } from "react-icons/md"; import { BiImageAlt, BiLink } from "react-icons/bi"; import { DeleteNoteModal } from "./modals/DeleteNote"; import { useRouter } from "next/router"; import { GetNoteQuery, useAddNoteToFolderMutation, useDeleteNoteFromFolderMutation, useMeQuery, } from "../../generated/graphql"; import { findNoteFolder } from "../../utils/findNoteFolder"; import { Listbox, Transition } from "@headlessui/react"; import { findFolderId } from "../../utils/FindFolderId"; import { useApolloClient } from "@apollo/client"; import { insertImage } from "./editor/core/renderElement"; import { AddImageModal } from "./modals/AddImage"; import { timeSince, timeSinceShort } from "../../utils/timeSince"; interface NavbarProps { saving: boolean; id: number; note: GetNoteQuery["getNote"]; } type SlateEditor = BaseEditor & ReactEditor; function getActiveStyles(editor: SlateEditor) { return new Set(Object.keys(StaticEditor.marks(editor) ?? {})); } export function isLinkNodeAtSelection(editor: SlateEditor, selection: any) { if (selection == null) { return false; } return ( StaticEditor.above(editor, { at: selection, match: (n: any) => n.type === "link", }) != null ); } export function toggleStyle(editor: SlateEditor, style: any) { const activeStyles = getActiveStyles(editor); if (activeStyles.has(style)) { StaticEditor.removeMark(editor, style); } else { StaticEditor.addMark(editor, style, true); } } const CHARACTER_STYLES = ["bold", "italic", "underline", "code", "highlighted"]; function getTextBlockStyle(editor: SlateEditor) { const selection = editor.selection; if (selection == null) { return null; } // gives the forward-direction points in case the selection was // was backwards. const [start, end] = Range.edges(selection); //path[0] gives us the index of the top-level block. let startTopLevelBlockIndex = start.path[0]; const endTopLevelBlockIndex = end.path[0]; let blockType = null; while (startTopLevelBlockIndex <= endTopLevelBlockIndex) { const [node, _] = StaticEditor.node(editor, [startTopLevelBlockIndex]); if (blockType == null) { blockType = (node as any).type; } else if (blockType !== (node as any).type) { return "multiple"; } startTopLevelBlockIndex++; } return blockType; } function toggleBlockType(editor: SlateEditor, blockType: any) { const currentBlockType = getTextBlockStyle(editor); const changeTo = currentBlockType === blockType ? "paragraph" : blockType; Transforms.setNodes( editor, { type: changeTo }, { at: editor.selection as any, match: (n) => StaticEditor.isBlock(editor, n), } ); } export const Navbar: React.FC<NavbarProps> = ({ saving, id, note }) => { const editor = useSlateStatic(); const onBlockTypeChange = useCallback( (targetType) => { if (targetType === "multiple") { return; } toggleBlockType(editor, targetType); }, [editor] ); const blockType = getTextBlockStyle(editor); const [open, setOpen] = useState(false); const [imageOpen, setImageOpen] = useState(false); const router = useRouter(); const { data, loading } = useMeQuery(); const [selected, setSelected] = useState( findNoteFolder(id, data && !loading && data.me?.folders) ); const [deleteNoteFromFolderMutation] = useDeleteNoteFromFolderMutation(); const [addNoteToFolderMutation] = useAddNoteToFolderMutation(); const client = useApolloClient(); useEffect(() => { const currentFolder = findNoteFolder(id, data?.me?.folders); const currentFolderId = findFolderId( currentFolder, (data as any).me?.folders as any ); console.log(currentFolderId); if (currentFolder == selected) { return; } (async () => { await deleteNoteFromFolderMutation({ variables: { folderId: currentFolderId, noteId: id, }, }); })(); if (selected == "No Folder") { (async () => { await client.resetStore(); })(); return; } const newFolderId = findFolderId( selected, (data as any).me?.folders as any ); (async () => { await addNoteToFolderMutation({ variables: { folderId: newFolderId, noteId: id, }, }); await client.resetStore(); })(); }, [selected]); return ( <div className="z-10 flex items-center sticky top-0 px-2 py-1.5 bg-white dark:bg-black-navbar border-b border-gray-200 dark:border-transparent"> <ParaStyleDropDown initialValue={blockType} onChange={onBlockTypeChange} /> {CHARACTER_STYLES.map((style, i) => ( <Icon key={i} style={style} isActive={ style == "link" ? isLinkNodeAtSelection(editor, editor.selection) : getActiveStyles(editor).has(style) } editor={editor} /> ))} <BiImageAlt className={ "p-1 w-7 h-7 text-gray-800 rounded-sm cursor-pointer border border-white dark:border-black-navbar dark:hover:border-gray-700 mx-1 hover:bg-gray-100 hover:border-gray-300 dark:text-gray-200 dark:hover:bg-black-pantone" } onClick={() => setImageOpen(true)} /> {saving ? ( <p className="ml-2 text-sm font-medium text-gray-600 dark:text-gray-400"> Saving... </p> ) : ( <p className="ml-2 text-sm font-medium text-gray-600 dark:text-gray-400"> Saved{" "} <span className="font-normal"> {timeSinceShort(note.updatedAt)} ago </span> </p> )} <div className="flex items-center ml-auto mr-2"> {data && !loading && ( <> <div className="w-32"> <Listbox value={selected} onChange={setSelected}> <div className="relative mt-1"> <Listbox.Button className="text-left relative w-full py-1.5 pl-3 bg-gray-50 border border-gray-300 rounded-sm cursor-pointer sm:text-sm hover:bg-gray-100 dark:bg-black-700 dark:border-gray-700 transition duration-75 dark:hover:bg-black-600"> <span className="block truncate menlo dark:text-gray-200"> {selected} </span> </Listbox.Button> <Transition as={Fragment} leave="transition ease-in duration-100" leaveFrom="opacity-100" leaveTo="opacity-0" > <Listbox.Options className="absolute w-full py-1 mt-1 overflow-auto text-base bg-white rounded-md shadow-lg max-h-60 ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm dark:bg-black-700"> {data.me?.folders.map((folder) => ( <Listbox.Option className="relative py-2 pl-4 pr-4 text-gray-900 cursor-pointer hover:bg-gray-100 dark:hover:bg-black-600 dark:text-gray-200" value={folder.name} key={folder.id} > <span className="block truncate menlo"> {folder.name} </span> </Listbox.Option> ))} <Listbox.Option className="relative py-2 pl-4 pr-4 text-gray-900 cursor-pointer hover:bg-gray-100 dark:hover:bg-black-600 dark:text-gray-200" value={"No Folder"} > <span className="block truncate menlo"> No Folder </span> </Listbox.Option> </Listbox.Options> </Transition> </div> </Listbox> </div> <MdOutlineDelete onClick={() => setOpen(true)} className="p-1 ml-2 rounded-sm cursor-pointer w-7 h-7 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-gray-700" /> </> )} </div> <DeleteNoteModal open={open} setOpen={setOpen} id={ typeof router.query.id == "string" ? parseInt(router.query.id) : -1 } /> <AddImageModal editor={editor} open={imageOpen} setOpen={setImageOpen} /> </div> ); };
the_stack
import * as React from 'react'; import { observer, inject } from 'mobx-react'; import { Link, RouteComponentProps } from 'react-router-dom'; import Helmet from 'react-helmet'; import cs from 'classnames'; import _ from 'lodash'; import tocbot from 'tocbot'; import hljs from 'highlight.js'; import baguetteBox from 'baguettebox.js'; import { TwitterIcon, TwitterShareButton } from 'react-share'; import 'baguettebox.js/dist/baguetteBox.min.css'; import 'tocbot/dist/tocbot.css'; import './BlogDetail.scss'; import Like from '@components/Post/Like/Like'; import Skeletons from '@components/Skeletons/BlogDetailSkeleton/Skeletons'; import { initLivere, formatJSONDate, noop } from '@tools/tools'; import { webpSuffix, byNcSa, livere } from '@constants/constants'; import routePath from '@constants/routePath'; import { IArticleProps } from '../../types/article'; @inject('articleStore') @observer class BlogDetail extends React.Component< IArticleProps & RouteComponentProps<any>, {} > { constructor(props: IArticleProps & RouteComponentProps<any>) { super(props); this.state = {}; } public async componentDidMount() { const { articleStore, match } = this.props; const curId = match.params.id; await articleStore!.getPostById(curId); this.tocbotInit(); this.fixToc(); this.hljsInit(); this.addLineNumbers(); this.deleteEmptyTag(); this.showImageAlt(); this.wrapImg(); this.initBaguetteBox(); await articleStore!.getIp(); articleStore!.getLikes(curId, articleStore!.curIp); articleStore!.increasePV(curId); initLivere(); } public wrapImg = () => { const imgDom = document.querySelectorAll('.article_content img'); const imgWrapper = document.querySelectorAll('.img-group'); for (let i = 0, len = imgDom.length; i < len; i += 1) { imgWrapper[i].innerHTML = `<a href='${ (imgDom[i] as HTMLImageElement).src }' data-caption='${(imgDom[i] as HTMLImageElement).alt}'>${ imgWrapper[i].innerHTML }</a>`; } }; public initBaguetteBox() { baguetteBox.run('.article_content'); } public tocbotInit() { const headers = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); for (let i = 0, len = headers.length; i < len; i += 1) { headers[i].id = `header-${i}`; } tocbot.init({ tocSelector: '.menu', contentSelector: '.article_content', headingSelector: 'h2, h3, h4, h5, h6', }); } public fixToc() { const menu = document.querySelector('.menu'); window.addEventListener( 'scroll', _.throttle(() => { const tops = document.documentElement.scrollTop || document.body.scrollTop; if (tops < 440) { (menu as HTMLElement).style.top = `${512 - tops}px`; } else { (menu as HTMLElement).style.top = '4rem'; } }, 10), ); } public showImageAlt() { const imgList: any[] = []; const imgTag = document.querySelectorAll('img'); for (let i = 0, l = imgTag.length; i < l; i += 1) { imgList.push(imgTag[i].alt); (imgTag[i].parentNode as HTMLDivElement).classList.add('img-group'); (imgTag[i].parentNode as HTMLDivElement).insertAdjacentHTML( 'beforeend', `<span class='img-info'>${imgList[i]}</span>`, ); } } public addLineNumbers() { const hljsDOM = document.querySelectorAll('.hljs'); for (let i = 0, l = hljsDOM.length; i < l; i += 1) { hljsDOM[ i ].innerHTML = `<ol class="rounded-list"><li class="hljs-ln-line">${hljsDOM[ i ].innerHTML.replace( /\n/g, '\n</li><li class="hljs-ln-line">', )}\n</li></ol>`; } } public hljsInit() { const codeBlock = document.querySelectorAll('pre code'); for (let i = 0, l = codeBlock.length; i < l; i += 1) { hljs.highlightBlock(codeBlock[i]); } } public deleteEmptyTag() { const ul = document.getElementsByClassName('rounded-list') as any; for (let i = 0, l = ul.length; i < l; i += 1) { if (ul[i].lastChild.innerHTML.trim() === '') { ul[i].removeChild(ul[i].lastChild); } } } public componentWillUnmount() { window.removeEventListener('scroll', noop); } public render() { const { articleStore } = this.props; const isWebp = window.localStorage.getItem('isWebp') === 'true'; return ( <main className='article_detail_wrapper'> <Helmet> <title>{articleStore!.detail.curArticle.title}</title> <meta name='twitter:card' content='summary_large_image' /> <meta name='twitter:site' content='@YanceyOfficial' /> <meta name='twitter:creator' content='@YanceyOfficial' /> <meta name='twitter:title' content={articleStore!.detail.curArticle.title} /> <meta name='twitter:description' content={articleStore!.detail.curArticle.summary} /> <meta name='twitter:image' content={`https:${articleStore!.detail.curArticle.header_cover}`} /> <meta name='twitter:image:alt' content={articleStore!.detail.curArticle.title} /> <meta name='twitter:url' content={location.href} /> </Helmet> <section className='article_meta_wrapper' style={{ backgroundImage: `url(${ isWebp ? `${articleStore!.detail.curArticle.header_cover}${webpSuffix}` : articleStore!.detail.curArticle.header_cover })`, }} /> {articleStore!.isDetailLoading ? ( <Skeletons /> ) : ( <> {/* content wrapper */} <div className='content_wrapper'> {/* meta */} <h1 className='title'>{articleStore!.detail.curArticle.title}</h1> <span className='publish_date' data-modify={`最后修改时间: ${formatJSONDate( articleStore!.detail.curArticle.last_modified_date, )}`} > 发布时间:{' '} {formatJSONDate(articleStore!.detail.curArticle.publish_date)} </span> <span className='page_view'> {articleStore!.detail.curArticle.pv_count} 阅读 </span> <ul className='tags_list'> {articleStore!.detail.curArticle.tags.map( (item: string, index: number) => ( <li key={index}> <Link to={`/t/${item}`}>{item}</Link> </li> ), )} </ul> {/* summary */} <blockquote className='summary'> {articleStore!.detail.curArticle.summary} </blockquote> {/* content */} <section className='article_content' dangerouslySetInnerHTML={{ __html: articleStore!.detail.curArticle.content, }} /> {/* menu */} <aside className='menu' /> </div> <div className='attachment_wrapper'> {/* copyright share like */} <section className='copyright_share_wrapper'> <a href={byNcSa} target='_blank' rel='noopener noreferrer'> Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) </a> {/* share To Twitter Btn */} <div className='share_btn'> <TwitterShareButton title={articleStore!.detail.curArticle.title} url={window.location.href} via='YanceyOfficial' className='Demo__some-network__share-button' > <TwitterIcon size={32} round /> </TwitterShareButton> <Like /> </div> </section> {/* Previous and Next Articles Link */} <section className='prev_next_wrapper'> {JSON.stringify(articleStore!.detail.previousArticle) === '{}' ? null : ( <Link className='prev_next' to={`${routePath.blogDetail}${ articleStore!.detail.previousArticle.id }`} > <div className={cs('prev_next_container', 'prev')} style={{ backgroundImage: `url(${ isWebp ? `${ articleStore!.detail.previousArticle .header_cover }${webpSuffix}` : articleStore!.detail.previousArticle.header_cover })`, }} > <div className={cs('prev_next_meta', 'prev_meta')}> <p className='directive'>PREVIOUS POST</p> <p className='title'> {articleStore!.detail.previousArticle.title} </p> </div> <div className='overlay' /> </div> </Link> )} {JSON.stringify(articleStore!.detail.nextArticle) === '{}' ? null : ( <Link className='prev_next' to={`${routePath.blogDetail}${ articleStore!.detail.nextArticle.id }`} > <div className={cs('prev_next_container', 'next')} style={{ backgroundImage: `url(${ isWebp ? `${ articleStore!.detail.nextArticle.header_cover }${webpSuffix}` : articleStore!.detail.nextArticle.header_cover })`, }} > <div className={cs('prev_next_meta', 'next_meta')}> <p className='directive'>NEXT POST</p> <p className='title'> {articleStore!.detail.nextArticle.title} </p> </div> <div className='overlay' /> </div> </Link> )} </section> {/* Livere Comment */} <section className='comment_wrapper'> <p className='comment_title'>Comments</p> <div id='lv-container' data-id='city' data-uid={livere} /> </section> </div> </> )} </main> ); } } export default BlogDetail;
the_stack
* This module executes inside of electron's main process. You can start * electron renderer process from here and communicate with the other processes * through IPC. * * When running `yarn build` or `yarn build-main`, this file is compiled to * `./desktop/main.prod.js` using webpack. This gives us some performance wins. */ import 'core-js/stable'; import path from 'path'; import fs from 'fs'; import { app, BrowserWindow, BrowserView, ipcMain, Tray, Menu, dialog, nativeTheme, shell } from 'electron'; import 'regenerator-runtime/runtime'; import fetch from 'electron-fetch'; import { ipcConsts } from '../app/vars'; import { PublicService } from '../shared/types'; import { stringifySocketAddress, toPublicService } from '../shared/utils'; import MenuBuilder from './menu'; import AutoStartManager from './autoStartManager'; import StoreService from './storeService'; import WalletManager from './WalletManager'; import NodeManager from './NodeManager'; import NotificationManager from './notificationManager'; import SmesherManager from './SmesherManager'; import './wasm_exec'; import { isDev, writeFileAsync } from './utils'; import prompt from './prompt'; require('dotenv').config(); const DISCOVERY_URL = 'https://discover.spacemesh.io/networks.json'; (async function () { const filePath = path.resolve(app.getAppPath(), isDev() ? './' : 'desktop/', 'ed25519.wasm'); const bytes = fs.readFileSync(filePath); // const bytes = await response.arrayBuffer(); // @ts-ignore const go = new Go(); // eslint-disable-line no-undef const { instance } = await WebAssembly.instantiate(bytes, go.importObject); await go.run(instance); })(); const unhandled = require('electron-unhandled'); unhandled(); StoreService.init(); if (process.env.NODE_ENV === 'production') { const sourceMapSupport = require('source-map-support'); sourceMapSupport.install(); } const DEBUG = isDev() || process.env.DEBUG_PROD === 'true'; DEBUG && require('electron-debug')(); let mainWindow: BrowserWindow; let browserView: BrowserView; let tray: Tray; let nodeManager: NodeManager; let smesherManager: SmesherManager; let notificationManager: NotificationManager; let isDarkMode: boolean = nativeTheme.shouldUseDarkColors; let closingApp = false; let shouldShowWindowOnLoad = true; const isSmeshing = async () => smesherManager && (await smesherManager.isSmeshing()); enum CloseAppPromptResult { CANCELED = 1, // To avoid conversion to `false` KEEP_SMESHING = 2, CLOSE = 3, } const promptClosingApp = async () => { const { response } = await dialog.showMessageBox(mainWindow, { title: 'Quit App', message: '\nQuitting stops smeshing and may cause loss of future due smeshing rewards.' + '\n\n\n• Click RUN IN BACKGROUND to close the App window and to keep smeshing in the background.' + '\n\n• Click QUIT to close the app and stop smeshing.\n', buttons: ['RUN IN BACKGROUND', 'QUIT', 'Cancel'], cancelId: 2, }); switch (response) { default: case 2: return CloseAppPromptResult.CANCELED; case 0: return CloseAppPromptResult.KEEP_SMESHING; case 1: return CloseAppPromptResult.CLOSE; } }; const handleClosingApp = async (event: Electron.Event) => { if (closingApp) return; event.preventDefault(); const promptResult = ((await isSmeshing()) && (await promptClosingApp())) || CloseAppPromptResult.CLOSE; if (promptResult === CloseAppPromptResult.KEEP_SMESHING) { setTimeout(() => { notificationManager.showNotification({ title: 'Spacemesh', body: 'Smesher is running in the background.', }); }, 1000); mainWindow.hide(); shouldShowWindowOnLoad = false; mainWindow.reload(); } else if (promptResult === CloseAppPromptResult.CLOSE) { mainWindow.webContents.send(ipcConsts.CLOSING_APP); await nodeManager.stopNode(); closingApp = true; app.quit(); } }; app.on('before-quit', handleClosingApp); const createTray = () => { tray = new Tray(path.join(__dirname, '..', 'resources', 'icons', '16x16.png')); tray.setToolTip('Spacemesh'); const eventHandler = () => { mainWindow.show(); mainWindow.focus(); }; const contextMenu = Menu.buildFromTemplate([ { label: 'Show App', click: () => eventHandler(), }, { label: 'Quit', click: () => app.quit(), }, ]); tray.on('double-click', () => eventHandler()); tray.setContextMenu(contextMenu); }; const createBrowserView = () => { browserView = new BrowserView({ webPreferences: { nodeIntegration: false, }, }); }; const addIpcEventListeners = () => { ipcMain.handle(ipcConsts.GET_OS_THEME_COLOR, () => nativeTheme.shouldUseDarkColors); ipcMain.on(ipcConsts.OPEN_BROWSER_VIEW, () => { createBrowserView(); mainWindow.setBrowserView(browserView); browserView.webContents.on('new-window', (event, url) => { event.preventDefault(); shell.openExternal(url); }); const contentBounds = mainWindow.getContentBounds(); browserView.setBounds({ x: 0, y: 90, width: contentBounds.width - 35, height: 600 }); browserView.setAutoResize({ width: true, height: true, horizontal: true, vertical: true }); const dashUrl = StoreService.get('netSettings.dashUrl'); browserView.webContents.loadURL(`${dashUrl}?hide-right-line${isDarkMode ? '&darkMode' : ''}`); }); ipcMain.on(ipcConsts.DESTROY_BROWSER_VIEW, () => { browserView.setBounds({ x: 0, y: 0, width: 0, height: 0 }); // browserView.destroy(); }); ipcMain.on(ipcConsts.SEND_THEME_COLOR, (_event, request) => { isDarkMode = request.isDarkMode; }); ipcMain.on(ipcConsts.PRINT, (_event, request: { content: string }) => { const printerWindow = new BrowserWindow({ width: 800, height: 800, show: true, webPreferences: { nodeIntegration: true, devTools: false } }); const html = `<body>${request.content}</body><script>window.onafterprint = () => setTimeout(window.close, 3000); window.print();</script>`; printerWindow.loadURL(`data:text/html;charset=utf-8,${encodeURI(html)}`); }); ipcMain.on(ipcConsts.RELOAD_APP, () => { mainWindow.reload(); }); }; const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { app.quit(); } else { app.on('second-instance', () => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } }); } const isDevNet = (proc = process): proc is NodeJS.Process & { env: { NODE_ENV: 'development'; DEV_NET_URL: string } } => proc.env.NODE_ENV === 'development' && !!proc.env.DEV_NET_URL; const promptNetworkSelection = async (networks) => { const options = Object.fromEntries(networks.map((conf, idx) => [idx, `${conf.netName} (${conf.netID})`])); const res = await prompt({ title: 'Spacemesh App: Choose the network', label: 'Please, choose the network:', type: 'select', selectOptions: options, alwaysOnTop: true, }); return res ? parseInt(res, 10) : 0; }; const selectNetwork = async (currentNetId, networks) => { if (currentNetId) { const currentNetConfig = networks.find((conf) => conf.netID === currentNetId); if (currentNetConfig) return currentNetConfig; } const netIndex = networks.length > 1 ? await promptNetworkSelection(networks) : 0; return networks[netIndex]; }; const getInitialConfig = async (savedNetId) => { if (isDevNet(process)) { return { netName: 'Dev Net', conf: process.env.DEV_NET_URL, explorer: '', dash: '', grpcAPI: process.env.DEV_NET_REMOTE_API?.split(',')[0] || '', }; } const res = await fetch(DISCOVERY_URL); const networks = await res.json(); return selectNetwork(savedNetId, networks); }; const getNetConfig = async (configUrl) => { const resp = await fetch(configUrl); return resp.json(); }; const getConfigs = async () => { const savedNetId = StoreService.get('netSettings.netId'); const initialConfig = await getInitialConfig(savedNetId); const netConfig = await getNetConfig(initialConfig.conf); const netId = parseInt(initialConfig.netID) || netConfig.p2p['network-id']; const isCleanStart = savedNetId !== netId; return { initialConfig, netConfig, netId, isCleanStart, }; }; const createWindow = async () => { mainWindow = new BrowserWindow({ show: false, width: 1280, height: 700, minWidth: 1100, minHeight: 680, center: true, webPreferences: { nodeIntegration: true, }, }); mainWindow.on('close', handleClosingApp); createTray(); // @TODO: Use 'ready-to-show' event // https://github.com/electron/electron/blob/master/docs/api/browser-window.md#using-ready-to-show-event mainWindow.webContents.on('did-finish-load', () => { if (!mainWindow) { throw new Error('"mainWindow" is not defined'); } if (shouldShowWindowOnLoad) { mainWindow.show(); mainWindow.focus(); } }); addIpcEventListeners(); const menuBuilder = new MenuBuilder(mainWindow); menuBuilder.buildMenu(); // Open urls in the user's browser mainWindow.webContents.on('new-window', (event, url) => { event.preventDefault(); shell.openExternal(url); }); const configFilePath = path.resolve(app.getPath('userData'), 'node-config.json'); const { initialConfig, netConfig, isCleanStart, netId } = await getConfigs(); if (isCleanStart) { StoreService.clear(); StoreService.set('netSettings.netId', netId); StoreService.set('netSettings.netName', initialConfig.netName); StoreService.set('netSettings.explorerUrl', initialConfig.explorer); StoreService.set('netSettings.dashUrl', initialConfig.dash); StoreService.set('netSettings.minCommitmentSize', parseInt(netConfig.post['post-space'])); StoreService.set('netSettings.layerDurationSec', netConfig.main['layer-duration-sec']); StoreService.set('netSettings.genesisTime', netConfig.main['genesis-time']); StoreService.set('nodeConfigFilePath', configFilePath); netConfig.smeshing = {}; // Ensure that the net config does not provide preinstalled defaults for smeshing await writeFileAsync(configFilePath, JSON.stringify(netConfig)); } const subscribeListingGrpcApis = (initialConfig) => { const walletServices: PublicService[] = [ toPublicService(initialConfig.netName, initialConfig.grpcAPI), ...(isDevNet(process) && process.env.DEV_NET_REMOTE_API ? process.env.DEV_NET_REMOTE_API?.split(',') .slice(1) .map((url) => toPublicService(initialConfig.netName, url)) : []), ]; StoreService.set('netSettings.grpcAPI', walletServices.map(stringifySocketAddress)); ipcMain.handle(ipcConsts.LIST_PUBLIC_SERVICES, () => walletServices); }; smesherManager = new SmesherManager(mainWindow, configFilePath); nodeManager = new NodeManager(mainWindow, isCleanStart, smesherManager); // eslint-disable-next-line no-new new WalletManager(mainWindow, nodeManager); notificationManager = new NotificationManager(mainWindow); new AutoStartManager(); // eslint-disable-line no-new subscribeListingGrpcApis(initialConfig); // Load page after initialization complete mainWindow.loadURL(`file://${__dirname}/index.html`); }; const installDevTools = async () => { if (!DEBUG) return; const { default: installExtension, REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer'); await installExtension([REDUX_DEVTOOLS, REACT_DEVELOPER_TOOLS], { loadExtensionOptions: { allowFileAccess: true }, forceDownload: false }).then( (names) => console.log('DevTools Installed:', names), // eslint-disable-line no-console (err) => console.log('DevTools Installation Error:', err) // eslint-disable-line no-console ); }; app .whenReady() .then(() => installDevTools()) .then(createWindow) .catch(console.log); // eslint-disable-line no-console app.on('activate', () => { if (mainWindow === null) { createWindow(); } else if (mainWindow) { mainWindow.show(); mainWindow.focus(); } });
the_stack
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Since the template for the form changes within the user interface * the form component needs to be re-compiled each time the template changes. * * This file exports a the `createFormComponentFactory` function which * creates a new form component factory based on the provided template. * * Within that function is the `FormComponent`. This component takes in the * provided template and then initialises the form. * * Form initialisation logic and ordering is all defined within the `initialiseForm` * function within the `FormComponent`. */ import { Component, ViewChildren, QueryList, Compiler, ComponentFactory, NgModule, ModuleWithComponentFactories, ChangeDetectorRef, AfterViewInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { PromiseDelegate } from '@phosphor/coreutils'; import { Kernel } from '@jupyterlab/services'; import { MaterialModule } from '../../vendors/material.module'; import { sessionStartCode } from './session-start-code'; import { KernelService } from '../services/kernel.service'; import { VariableService } from '../services/variable.service'; import { SectionsModule } from '../sections-module/sections.module'; import { StartComponent } from '../sections-module/start.component'; import { LiveComponent } from '../sections-module/live.component'; import { ButtonComponent } from '../sections-module/button.component'; import { OutputComponent } from '../sections-module/output.component'; import { SectionFileChangeComponent } from '../sections-module/section-file-change.component'; import { VariablesModule } from '../variables-module/variables.module'; import { ToggleComponent } from '../variables-module/toggle.component'; import { TickComponent } from '../variables-module/tick.component'; import { NumberComponent } from '../variables-module/number.component'; import { SliderComponent } from '../variables-module/slider.component'; import { VariableTableComponent } from '../variables-module/variable-table.component'; import { StringComponent } from '../variables-module/string.component'; import { DropdownComponent } from '../variables-module/dropdown.component'; import { VariableFileComponent } from '../variables-module/variable-file.component'; import { VariableParameterComponent } from '../variables-module/variable-parameter.component'; import { CodeModule } from '../code-module/code.module'; import { CodeComponent } from '../code-module/code.component'; import { VariableComponent } from '../types/variable-component'; import { SectionComponent } from '../types/section-component'; export interface IFormComponent { formViewInitialised: PromiseDelegate<void>; formReady: PromiseDelegate<void>; restartFormKernel(): Promise<void>; } /** * Create a form component factory given an Angular template in the form of metadata. * * @param compiler the Angular compiler * @param metadata the template containing metadata * * @returns a factory which creates form components */ export function createFormComponentFactory( compiler: Compiler, metadata: Component): ComponentFactory<IFormComponent> { /** * The form component that is built each time the template changes */ @Component(metadata) class FormComponent implements IFormComponent, AfterViewInit { formViewInitialised = new PromiseDelegate<void>(); formReady = new PromiseDelegate<void>(); variableComponents: VariableComponent[] = []; sectionComponents: SectionComponent[] = []; // Sections @ViewChildren(StartComponent) startComponents: QueryList<StartComponent>; @ViewChildren(LiveComponent) liveComponents: QueryList<LiveComponent>; @ViewChildren(ButtonComponent) buttonComponents: QueryList<ButtonComponent>; @ViewChildren(OutputComponent) outputComponents: QueryList<OutputComponent>; @ViewChildren(SectionFileChangeComponent) sectionFileChangeComponents: QueryList<SectionFileChangeComponent>; // Variables @ViewChildren(ToggleComponent) toggleComponents: QueryList<ToggleComponent>; @ViewChildren(TickComponent) tickComponents: QueryList<TickComponent>; @ViewChildren(NumberComponent) numberComponents: QueryList<NumberComponent>; @ViewChildren(SliderComponent) sliderComponents: QueryList<SliderComponent>; @ViewChildren(VariableTableComponent) variableTableComponents: QueryList<VariableTableComponent>; @ViewChildren(StringComponent) stringComponents: QueryList<StringComponent>; @ViewChildren(DropdownComponent) dropdownComponents: QueryList<DropdownComponent>; @ViewChildren(VariableFileComponent) variableFileComponents: QueryList<VariableFileComponent>; // Code @ViewChildren(CodeComponent) codeComponents: QueryList<CodeComponent>; constructor( private myKernelService: KernelService, private myVariableService: VariableService, private myChangeDetectorRef: ChangeDetectorRef ) { } ngAfterViewInit() { this.formViewInitialised.resolve(null); this.variableComponents = this.variableComponents.concat(this.toggleComponents.toArray()); this.variableComponents = this.variableComponents.concat(this.tickComponents.toArray()); this.buttonComponents.toArray().forEach(buttonComponent => { if (buttonComponent.conditional) { this.variableComponents = this.variableComponents.concat([buttonComponent.conditionalComponent]); } }); this.variableComponents = this.variableComponents.concat(this.numberComponents.toArray()); this.variableComponents = this.variableComponents.concat(this.sliderComponents.toArray()); this.variableComponents = this.variableComponents.concat(this.variableTableComponents.toArray()); this.variableTableComponents.toArray().forEach(variableTableComponent => { if (variableTableComponent.inputTypes) { this.variableComponents = this.variableComponents.concat([variableTableComponent.variableInputTypes]); } if (variableTableComponent.dropdownItems) { this.variableComponents = this.variableComponents.concat([variableTableComponent.variableDropdownItems]); } }); this.variableComponents = this.variableComponents.concat(this.stringComponents.toArray()); this.variableComponents = this.variableComponents.concat(this.dropdownComponents.toArray()); // this.dropdownComponents.toArray().forEach(dropdownComponent => { // if (dropdownComponent.items) { // this.variableComponents = this.variableComponents.concat([dropdownComponent.variableParameterComponent]); // } // }); this.variableComponents = this.variableComponents.concat(this.variableFileComponents.toArray()); this.sectionComponents = this.sectionComponents.concat(this.startComponents.toArray()); this.sectionComponents = this.sectionComponents.concat(this.liveComponents.toArray()); this.sectionComponents = this.sectionComponents.concat(this.buttonComponents.toArray()); this.sectionComponents = this.sectionComponents.concat(this.outputComponents.toArray()); this.sectionComponents = this.sectionComponents.concat(this.sectionFileChangeComponents.toArray()); this.sectionFileChangeComponents.toArray().forEach(sectionFileChangeComponent => { this.variableComponents = this.variableComponents.concat([sectionFileChangeComponent.variableParameterComponent]); }); // Make parameter components be appended to the variable component list this.variableComponents.forEach(variableComponent => { variableComponent.variableParameterMap.forEach(map => { const parameterComponent = <VariableParameterComponent>map[0] if (parameterComponent) { console.log(parameterComponent) this.variableComponents = this.variableComponents.concat([parameterComponent]); } }) }) console.log(this.variableComponents) this.sectionComponents.forEach((sectionComponent, index) => { sectionComponent.setId(index); }); this.variableComponents.forEach((variableComponent, index) => { variableComponent.setId(index); }); this.myChangeDetectorRef.detectChanges(); this.initialiseForm(); } /** * Initialise the form. Code ordering during initialisation is defined here. */ private initialiseForm() { this.myVariableService.resetVariableService(); this.myKernelService.queueReset(); const sessionStartCodeComplete = new PromiseDelegate<boolean>(); this.myKernelService.runCode(sessionStartCode, '"session_start_code"') .then((future: Kernel.IFuture) => { if (future) { let textContent = ''; future.onIOPub = (msg => { if (msg.content.text) { textContent = textContent.concat(String(msg.content.text)); } }); future.done.then(() => sessionStartCodeComplete.resolve(JSON.parse(textContent))); } }); sessionStartCodeComplete.promise.then(isNewSession => { if (isNewSession) { console.log('Restoring old session'); } else { console.log('Starting a new session'); } this.variableComponents.forEach((variableComponent, index) => { variableComponent.initialise(); }); this.myVariableService.startListeningForChanges(); this.myVariableService.allVariablesInitilised().then(() => { const initialPromise = Promise.resolve(null); const startPromiseList: Promise<null>[] = [initialPromise]; this.startComponents.toArray().forEach((startComponent, index) => { // console.log(startComponent); if (isNewSession) { startPromiseList.push( startPromiseList[startPromiseList.length - 1].then(() => startComponent.runCode()) ); } else if (startComponent.always === '') { startPromiseList.push( startPromiseList[startPromiseList.length - 1].then(() => startComponent.runCode()) ); } }); return Promise.all(startPromiseList); }).then(() => { const initialPromise = Promise.resolve(null); const sectionPromiseList: Promise<null>[] = [initialPromise]; this.sectionComponents.forEach(sectionComponent => { if (sectionComponent.onLoad === '') { sectionPromiseList.push( sectionPromiseList[sectionPromiseList.length - 1].then(() => sectionComponent.runCode()) ); } }); // Wait until the code queue is complete before declaring form ready to // the various components. return Promise.all(sectionPromiseList); }) .then(() => { this.liveComponents.toArray().forEach(liveComponent => liveComponent.subscribe()); this.outputComponents.toArray().forEach(outputComponent => outputComponent.subscribeToVariableChanges()); this.sectionComponents.forEach(sectionComponent => sectionComponent.formReady(true)); this.variableComponents.forEach(variableComponent => variableComponent.formReady(true)); this.formReady.resolve(null); }); }); } public restartFormKernel() { this.formReady = new PromiseDelegate<void>(); this.variableComponents.forEach(variableComponent => { variableComponent.variableValue = null; variableComponent.formReady(false); }); this.sectionComponents.forEach(sectionComponent => { sectionComponent.kernelReset(); sectionComponent.formReady(false); }); this.myKernelService.restartKernel().then(() => { this.initialiseForm(); }); return this.formReady.promise; } } // The Angular module for the form component @NgModule( { imports: [ CommonModule, FormsModule, MaterialModule, SectionsModule, VariablesModule, CodeModule ], declarations: [ FormComponent ] } ) class FormComponentModule { } // Compile the template const module: ModuleWithComponentFactories<FormComponentModule> = ( compiler.compileModuleAndAllComponentsSync(FormComponentModule)); // Return the factory return module.componentFactories.find( f => f.componentType === FormComponent); }
the_stack
import React, { useState, useEffect, Dispatch, SetStateAction, useContext, ReactNode, useRef, } from 'react'; import DragHelper from '@inovua/reactdatagrid-community/packages/drag-helper'; import Region from '@inovua/reactdatagrid-community/packages/region'; import join from '@inovua/reactdatagrid-community/packages/join'; import selectParent from '@inovua/reactdatagrid-community/common/selectParent'; import isMobile from '@inovua/reactdatagrid-community/packages/isMobile'; import GridContext from '@inovua/reactdatagrid-community/context'; import { id as ROW_INDEX_COLUMN_ID } from '@inovua/reactdatagrid-community/normalizeColumns/defaultRowIndexColumnId'; import { TypeComputedProps } from '@inovua/reactdatagrid-community/types'; import batchUpdate from '@inovua/reactdatagrid-community/utils/batchUpdate'; import { TypeComputedColumn } from '@inovua/reactdatagrid-community/types/TypeColumn'; type TypeRowResizeHandleProps = { data: any; rowIndex: number; remoteRowIndex: number; rowIndexInGroup: number; renderIndex?: (index: number) => ReactNode; column: TypeComputedColumn; }; const stopPropagation = e => e.stopPropagation(); const useRowResize = ( rowIndex: number | null, config?: { data: any; rowIndexInGroup: number | null; remoterRowIndex: number; setActive: (active: boolean) => void; setConstrained: (constrained: boolean) => void; } ) => { const computedProps: TypeComputedProps = useContext<TypeComputedProps>( GridContext ); if (rowIndex == null) { rowIndex = computedProps.rowResizeIndexRef.current; } const setActive = (active: boolean) => { const queue = batchUpdate(); queue.commit(() => { if (config && config.setActive) { config.setActive(active); } computedProps.rowResizeHandleRef.current.setHovered(false); computedProps.rowResizeHandleRef.current.setActive(active); computedProps.coverHandleRef.current.setActive(active); computedProps.coverHandleRef.current.setCursor(active ? 'ns-resize' : ''); }); }; const setConstrained = (constrained: boolean) => { const queue = batchUpdate(); queue.commit(() => { if (config && config.setConstrained) { config.setConstrained(constrained); } computedProps.rowResizeHandleRef.current.setConstrained(constrained); }); }; const onResizeDragInit = ({ constrained, offset, }: { constrained: boolean; offset: number; }) => { const queue = batchUpdate(); queue.commit(() => { setActive(true); setConstrained(constrained); computedProps.rowResizeIndexRef.current = rowIndex!; computedProps.rowResizeHandleRef.current.setOffset(offset); }); }; const onResizeDrag = ({ constrained, offset, }: { constrained: boolean; offset: number; }) => { const queue = batchUpdate(); queue.commit(() => { setConstrained(constrained); computedProps.rowResizeHandleRef.current.setOffset(offset); }); }; const onResizeDrop = ({ rowHeight, rowId }) => { const queue = batchUpdate(); queue.commit(() => { setActive(false); setConstrained(false); computedProps.setRowHeightById(rowHeight, rowId); computedProps.rowResizeIndexRef.current = null; }); }; const onDoubleClick = () => { const rowId = computedProps.getItemId(config.data); const defaultRowHeight: number = computedProps.rowHeight; const currentRowHeight: number = computedProps.getRowHeightById(rowId); if (currentRowHeight !== defaultRowHeight) { const queue = batchUpdate(); queue.commit(() => { setActive(false); setConstrained(false); computedProps.setRowHeightById(null, rowId); }); } }; const onMouseDown = event => { event.preventDefault(); let rowNode = selectParent('.InovuaReactDataGrid__row', event.target); if (!rowNode) { rowNode = computedProps .getVirtualList() .rows.filter(r => r.props.index === rowIndex)[0]; if (rowNode) { rowNode = rowNode.node; } } const constrainTo = Region.from(computedProps.getDOMNode()); const rowRegion = Region.from(rowNode); const rowId = computedProps.getItemId(config.data); const initialPosition = rowRegion.bottom - constrainTo.top - 1; // TODO remove this magic constant const initialSize = computedProps.getRowHeightById(rowId); const minRowHeight = computedProps.minRowHeight || 10; const maxRowHeight = computedProps.maxRowHeight; constrainTo.set({ top: rowRegion.top + minRowHeight }); if (maxRowHeight) { constrainTo.set({ bottom: rowRegion.top + maxRowHeight }); } const isContrained = dragRegion => { const constrained = dragRegion.top <= constrainTo.top || dragRegion.bottom >= constrainTo.bottom; return constrained; }; rowRegion.set({ top: rowRegion.bottom }); let dropped = false; DragHelper(event, { constrainTo, region: rowRegion, onDragInit: (e, config) => { const constrained = isContrained(config.dragRegion); setTimeout(() => { if (dropped) { return; } onResizeDragInit({ offset: initialPosition, constrained, }); }, 150); // TODO improve this - allow 150ms for dblclick to be able to go through }, onDrag(e, config) { e.preventDefault(); e.stopPropagation(); const diff = config.diff.top; const offset = initialPosition + diff; const constrained = isContrained(config.dragRegion); e.preventDefault(); onResizeDrag({ constrained, offset, }); }, onDrop(e, config) { dropped = true; const diff = config.diff.top; onResizeDrop({ rowHeight: initialSize + diff, rowId, }); }, }); }; return { onMouseDown, onDoubleClick, }; }; export const RowResizeIndicator = ({ handle, height, column, }: { column: TypeComputedColumn; height: number; handle: (handleArg: { setOffset: Dispatch<SetStateAction<number>>; setActive: Dispatch<SetStateAction<boolean>>; setHovered: Dispatch<SetStateAction<boolean>>; setConstrained: Dispatch<SetStateAction<boolean>>; setInitialWidth: Dispatch<SetStateAction<number>>; }) => void; }) => { const [offset, setOffset] = useState<number>(0); const [hovered, setHovered] = useState<boolean>(false); const [active, setActive] = useState<boolean>(false); const [constrained, setConstrained] = useState<boolean>(false); const [initialWidth, setInitialWidth] = useState<number>(0); useEffect(() => { handle({ setOffset, setActive, setConstrained, setHovered, setInitialWidth, }); }, []); const { onMouseDown, onDoubleClick } = useRowResize(null); const style: { [key: string]: string | number } = { transform: `translate3d(0px, ${offset - Math.floor(height / 2) - 1}px, 0px)`, height, left: column.computedOffset, }; if (hovered && !(active || constrained)) { style.width = initialWidth || 20; } return ( <div style={style} className={join( `InovuaReactDataGrid__row-resize-indicator`, active && `InovuaReactDataGrid__row-resize-indicator--active`, hovered && `InovuaReactDataGrid__row-resize-indicator--hovered`, isMobile && `InovuaReactDataGrid__row-resize-indicator--mobile`, constrained && `InovuaReactDataGrid__row-resize-indicator--constrained` )} // this is for mobile, since on mobile this remains visible onTouchStart={onMouseDown} onClick={stopPropagation} onDoubleClick={onDoubleClick} /> ); }; export const RowResizeHandle = React.memo( ({ rowIndex, data, remoteRowIndex, renderIndex, rowIndexInGroup, column, }: TypeRowResizeHandleProps) => { const computedProps: TypeComputedProps | null = useContext<TypeComputedProps | null>( GridContext ); const [active, doSetActive] = useState<boolean>(false); const [constrained, doSetConstrained] = useState<boolean>(false); const domRef = useRef<HTMLDivElement>(null); const { onMouseDown, onDoubleClick } = useRowResize(rowIndex, { rowIndexInGroup, data, remoteRowIndex, setActive: doSetActive, setConstrained: doSetConstrained, }); const onMouseEnter = () => { if (!computedProps) { return; } const queue = batchUpdate(); const constrainTo = Region.from(computedProps.getDOMNode()); const handleRegion = Region.from(domRef.current); const initialPosition = handleRegion.bottom - constrainTo.top; queue.commit(() => { computedProps.rowResizeHandleRef.current.setHovered(true); computedProps.rowResizeHandleRef.current.setOffset(initialPosition); computedProps.rowResizeHandleRef.current.setInitialWidth( column.computedWidth ); }); }; const onMouseLeave = () => { if (!computedProps) { return; } computedProps.rowResizeHandleRef.current.setHovered(false); }; const indexToRender = rowIndexInGroup != null ? rowIndexInGroup : remoteRowIndex; return ( <> {renderIndex ? renderIndex(indexToRender) : indexToRender + 1} <div ref={domRef} className={join( `InovuaReactDataGrid__row-resize-handle`, isMobile && `InovuaReactDataGrid__row-resize-handle--mobile` )} style={{ width: column.computedWidth, height: computedProps ? computedProps.rowResizeHandleWidth : 10, }} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onMouseDown={onMouseDown} onClick={stopPropagation} onDoubleClick={onDoubleClick} /> </> ); } ); export default { id: ROW_INDEX_COLUMN_ID, rowIndexColumn: true, rowResize: true, cellSelectable: false, autoLock: true, headerAlign: 'center', textAlign: 'center', className: 'InovuaReactDataGrid__row-index-column', render: ( { remoteRowIndex, data, rowIndex, rowIndexInGroup, }: { data: any; rowIndexInGroup: number; rowIndex: number; remoteRowIndex: number; }, { column, }: { column: TypeComputedColumn & { renderIndex?: (index: number) => ReactNode; }; } ) => { return ( <RowResizeHandle data={data} rowIndex={rowIndex} rowIndexInGroup={rowIndexInGroup} remoteRowIndex={remoteRowIndex} renderIndex={column.renderIndex} column={column} /> ); }, header: '', showInContextMenu: false, showColumnMenuSortOptions: false, showColumnMenuGroupOptions: false, showColumnMenuTool: false, sortable: false, editable: false, draggable: false, groupBy: false, defaultWidth: 40, minWidth: 40, }; export { ROW_INDEX_COLUMN_ID as rowExpandColumnId };
the_stack
import React, { forwardRef, useImperativeHandle, useRef } from 'react'; import { Tooltip, Spin } from 'antd'; import MxFactory from '@/components/mxGraph'; import Fullscreen from '@/components/fullScreen'; import { AlignCenterOutlined, ArrowsAltOutlined, ShrinkOutlined, SyncOutlined, ZoomInOutlined, ZoomOutOutlined, } from '@ant-design/icons'; interface IProps { targetKey?: string; isSubVertex?: boolean; loading?: boolean; refresh?: () => void; onInit?: (graph: IMxGraph, Mx: any) => void; } export interface GraphEditorRef { graph: IMxGraph; getStyles: () => string; Mx: any; executeLayout: ( change: null | (() => void), post: null | (() => void), direction?: 'north' | 'west', ) => void; } type IMxGraph = typeof mxGraph; const Mx = MxFactory.create(); const { mxGraph, mxEvent, mxRubberband, mxConstants, mxRectangle, mxPoint, mxUtils, mxPerimeter, mxEdgeStyle, mxHierarchicalLayout, } = Mx; const GraphEditor = forwardRef( ({ loading, targetKey, isSubVertex, refresh, onInit }: IProps, ref) => { const container = useRef<HTMLDivElement>(null); const graph = useRef<IMxGraph>(); useImperativeHandle(ref, () => ({ graph: graph.current, getStyles: () => 'whiteSpace=wrap;fillColor=#ffffff', Mx, executeLayout, })); const loadEditor = (container: HTMLDivElement) => { // mxClient.NO_FO = true; mxEvent.disableContextMenu(container); graph.current = new mxGraph(container); // 启用绘制 graph.current.setPanning(true); graph.current.keepEdgesInBackground = true; // 允许鼠标移动画布 graph.current.panningHandler.useLeftButtonForPanning = true; graph.current.setCellsMovable(false); graph.current.setEnabled(true); // 设置启用,就是允不允许你改变CELL的形状内容。 graph.current.setConnectable(false); // 是否允许Cells通过其中部的连接点新建连接,false则通过连接线连接 graph.current.setCellsResizable(false); // 禁止改变元素大小 graph.current.setAutoSizeCells(false); graph.current.centerZoom = true; graph.current.setTooltips(false); graph.current.view.setScale(1); // Enables HTML labels graph.current.setHtmlLabels(true); graph.current.setAllowDanglingEdges(false); // 禁止Edge对象移动 graph.current.isCellsMovable = function () { var cell = graph.current.getSelectionCell(); return !(cell && (cell.edge || cell.value === 'pagination')); }; // 禁止cell编辑 graph.current.isCellEditable = function () { return false; }; // 设置Vertex样式 const vertexStyle = getDefaultVertexStyle(); graph.current.getStylesheet().putDefaultVertexStyle(vertexStyle); // 默认边界样式 let edgeStyle = getDefaultEdgeStyle(); graph.current.getStylesheet().putDefaultEdgeStyle(edgeStyle); // anchor styles mxConstants.HANDLE_FILLCOLOR = '#ffffff'; mxConstants.HANDLE_STROKECOLOR = '#42B1FB'; mxConstants.VERTEX_SELECTION_COLOR = '#42B1FB'; mxConstants.VERTEX_SELECTION_DASHED = false; mxConstants.CURSOR_MOVABLE_VERTEX = 'pointer'; mxConstants.EDGE_SELECTION_COLOR = '#2491F7'; mxConstants.EDGE_SELECTION_DASHED = false; // 重置tooltip // enables rubberband initContainerScroll(); new mxRubberband(graph.current); // eslint-disable-line onInit && onInit(graph.current, Mx); }; // 滚动监听,一般为默认,不需要更改 const initContainerScroll = () => { /** * Specifies the size of the size for "tiles" to be used for a graph with * scrollbars but no visible background page. A good value is large * enough to reduce the number of repaints that is caused for auto- * translation, which depends on this value, and small enough to give * a small empty buffer around the graph. Default is 400x400. */ // eslint-disable-next-line new-cap graph.current.scrollTileSize = new mxRectangle(0, 0, 200, 200); /** * Returns the padding for pages in page view with scrollbars. */ graph.current.getPagePadding = function () { // eslint-disable-next-line new-cap return new mxPoint( Math.max(0, Math.round(graph.current.container.offsetWidth - 40)), Math.max(0, Math.round(graph.current.container.offsetHeight - 40)), ); }; /** * Returns the size of the page format scaled with the page size. */ graph.current.getPageSize = function () { // eslint-disable-next-line new-cap return this.pageVisible ? new mxRectangle( 0, 0, this.pageFormat.width * this.pageScale, this.pageFormat.height * this.pageScale, ) : this.scrollTileSize; }; /** * Returns a rectangle describing the position and count of the * background pages, where x and y are the position of the top, * left page and width and height are the vertical and horizontal * page count. */ graph.current.getPageLayout = function () { var size = this.pageVisible ? this.getPageSize() : this.scrollTileSize; var bounds = this.getGraphBounds(); if (bounds.width == 0 || bounds.height == 0) { // eslint-disable-next-line new-cap return new mxRectangle(0, 0, 1, 1); } else { // Computes untransformed graph bounds var x = Math.ceil(bounds.x / this.view.scale - this.view.translate.x); var y = Math.ceil(bounds.y / this.view.scale - this.view.translate.y); var w = Math.floor(bounds.width / this.view.scale); var h = Math.floor(bounds.height / this.view.scale); var x0 = Math.floor(x / size.width); var y0 = Math.floor(y / size.height); var w0 = Math.ceil((x + w) / size.width) - x0; var h0 = Math.ceil((y + h) / size.height) - y0; // eslint-disable-next-line new-cap return new mxRectangle(x0, y0, w0, h0); } }; // Fits the number of background pages to the graph graph.current.view.getBackgroundPageBounds = function () { var layout = this.graph.getPageLayout(); var page = this.graph.getPageSize(); // eslint-disable-next-line new-cap return new mxRectangle( this.scale * (this.translate.x + layout.x * page.width), this.scale * (this.translate.y + layout.y * page.height), this.scale * layout.width * page.width, this.scale * layout.height * page.height, ); }; graph.current.getPreferredPageSize = function (bounds: any, width: any, height: any) { var pages = this.getPageLayout(); var size = this.getPageSize(); // eslint-disable-next-line new-cap return new mxRectangle(0, 0, pages.width * size.width, pages.height * size.height); }; /** * Guesses autoTranslate to avoid another repaint (see below). * Works if only the scale of the graph changes or if pages * are visible and the visible pages do not change. */ var graphViewValidate = graph.current.view.validate; graph.current.view.validate = function () { if (this.graph.container != null && mxUtils.hasScrollbars(this.graph.container)) { var pad = this.graph.getPagePadding(); var size = this.graph.getPageSize(); // Updating scrollbars here causes flickering in quirks and is not needed // if zoom method is always used to set the current scale on the graph. // var tx = this.translate.x; // var ty = this.translate.y; this.translate.x = pad.x / this.scale - (this.x0 || 0) * size.width; this.translate.y = pad.y / this.scale - (this.y0 || 0) * size.height; } graphViewValidate.apply(this, arguments); }; var graphSizeDidChange = graph.current.sizeDidChange; graph.current.sizeDidChange = function () { if (this.container != null && mxUtils.hasScrollbars(this.container)) { var pages = this.getPageLayout(); var pad = this.getPagePadding(); var size = this.getPageSize(); // Updates the minimum graph size var minw = Math.ceil((2 * pad.x) / this.view.scale + pages.width * size.width); var minh = Math.ceil( (2 * pad.y) / this.view.scale + pages.height * size.height, ); var min = graph.current.minimumGraphSize; // LATER: Fix flicker of scrollbar size in IE quirks mode // after delayed call in window.resize event handler if (min == null || min.width != minw || min.height != minh) { // eslint-disable-next-line new-cap graph.current.minimumGraphSize = new mxRectangle(0, 0, minw, minh); } // Updates auto-translate to include padding and graph size var dx = pad.x / this.view.scale - pages.x * size.width; var dy = pad.y / this.view.scale - pages.y * size.height; if ( !this.autoTranslate && (this.view.translate.x != dx || this.view.translate.y != dy) ) { this.autoTranslate = true; this.view.x0 = pages.x; this.view.y0 = pages.y; var tx = graph.current.view.translate.x; var ty = graph.current.view.translate.y; graph.current.view.setTranslate(dx, dy); graph.current.container.scrollLeft += (dx - tx) * graph.current.view.scale; graph.current.container.scrollTop += (dy - ty) * graph.current.view.scale; this.autoTranslate = false; return; } graphSizeDidChange.apply(this, arguments); } }; }; // 更新布局 const executeLayout = ( change: null | (() => void), post: null | (() => void), direction?: 'north' | 'west', ) => { const model = graph.current.getModel(); model.beginUpdate(); try { const layout = new mxHierarchicalLayout(graph.current, false); layout.orientation = direction || (isSubVertex ? 'north' : 'west'); layout.disableEdgeStyle = false; layout.interRankCellSpacing = 60; layout.intraCellSpacing = 80; if (change != null) { change(); } layout.execute(graph.current.getDefaultParent()); } catch (e) { throw e; } finally { model.endUpdate(); if (post != null) { post(); } } }; const alignCenter = () => { executeLayout( null, () => { graph.current.center(); }, 'west', ); }; React.useEffect(() => { if (container.current) { container.current.innerHTML = ''; graph.current = undefined; loadEditor(container.current); } }, []); return ( <div className="graph-editor"> {loading && <Spin spinning={loading} className="graph_loading"></Spin>} <div className="graph_container" ref={container} /> <div className="graph_toolbar"> <div className="basic_bar"> {isSubVertex ? null : ( <Tooltip placement="left" title="刷新"> <div className="toolbar-icon"> <SyncOutlined onClick={() => { refresh?.(); alignCenter(); }} /> </div> </Tooltip> )} <Tooltip placement="left" title="居中"> <div className="toolbar-icon"> <AlignCenterOutlined onClick={alignCenter} /> </div> </Tooltip> <Tooltip placement="left" title="放大"> <div className="toolbar-icon"> <ZoomInOutlined onClick={() => graph.current.zoomIn()} /> </div> </Tooltip> <Tooltip placement="left" title="缩小"> <div className="toolbar-icon"> <ZoomOutOutlined onClick={() => graph.current.zoomOut()} /> </div> </Tooltip> {!isSubVertex ? null : ( <div onClick={() => { // 延迟冒泡重新 resize setTimeout(() => { alignCenter(); }, 100); }} > <Fullscreen className="graph-fullscreen" target={targetKey} fullIcon={<ArrowsAltOutlined />} exitFullIcon={<ShrinkOutlined />} isShowTitle={false} /> </div> )} </div> </div> </div> ); }, ); function getDefaultVertexStyle() { let style: any = []; style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_RECTANGLE; style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter; style[mxConstants.STYLE_STROKECOLOR] = 'none'; style[mxConstants.STYLE_FILLCOLOR] = 'none'; style[mxConstants.STYLE_FONTCOLOR] = '#333333'; style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER; style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_MIDDLE; style[mxConstants.STYLE_FONTSIZE] = '12'; style[mxConstants.STYLE_FONTSTYLE] = 1; style[mxConstants.STYLE_ARCSIZE] = 1; style[mxConstants.STYLE_ROUNDED] = true; return style; } function getDefaultEdgeStyle() { let style: any = []; style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_CONNECTOR; style[mxConstants.STYLE_STROKECOLOR] = '#95AFC7'; style[mxConstants.STYLE_STROKEWIDTH] = 1; style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER; style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_MIDDLE; style[mxConstants.STYLE_EDGE] = mxEdgeStyle.EntityRelation; style[mxConstants.STYLE_ENDARROW] = mxConstants.ARROW_BLOCK; style[mxConstants.STYLE_FONTSIZE] = '10'; style[mxConstants.STYLE_ROUNDED] = true; style[mxConstants.STYLE_CURVED] = false; return style; } export default GraphEditor;
the_stack
import execa from 'execa'; import { Arg, Command, INTERNAL_PROGRAM } from '../src'; import { mockProgram, mockStreams, runCommand } from '../src/test'; import { AllDecoratorCommand } from './__fixtures__/AllDecoratorCommand'; import { AllInitializerCommand } from './__fixtures__/AllInitializerCommand'; import { AllPropsCommand } from './__fixtures__/AllPropsCommand'; import { BuildDecoratorCommand } from './__fixtures__/BuildDecoratorCommand'; import { BuildInitializerCommand } from './__fixtures__/BuildInitializerCommand'; import { BuildPropsCommand } from './__fixtures__/BuildPropsCommand'; import { Child, GrandChild, Parent, UnknownChild, UnknownGrandChild, } from './__fixtures__/commands'; import { InstallDecoratorCommand } from './__fixtures__/InstallDecoratorCommand'; import { InstallInitializerCommand } from './__fixtures__/InstallInitializerCommand'; import { InstallPropsCommand } from './__fixtures__/InstallPropsCommand'; jest.mock('execa'); jest.mock('term-size'); describe('Command', () => { describe('executeCommand()', () => { function mockExeca() { (execa as unknown as jest.Mock).mockImplementation((command, args) => ({ command: `${command} ${args.join(' ')}`, })); } beforeEach(() => { mockExeca(); }); it('runs a local command', async () => { const streams = mockStreams(); const command = new BuildDecoratorCommand(); command[INTERNAL_PROGRAM] = mockProgram({}, streams); const result = await command.executeCommand('yarn', ['-v']); expect(execa).toHaveBeenCalledWith('yarn', ['-v'], streams); expect(result).toEqual(expect.objectContaining({ command: 'yarn -v' })); }); }); describe('getArguments()', () => { it('returns an args object', async () => { const command = new BuildDecoratorCommand(); await runCommand(command, ['foo'], { dst: './lib' }); expect(command.getArguments()).toEqual({ command: ['build'], errors: [], options: { dst: './lib', help: false, locale: 'en', version: false, }, params: ['foo'], rest: [], unknown: {}, }); }); }); describe('decorators', () => { it('inherits metadata from @Config and sets static properties', () => { const command = new BuildDecoratorCommand(); const meta = command.getMetadata(); expect(BuildDecoratorCommand.aliases).toEqual(['compile']); expect(BuildDecoratorCommand.description).toBe('Build a project'); expect(BuildDecoratorCommand.path).toBe('build'); expect(BuildDecoratorCommand.usage).toBe('build -S ./src -D ./lib'); expect(BuildDecoratorCommand.description).toBe(meta.description); expect(BuildDecoratorCommand.path).toBe(meta.path); expect(BuildDecoratorCommand.usage).toBe(meta.usage); expect(BuildDecoratorCommand.category).toBe(meta.category); // Again with different properties const command2 = new InstallDecoratorCommand(); const meta2 = command2.getMetadata(); expect(InstallDecoratorCommand.description).toBe('Install package(s)'); expect(InstallDecoratorCommand.path).toBe('install'); expect(InstallDecoratorCommand.deprecated).toBe(true); expect(InstallDecoratorCommand.hidden).toBe(true); expect(InstallDecoratorCommand.description).toBe(meta2.description); expect(InstallDecoratorCommand.path).toBe(meta2.path); expect(InstallDecoratorCommand.deprecated).toBe(meta2.deprecated); expect(InstallDecoratorCommand.hidden).toBe(meta2.hidden); expect(InstallDecoratorCommand.category).toBe(meta2.category); }); it('inherits global options from parent', () => { const command = new BuildDecoratorCommand(); const { options } = command.getMetadata(); expect(options).toEqual({ dst: { short: 'D', default: '', description: 'Destination path', type: 'string' }, src: { short: 'S', default: './src', description: 'Source path', type: 'string' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }); }); it('inherits global categories from parent', () => { const command = new InstallDecoratorCommand(); const { categories } = command.getMetadata(); expect(categories).toEqual({ special: 'Special', }); }); it('sets params with @Arg.Params', () => { const command = new InstallDecoratorCommand(); const { params } = command.getMetadata(); expect(params).toEqual([ { description: 'Package name', label: 'pkg', required: true, type: 'string' }, ]); }); it('supports all options and params types', () => { const command = new AllDecoratorCommand(); const { options, params } = command.getMetadata(); expect(options).toEqual( expect.objectContaining({ flag: { default: true, description: 'Boolean flag', short: 'F', type: 'boolean' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, num: { count: true, default: 0, description: 'Single number', short: 'N', type: 'number', }, nums: { default: [], deprecated: true, description: 'List of numbers', multiple: true, type: 'number', }, str: { choices: ['a', 'b', 'c'], default: 'a', description: 'Single string', hidden: true, type: 'string', }, strs: { arity: 5, default: [], description: 'List of strings', multiple: true, short: 'S', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }), ); expect(params).toEqual([ { description: 'String', label: 'char', required: true, type: 'string' }, { description: 'Boolean', type: 'boolean', default: true }, { description: 'Number', label: 'int', type: 'number', default: 123 }, ]); }); it('errors if @Params is not on the run method', () => { expect(() => { // eslint-disable-next-line @typescript-eslint/no-unused-vars class TestCommand extends Command { @Arg.Params() unknownArg() {} run() { return Promise.resolve(''); } } }).toThrow('Parameters must be defined on the `run()` method.'); }); it('errors if option is using a reserved name', () => { expect(() => { // eslint-disable-next-line @typescript-eslint/no-unused-vars class TestCommand extends Command { @Arg.String('Description') override locale: string = ''; run() { return Promise.resolve(''); } } }).toThrow('Option "locale" is a reserved name and cannot be used.'); }); it('returns command line path', () => { const command = new BuildDecoratorCommand(); expect(command.getPath()).toBe('build'); }); it('returns parser options', () => { const command = new BuildDecoratorCommand(); expect(command.getParserOptions()).toEqual({ commands: ['build', 'compile'], options: { dst: { default: '', short: 'D', description: 'Destination path', type: 'string' }, src: { default: './src', short: 'S', description: 'Source path', type: 'string' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }, params: [], unknown: false, variadic: false, }); }); }); describe('initializers', () => { it('inherits metadata from static properties', () => { const command = new BuildInitializerCommand(); const meta = command.getMetadata(); expect(BuildInitializerCommand.aliases).toEqual(['compile']); expect(BuildInitializerCommand.description).toBe('Build a project'); expect(BuildInitializerCommand.path).toBe('build'); expect(BuildInitializerCommand.usage).toBe('build -S ./src -D ./lib'); expect(BuildInitializerCommand.description).toBe(meta.description); expect(BuildInitializerCommand.path).toBe(meta.path); expect(BuildInitializerCommand.usage).toBe(meta.usage); expect(BuildInitializerCommand.category).toBe(meta.category); // Again with different properties const command2 = new InstallInitializerCommand(); const meta2 = command2.getMetadata(); expect(InstallInitializerCommand.description).toBe('Install package(s)'); expect(InstallInitializerCommand.path).toBe('install'); expect(InstallInitializerCommand.deprecated).toBe(true); expect(InstallInitializerCommand.hidden).toBe(false); expect(InstallInitializerCommand.description).toBe(meta2.description); expect(InstallInitializerCommand.path).toBe(meta2.path); expect(InstallInitializerCommand.deprecated).toBe(meta2.deprecated); expect(InstallInitializerCommand.hidden).toBe(meta2.hidden); expect(InstallInitializerCommand.category).toBe(meta2.category); }); it('inherits global options from parent', () => { const command = new BuildInitializerCommand(); const { options } = command.getMetadata(); expect(options).toEqual({ dst: { short: 'D', default: '', description: 'Destination path', type: 'string' }, src: { short: 'S', default: './src', description: 'Source path', type: 'string' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }); }); it('inherits global categories from parent', () => { const command = new InstallInitializerCommand(); const { categories } = command.getMetadata(); expect(categories).toEqual({ special: 'Special', }); }); it('sets params with @Arg.Params', () => { const command = new InstallInitializerCommand(); const { params } = command.getMetadata(); expect(params).toEqual([ { description: 'Package name', label: 'pkg', required: true, type: 'string' }, ]); }); it('supports all options and params types', () => { const command = new AllInitializerCommand(); const { options, params } = command.getMetadata(); expect(options).toEqual( expect.objectContaining({ flag: { default: true, description: 'Boolean flag', short: 'F', type: 'boolean' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, num: { count: true, default: 0, description: 'Single number', short: 'N', type: 'number', }, nums: { default: [], deprecated: true, description: 'List of numbers', multiple: true, type: 'number', }, str: { choices: ['a', 'b', 'c'], default: 'a', description: 'Single string', hidden: true, type: 'string', }, strs: { arity: 5, default: [], description: 'List of strings', multiple: true, short: 'S', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }), ); expect(params).toEqual([ { description: 'String', label: 'char', required: true, type: 'string' }, { description: 'Boolean', type: 'boolean', default: true }, { description: 'Number', label: 'int', type: 'number', default: 123 }, ]); }); it('errors if option is using a reserved name', () => { expect(() => { class TestCommand extends Command { override locale = Arg.string('Description'); run() { return Promise.resolve(''); } } // Initializers have to be triggered return new TestCommand().getMetadata(); }).toThrow('Option "locale" is a reserved name and cannot be used.'); }); it('returns command line path', () => { const command = new BuildInitializerCommand(); expect(command.getPath()).toBe('build'); }); it('returns parser options', () => { const command = new BuildInitializerCommand(); expect(command.getParserOptions()).toEqual({ commands: ['build', 'compile'], options: { dst: { default: '', short: 'D', description: 'Destination path', type: 'string' }, src: { default: './src', short: 'S', description: 'Source path', type: 'string' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }, params: [], unknown: false, variadic: false, }); }); }); describe('static properties', () => { it('inherits metadata from static properties', () => { const command = new BuildPropsCommand(); const meta = command.getMetadata(); expect(BuildPropsCommand.aliases).toEqual(['compile']); expect(BuildPropsCommand.description).toBe('Build a project'); expect(BuildPropsCommand.path).toBe('build'); expect(BuildPropsCommand.usage).toBe('build -S ./src -D ./lib'); expect(BuildPropsCommand.description).toBe(meta.description); expect(BuildPropsCommand.path).toBe(meta.path); expect(BuildPropsCommand.usage).toBe(meta.usage); expect(BuildPropsCommand.category).toBe(meta.category); // Again with different properties const command2 = new InstallPropsCommand(); const meta2 = command2.getMetadata(); expect(InstallPropsCommand.description).toBe('Install package(s)'); expect(InstallPropsCommand.path).toBe('install'); expect(InstallPropsCommand.deprecated).toBe(true); expect(InstallPropsCommand.hidden).toBe(true); expect(InstallPropsCommand.description).toBe(meta2.description); expect(InstallPropsCommand.path).toBe(meta2.path); expect(InstallPropsCommand.deprecated).toBe(meta2.deprecated); expect(InstallPropsCommand.hidden).toBe(meta2.hidden); expect(InstallPropsCommand.category).toBe(meta2.category); }); it('inherits global options from parent', () => { const command = new BuildPropsCommand(); const { options } = command.getMetadata(); expect(options).toEqual({ dst: { short: 'D', default: '', description: 'Destination path', type: 'string' }, src: { short: 'S', default: './src', description: 'Source path', type: 'string' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }); }); it('inherits global categories from parent', () => { const command = new InstallPropsCommand(); const { categories } = command.getMetadata(); expect(categories).toEqual({ special: 'Special', }); }); it('sets params', () => { const command = new InstallPropsCommand(); const { params } = command.getMetadata(); expect(params).toEqual([ { description: 'Package name', label: 'pkg', required: true, type: 'string' }, ]); }); it('supports all options and params types', () => { const command = new AllPropsCommand(); const { options, params } = command.getMetadata(); expect(options).toEqual({ flag: { short: 'F', default: false, description: 'Boolean flag', type: 'boolean' }, num: { count: true, default: 0, short: 'N', description: 'Single number', type: 'number' }, nums: { default: [], deprecated: true, description: 'List of numbers', multiple: true, type: 'number', }, str: { choices: ['a', 'b', 'c'], default: 'a', hidden: true, description: 'Single string', type: 'string', }, strs: { arity: 5, default: [], short: 'S', validate: expect.any(Function), description: 'List of strings', multiple: true, type: 'string', }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }); expect(params).toEqual([ { description: 'String', label: 'char', required: true, type: 'string' }, { description: 'Boolean', type: 'boolean', default: true }, { description: 'Number', label: 'int', type: 'number', default: 123 }, ]); }); it('returns command line path', () => { const command = new BuildPropsCommand(); expect(command.getPath()).toBe('build'); }); it('returns parser options', () => { const command = new BuildPropsCommand(); expect(command.getParserOptions()).toEqual({ commands: ['build', 'compile'], options: { dst: { default: '', short: 'D', description: 'Destination path', type: 'string' }, src: { default: './src', short: 'S', description: 'Source path', type: 'string' }, help: { category: 'global', default: false, description: 'Display help and usage menu', short: 'h', type: 'boolean', }, locale: { category: 'global', default: 'en', description: 'Display output in the chosen locale', type: 'string', validate: expect.any(Function), }, version: { category: 'global', default: false, description: 'Display version number', short: 'v', type: 'boolean', }, }, params: [], unknown: false, variadic: false, }); }); }); describe('sub-commands', () => { it('errors if child is not prefixed with parent', () => { const command = new Parent(); expect(() => { command.register(new UnknownChild()); }).toThrow('Sub-command "unknown" must start with "parent:".'); }); it('errors if child is not prefixed with parent (grand depth)', () => { const child = new Child(); expect(() => { child.register(new UnknownGrandChild()); }).toThrow('Sub-command "parent:unknown" must start with "parent:child:".'); }); it('errors if the same path is registered', () => { const command = new Parent(); expect(() => { command.register(new Child()); command.register(new Child()); }).toThrow('A command already exists with the canonical path "parent:child".'); }); it('returns null for empty path', () => { const parent = new Parent(); const child = new Child(); parent.register(child); expect(parent.getCommand('')).toBeNull(); }); it('returns null for unknown path', () => { const parent = new Parent(); const child = new Child(); parent.register(child); expect(parent.getCommand('unknown')).toBeNull(); }); it('supports children', () => { const parent = new Parent(); const child = new Child(); parent.register(child); expect(parent.getMetadata().commands).toEqual({ 'parent:child': child, }); }); it('supports grand children', () => { const parent = new Parent(); const child = new Child(); const grandChild = new GrandChild(); parent.register(child); child.register(grandChild); expect(parent.getMetadata().commands).toEqual({ 'parent:child': child, }); expect(child.getMetadata().commands).toEqual({ 'parent:child:grandchild': grandChild, }); }); }); });
the_stack
import bowser from 'bowser'; import Event from '../Event'; import MainHelper from '../helpers/MainHelper'; import { addCssClass, addDomElement, getPlatformNotificationIcon, once, removeDomElement, removeCssClass, getDomElementOrStub } from '../utils'; import { SlidedownPromptOptions, DelayedPromptType } from '../models/Prompts'; import { SERVER_CONFIG_DEFAULTS_SLIDEDOWN } from '../config'; import { getLoadingIndicatorWithColor } from './LoadingIndicator'; import { getRetryIndicator } from './RetryIndicator'; import { SLIDEDOWN_CSS_CLASSES, SLIDEDOWN_CSS_IDS, COLORS } from "./constants"; import { TagCategory } from '../models/Tags'; import { getSlidedownElement } from './SlidedownElement'; import { Utils } from '../context/shared/utils/Utils'; import ChannelCaptureContainer from './ChannelCaptureContainer'; import { InvalidChannelInputField } from '../errors/ChannelCaptureError'; import PromptsHelper from '../helpers/PromptsHelper'; export default class Slidedown { public options: SlidedownPromptOptions; public notificationIcons: NotificationIcons | null; public channelCaptureContainer: ChannelCaptureContainer | null; // category slidedown public isShowingFailureState: boolean; private tagCategories : TagCategory[] | undefined; private savingButton : string = SERVER_CONFIG_DEFAULTS_SLIDEDOWN.savingText; private errorButton : string = SERVER_CONFIG_DEFAULTS_SLIDEDOWN.errorButton; private updateMessage ?: string; private positiveUpdateButton ?: string; private negativeUpdateButton ?: string; constructor(options: SlidedownPromptOptions) { this.options = options; this.options.text.actionMessage = options.text.actionMessage.substring(0, 90); this.options.text.acceptButton = options.text.acceptButton.substring(0, 16); this.options.text.cancelButton = options.text.cancelButton.substring(0, 16); this.notificationIcons = null; this.channelCaptureContainer = null; this.isShowingFailureState = false; switch (options.type) { case DelayedPromptType.Category: this.negativeUpdateButton = this.options.text.negativeUpdateButton?.substring(0, 16); this.positiveUpdateButton = this.options.text.positiveUpdateButton?.substring(0, 16); this.updateMessage = this.options.text.updateMessage?.substring(0, 90); this.tagCategories = options.categories; this.errorButton = Utils.getValueOrDefault(this.options.text.positiveUpdateButton, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.errorButton); break; case DelayedPromptType.Sms: case DelayedPromptType.Email: case DelayedPromptType.SmsAndEmail: this.errorButton = Utils.getValueOrDefault(this.options.text.acceptButton, SERVER_CONFIG_DEFAULTS_SLIDEDOWN.errorButton); break; default: break; } } async create(isInUpdateMode?: boolean): Promise<void> { // TODO: dynamically change btns depending on if its first or repeat display of slidedown (subscribe vs update) if (this.notificationIcons === null) { const icons = await MainHelper.getNotificationIcons(); this.notificationIcons = icons; // Remove any existing container if (this.container.className.includes(SLIDEDOWN_CSS_CLASSES.container)) { removeDomElement(`#${SLIDEDOWN_CSS_IDS.container}`); } const positiveButtonText = isInUpdateMode && !!this.tagCategories ? this.positiveUpdateButton : this.options.text.acceptButton; const negativeButtonText = isInUpdateMode && !!this.tagCategories ? this.negativeUpdateButton : this.options.text.cancelButton; const messageText = isInUpdateMode && !!this.tagCategories ? this.updateMessage : this.options.text.actionMessage; // use the prompt-specific icon OR the app default icon const icon = this.options.icon || this.getPlatformNotificationIcon(); const slidedownElement = getSlidedownElement({ messageText, icon, positiveButtonText, negativeButtonText }); const slidedownContainer = document.createElement("div"); const dialogContainer = document.createElement("div"); // Insert the container slidedownContainer.id = SLIDEDOWN_CSS_IDS.container; addCssClass(slidedownContainer, SLIDEDOWN_CSS_CLASSES.container); addCssClass(slidedownContainer, SLIDEDOWN_CSS_CLASSES.reset); getDomElementOrStub('body').appendChild(slidedownContainer); // Insert the dialog dialogContainer.id = SLIDEDOWN_CSS_IDS.dialog; addCssClass(dialogContainer, SLIDEDOWN_CSS_CLASSES.dialog); dialogContainer.appendChild(slidedownElement); this.container.appendChild(dialogContainer); // Animate it in depending on environment addCssClass(this.container, bowser.mobile ? SLIDEDOWN_CSS_CLASSES.slideUp : SLIDEDOWN_CSS_CLASSES.slideDown); // Add click event handlers this.allowButton.addEventListener('click', this.onSlidedownAllowed.bind(this)); this.cancelButton.addEventListener('click', this.onSlidedownCanceled.bind(this)); } } static async triggerSlidedownEvent(eventName: string): Promise<void> { await Event.trigger(eventName); } async onSlidedownAllowed(_: any): Promise<void> { await Slidedown.triggerSlidedownEvent(Slidedown.EVENTS.ALLOW_CLICK); } onSlidedownCanceled(_: any): void { Slidedown.triggerSlidedownEvent(Slidedown.EVENTS.CANCEL_CLICK); this.close(); Slidedown.triggerSlidedownEvent(Slidedown.EVENTS.CLOSED); } close(): void { addCssClass(this.container, SLIDEDOWN_CSS_CLASSES.closeSlidedown); once(this.dialog, 'animationend', (event: any, destroyListenerFn: () => void) => { if (event.target === this.dialog && (event.animationName === 'slideDownExit' || event.animationName === 'slideUpExit')) { // Uninstall the event listener for animationend removeDomElement(`#${SLIDEDOWN_CSS_IDS.container}`); destroyListenerFn(); /** * Remember to trigger closed event after invoking close() * This is due to the once() function not running correctly in test environment */ } }, true); } /** * To be used with slidedown types other than `push` type */ setSaveState(): void { // note: savingButton is hardcoded in constructor. TODO: pull from config & set defaults for future release this.allowButton.disabled = true; this.allowButton.textContent = null; this.allowButton.insertAdjacentElement('beforeend', this.getTextSpan(this.savingButton)); this.allowButton.insertAdjacentElement('beforeend', this.getIndicatorHolder()); addDomElement(this.buttonIndicatorHolder,'beforeend', getLoadingIndicatorWithColor(COLORS.whiteLoadingIndicator)); addCssClass(this.allowButton, 'disabled'); addCssClass(this.allowButton, SLIDEDOWN_CSS_CLASSES.savingStateButton); } /** * To be used with slidedown types other than `push` type */ removeSaveState(): void { this.allowButton.textContent = this.positiveUpdateButton; removeDomElement(`#${SLIDEDOWN_CSS_CLASSES.buttonIndicatorHolder}`); this.allowButton.disabled = false; removeCssClass(this.allowButton, 'disabled'); removeCssClass(this.allowButton, SLIDEDOWN_CSS_CLASSES.savingStateButton); } /** * @param {InvalidChannelInputField} invalidChannelInput? - for use in Web Prompts only! * we want the ability to be able to specify which channel input failed validation * @returns void */ setFailureState(): void { this.allowButton.textContent = null; this.allowButton.insertAdjacentElement('beforeend', this.getTextSpan(this.errorButton)); if (this.options.type === DelayedPromptType.Category) { this.allowButton.insertAdjacentElement('beforeend', this.getIndicatorHolder()); addDomElement(this.buttonIndicatorHolder, 'beforeend', getRetryIndicator()); addCssClass(this.allowButton, 'onesignal-error-state-button'); } this.isShowingFailureState = true; } setFailureStateForInvalidChannelInput(invalidChannelInput: InvalidChannelInputField): void { switch (invalidChannelInput) { case InvalidChannelInputField.InvalidSms: ChannelCaptureContainer.showSmsInputError(true); break; case InvalidChannelInputField.InvalidEmail: ChannelCaptureContainer.showEmailInputError(true); break; case InvalidChannelInputField.InvalidEmailAndSms: ChannelCaptureContainer.showSmsInputError(true); ChannelCaptureContainer.showEmailInputError(true); break; default: break; } } removeFailureState(): void { removeDomElement('#onesignal-button-indicator-holder'); removeCssClass(this.allowButton, 'onesignal-error-state-button'); if (!PromptsHelper.isSlidedownPushDependent(this.options.type)) { ChannelCaptureContainer.resetInputErrorStates(this.options.type); } this.isShowingFailureState = false; } getPlatformNotificationIcon(): string { return getPlatformNotificationIcon(this.notificationIcons); } getIndicatorHolder(): Element { const indicatorHolder = document.createElement("div"); indicatorHolder.id = SLIDEDOWN_CSS_IDS.buttonIndicatorHolder; addCssClass(indicatorHolder, SLIDEDOWN_CSS_CLASSES.buttonIndicatorHolder); return indicatorHolder; } getTextSpan(text: string): Element { const textHolder = document.createElement("span"); textHolder.textContent = text; return textHolder; } get container() { return getDomElementOrStub(`#${SLIDEDOWN_CSS_IDS.container}`); } get dialog() { return getDomElementOrStub(`#${SLIDEDOWN_CSS_IDS.dialog}`); } get allowButton() { return getDomElementOrStub(`#${SLIDEDOWN_CSS_IDS.allowButton}`) as HTMLButtonElement; } get cancelButton() { return getDomElementOrStub(`#${SLIDEDOWN_CSS_IDS.cancelButton}`) as HTMLButtonElement; } get buttonIndicatorHolder() { return getDomElementOrStub(`#${SLIDEDOWN_CSS_IDS.buttonIndicatorHolder}`); } get slidedownFooter() { return getDomElementOrStub(`#${SLIDEDOWN_CSS_IDS.footer}`); } static get EVENTS() { return { ALLOW_CLICK: 'popoverAllowClick', CANCEL_CLICK: 'popoverCancelClick', SHOWN: 'popoverShown', CLOSED: 'popoverClosed', QUEUED: 'popoverQueued' }; } } export function manageNotifyButtonStateWhileSlidedownShows(): void { const notifyButton = OneSignal.notifyButton; if (notifyButton && notifyButton.options.enable && OneSignal.notifyButton.launcher.state !== 'hidden') { OneSignal.notifyButton.launcher.waitUntilShown() .then(() => { OneSignal.notifyButton.launcher.hide(); }); } OneSignal.emitter.once(Slidedown.EVENTS.CLOSED, () => { if (OneSignal.notifyButton && OneSignal.notifyButton.options.enable) { OneSignal.notifyButton.launcher.show(); } }); }
the_stack
import * as chai from "chai"; import { extractIncludes } from "../src/domInjection/includesProcessor"; import { JSDOM } from "jsdom"; import { expect } from "chai"; import { tryDotNetModes } from "../src/domInjection/types"; chai.should(); describe("include blocks", () => { it("can be extracted from dom", () => { let configuration = { hostOrigin: "https://docs.microsoft.com" }; let dom = new JSDOM( `<!DOCTYPE html> <html lang="en"> <body> <pre> <code data-trydotnet-mode="include"> public class Utility{ } <code> </pre> <pre> <code data-trydotnet-mode="include"> public class AnotherUtility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-session-id="sessionInclude"> public class AnotherUtilityWhyNot{ } <code> </pre> </body> </html>`, { url: configuration.hostOrigin, runScripts: "dangerously" }); let includes = extractIncludes(dom.window.document); expect(includes).not.to.be.null; expect(includes).not.to.be.undefined; expect(includes.global).not.to.be.undefined; expect(includes.global).not.to.be.null; let file = includes.global.files[0]; expect(file).not.to.be.null; expect(includes["sessionInclude"]).not.to.be.undefined; expect(includes["sessionInclude"]).not.to.be.null; file = includes["sessionInclude"].files[0]; expect(file).not.to.be.null; }); it("can declare documents", () => { let configuration = { hostOrigin: "https://docs.microsoft.com" }; let dom = new JSDOM( `<!DOCTYPE html> <html lang="en"> <body> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region1"> public class Utility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2"> public class AnotherUtility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2"> public class AnotherUtilityAgain{ } <code> </pre> </body> </html>`, { url: configuration.hostOrigin, runScripts: "dangerously" }); let includes = extractIncludes(dom.window.document); expect(includes).not.to.be.null; expect(includes).not.to.be.undefined; expect(includes.global).not.to.be.undefined; expect(includes.global).not.to.be.null; let file = includes.global.files[0]; expect(file).not.to.be.null; includes.global.documents.length.should.be.equal(2); let documentOne = includes.global.documents[0]; expect(documentOne).not.to.be.null; documentOne.region.should.be.contain("region1"); let documentTwo = includes.global.documents[1]; expect(documentTwo).not.to.be.null; documentTwo.region.should.be.contain("region2"); documentOne.fileName.should.be.equal(documentTwo.fileName); }); it("can concatenate code snippets targeting a single region", () => { let configuration = { hostOrigin: "https://docs.microsoft.com" }; let dom = new JSDOM( `<!DOCTYPE html> <html lang="en"> <body> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region1"> public class Utility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2" data-trydotnet-injection-point="before"> public class AnotherUtility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2" data-trydotnet-injection-point="after"> public class AnotherUtilityAgain{ } <code> </pre> </body> </html>`, { url: configuration.hostOrigin, runScripts: "dangerously" }); let includes = extractIncludes(dom.window.document); expect(includes).not.to.be.null; expect(includes).not.to.be.undefined; expect(includes.global).not.to.be.undefined; expect(includes.global).not.to.be.null; let file = includes.global.files[0]; expect(file).not.to.be.null; includes.global.documents.length.should.be.equal(3); let documentOne = includes.global.documents[0]; expect(documentOne).not.to.be.null; documentOne.region.should.be.contain("region1"); let documentTwo = includes.global.documents[1]; expect(documentTwo).not.to.be.null; documentTwo.region.should.be.equal("region2[before]"); let documentThree = includes.global.documents[2]; expect(documentThree).not.to.be.null; documentThree.region.should.be.equal("region2[after]"); documentOne.fileName.should.be.equal(documentTwo.fileName); }); it("can declare documents wrapping around editable one", () => { let configuration = { hostOrigin: "https://docs.microsoft.com" }; let dom = new JSDOM( `<!DOCTYPE html> <html lang="en"> <body> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2"> public class ClassBefore{ } <code> </pre> <pre> <code data-trydotnet-mode="editor" data-trydotnet-region="region2"> public class EditableCode{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2"> public class ClassAfter{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2"> public class AnotherClassAfter{ } <code> </pre> </body> </html>`, { url: configuration.hostOrigin, runScripts: "dangerously" }); let includes = extractIncludes(dom.window.document); expect(includes).not.to.be.null; expect(includes).not.to.be.undefined; expect(includes.global).not.to.be.undefined; expect(includes.global).not.to.be.null; let file = includes.global.files[0]; expect(file).not.to.be.null; includes.global.documents.length.should.be.equal(2); let documentOne = includes.global.documents[0]; expect(documentOne).not.to.be.null; documentOne.region.should.be.contain("region2[before]"); let documentTwo = includes.global.documents[1]; expect(documentTwo).not.to.be.null; documentTwo.region.should.be.equal("region2[after]"); documentOne.fileName.should.be.equal(documentTwo.fileName); }); it("can declare documents wrapping around editable one following the order attribute", () => { let configuration = { hostOrigin: "https://docs.microsoft.com" }; let dom = new JSDOM( `<!DOCTYPE html> <html lang="en"> <body> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2" data-trydotnet-order="158"> public class ClassBefore{ } <code> </pre> <div> <div> <pre> <code data-trydotnet-mode="editor" data-trydotnet-region="region2" data-trydotnet-order="161"> public class EditableCode{ } <code> </pre> </div> </div> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2" data-trydotnet-order="159"> public class ClassAfter{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-region="region2" data-trydotnet-order="160"> public class AnotherClassAfter{ } <code> </pre> </body> </html>`, { url: configuration.hostOrigin, runScripts: "dangerously" }); let includes = extractIncludes(dom.window.document); expect(includes).not.to.be.null; expect(includes).not.to.be.undefined; expect(includes.global).not.to.be.undefined; expect(includes.global).not.to.be.null; let file = includes.global.files[0]; expect(file).not.to.be.null; includes.global.documents.length.should.be.equal(1); let documentOne = includes.global.documents[0]; expect(documentOne).not.to.be.null; documentOne.region.should.be.contain("region2[before]"); }); it("remmoves dom elements that are hidden", () => { let configuration = { hostOrigin: "https://docs.microsoft.com" }; let dom = new JSDOM( `<!DOCTYPE html> <html lang="en"> <body> <pre> <code data-trydotnet-mode="include" data-trydotnet-visibility="hidden"> public class Utility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-visibility="hidden"> public class AnotherUtility{ } <code> </pre> <pre> <code data-trydotnet-mode="include" data-trydotnet-session-id="sessionInclude", data-trydotnet-visibility="hidden"> public class AnotherUtilityWhyNot{ } <code> </pre> </body> </html>`, { url: configuration.hostOrigin, runScripts: "dangerously" }); let includes = extractIncludes(dom.window.document); expect(includes).not.to.be.null; let includeElements = dom.window.document.querySelectorAll( `pre>code[data-trydotnet-mode=${ tryDotNetModes[tryDotNetModes.include] }]` ); includeElements.length.should.be.equal(0); }); });
the_stack
import * as Fs from 'fs-extra'; import * as Tmp from 'tmp'; import { localStorage } from './local-storage'; import { Paths, resolveProject } from './paths'; import { Submodule } from './submodule'; import { freeText, pluckRemoteData, Utils } from './utils'; /** Contains general git utilities. */ const exec = Utils.exec; // This RegExp will help us pluck the versions in a conflict and solve it const conflict = /\n\s*<<<<<<< [^\n]+(\n(?:.|\n)+?)\n\s*=======(\n(?:.|\n)+?)\n\s*>>>>>>> [^\n]+/; function git(argv, options?) { return gitBody(Utils.git, argv, options); } const gitPrint = (git as any).print = (argv, options = {}) => { return gitBody(Utils.git.print, argv, options); }; // Create a compare link e.g. https://github.com/Urigo/WhatsApp/compare/xxxxxxx..xxxxxxx function reviewTutorial(remote: string, branch: string) { const remoteUrl = Git(['remote', 'get-url', remote]) let remoteData = pluckRemoteData(remoteUrl) if (process.env.NODE_ENV === 'test') { remoteData = { host: 'host', owner: 'owner', repo: 'repo' } } if (!remoteData) { throw Error('Provided remote is neither HTTP nor SSH') } const { host, owner, repo } = remoteData const checkoutDir = Tmp.dirSync({ unsafeCleanup: true }) const compareDir = Tmp.dirSync({ unsafeCleanup: true }) let compareUrl = `https://${host}/${owner}/${repo}` try { // This will contain a new branch with 2 commits: // The first commit represents the current branch and the second one represents the changed one Git(['init', compareDir.name]) // Create the commit for the current branch Fs.copySync(`${Utils.cwd()}/.git`, `${checkoutDir.name}/.git`) Git(['stash'], { cwd: checkoutDir.name }) Git(['fetch', remote], { cwd: checkoutDir.name }) Git(['checkout', `remotes/${remote}/${branch}`], { cwd: checkoutDir.name }) Fs.removeSync(`${checkoutDir.name}/.git`) Fs.moveSync(`${compareDir.name}/.git`, `${checkoutDir.name}/.git`) Git(['add', '.'], { cwd: checkoutDir.name }) Git(['commit', '-m', `Current ${branch}`], { cwd: checkoutDir.name }) Fs.moveSync(`${checkoutDir.name}/.git`, `${compareDir.name}/.git`) // Create the commit for the new branch Fs.copySync(`${Utils.cwd()}/.git`, `${checkoutDir.name}/.git`) Git(['stash'], { cwd: checkoutDir.name }) Git(['checkout', `refs/heads/${branch}`], { cwd: checkoutDir.name }) Fs.removeSync(`${checkoutDir.name}/.git`) Fs.moveSync(`${compareDir.name}/.git`, `${checkoutDir.name}/.git`) Git(['add', '.'], { cwd: checkoutDir.name }) try { Git(['commit', '-m', `New ${branch}`], { cwd: checkoutDir.name }) } catch (e) { throw Error('Remote and local branches are equal') } Fs.moveSync(`${checkoutDir.name}/.git`, `${compareDir.name}/.git`) // Prepare and push const currBranchHash = Git(['rev-list', '--max-parents=0', 'HEAD'], { cwd: compareDir.name }) const newBranchHash = Git(['rev-parse', 'HEAD'], { cwd: compareDir.name }) const compareBranch = `compare-${currBranchHash.slice(0, 7)}_${newBranchHash.slice(0, 7)}` Git(['checkout', '-b', compareBranch], { cwd: compareDir.name }) Git.print(['push', remoteUrl, compareBranch], { cwd: compareDir.name }) Git(['checkout', newBranchHash], { cwd: compareDir.name }) Git(['branch', '-D', compareBranch], { cwd: compareDir.name }) Git.print(['push', remoteUrl, `:refs/heads/${compareBranch}`], { cwd: compareDir.name }) compareUrl += `/compare/${currBranchHash}..${newBranchHash}` } finally { checkoutDir.removeCallback() compareDir.removeCallback() } return compareUrl } // Push a tutorial based on the provided branch. // e.g. given 'master' then 'master-history', 'master-root', 'master@0.1.0', etc, will be pushed. // Note that everything will be pushed by FORCE and will override existing refs within the remote function pushTutorial(remote: string, baseBranch: string) { const allBranches = git(['branch', '-l', '-a']) .split('\n') .map(b => b.split(/\*?\s+/).filter(Boolean)[0]) const relatedBranches = allBranches.map((branch) => { if (!branch) { return null; } const pathNodes = branch.split('/') const branchName = pathNodes.pop(); if (pathNodes[0] === 'remotes') { if (pathNodes[1] !== remote) { return; } // Local branch is more important than upstream branch // ie: master > remotes/origin/master if (allBranches.includes(branchName)) { return; } } if (branchName === baseBranch) { return branch; } if (branchName === `${baseBranch}-history`) { return branch; } if (branchName === `${baseBranch}-root`) { return branch; } if (new RegExp(`^${baseBranch}-step\\d+$`).test(branchName)) { return branch; } }).filter(Boolean); const relatedTags = git(['tag', '-l']).split('\n').map(tag => { if (!tag) { return null; } if (new RegExp(`^${baseBranch}@(\\d+\\.\\d+\\.\\d+|next)$`).test(tag)) { return tag; } if (new RegExp(`^${baseBranch}@root@(\\d+\\.\\d+\\.\\d+|next)$`).test(tag)) { return tag; } if (new RegExp(`^${baseBranch}@step\\d+@(\\d+\\.\\d+\\.\\d+|next)$`).test(tag)) { return tag; } }).filter(Boolean); const relatedBranchesNames = relatedBranches.map(b => b.split('/').pop()) const deletedBranches = git(['ls-remote', '--heads', remote]) .split('\n') .filter(Boolean) .map(line => line.split(/\s+/).pop()) .filter(ref => !relatedBranchesNames.includes(ref.split('/').pop())) .filter(ref => { const branch = ref.split('/').pop(); return ( branch === baseBranch || branch === `${baseBranch}-history` || branch === `${baseBranch}-root` || new RegExp(`^${baseBranch}-step\\d+$`).test(branch) ); }) // https://stackoverflow.com/questions/5480258/how-to-delete-a-remote-tag .map(ref => `:${ref}`); const deletedTags = git(['ls-remote', '--tags', remote]) .split('\n') .filter(Boolean) .map(line => line.split(/\s+/).pop()) .filter(ref => !relatedTags.includes(ref.split('/').pop())) .filter(ref => new RegExp(`^refs/tags/${baseBranch}@(\\d+\\.\\d+\\.\\d+|next)$`).test(ref) || new RegExp(`^refs/tags/${baseBranch}@root@(\\d+\\.\\d+\\.\\d+|next)$`).test(ref) || new RegExp(`^refs/tags/${baseBranch}@step\\d+@(\\d+\\.\\d+\\.\\d+|next)$`).test(ref) ) // https://stackoverflow.com/questions/5480258/how-to-delete-a-remote-tag .map(ref => `:${ref}`) const refs = [...relatedBranches, ...relatedTags, ...deletedBranches, ...deletedTags]; return gitPrint(['push','-f', remote, ...refs]); } // Pull a tutorial based on the provided branch. e.g. given 'master' then 'master-history', // 'master-root', 'master@0.1.0', etc, will be pulled. function pullTutorial(remote: string, baseBranch: string) { const relatedBranches = []; const relatedTags = []; git(['ls-remote', '--tags', '--heads', remote]).split('\n').forEach(line => { if (!line) { return; } const [, ref] = line.split(/\s+/); if ( new RegExp(`^refs/tags/${baseBranch}@(root|step-\\d+@)?(\\d+\\.\\d+\\.\\d+|next)$`).test(ref) ) { relatedTags.push(ref.split('/').slice(2).join('/')); } if ( new RegExp(`^refs/heads/${baseBranch}(-root|-history|-step\\d+)?$`).test(ref) ) { relatedBranches.push(ref.split('/').slice(2).join('/')); } }); const refs = [...relatedBranches, ...relatedTags]; const activeBranchName = Git.activeBranchName(); try { const sha1 = Git(['rev-parse', activeBranchName]); // Detach HEAD so we can change the reference of the branch Git(['checkout', sha1]); // --tags flag will overwrite tags gitPrint(['fetch', '--tags', '-f', remote, ...refs]); // Make sure that all local branches track the right remote branches relatedBranches.forEach(branch => { try { Git(['branch', '-D', branch]); } catch (e) { // Branch doesn't exist } Git.print(['branch', '--track', branch, `remotes/${remote}/${branch}`]); }); } finally { // Get back to where we were, regardless of the outcome Git(['checkout', activeBranchName]); } } // Used internally by tutorialStatus() to get the right step message function getRefStep(ref = 'HEAD') { if (getRootHash() === Git(['rev-parse', ref])) { return 'root'; } const match = Git(['log', ref, '-1', '--format=%s']).match(/^Step (\d+(?:\.\d+)?)/); if (match) { return match[1]; } return Git(['rev-parse', '--short', ref]); } // Print edit status followed by git-status function tutorialStatus(options: { instruct?: boolean } = {}) { Git.print(['status']); let instructions; position: if (isRebasing()) { const head = Git(['rev-parse', 'HEAD']); const rebaseHead = Git(['rev-parse', 'REBASE_HEAD']); const headStep = getRefStep('HEAD'); if (head === rebaseHead) { console.log(`\nEditing ${headStep}`); instructions = 'edit'; break position; } const rebaseHeadStep = getRefStep('REBASE_HEAD'); const isConflict = localStorage.getItem('REBASE_NEW_STEP') !== headStep; if (isConflict) { console.log(`\nSolving conflict between ${headStep} and ${rebaseHeadStep}`); instructions = 'conflict'; break position; } console.log(`\nBranched out from ${rebaseHeadStep} to ${headStep}`); instructions = 'edit'; } switch (options.instruct && instructions) { case 'edit': console.log('\n' + freeText(` To edit the current step, stage your changes and amend them: $ git add xxx $ git commit --amend Feel free to push or pop steps: $ tortilla step push/pop Once you finish, continue the rebase and Tortilla will take care of the rest: $ git rebase --continue You can go back to re-edit previous steps at any point, but be noted that this will discard all your changes thus far: $ tortilla step back If for some reason, at any point you decide to quit, use the comand: $ git rebase --abort `)) case 'conflict': console.log('\n' + freeText(` Once you solved the conflict, stage your changes and continue the rebase. DO NOT amend your changes, push or pop steps: $ git add xxx $ git rebase --continue You can go back to re-edit previous steps at any point, but be noted that this will discard all your changes thus far: $ tortilla step back If for some reason, at any point you decide to quit, use the comand: $ git rebase --abort `)) } } // The body of the git execution function, useful since we use the same logic both for // exec and spawn function gitBody(handler, argv, options) { options = { env: {}, ...options }; // Zeroing environment vars which might affect other executions options.env = { GIT_DIR: null, GIT_WORK_TREE: null, ...options.env }; return handler(argv, options); } // Tells if rebasing or not function isRebasing(path = null) { const paths = path ? resolveProject(path).git : Paths.git; return Utils.exists(paths.rebaseMerge) || Utils.exists(paths.rebaseApply); } // Tells if cherry-picking or not function isCherryPicking() { return Utils.exists(Paths.git.heads.cherryPick) || Utils.exists(Paths.git.heads.revert); } // Tells if going to amend or not function gonnaAmend() { return Utils.childProcessOf('git', ['commit', '--amend']); } // Tells if a tag exists or not function tagExists(tag) { try { git(['rev-parse', tag]); return true; } catch (err) { return false; } } // Get the recent commit by the provided arguments. An offset can be specified which // means that the recent commit from several times back can be fetched as well function getRecentCommit(offset, argv, options, path = null) { if (offset instanceof Array) { options = argv; argv = offset; offset = 0; } else { argv = argv || []; offset = offset || 0; } const hash = typeof offset === 'string' ? offset : (`HEAD~${offset}`); argv = ['log', hash, '-1'].concat(argv); return git(argv, path ? { ...options, cwd: path } : options); } // Gets a list of the modified files reported by git matching the provided pattern. // This includes untracked files, changed files and deleted files function getStagedFiles(pattern?) { const stagedFiles = git(['diff', '--name-only', '--cached']) .split('\n') .filter(Boolean); return Utils.filterMatches(stagedFiles, pattern); } // Gets active branch name function getActiveBranchName(path = null) { if (!isRebasing(path)) { return git(['rev-parse', '--abbrev-ref', 'HEAD'], path ? { cwd: path } : null); } // Getting a reference for the hash of which the rebase have started const branchHash = git(['reflog', '--format=%gd %gs'], path ? { cwd: path } : null) .split('\n') .filter(Boolean) .map((line) => line.split(' ')) .map((split) => [split.shift(), split.join(' ')]) .find(([ref, msg]) => msg.match(/^rebase -i \(start\)/)) .shift() .match(/^HEAD@\{(\d+)\}$/) .slice(1) .map((i) => `HEAD@{${++i}}`) .map((ref) => git(['rev-parse', ref])) .pop(); // Comparing the found hash to each of the branches' hashes return Fs.readdirSync(Paths.git.refs.heads).find((branchName) => { return git(['rev-parse', branchName], path ? { cwd: path } : null) === branchHash; }); } // Gets the root hash of HEAD function getRootHash(head = 'HEAD', options = {}) { return git(['rev-list', '--max-parents=0', head], options); } function getRoot() { try { return git(['rev-parse', '--show-toplevel']); // Not a git project } catch (e) { return ''; } } function edit(initialContent) { const editor = getEditor(); const file = Tmp.fileSync(); Fs.writeFileSync(file.name, initialContent); (exec as any).print('sh', ['-c', `${editor} ${file.name}`]); const content = Fs.readFileSync(file.name).toString(); file.removeCallback(); return content; } // https://github.com/git/git/blob/master/git-rebase--interactive.sh#L257 function getEditor() { let editor = process.env.GIT_EDITOR; if (!editor) { try { editor = git(['config', 'core.editor']); } catch (e) { // Ignore } } if (!editor) { try { editor = git(['var', 'GIT_EDITOR']); } catch (e) { // Ignore } } if (!editor) { throw Error('Git editor could not be found'); } return editor; } // Commander will split equal signs e.g. `--format=%H` which is is not the desired // behavior for git. This puts the everything back together when necessary function normalizeArgv(argv: string[]): string[] { argv = [...argv] { const i = argv.indexOf('--format') if (i !== -1) { argv.splice(i, 2, `--format=${argv[i + 1]}`) } } return argv } function getRevisionIdFromObject(object: string): string { return git(['rev-list', '-n', '1', object]); } function getCWD(module?) { let cwd = git(['rev-parse', '--show-toplevel']); // In case a submodule was specified then all our git commands should be executed // from that module if (module) { // Use the cloned repo that is used for development if (process.env.TORTILLA_SUBDEV) { cwd = Submodule.getCwd(module); } else { cwd = `${cwd}/${module}`; } } return cwd; } export const Git = Utils.extend(git.bind(null), git, { pushTutorial, pullTutorial, reviewTutorial, tutorialStatus, conflict, rebasing: isRebasing, cherryPicking: isCherryPicking, gonnaAmend, tagExists, recentCommit: getRecentCommit, stagedFiles: getStagedFiles, activeBranchName: getActiveBranchName, rootHash: getRootHash, root: getRoot, edit, editor: getEditor, normalizeArgv, getRevisionIdFromObject, getCWD });
the_stack
interface Sprite_Base { z, zIndex, layerId, } interface Tilemap { initialize(data?): void } interface ShaderTilemap { initialize(data?): void } let init = Tilemap.prototype.initialize; Tilemap.prototype.initialize = function (data) { this._data = data; init.call(this); } namespace PE { /** * Custom tilemap class for the Scene_Map */ export class Tiledmap extends ShaderTilemap { private _data: any; roundPixels: any; _needsRepaint: boolean; _animDuration: {}; _animFrame: {}; _priorityTilesCount: number; _priorityTiles: any[]; _layers: any[]; // constructor(data){ // // super(); // } initialize(data) { this._layers = []; this._priorityTiles = []; this._priorityTilesCount = 0; this._data = data; super.initialize(data); this.setupTiled(); } get data() { return this._data; } set data(val) { this._data = val; this.setupTiled(); } setupTiled() { this._setupSize(); this._setupAnim(); } _setupSize() { let width = this._width; let height = this._height; let margin = this._margin; let tileCols = Math.ceil(width / this._tileWidth) + 1; let tileRows = Math.ceil(height / this._tileHeight) + 1; this._tileWidth = this.data.tilewidth; this._tileHeight = this.data.tileheight; this._layerWidth = tileCols * this._tileWidth; this._layerHeight = tileRows * this._tileHeight; this._mapWidth = this.data.width; this._mapHeight = this.data.height; } _setupAnim() { this._animFrame = {}; this._animDuration = {}; } _createLayers() { let id = 0; this._needsRepaint = true; let useSquareShader = 0; for (let layerData of this.data.layers) { let zIndex = 0; if (layerData.type != "tilelayer") { id++; continue; } if (!!layerData.properties && !!layerData.properties.zIndex) { zIndex = parseInt(layerData.properties.zIndex); } if (!!layerData.properties && !!layerData.properties.collision) { id++; continue; } if (!!layerData.properties && !!layerData.properties.toLevel) { id++; continue; } if (!!layerData.properties && !!layerData.properties.regionId) { id++; continue; } let layer = new PIXI.tilemap.CompositeRectTileLayer(zIndex, [], useSquareShader); layer.layerId = id; // @dryami: hack layer index layer.spriteId = Sprite._counter++; this._layers.push(layer); this.addChild(layer); id++; } this._createPriorityTiles(); } _createPriorityTiles() { let size = 256 let zIndex = 5; for (let x of Utils.range(size)) { let sprite = new Sprite_Base(); sprite.z = sprite.zIndex = zIndex; sprite.layerId = -1; sprite.hide(); this.addChild(sprite); this._priorityTiles.push(sprite); } } _hackRenderer(renderer) { return renderer; } refreshTileset() { var bitmaps = this.bitmaps.map(function (x) { return x._baseTexture ? new PIXI.Texture(x._baseTexture) : x; }); for (let layer of this._layers) { layer.setBitmaps(bitmaps); } } update() { super.update(); this._updateAnim(); } _updateAnim() { let needRefresh = false; for (let key in this._animDuration) { this._animDuration[key] -= 1; if (this._animDuration[key] <= 0) { this._animFrame[key] += 1; needRefresh = true; } } if (needRefresh) { this.refresh(); } } _updateLayerPositions(startX, startY) { let ox = 0; let oy = 0; if (this.roundPixels) { ox = Math.floor(this.origin.x); oy = Math.floor(this.origin.y); } else { ox = this.origin.x; oy = this.origin.y; } for (let layer of this._layers) { let layerData = this.data.layers[layer.layerId]; let offsetX = layerData.offsetx || 0; let offsetY = layerData.offsety || 0; layer.position.x = startX * this._tileWidth - ox + offsetX; layer.position.y = startY * this._tileHeight - oy + offsetY; } for (let sprite of this._priorityTiles) { let layerData = this.data.layers[sprite.layerId]; let offsetX = layerData ? layerData.offsetx || 0 : 0; let offsetY = layerData ? layerData.offsety || 0 : 0; sprite.x = sprite.origX + startX * this._tileWidth - ox + offsetX + sprite.width / 2; sprite.y = sprite.origY + startY * this._tileHeight - oy + offsetY + sprite.height; } } _paintAllTiles(startX, startY) { this._priorityTilesCount = 0; for (let layer of this._layers) { layer.clear(); this._paintTiles(layer, startX, startY); } let id = 0; for (let layerData of this.data.layers) { if (layerData.type != "objectgroup") { id++; continue; } this._paintObjectLayers(id, startX, startY); id++; } while (this._priorityTilesCount < this._priorityTiles.length) { let sprite = this._priorityTiles[this._priorityTilesCount]; sprite.hide(); sprite.layerId = -1; this._priorityTilesCount++; } } _paintTiles(layer, startX, startY) { let layerData = this.data.layers[layer.layerId]; if (!layerData.visible) { return; } if (layerData.type == "tilelayer") { this._paintTilesLayer(layer, startX, startY); } } _paintObjectLayers(layerId, startX, startY) { let layerData = this.data.layers[layerId]; let objects = layerData.objects || []; for (let obj of objects) { if (!obj.gid) { continue; } if (!obj.visible) { continue; } let tileId = obj.gid; let textureId = this._getTextureId(tileId); let dx = obj.x - startX * this._tileWidth; let dy = obj.y - startY * this._tileHeight - obj.height; this._paintPriorityTile(layerId, textureId, tileId, startX, startY, dx, dy); } } _paintTilesLayer(layer, startX, startY) { let tileCols = Math.ceil(this._width / this._tileWidth) + 1; let tileRows = Math.ceil(this._height / this._tileHeight) + 1; for (let y of Utils.range(tileRows)) { for (let x of Utils.range(tileCols)) { this._paintTile(layer, startX, startY, x, y); } } } _paintTile(layer, startX, startY, x, y) { let mx = x + startX; let my = y + startY; if (this.horizontalWrap) { mx = mx.mod(this._mapWidth); } if (this.verticalWrap) { my = my.mod(this._mapHeight); } let tilePosition = mx + my * this._mapWidth; let tileId = this.data.layers[layer.layerId].data[tilePosition]; let rectLayer = layer.children[0]; let textureId = 0; if (!tileId) { return; } // TODO: Problem with offsets if (mx < 0 || mx >= this._mapWidth || my < 0 || my >= this._mapHeight) { return; } textureId = this._getTextureId(tileId); let tileset = this.data.tilesets[textureId]; let dx = x * this._tileWidth; let dy = y * this._tileHeight; let w = tileset.tilewidth; let h = tileset.tileheight; let tileCols = tileset.columns; let rId = this._getAnimTileId(textureId, tileId - tileset.firstgid); let ux = (rId % tileCols) * w; let uy = Math.floor(rId / tileCols) * h; if (this._isPriorityTile(layer.layerId)) { this._paintPriorityTile(layer.layerId, textureId, tileId, startX, startY, dx, dy); return; } rectLayer.addRect(textureId, ux, uy, dx, dy, w, h); } _paintPriorityTile(layerId, textureId, tileId, startX, startY, dx, dy) { let tileset = this.data.tilesets[textureId]; let w = tileset.tilewidth; let h = tileset.tileheight; let tileCols = tileset.columns; let rId = this._getAnimTileId(textureId, tileId - tileset.firstgid); let ux = (rId % tileCols) * w; let uy = Math.floor(rId / tileCols) * h; let sprite = this._priorityTiles[this._priorityTilesCount]; let layerData = this.data.layers[layerId]; let offsetX = layerData ? layerData.offsetx || 0 : 0; let offsetY = layerData ? layerData.offsety || 0 : 0; let ox = 0; let oy = 0; if (this.roundPixels) { ox = Math.floor(this.origin.x); oy = Math.floor(this.origin.y); } else { ox = this.origin.x; oy = this.origin.y; } if (this._priorityTilesCount >= this._priorityTiles.length) { return; } sprite.layerId = layerId; sprite.anchor.x = 0.5; sprite.anchor.y = 1.0; sprite.origX = dx; sprite.origY = dy; sprite.x = sprite.origX + startX * this._tileWidth - ox + offsetX + w / 2; sprite.y = sprite.origY + startY * this._tileHeight - oy + offsetY + h; sprite.bitmap = this.bitmaps[textureId]; sprite.setFrame(ux, uy, w, h); sprite.priority = this._getPriority(layerId); sprite.z = sprite.zIndex = this._getZIndex(layerId); sprite.show(); this._priorityTilesCount += 1; } _getTextureId(tileId) { let textureId = 0; for (let tileset of this.data.tilesets) { if (tileId < tileset.firstgid || tileId >= tileset.firstgid + tileset.tilecount) { textureId++; continue; } break; } return textureId; } _getAnimTileId(textureId, tileId) { let tilesData = this.data.tilesets[textureId].tiles; if (!tilesData) return tileId; if (!tilesData[tileId]) return tileId; if (!tilesData[tileId].animation) return tileId; let animation = tilesData[tileId].animation; this._animFrame[tileId] = this._animFrame[tileId] || 0; let frame = this._animFrame[tileId]; this._animFrame[tileId] = !!animation[frame] ? frame : 0; frame = this._animFrame[tileId]; let duration = animation[frame].duration / 1000 * 60; this._animDuration[tileId] = this._animDuration[tileId] || duration; if (this._animDuration[tileId] <= 0) this._animDuration[tileId] = duration; return animation[frame].tileid; } _getPriority(layerId) { let layerData = this.data.layers[layerId]; if (!layerData.properties) return 0; if (!layerData.properties.priority) return 0; return parseInt(layerData.properties.priority) } _isPriorityTile(layerId) { let playerZIndex = 3; let zIndex = this._getZIndex(layerId); return this._getPriority(layerId) > 0 && zIndex === playerZIndex; } _getZIndex(layerId) { let layerData = this.data.layers[layerId]; if (!layerData) { return 0; } if (!layerData.properties || !layerData.properties.zIndex) { return 0; } return parseInt(layerData.properties.zIndex); } hideOnLevel(level) { let layerIds = []; for (let layer of this._layers) { let layerData = this.data.layers[layer.layerId]; if (layerData.properties && layerData.properties.hasOwnProperty("hideOnLevel")) { if (parseInt(layerData.properties.hideOnLevel) !== level) { this.addChild(layer); continue; } layerIds.push(layer.layerId); this.removeChild(layer); } } for (let sprite of this._priorityTiles) { if (layerIds.indexOf(sprite.layerId) === -1) { continue; } sprite.visible = false; } } _compareChildOrder(a, b) { if ((a.z || 0) !== (b.z || 0)) { return (a.z || 0) - (b.z || 0); } else if ((a.y || 0) !== (b.y || 0)) { return (a.y || 0) - (b.y || 0); } else if ((a.priority || 0) !== (b.priority || 0)) { return (a.priority || 0) - (b.priority || 0); } else { return a.spriteId - b.spriteId; } } } } //====================================================================================================================== //DataManager, Overwrite maps data load functions interface DataManagerStatic { _tempTiledData: any, _tiledLoaded: boolean, loadTiledMapData(mapId: number): void, unloadTiledMapData(): void, loadTilesetFromSource(source: string, callback: any) } DataManager._tempTiledData = null; DataManager._tiledLoaded = false; let alias_DataManager_loadMapData = DataManager.loadMapData; DataManager.loadMapData = function (mapId) { alias_DataManager_loadMapData.call(this, mapId); if (mapId > 0) { this.loadTiledMapData(mapId); } else { this.unloadTiledMapData(); } }; DataManager.loadTiledMapData = function (mapId) { var xhr = new XMLHttpRequest(); var filename = "./maps/map" + mapId + ".json"; xhr.open('GET', filename); xhr.overrideMimeType('application/json'); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.responseText !== "") { DataManager._tempTiledData = JSON.parse(xhr.responseText); } else { throw new Error(`Map Loading Error: couldn't find file ${filename}`) } DataManager._tiledLoaded = true; } }; try { this.unloadTiledMapData(); xhr.send(); } catch (err) { this.unloadTiledMapData(); } }; DataManager.unloadTiledMapData = function () { DataManager._tempTiledData = null; DataManager._tiledLoaded = false; }; let alias_DataManager_isMapLoaded = DataManager.isMapLoaded; DataManager.isMapLoaded = function () { let defaultLoaded = alias_DataManager_isMapLoaded.call(this); let tiledLoaded = DataManager._tiledLoaded; return defaultLoaded && tiledLoaded; }; DataManager.loadTilesetFromSource = function (source, callback) { var xhr = new XMLHttpRequest(); var filepath = source; var filepathParts = filepath.split('/'); var filename = filepathParts[filepathParts.length - 1]; var path = "./img/tilesets/" + filename; xhr.open('GET', path); xhr.overrideMimeType('application/json'); // on success callback xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200 || xhr.responseText !== "") { callback(JSON.parse(xhr.responseText)); } else { throw new Error('Map Loading error on tileset: \'' + source + '\''); } } }; xhr.send(); } //====================================================================================================================== //====================================================================================================================== // ImageManager, add tileset load function interface ImageManagerStatic { loadParserTileset(path: string, hue: any): void } ImageManager.loadParserTileset = function (path, hue) { if (!path) return this.loadEmptyBitmap(); let paths = path.split("/"); let filename = paths[paths.length - 1]; let realPath = "img/tilesets/" + filename; return this.loadNormalBitmap(realPath, hue); }; //====================================================================================================================== //====================================================================================================================== // Game_CharacterBase, Overwrite zdeep and move distance functions Game_CharacterBase.prototype.screenZ = function () { if (this._priorityType == 0) return 1; if (this._priorityType == 2) return 5; return 3; }; let alias_Game_CharacterBase_distancePerFrame = Game_CharacterBase.prototype.distancePerFrame; Game_CharacterBase.prototype.distancePerFrame = function () { let distance = alias_Game_CharacterBase_distancePerFrame.call(this); return distance * (48 / Math.min($gameMap.tileWidth(), $gameMap.tileHeight())); }; //====================================================================================================================== //====================================================================================================================== // #region Game_Map, Ovewrite Game_Map object to use custom Tiledmap class interface Game_Map { tiledData: any currentMapLevel, isTiledMap(): boolean, _setupTiled(): void, _initializeMapLevel(id): void, _setupCollision(): void, _setupCollisionFull(): any, _setupCollisionArrow(): any, _setupRegion(): void, _setupMapLevelChange(): void, _setupTiledEvents(): void, isHalfTile(): void, checkMapLevelChanging(x, y), _getTextureId(tileId), checkTilePropertie(index, attr), getTilePropertie(index, attr), tilaHasPropertie(index, attr), } Object.defineProperty(Game_Map.prototype, 'tiledData', { get: function () { return DataManager._tempTiledData; }, configurable: true }); Object.defineProperty(Game_Map.prototype, 'currentMapLevel', { get: function () { let pluginParams = PluginManager.parameters("YED_Tiled"); let varID = 23; if (!varID) { return this._currentMapLevel; } else { return $gameVariables.value(varID); } }, set: function (value) { let pluginParams = PluginManager.parameters("YED_Tiled"); let varID = 23; if (!varID) { this._currentMapLevel = value; } else { $gameVariables.setValue(varID, value); } }, configurable: true }); let alias_Game_Map_setup = Game_Map.prototype.setup; Game_Map.prototype.setup = function (mapId) { alias_Game_Map_setup.call(this, mapId); this._collisionMap = []; this._arrowCollisionMap = []; this._regions = []; this._mapLevelChange = []; this._currentMapLevel = 0; this.currentMapLevel = 0; if (this.isTiledMap()) { $dataMap.width = this.tiledData.width; $dataMap.height = this.tiledData.height; this._setupTiled(); } }; Game_Map.prototype.isTiledMap = function () { return !!this.tiledData; }; Game_Map.prototype._setupTiled = function () { this._initializeMapLevel(0); this._setupCollision(); this._setupRegion(); this._setupMapLevelChange(); this._setupTiledEvents(); }; Game_Map.prototype._initializeMapLevel = function (id) { let width = this.width(); let height = this.height(); let size = width * height; if (!!this._collisionMap[id]) return; this._collisionMap[id] = []; this._arrowCollisionMap[id] = []; this._regions[id] = []; this._mapLevelChange[id] = []; for (let x of PE.Utils.range(size)) { this._collisionMap[id].push(0); this._arrowCollisionMap[id].push(1 | 2 | 4 | 8); this._regions[id].push(0); this._mapLevelChange[id].push(-1); } }; Game_Map.prototype._setupCollision = function () { this._setupCollisionFull(); this._setupCollisionArrow(); }; Game_Map.prototype._setupCollisionFull = function () { let width = this.width(); let height = this.height(); let size = width * height; let halfWidth = width / 2; let halfHeight = height / 2; if (this.isHalfTile()) size /= 4; for (let layerData of this.tiledData.layers) { if (!layerData.properties || !layerData.properties.collision) continue; if (layerData.properties.collision !== "full" && layerData.properties.collision !== "up-left" && layerData.properties.collision !== "up-right" && layerData.properties.collision !== "down-left" && layerData.properties.collision !== "down-right") { continue; } let level = parseInt(layerData.properties.level) || 0; this._initializeMapLevel(level); for (let x of PE.Utils.range(size)) { let realX = x; let ids = []; if (this.isHalfTile()) { realX = Math.floor(x / halfWidth) * width * 2 + (x % halfWidth) * 2; } if (!!layerData.data[x]) { if (layerData.properties.collision === "full") { ids.push(realX); if (this.isHalfTile()) { ids.push(realX + 1, realX + width, realX + width + 1); } } if (layerData.properties.collision === "up-left") { ids.push(realX); } if (layerData.properties.collision === "up-right") { ids.push(realX + 1); } if (layerData.properties.collision === "down-left") { ids.push(realX + width); } if (layerData.properties.collision === "down-right") { ids.push(realX + width + 1); } for (let id of ids) { this._collisionMap[level][id] = 1; } } } } }; Game_Map.prototype._setupCollisionArrow = function () { let width = this.width(); let height = this.height(); let size = width * height; let bit = 0; let halfWidth = width / 2; let halfHeight = height / 2; if (this.isHalfTile()) size /= 4; for (let layer of this.tiledData.layers) { if (!layer.properties || !layer.properties.collisions) continue; let level = 0; this._initializeMapLevel(level); let arrowCollisionMap = this._arrowCollisionMap[level]; for (let x of PE.Utils.range(size)) { let realX = x; // if (this.isHalfTile()) { // realX = Math.floor(x / halfWidth) * width * 2 + (x % halfWidth) * 2; // } if (this.tilaHasPropertie(x, 'collideLeft')) bit = 1; if (this.tilaHasPropertie(x, 'collideUp')) bit = 2; if (this.tilaHasPropertie(x, 'collideRight')) bit = 4; if (this.tilaHasPropertie(x, 'collideDown')) bit = 8; if (!!layer.data[x]) { arrowCollisionMap[realX] = arrowCollisionMap[realX] ^ bit; // if (this.isHalfTile()) { // arrowCollisionMap[realX + 1] = arrowCollisionMap[realX + 1] ^ bit; // arrowCollisionMap[realX + width] = arrowCollisionMap[realX + width] ^ bit; // arrowCollisionMap[realX + width + 1] = arrowCollisionMap[realX + width + 1] ^ bit; // } } this._arrowCollisionMap[level] = arrowCollisionMap; } } }; Game_Map.prototype._setupRegion = function () { let width = this.width(); let height = this.height(); let size = width * height; let halfWidth = width / 2; let halfHeight = height / 2; if (this.isHalfTile()) size /= 4; for (let layerData of this.tiledData.layers) { if (!layerData.properties || !layerData.properties.regionId) { continue; } let level = parseInt(layerData.properties.level) || 0; this._initializeMapLevel(level); let regionMap = this._regions[level]; for (let x of PE.Utils.range(size)) { let realX = x; if (this.isHalfTile()) { realX = Math.floor(x / halfWidth) * width * 2 + (x % halfWidth) * 2; } if (!!layerData.data[x]) { var properties = this.getTilePropertie(x, function (properties) { return properties; }); regionMap[realX] = parseInt(properties.region); if (this.isHalfTile()) { regionMap[realX + 1] = parseInt(properties.region); regionMap[realX + width] = parseInt(properties.region); regionMap[realX + width + 1] = parseInt(properties.region); } } } } }; Game_Map.prototype._setupMapLevelChange = function () { let width = this.width(); let height = this.height(); let size = width * height; let halfWidth = width / 2; let halfHeight = height / 2; if (this.isHalfTile()) size /= 4; for (let layerData of this.tiledData.layers) { if (!layerData.properties || !layerData.properties.toLevel) continue; let level = parseInt(layerData.properties.level) || 0; this._initializeMapLevel(level); let levelChangeMap = this._mapLevelChange[level]; for (let x of PE.Utils.range(size)) { let realX = x; let toLevel = parseInt(layerData.properties.toLevel); if (this.isHalfTile()) { realX = Math.floor(x / halfWidth) * width * 2 + (x % halfWidth) * 2; } if (!!layerData.data[x]) { levelChangeMap[realX] = toLevel; if (this.isHalfTile()) { levelChangeMap[realX + 1] = toLevel; levelChangeMap[realX + width] = toLevel; levelChangeMap[realX + width + 1] = toLevel; } } } } }; Game_Map.prototype._setupTiledEvents = function () { for (let layerData of this.tiledData.layers) { if (layerData.type !== "objectgroup") continue; for (let object of layerData.objects) { if (!object.properties) continue; if (!object.properties.eventId) continue; let eventId = parseInt(object.properties.eventId); let event = this._events[eventId]; if (!event) continue; let x = Math.floor(object.x / this.tileWidth()); let y = Math.floor(object.y / this.tileHeight()); if (this.isHalfTile()) { x += 1; y += 1; } event.locate(x, y); } } }; // Game_Map.prototype.setupEvents = function () { // this._events = []; // for (var i = 0; i < $dataEvents[this._mapId].length; i++) { // if ($dataEvents[this._mapId][i]) { // this._events[i] = new Game_Event(this._mapId, i); // } // } // this._commonEvents = this.parallelCommonEvents().map(function (commonEvent) { // return new Game_CommonEvent(commonEvent.id); // }); // this.refreshTileEvents(); // }; Game_Map.prototype.isHalfTile = function () { return false; }; Game_Map.prototype.tileWidth = function () { let tileWidth = this.tiledData.tilewidth; if (this.isHalfTile()) tileWidth /= 2; return tileWidth; }; Game_Map.prototype.tileHeight = function () { let tileHeight = this.tiledData.tileheight; if (this.isHalfTile()) tileHeight /= 2; return tileHeight; }; Game_Map.prototype.width = function () { let width = this.tiledData.width; if (this.isHalfTile()) width *= 2; return width; }; Game_Map.prototype.height = function () { let height = this.tiledData.height; if (this.isHalfTile()) height *= 2; return height; }; let _regionId = Game_Map.prototype.regionId; Game_Map.prototype.regionId = function (x, y) { if (!this.isTiledMap()) return _regionId.call(this, x, y); let index = x + this.width() * y; let regionMap = this._regions[this.currentMapLevel]; return regionMap[index]; }; let alias_Game_Map_isPassable = Game_Map.prototype.isPassable; Game_Map.prototype.isPassable = function (x, y, d) { if (!this.isTiledMap()) { return alias_Game_Map_isPassable.call(this, x, y, d); } let index = x + this.width() * y; let arrows = this._arrowCollisionMap[this.currentMapLevel]; if (this.tilaHasPropertie(index, 'collide')) return false; if (d === 6 && (this.tilaHasPropertie(index, 'collideLeft'))) return false; if (d === 2 && (this.tilaHasPropertie(index, 'collideUp'))) return false; if (d === 4 && (this.tilaHasPropertie(index, 'collideRight'))) return false; if (d === 8 && (this.tilaHasPropertie(index, 'collideDown'))) return false; return this._collisionMap[this.currentMapLevel][index] === 0; }; Game_Map.prototype.checkMapLevelChanging = function (x, y) { let mapLevelChange = this._mapLevelChange[this.currentMapLevel]; let id = y * this.width() + x; if (mapLevelChange[id] < 0) return false; this.currentMapLevel = mapLevelChange[id]; return true; }; Game_Map.prototype._getTextureId = function (tileId) { var textureId = 0; for (var tileset of this.tiledData.tilesets) { if (tileId < tileset.firstgid || tileId >= tileset.firstgid + tileset.tilecount) { textureId++; continue; } break; } return textureId; } // Game_Map.prototype.getTilePropertie = function (index, attr) { // var layers = this.tiledData.layers; // // start at the top (layers on top trump layers on bottom) // for (const layer of layers) { // if (!layer.properties || !layer.properties.collisions) continue; // var tileId = layer.data[index]; // if (tileId <= 0) continue; // var textureId = this._getTextureId(tileId); // if (!textureId) continue; // var localTileId = tileId - this.tiledData.tilesets[textureId].firstgid; // if (!this.tiledData.tilesets[textureId].tileproperties) continue; // var properties = this.tiledData.tilesets[textureId].tileproperties[localTileId]; // if (properties && properties[attr]) { // return properties[attr]; // } // } // return null; // } Game_Map.prototype.getTilePropertie = function (tileId, attr) { if (tileId <= 0) return null; var textureId = this._getTextureId(tileId); if (!textureId) return null; 6 var localTileId = tileId - this.tiledData.tilesets[textureId].firstgid; if (!this.tiledData.tilesets[textureId].tileproperties) return null; var properties = this.tiledData.tilesets[textureId].tileproperties[localTileId]; if (properties && properties[attr]) { return properties[attr]; } return null; } Game_Map.prototype.tilaHasPropertie = function (index, propertie) { for (const layer of this.tiledData.layers) { if (!layer.properties || !layer.properties.collisions) continue; let result = this.getTilePropertie(layer.data[index], propertie); if (!result || result === "false") return false; return true; } return false; } Game_Map.prototype.checkTilePropertie = function (index, attr) { let propertie = this.getTilePropertie(index, attr); if (!propertie || propertie === "false") return false; return true; } Game_Map.prototype.isBush = function (x, y) { var index = x + this.width() * y; return this.isValid(x, y) && this.checkTilePropertie(index, "bush"); }; Game_Map.prototype.terrainTag = function (x, y) { var index = x + this.width() * y; if (this.isValid(x, y)) { var terrainTag = this.getTilePropertie(index, "terrainTag"); if (terrainTag) return terrainTag; } return 0; } // #endregion //====================================================================================================================== //====================================================================================================================== // Game_Event, use the new $dataEvents to get th map events // Game_Event.prototype.event = function () { // return $dataEvents[this._mapId][this._eventId]; // }; //====================================================================================================================== //====================================================================================================================== // Game_Player, Add auto level changing interface Game_Player { _checkMapLevelChangingHere(): void } let alias_Game_Player_checkEventTriggerHere = Game_Player.prototype.checkEventTriggerHere; Game_Player.prototype.checkEventTriggerHere = function (triggers) { alias_Game_Player_checkEventTriggerHere.call(this, triggers); this._checkMapLevelChangingHere(); }; Game_Player.prototype._checkMapLevelChangingHere = function () { $gameMap.checkMapLevelChanging(this.x, this.y); }; //====================================================================================================================== //====================================================================================================================== // Spriteset_Map, Overwrite Spriteset_Map to use custom Tilemap class interface Spriteset_Map { _updateHideOnLevel(): void } let alias_Spriteset_Map_createTilemap = Spriteset_Map.prototype.createTilemap; Spriteset_Map.prototype.createTilemap = function () { if (!$gameMap.isTiledMap()) { alias_Spriteset_Map_createTilemap.call(this); return; } this._tilemap = new PE.Tiledmap($gameMap.tiledData); this._tilemap.horizontalWrap = $gameMap.isLoopHorizontal(); this._tilemap.verticalWrap = $gameMap.isLoopVertical(); this.loadTileset(); this._baseSprite.addChild(this._tilemap); }; let alias_Spriteset_Map_loadTileset = Spriteset_Map.prototype.loadTileset; Spriteset_Map.prototype.loadTileset = function () { if (!$gameMap.isTiledMap()) { alias_Spriteset_Map_loadTileset.call(this); return; } let i = 0; let tilesets = []; for (let tileset of $gameMap.tiledData.tilesets) { if (tileset.image) { this._tilemap.bitmaps[i] = ImageManager.loadParserTileset(tileset.image, 0); i++; } else { DataManager.loadTilesetFromSource(tileset.source, function (data) { Object.assign(tileset, data); $gameMap._setupCollision(); }); } tilesets.push(tileset); } this._tilemap.refreshTileset(); this._tileset = tilesets; }; let alias_Spriteset_Map_update = Spriteset_Map.prototype.update; Spriteset_Map.prototype.update = function () { alias_Spriteset_Map_update.call(this); this._updateHideOnLevel(); }; Spriteset_Map.prototype.updateTileset = function () { if (this._tileset !== $gameMap.tiledData.tilesets) { this.loadTileset(); } }; Spriteset_Map.prototype._updateHideOnLevel = function () { this._tilemap.hideOnLevel($gameMap.currentMapLevel); }; //====================================================================================================================== Game_CharacterBase.prototype.isMapPassable = function (x, y, d) { var x2 = $gameMap.roundXWithDirection(x, d); var y2 = $gameMap.roundYWithDirection(y, d); var d2 = this.reverseDir(d); return $gameMap.isPassable(x2, y2, d2); };
the_stack
const { ccclass, property } = cc._decorator; //材质球可设置的属性: const diffuseTexture = "diffuseTexture"; const startColor = "startColor"; const endColor = "endColor"; /** * 拖尾特效。 * * 使用方法: * 先 init 初始化(可以添加方法 onload ,直接调用 init,这里的 init reset 是为了适配我的框架写的),再 setShape 设置横截面形状; * * 其他属性如柔软度、起始颜色、纹理等,可在属性面板中设置,也可以通过代码设置; * * 请尽量在设置横截面之前将曲面细分等级设置好,并避免在运行过程中修改细分等级,因为设置细分等级后,需要重新设置网格的顶点数据。 * * 怎样让它动起来呢: * * (一) * 由update方法自动更新时,将挂载本脚本的节点与要跟随的目标节点放在同一父节点下,拖尾节点坐标(0,0,0),角度(0,0,0); * 设置跟随的目标节点,跟随目标节点的位置偏移; * * 注:默认的 update 方法已注释掉!要使用它请自行取消注释(在最底部)。 * * (二) * 自行使用代码更新时,将挂载本脚本的节点放置在3D场景根节点下,坐标(0,0,0),角度(0,0,0), * 通过方法 moveTo 设置拖尾头部的世界坐标即可。 * * 注: * 需要设置拖尾横截面形状才能看到曲面; * */ @ccclass export default class TrailEffect extends cc.Component { @property(cc.MeshRenderer) protected meshRenderer: cc.MeshRenderer = null; protected mesh: cc.Mesh = null; protected mat: cc.Material = null; protected initMat() { this.mat = this.meshRenderer.getMaterial(0); let c = [this.startColor.r / 255, this.startColor.g / 255, this.startColor.b / 255, this.startColor.a / 255]; this.mat.setProperty(startColor, c); c = [this.endColor.r / 255, this.endColor.g / 255, this.endColor.b / 255, this.endColor.a / 255]; this.mat.setProperty(endColor, c); if (!!this.diffuseTexture) { this.mat.setProperty(diffuseTexture, this.diffuseTexture); } } @property({ type: cc.Texture2D }) protected diffuseTexture: cc.Texture2D = null; /**设置拖尾纹理 */ public setTexture(t: cc.Texture2D) { this.diffuseTexture = t; this.mat.setProperty(diffuseTexture, this.diffuseTexture); } @property(cc.Color) protected startColor: cc.Color = cc.Color.WHITE; /**设置拖尾头部的颜色及透明度 */ public setStartColor(color: cc.Color) { if (this.startColor.equals(color)) return; this.startColor.set(color); if (!!this.mat) { let c = [this.startColor.r / 255, this.startColor.g / 255, this.startColor.b / 255, this.startColor.a / 255]; this.mat.setProperty(startColor, c); } } @property(cc.Color) protected endColor: cc.Color = cc.color(255, 255, 255, 0); /**设置拖尾尾部的颜色及透明度 */ public setEndColor(color: cc.Color) { if (this.endColor.equals(color)) return; this.endColor.set(color); if (!!this.mat) { let c = [this.endColor.r / 255, this.endColor.g / 255, this.endColor.b / 255, this.endColor.a / 255]; this.mat.setProperty(endColor, c); } } /**Z轴方向的曲面细分等级 */ @property(cc.Integer) protected level: number = 5; /**设置Z轴方向的曲面细分等级 */ public setLevel(level: number) { if (this.level === level || level <= 0) return; this.level = level; if (this.polygon.length > 0) { cc.warn("提示:修改细分等级后,将重新设置拖尾的顶点数据,请尽量在设置横截面之前设置好细分等级,并避免频繁修改。"); this.createVerts(); this.createMesh(); } } @property(cc.Integer) /**拖尾的柔软度,值越大尾巴越柔软 */ protected soft: number = 5; /**设置拖尾的柔软度,值越大尾巴越柔软,拉伸的越长,默认值为5 */ public setSoft(soft: number) { if (this.soft === soft || soft <= 0) return; this.soft = soft; } /**是否跟随目标节点的角度 */ @property(cc.Boolean) protected followAngle: boolean = false; /**拖尾头部的坐标 */ protected startPosition: cc.Vec3 = cc.v3(); protected initPosition() { this.startPosition = cc.v3(); } /**网格顶点数据 */ protected verts: cc.Vec3[] = []; /**拖尾横截面的顶点坐标x、y,按逆时针排列 */ @property({ type: [cc.Vec2], tooltip: "拖尾的横截面多边形的顶点坐标,该横截面为从 cc.v3(0, 0, 1) 位置看向XY平面时的形状,顶点坐标按逆时针排列,建议通过setShape在代码中设置。" }) protected polygon: cc.Vec2[] = []; /**横截面是否为闭合的多边形 */ @property({ tooltip: "横截面是否为闭合的多边形" }) protected polygonClosed: boolean = false; protected initPolygon() { this.polygon = []; } protected resetPolygon() { this.polygon = []; this.polygonClosed = false; } /** * 设置拖尾的横截面多边形的顶点坐标,该横截面为从 cc.v3(0, 0, 1) 位置看向XY平面时的形状,顶点坐标按逆时针排列 * @param polygon 顶点坐标数组 * @param close 是否闭合的多边形 */ public setShape(polygon: cc.Vec2[], close: boolean = false) { this.polygon = [].concat(polygon); this.polygonClosed = !!close; this.createVerts(); this.createMesh(); } /**根据截面形状和拖尾位置创建网格顶点 */ protected createVerts() { //顶点的Z轴偏移为0 this.verts = []; let nPolygon = this.polygon.length; if (nPolygon > 2 && this.polygonClosed) { for (let i = 0; i <= this.level; ++i) { for (let j = 0; j < nPolygon; ++j) { this.verts.push(cc.v3(this.polygon[j].x, this.polygon[j].y, 0).addSelf(this.startPosition)); } this.verts.push(cc.v3(this.polygon[0].x, this.polygon[0].y, 0).addSelf(this.startPosition)); } } else { for (let i = 0; i <= this.level; ++i) { for (let j = 0; j < nPolygon; ++j) { this.verts.push(cc.v3(this.polygon[j].x, this.polygon[j].y, 0).addSelf(this.startPosition)); } } } } /**创建网格数据 */ protected createMesh() { // let gfx = cc.renderer.renderEngine.gfx; let gfx = cc.gfx; // 定义顶点数据格式,只需要指明所需的属性,避免造成存储空间的浪费 var vfmtPosColor = new gfx.VertexFormat([ // 用户需要创建一个三维的盒子,所以需要三个值来保存位置信息 { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3 }, { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2 }, { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, normalize: true }, ]); this.mesh = new cc.Mesh(); this.meshRenderer.mesh = this.mesh; let mesh = this.mesh; // 初始化网格信息 mesh.init(vfmtPosColor, this.verts.length, true); // 修改 position 顶点数据 mesh.setVertices(gfx.ATTR_POSITION, this.verts); // 修改 color 顶点数据 let colors = []; for (let i = 0, c = this.verts.length; i < c; ++i) { colors.push(cc.Color.WHITE); } mesh.setVertices(gfx.ATTR_COLOR, colors); // 修改 uv 顶点数据 let uv: cc.Vec2[] = []; let nPolygon = this.polygon.length; if (nPolygon > 2 && this.polygonClosed) { for (let i = 0; i <= this.level; ++i) { let uv_x = 1 - i / this.level; for (let j = 0; j <= nPolygon; ++j) { uv.push(cc.v2(uv_x, j / nPolygon)); } } } else { for (let i = 0; i <= this.level; ++i) { let uv_x = 1 - i / this.level; for (let j = 0; j < nPolygon; ++j) { uv.push(cc.v2(uv_x, j / nPolygon)); } } } mesh.setVertices(gfx.ATTR_UV0, uv); // 修改索引数据 let frag: number[] = []; if (nPolygon > 2 && this.polygonClosed) { let p2 = nPolygon + 1; let p3 = nPolygon + 2; for (let i = 0; i < this.level; ++i) { for (let j = 0; j < nPolygon; ++j) { let index = i * nPolygon + i + j; frag.push(index, index + 1, index + p3); frag.push(index, index + p3, index + p2); } } } else { let p2 = nPolygon; let p3 = nPolygon + 1; let maxJ = nPolygon - 2; for (let i = 0; i < this.level; ++i) { for (let j = 0; j <= maxJ; ++j) { let index = i * nPolygon + j; frag.push(index, index + 1, index + p3); frag.push(index, index + p3, index + p2); } } } mesh.setIndices(frag); } protected resetMesh() { let nPolygon = this.polygon.length; if (nPolygon > 2 && this.polygonClosed) { for (let i = 0; i <= this.level; ++i) { for (let j = 0; j < nPolygon; ++j) { this.verts[i * nPolygon + i + j].set(cc.v3(this.polygon[j].x, this.polygon[j].y, 0).addSelf(this.startPosition)); } this.verts[i * nPolygon + i + nPolygon].set(cc.v3(this.polygon[0].x, this.polygon[0].y, 0).addSelf(this.startPosition)); } } else { for (let i = 0; i <= this.level; ++i) { for (let j = 0; j < nPolygon; ++j) { this.verts[i * nPolygon + j].set(cc.v3(this.polygon[j].x, this.polygon[j].y, 0).addSelf(this.startPosition)); } } } let gfx = cc.gfx; this.mesh.setVertices(gfx.ATTR_POSITION, this.verts); } /**更新网格形状 */ protected updateMesh() { let rate = this.soft == 0 ? 0.2 : (1 / this.soft); let nPolygon = this.polygon.length; if (nPolygon > 2 && this.polygonClosed) { let offset = nPolygon + 1; for (let i = 1; i <= this.level; ++i) { let index = i * offset; for (let j = 0; j <= nPolygon; ++j) { let previousVert = this.verts[index - offset + j]; let nextVert = this.verts[index + j]; this.interpolationPos(nextVert, previousVert, rate); } } } else { let offset = nPolygon; for (let i = 1; i <= this.level; ++i) { let index = i * offset; for (let j = 0; j < nPolygon; ++j) { let previousVert = this.verts[index - offset + j]; let nextVert = this.verts[index + j]; this.interpolationPos(nextVert, previousVert, rate); } } } let gfx = cc.gfx; this.mesh.setVertices(gfx.ATTR_POSITION, this.verts); } protected getInterpplation(a: number, b: number, r: number) { return (b - a) * r; } protected interpolationPos(p1: cc.Vec3, p2: cc.Vec3, rate: number) { p1.x += this.getInterpplation(p1.x, p2.x, rate); p1.y += this.getInterpplation(p1.y, p2.y, rate); p1.z += this.getInterpplation(p1.z, p2.z, rate); } public init() { this.initPosition(); this.initPolygon(); this.initMat(); } public reset() { this.resetMesh(); this._playing = false; } public clear() { } protected _playing: boolean = false; /**是否正在运行 */ public get playing() { return this._playing; } /** * 开始运行 * @param startPosition 拖尾头部坐标,将从该位置开始出现拖尾 * @param angle 拖尾初始角度(该功能暂未完成) */ public play(startPosition: cc.Vec3, angle?: cc.Vec3) { if (this.polygon.length == 0) { cc.warn("拖尾特效未设置横截面形状!"); return; } if (!this.target) { cc.warn("拖尾未设置跟随的目标节点!"); return; } this._playing = true; this.startPosition.set(startPosition); this.resetMesh(); } /**停止运行,拖尾将逐渐缩短消失 */ public stop() { this._playing = false; } /** * 设置拖尾头部的位置,可通过定时调用该方法驱动拖尾运行 * @param pos 头尾头部坐标 * @param angle 拖尾头部的方向,默认为垂直朝向XY平面 */ public moveTo(pos: cc.Vec3, angle?: cc.Vec3) { this.startPosition = pos; let maxIndex = this.polygon.length - 1; if (undefined === angle) { for (let i = maxIndex; i >= 0; --i) { this.verts[i].x = this.startPosition.x + this.polygon[i].x; this.verts[i].y = this.startPosition.y + this.polygon[i].y; this.verts[i].z = this.startPosition.z; } if (maxIndex >= 2 && this.polygonClosed) { maxIndex++; this.verts[maxIndex].x = this.startPosition.x + this.polygon[0].x; this.verts[maxIndex].y = this.startPosition.y + this.polygon[0].y; this.verts[maxIndex].z = this.startPosition.z; } } else { for (let i = maxIndex; i >= 0; --i) { let offset = cc.v3(this.polygon[i].x, this.polygon[i].y, 0); offset = this.rotatePos(offset, angle); this.verts[i].x = this.startPosition.x + offset.x; this.verts[i].y = this.startPosition.y + offset.y; this.verts[i].z = this.startPosition.z + offset.z; } if (maxIndex >= 2 && this.polygonClosed) { maxIndex++; let offset = cc.v3(this.polygon[0].x, this.polygon[0].y, 0); offset = this.rotatePos(offset, angle); this.verts[maxIndex].x = this.startPosition.x + offset.x; this.verts[maxIndex].y = this.startPosition.y + offset.y; this.verts[maxIndex].z = this.startPosition.z + offset.z; } } this.updateMesh(); } protected rotatePos(p: cc.Vec3, angle: cc.Vec3): cc.Vec3 { //旋转顺序:Y-X-Z let p1 = cc.v2(p.x, p.z); this.rotateV2(p1, angle.y); let p2 = cc.v2(p.y, p1.y); this.rotateV2(p2, angle.x); let p3 = cc.v2(p1.x, p2.x); this.rotateV2(p3, angle.z); p.x = p3.x; p.y = p3.y; p.z = p2.y; return p; } protected rotateV2(p: cc.Vec2, angle: number) { let radian = angle * 0.017453; let sin = Math.sin(radian); let cos = Math.cos(radian); let x = p.x; let y = p.y; p.x = x * cos - y * sin; p.y = x * sin + y * cos; } /**跟随的目标节点 */ protected target: cc.Node; protected offset: cc.Vec3; /** * 设置拖尾跟随的目标节点 * @param target 目标节点,需要与本节点在同一父节点下,或者其所有父节点的坐标、角度为(0,0,0),缩放为(1,1,1) * @param offset 拖尾的中心点相对目标节点的坐标的偏移量 */ public setTarget(target: cc.Node, offset: cc.Vec3) { this.target = target; this.offset = offset.clone(); } //自定义方法,针对实际需求优化: public customUpdate(dt: number) { if (!this._playing) { this.moveTo(this.startPosition); } else { this.moveTo(cc.v3(0, this.target.y + 0.5, this.target.z)); } } //通用方法: // public update(dt: number) { // if (!this.playing || !this.target) return; // let pos = cc.v3(); // this.target.getPosition(pos); // pos.addSelf(this.offset); // if (!this.followAngle) { // this.moveTo(pos); // } else { // this.moveTo(pos, this.target.eulerAngles); // } // } }
the_stack
import React, { useEffect, useRef, useState, useCallback } from 'react' import { Row, Col, Card, weaverTheme, Button, PlusOutlined, MinusOutlined, AimOutlined, DownloadOutlined, Tooltip, } from '@episclera/weaver' import { useQuery } from '@apollo/client' import type { Graph as GraphType, Node, Edge } from '@antv/x6' import { DagreLayout } from '@antv/layout' import { GET_WORKSPACE_INFO } from '../executor-api' import { TargetWorkspaceInfo } from '../../api-executor-types' import { ROOT_NODE_ID } from './constants' // using require because in prod mode the less loader has problems to import styles using "import" require('./styles.less') /** * Graph which shows the dependencies between packages. */ const PackagesGraph: React.FC = function () { const graphWrapperRef = useRef<HTMLDivElement>(null) const graphRef = useRef<HTMLDivElement>(null) const miniMapRef = useRef<HTMLDivElement>(null) const [graph, setGraph] = useState<GraphType | null>(null) /** * Workspace info query */ const { data, loading } = useQuery<{ getWorkspaceInfo?: TargetWorkspaceInfo }>(GET_WORKSPACE_INFO, { // directing this request to the Executor api endpoint (because is part of the Executor api) context: { clientName: 'executor-api' }, }) /** * This use effect is used to initialize and set the graph in state */ useEffect(() => { // Initialize graph only if it is null and graph container is mounted // Important: looking to !loading because our Card has a loading prop which will render the graph-container only after this will be false // so if we don't check for loading, This if will not work because graphRef will be null at that time and nothing will be rendered if (graphRef?.current && graphWrapperRef?.current && !graph && !loading) { // Loading Graph dynamically because is not SSR compatible // NOTE: using dynamic from next/dynamic also is not possible because for some reason it transform the return to a react component but our lib is a simple js library but not react component import('@antv/x6') .then(({ Graph }) => { // using graph wrapper bounds because it will not have any scroll etc and the Antv lib will not change his width so we will be safer const graphWrapperBounds = graphWrapperRef?.current?.getBoundingClientRect() const graphInstance = new Graph({ // Mounting on graph container: graphRef.current as HTMLElement, // Unsinging the graph wrapper bounds because it will not have any scroll etc and the Antv lib will not change his width so we will be safer width: graphWrapperBounds?.width, height: graphWrapperBounds?.height, // Enabling scroll scroller: { enabled: true, // pannable will not work if selecting is enabled }, // enabling selection selecting: { enabled: true, // mouse selection rubberband: true, // Will show border on selected nodes (both showNodeSelectionBox and rubberNode are needed otherwise will not work) showNodeSelectionBox: true, rubberNode: true, }, // Styling the graph grid grid: { visible: true, size: 20, args: { color: weaverTheme('text-color-secondary') as string, thickness: 1, }, }, // minimap minimap: { container: miniMapRef.current as HTMLElement, enabled: true, width: 150, height: 150, }, }) setGraph(graphInstance) }) .catch(err => { // eslint-disable-next-line no-console console.error('Error loading graph', err) }) } }, [graphRef, graphWrapperRef, miniMapRef, graph, loading]) /** * Will scroll the graph to the root node in order to have it in the top-left quadrant */ const scrollToRootNode = useCallback((): void => { if (graph) { // firstly setting the zoom to the initial one 1 (Otherwise the scroll will not work as expected) graph.zoomTo(1) const graphJSON = graph.toJSON() const rootNodeInfo: Node.Metadata | null = graphJSON.cells?.find( (node: Node.Metadata) => node?.id === ROOT_NODE_ID, ) as Node.Metadata | null const graphWrapperRefBounds = graphWrapperRef.current?.getBoundingClientRect() if (rootNodeInfo) { // Setting the scroll to the root node and positioning it in the top-left quadrant to have more nodes visible on first screen graph.scrollToPoint( Number(rootNodeInfo.position?.x) + // dividing by 3 because if dividing by 2 that is to much because in the left side we have the Minimap Number(graphWrapperRefBounds?.width) / 3, // Adding half of the wrapper height to have the root node in top-center of the viewport Number(rootNodeInfo.position?.y) + Number(graphWrapperRefBounds?.height) / 2 - // minus node height to have the root node a bit down that the top of graph to be sure that the entire node will be in the screen Number(rootNodeInfo.size?.height), ) } else { // If the root element wasn't found the logging a warn message to know that we can't scroll to the root node // eslint-disable-next-line no-console console.warn( 'The root node was not found in the graph model. Can not scroll to the root node.', ) } } else { // eslint-disable-next-line no-console console.warn( 'The graph is not defined. Seems that you called this method before setting the graph.', ) } }, [graph, graphWrapperRef]) /** * This use effect will set the node and edges after the data will be fetched and scroll to the ROOT node */ useEffect(() => { // When we got the workspace info and graphInstance, we can start to render the graph nodes if (data?.getWorkspaceInfo && graph) { // Defining few useful constants const packagesEntries = Object.entries( data.getWorkspaceInfo.packagesInfo || {}, ) const packagesNames = Object.keys( data.getWorkspaceInfo.packagesInfo || {}, ) // Defining some default styles for nodes const nodeStyleAttrs = { width: 240, height: 50, attrs: { body: { fill: weaverTheme('component-background-color') as string, stroke: weaverTheme('text-color-secondary') as string, strokeWidth: 0.5, // rounded corners rx: 8, ry: 8, }, }, } // Creating nodes from workspace info // root node const rootWorkspaceNode: Node.Metadata = { // Using as ID the ROOT_NODE_ID constant which also will be used in other calculation so be careful if you change it id: ROOT_NODE_ID, label: `${data.getWorkspaceInfo.rootInfo?.name}\nWorkspace root`, ...nodeStyleAttrs, } // packages nodes const packagesNodes: Node.Metadata[] = packagesEntries.map( ([packageName, packageInfo]) => ({ id: packageName, label: `${packageName}\n${ ( (packageInfo as Record<string, any>) ?.packageJsonConfigContent as Record<string, any> )?.version as string }`, ...nodeStyleAttrs, }), ) // Creating edges from workspace info // Edges - are the dependencies between packages (Arrows which connect the packages) const edges: Edge.Metadata[] = packagesEntries.reduce( ( acc: Edge.Metadata[], [currentPackageName, currentPackageInfo], ): Edge.Metadata[] => { const currentPackageEdges: Edge.Metadata[] = [] const currentPackagePkgJsonConfigContent = ( currentPackageInfo as Record<string, any> )?.packageJsonConfigContent as Record<string, any> const currentPackageDependencies = (currentPackagePkgJsonConfigContent?.dependencies || {}) as Record< string, any > const currentPackageDevDependencies = (currentPackagePkgJsonConfigContent?.devDependencies || {}) as Record<string, any> // Concatenating dev deps with dependencies const currentPackageAllDependencies = { ...currentPackageDependencies, ...currentPackageDevDependencies, } // Looping through all packageNames to check with which one the current package depends packagesNames.forEach(packageName => { // Checking if the current package depends on the packageName if (currentPackageAllDependencies[packageName]) { // Drawing arrow from package to his dependency one // so that the package with more dependencies will be one of the first in the graph currentPackageEdges.push({ source: currentPackageName, target: packageName, router: 'metro', connector: { name: 'rounded', args: {}, }, attrs: { line: { stroke: weaverTheme('text-color-secondary') as string, strokeWidth: 0.5, sourceMarker: { tagName: 'circle', // radius r: 3, }, }, }, }) } }) return [...acc, ...currentPackageEdges] }, [], ) /** * Using a grid layout to render the graph nodes * because we don't wan't to calculate the position of the nodes by ourselves */ const gridLayout = new DagreLayout({ type: 'dagre', // left to right hierarchy rankdir: 'LR', // node sizes are needed for better layout calculations to not have nodes overlapping nodeSize: [nodeStyleAttrs.width, nodeStyleAttrs.height], }) const newModel = gridLayout.layout({ // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore nodes: [rootWorkspaceNode, ...packagesNodes], // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore edges, }) // Applying the resolved model to the graph graph.fromJSON(newModel) // Setting initial scroll position to the root node to be in the initial view (But in the top-left quadrant of the graph) scrollToRootNode() } }, [data, graph, graphRef, scrollToRootNode]) /** * Used to download the graph as a image */ const downloadGraph = useCallback(() => { if (graph) { // Loading DataUri dynamically because is not SSR compatible // NOTE: using dynamic from next/dynamic also is not possible because for some reason it transform the return to a react component but our lib is a simple js library but not react component import('@antv/x6') .then(({ DataUri }) => { graph.toPNG(dataUri => { DataUri.downloadDataUri(dataUri, 'workspace-deps-graph.png') }) }) .catch(() => {}) } else { // eslint-disable-next-line no-console console.warn( 'The graph is not defined. Seems that you called this method before setting the graph.', ) } }, [graph]) /** * Used to zoom in */ const zoomIn = useCallback(() => { if (graph) { const currentZoom = graph.zoom() graph.zoomTo(currentZoom + 0.2) } else { // eslint-disable-next-line no-console console.warn( 'The graph is not defined. Seems that you called this method before setting the graph.', ) } }, [graph]) /** * Used to zoom out */ const zoomOut = useCallback(() => { if (graph) { const currentZoom = graph.zoom() // Last possible zoom out is 0.2 thats why this check with 0.4 is needed if (currentZoom >= 0.4) { graph.zoomTo(currentZoom - 0.2) } } else { // eslint-disable-next-line no-console console.warn( 'The graph is not defined. Seems that you called this method before setting the graph.', ) } }, [graph]) return ( <section className='packages-graph'> <Row> <Col span={24}> <Card className='overflow-hidden' loading={loading} bodyStyle={{ padding: 0, }} > <div className='relative w-full h-[75vh]' ref={graphWrapperRef}> <div className='w-full h-full' ref={graphRef} /> {/* Minimap */} <div className='absolute bottom-3 left-2 z-10 shadow-lg rounded-md overflow-hidden' ref={miniMapRef} /> <div className='absolute top-5 left-5 z-10 flex flex-col items-center '> <Tooltip title='Scroll to root' placement='right'> <Button onClick={() => scrollToRootNode()} className='shadow-md mb-2' shape='circle' > <AimOutlined /> </Button> </Tooltip> <Tooltip title='Zoom in' placement='right'> <Button onClick={() => zoomIn()} className='shadow-md mb-2' shape='circle' > <PlusOutlined /> </Button> </Tooltip> <Tooltip title='Zoom out' placement='right'> <Button onClick={() => zoomOut()} className='shadow-md mb-2' shape='circle' > <MinusOutlined /> </Button> </Tooltip> <Tooltip title='Download graph' placement='right'> <Button onClick={() => downloadGraph()} className='shadow-md mb-2' shape='circle' > <DownloadOutlined /> </Button> </Tooltip> </div> </div> </Card> </Col> </Row> </section> ) } export default PackagesGraph
the_stack
import debugging from 'debug'; import { SimplePeerData } from 'simple-peer'; import Transfer from "./Transfer"; import UploadProvider from "./uploadProviders/UploadProvider"; const debug = debugging('blymp:UploadService'); /** * Upload Service that handles uploading data to the partner peer */ export default class UploadService { /** * Current parent transfer */ private transfer : Transfer; /** * Current Upload Provider that returns the data slices needed for uploading */ private uploadProvider : UploadProvider; /** * Estimates made about the remaining time. * This is used to make the displayed time remaining more smoothed out instead * of creating a blank estimate on each packet */ lastEstimates : number[] = []; // Variables needed to calculate the estimates lastProgress = 0; // Last progess calculated. We use this to calculate how quickly we progress timeSince = 50; // Milliseconds since we last seen any change in the progress /** * Size of a file chunk used when uploading in bytes */ chunkSize : number; /** * Saves, if this instance has already been used to upload files */ private hasUploaded : boolean = false; // Variables about the current file size = 0; // Size in bytes transmitted = 0; // Transmitted bytes in the current file /** * Interval that gets executed every 50ms to update the estimated time remaining */ estimateInterval : number | NodeJS.Timeout | undefined; /** * Function to call after all files have been transferred */ private onUploadDone : Function = () => {}; /** * Create a new upload service * * @param transfer Transfer that parents this service * @param provider Upload provider that provides the file data */ constructor(transfer : Transfer, provider : UploadProvider) { this.transfer = transfer; this.uploadProvider = provider; // Chunk size is 15kb for WebRTC, 512kb for sockets this.chunkSize = transfer.connection.method === 'webrtc' ? 1024 * 15 : 1024 * 512; } /** * Emit a message to the partner * * @param data Data to transfer * @param isFilePart Set to true if the supplied data is part of the file * @param callback Callback to execute once the message is acknowledged from the partner */ private emit(data: String | ArrayBuffer | Object, isFilePart = false, callback : false | Function = false) { if (this.transfer.connection.method === 'webrtc') { if (!this.transfer.connection.peer) { throw new Error('Internal error: Cannot send data as no peer is connected'); } if (isFilePart) { try { this.transfer.connection.peer.send(data as SimplePeerData); if (callback) { this.transfer.connection.socket.once("acknowledge rtc data", callback); } } catch (e) { debug('Peer connection has been reset - falling back to sockets'); // Switching methods will change the transfer speed // Delete current estimates to get a more accurate one this.lastEstimates = []; this.transfer.connection.method = 'socket'; this.transfer.connection.socket.emit('proxy to partner', this.transfer.receiverId, { type: 'use transfer method', method: 'socket' }); this.emit(data, isFilePart, callback); return; } } else { try { this.transfer.connection.peer.send(JSON.stringify(data)); if (callback) { callback(); } } catch (e) { debug('Peer connection has been reset - falling back to sockets'); // Switching methods will change the transfer speed // Delete current estimates to get a more accurate one this.lastEstimates = []; this.transfer.connection.method = 'socket'; this.transfer.connection.socket.emit('proxy to partner', this.transfer.receiverId, { type: 'use transfer method', method: 'socket' }); this.emit(data, isFilePart, callback); return; } } } else if (isFilePart) { this.transfer.connection.socket.emit('proxy to partner', this.transfer.receiverId, `###${data}`, callback); } else { this.transfer.connection.socket.emit('proxy to partner', this.transfer.receiverId, data); if (callback) { callback(); } } }; /** * Update the estimated time remaining. * This function will be executed every 50ms and check how much the transfer has progressed in that time */ private updateEstimate() { // Don't calculate if we havn't progressed since if (this.lastProgress !== this.transfer.progress) { const timeForOnePercent = this.timeSince / (this.transfer.progress - this.lastProgress); const percentLeft = 100 - this.transfer.progress; const currentEstimate = Math.round((percentLeft * timeForOnePercent) / 1000); // Keep estimates based on time between intervals this.lastEstimates.push(currentEstimate); // Helper function that scales numbers to another range // Like arduino "map" function // eslint-disable-next-line max-len const scale = (num: number, inMin: number, inMax: number, outMin: number, outMax: number) => (num - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; // Number of estimates we should keep const keepEstimates = scale(this.timeSince, 50, 1000, 50, 5); // Remove excess estimates while (this.lastEstimates.length > keepEstimates) { this.lastEstimates.shift(); } // Normalize estimates let estimate = 0; // eslint-disable-next-line no-restricted-syntax for (const es of this.lastEstimates) { estimate += es; } estimate /= this.lastEstimates.length; estimate -= scale(this.lastEstimates.length, 5, 50, 0.5, 2); estimate = Math.round(estimate); if (estimate < 0) { estimate = 0; } // Inform partner about our new estimate this.emit({ type: 'time estimate', estimate, }); this.transfer.estimate = estimate; this.transfer.triggerUpdate(); this.lastProgress = this.transfer.progress; this.timeSince = 50; } else { this.timeSince += 50; } } /** * Send part of a file to the receiver. * This function will recusively call itself until all files are transferred so this method * only needs to be executed once. * * The function will use the upload provider to request a new slice, then give the new slice to * the "handleFileSlice" which will handle sending it and which will also call this method again * requesting the next slice. * * @param position Position in the file */ private async sendFileData(position: number) { if (!this.uploadProvider) { throw new Error('Internal error: Cannot upload files as no files were selected'); } this.transfer.triggerUpdate(); if (position === 0) { // We are at the beginning of the file - no data has been sent yet // Let the upload provider prepare the file before we perform any real actions on it // Already fetch the name for the new file so we can show that info. const fileInfoBeforePrepare = this.uploadProvider.getFileInfo(this.transfer.currentFile, true); this.transfer.currentFileName = fileInfoBeforePrepare.name; this.transfer.triggerUpdate(); // Let the provider prepare await this.uploadProvider.prepareFile(this.transfer.currentFile); } const fileInfo = this.uploadProvider.getFileInfo(this.transfer.currentFile, false); if (position === 0) { // We are at the beginning of the file - no data has been sent yet // Send file information to partner this.emit({ type: 'new file', ...fileInfo }); this.size = fileInfo.size; this.transfer.currentFileName = fileInfo.name; this.transfer.triggerUpdate(); debug('Starting new file', fileInfo); } // Read and handle the chunk const start = position * this.chunkSize; const end = start + Math.min(this.chunkSize, (fileInfo.size - start)); debug("Requesting new file slice from provider"); this.uploadProvider.getFileSlice(this.transfer.currentFile, start, end).then((v) => this.handleFileSlice(v)); } /** * Handle packaging and sending of part of file. * This method will be called from "sendFileData". * * @param value Value of the file slice */ private handleFileSlice(value : string | ArrayBuffer) { debug("Got new file slice"); let data = this.transfer.connection.prepareFileSliceForCurrentMethod(value); // Send file chunk to partner debug("Transmitting to partner..."); this.emit(data, true, () => { debug("Transmission successful"); this.transmitted += this.chunkSize; // Check if file transmitted completely if (this.transmitted >= this.size) { // We are done sending this file. Complete the process and start sending the next file // or end the transfer if all files are done. debug('Completed transfer of file', this.transfer.currentFile); this.transmitted = 0; this.transfer.currentFile += 1; // Inform partner that file is complete this.emit({ type: 'file complete', }); // Reset estimates this.transfer.estimate = -1; this.lastEstimates = []; this.transfer.triggerUpdate(); // Check if all files have been transmitted if (this.transfer.currentFile >= this.uploadProvider.getNumberOfFiles()) { // Finish transfer debug('Finished transferring all files'); this.transfer.finishedTransfer = true; this.onUploadDone(); this.transfer.openPage('/completed'); clearInterval(this.estimateInterval as number); return; } debug('Transferring next file', this.transfer.currentFile, this.uploadProvider.getNumberOfFiles()); } // Calculate progress this.transfer.progress = (this.transmitted / this.size) * 100; this.emit({ type: 'upload progress', progress: this.transfer.progress, }); this.transfer.triggerUpdate(); // Request next package const position = this.transmitted / this.chunkSize; this.sendFileData(position); }); } /** * Start the upload of the files in the upload provider */ startUpload() { // Make sure each service only gets used once if (this.hasUploaded) { throw new Error('Illegal state: UploadService can only be used once! Please create a new instance instead'); } return new Promise(resolve => { this.onUploadDone = resolve; this.transfer.setTransferStatusText("Transferring files..."); // Inform partner which DownloadProcessor they should use this.emit({ type: 'use processor', processor: this.uploadProvider.getDownloadProcessor() }); // Inform partner about number of files this.emit({ type: 'number of files', num: this.uploadProvider.getNumberOfFiles() }); // Total number of files we need to transfer this.transfer.totalFiles = this.uploadProvider.getNumberOfFiles(); this.transfer.progress = 0; // Start estimating the time remaining this.estimateInterval = setInterval(() => this.updateEstimate(), 50); this.transfer.triggerUpdate(); // Start file transfer this.sendFileData(0); }); } }
the_stack
import {expect} from "chai"; import * as React from "react"; import * as Sinon from "sinon"; import { BoxGeometry, Camera, Mesh, MeshLambertMaterial, Object3D, PerspectiveCamera, Scene, Vector3, WebGLRenderer, } from "three"; import ReactThreeRenderer from "../../../src/core/renderer/reactThreeRenderer"; import object3D from "../../../src/core/renderer/hostDescriptors/descriptors/objects/object3D"; import {RenderAction} from "../../../src/core/renderer/hostDescriptors/descriptors/render"; import webGLRenderer from "../../../src/core/renderer/hostDescriptors/descriptors/webGLRenderer"; import {mockConsole, testContainers} from "../index"; import Done = Mocha.Done; const {div: testDiv} = testContainers; describe("render", () => { function verifyRenderCall(rendererSpy: Sinon.SinonSpy) { expect(rendererSpy.callCount, "Render should only be called once").to.equal(1); const lastCall = rendererSpy.lastCall; const scene = lastCall.args[0] as Scene; expect(scene).to.be.instanceOf(Scene); expect(lastCall.args[1]).to.be.instanceOf(Camera); expect(scene.children.length, "Scene should only have one child").to.equal(1); const mesh = scene.children[0] as Mesh; expect(mesh).to.be.instanceOf(Mesh); expect(mesh.geometry).to.be.instanceOf(BoxGeometry); expect(mesh.material).to.be.instanceOf(MeshLambertMaterial); } it("should be able to be rendered into a renderer", (done) => { mockConsole.expectLog("THREE.WebGLRenderer", "100"); // mockConsole.expectWarn("THREE.WebGLProgram: gl.getProgramInfoLog()", "\n\n\n"); const renderer = new WebGLRenderer(); const renderCallSpy = Sinon.spy(renderer, "render"); ReactThreeRenderer.render(<render camera={<perspectiveCamera/>} scene={<scene> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/>, renderer); requestAnimationFrame(() => { verifyRenderCall(renderCallSpy); ReactThreeRenderer.unmountComponentAtNode(renderer, () => { done(); }); }); }); it("should be able to be rendered into a container within a renderer", (done) => { const rendererSpy = Sinon.spy(); const {canvas: testCanvas} = testContainers; ReactThreeRenderer.render(<webGLRenderer width={800} height={600} ref={rendererSpy} />, testCanvas); expect(rendererSpy.callCount).to.equal(1); const renderer = rendererSpy.lastCall.args[0]; expect(renderer).to.be.instanceOf(WebGLRenderer); const renderCallSpy = Sinon.spy(rendererSpy.lastCall.args[0], "render"); expect(renderCallSpy.notCalled).to.equal(true); ReactThreeRenderer.render(<webGLRenderer width={800} height={600} ref={rendererSpy} > <render camera={<perspectiveCamera/>} scene={<scene> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/> </webGLRenderer>, testCanvas); requestAnimationFrame(() => { verifyRenderCall(renderCallSpy); ReactThreeRenderer.unmountComponentAtNode(testCanvas, done); }); }); it("should not render if scene or camera are null", (done: Done) => { mockConsole.expectLog("THREE.WebGLRenderer", "100"); const renderer = new WebGLRenderer(); const renderCallSpy = Sinon.spy(renderer, "render"); ReactThreeRenderer.render(<render camera={null} scene={null} />, renderer); requestAnimationFrame(() => { expect(renderCallSpy.callCount).to.equal(0); ReactThreeRenderer.render(<render camera={null} scene={<scene> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/>, renderer); requestAnimationFrame(() => { expect(renderCallSpy.callCount).to.equal(0); ReactThreeRenderer.render(<render camera={<perspectiveCamera/>} scene={null}/>, renderer); requestAnimationFrame(() => { expect(renderCallSpy.callCount).to.equal(0); // mockConsole.expectWarn("THREE.WebGLProgram: gl.getProgramInfoLog()", "\n\n\n"); ReactThreeRenderer.render(<render camera={<perspectiveCamera/>} scene={<scene> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/>, renderer); requestAnimationFrame(() => { expect(renderCallSpy.callCount).to.equal(1); ReactThreeRenderer.unmountComponentAtNode(renderer, done); }); }); }); }); }); it("should call the camera and scene refs with the correct objects", (done) => { const perspectiveCameraRef = Sinon.spy(); const sceneRef = Sinon.spy(); const {canvas: testCanvas} = testContainers; ReactThreeRenderer.render(<webGLRenderer width={800} height={600} > <render camera={<perspectiveCamera ref={perspectiveCameraRef} name="some camera"/>} scene={<scene ref={sceneRef} name="some scene"> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/> </webGLRenderer>, testCanvas); expect(perspectiveCameraRef.callCount).to.equal(1); expect(sceneRef.callCount).to.equal(1); const firstCamera: Camera = perspectiveCameraRef.lastCall.args[0]; const firstScene: Scene = sceneRef.lastCall.args[0]; expect(firstCamera.name).to.equal("some camera"); expect(firstScene.name).to.equal("some scene"); // they should have mounted into the same group const renderActionGroup = firstScene.parent; expect(renderActionGroup).to.not.equal(null); if (renderActionGroup == null) { throw new Error(); } expect(renderActionGroup).to.equal(firstCamera.parent); ReactThreeRenderer.render(<webGLRenderer width={800} height={600} > <render camera={<perspectiveCamera ref={perspectiveCameraRef} name="same camera different name"/>} scene={<scene ref={sceneRef} name="same scene different name"> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/> </webGLRenderer>, testCanvas); // the refs should not be called again expect(perspectiveCameraRef.callCount).to.equal(1); expect(sceneRef.callCount).to.equal(1); expect(firstCamera.parent).to.equal(renderActionGroup); expect(firstScene.parent).to.equal(renderActionGroup); expect(firstCamera.name).to.equal("same camera different name"); expect(firstScene.name).to.equal("same scene different name"); ReactThreeRenderer.render(<webGLRenderer width={800} height={600} > <render camera={<perspectiveCamera ref={perspectiveCameraRef} name="another camera" key={"3"}/>} scene={<scene ref={sceneRef} name="another scene" key={"4"}> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/> </webGLRenderer>, testCanvas); // but for different keys, they should be! expect(perspectiveCameraRef.callCount).to.equal(3); expect(sceneRef.callCount).to.equal(3); // names should not have changed but they should have dismounted expect(firstCamera.name).to.equal("same camera different name"); expect(firstScene.name).to.equal("same scene different name"); expect(firstCamera.parent).to.equal(null); expect(firstScene.parent).to.equal(null); const secondCamera = perspectiveCameraRef.lastCall.args[0]; const secondScene = sceneRef.lastCall.args[0]; expect(secondCamera).to.not.equal(firstCamera); expect(secondScene).to.not.equal(firstScene); // they should have replaced the first camera and scene in the same group expect(secondCamera.parent).to.equal(renderActionGroup); expect(secondScene.parent).to.equal(renderActionGroup); expect(secondCamera.name).to.equal("another camera"); expect(secondScene.name).to.equal("another scene"); ReactThreeRenderer.render(<webGLRenderer width={800} height={600} > <render camera={<perspectiveCamera name="second camera but without ref this time" key={"3"}/>} scene={<scene name="second scene but without ref this time" key={"4"}> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/> </webGLRenderer>, testCanvas); expect(perspectiveCameraRef.callCount).to.equal(4); expect(sceneRef.callCount).to.equal(4); expect(perspectiveCameraRef.lastCall.args[0]).to.equal(null); expect(sceneRef.lastCall.args[0]).to.equal(null); expect(firstCamera.name).to.equal("same camera different name"); expect(firstScene.name).to.equal("same scene different name"); // sure the ref may not be called but it's still the same object expect(secondCamera.name).to.equal("second camera but without ref this time"); expect(secondScene.name).to.equal("second scene but without ref this time"); // and should remain in group expect(secondCamera.parent).to.equal(renderActionGroup); expect(secondScene.parent).to.equal(renderActionGroup); ReactThreeRenderer.render(<webGLRenderer width={800} height={600} > <render camera={<perspectiveCamera name="third camera" key={"10"}/>} scene={<scene name="third scene" key={"20"}> <mesh> <boxGeometry width={5} height={5} depth={5}/> <meshLambertMaterial/> </mesh> </scene>}/> </webGLRenderer>, testCanvas); expect(perspectiveCameraRef.callCount).to.equal(4); expect(sceneRef.callCount).to.equal(4); expect(perspectiveCameraRef.lastCall.args[0]).to.equal(null); expect(sceneRef.lastCall.args[0]).to.equal(null); expect(firstCamera.name).to.equal("same camera different name"); expect(firstScene.name).to.equal("same scene different name"); // second one should have dismounted, but the third one will be created expect(secondCamera.name).to.equal("second camera but without ref this time"); expect(secondScene.name).to.equal("second scene but without ref this time"); expect(secondCamera.parent).to.equal(null); expect(secondScene.parent).to.equal(null); const thirdCamera = renderActionGroup.children.filter((child) => child instanceof Camera)[0]; const thirdScene = renderActionGroup.children.filter((child) => child instanceof Scene)[0]; expect(thirdCamera.name).to.equal("third camera"); expect(thirdScene.name).to.equal("third scene"); ReactThreeRenderer.unmountComponentAtNode(testCanvas, done); }); it("should accept a scene as a parameter", (done) => { mockConsole.expectLog("THREE.WebGLRenderer", "100"); const renderer = new WebGLRenderer(); const renderCallSpy = Sinon.spy(renderer, "render"); const perspectiveCameraSpy = Sinon.spy(); const scene = new Scene(); ReactThreeRenderer.render(<render camera={<perspectiveCamera ref={perspectiveCameraSpy}/>} scene={scene} />, renderer); requestAnimationFrame(() => { const lastCall = renderCallSpy.lastCall; expect(lastCall.args[0], "Scene from object reference should have been used") .to.equal(scene); expect(lastCall.args[1], "Camera from element should have been used") .to.equal(perspectiveCameraSpy.lastCall.args[0]); ReactThreeRenderer.unmountComponentAtNode(testDiv, done); }); }); it("should accept a camera as a parameter", (done) => { mockConsole.expectLog("THREE.WebGLRenderer", "100"); const renderer = new WebGLRenderer(); const renderCallSpy = Sinon.spy(renderer, "render"); const sceneRef = Sinon.spy(); const camera = new PerspectiveCamera(); ReactThreeRenderer.render(<render camera={camera} scene={<scene ref={sceneRef}/>} />, renderer); requestAnimationFrame(() => { const lastCall = renderCallSpy.lastCall; expect(lastCall.args[0], "Scene from element should have been used") .to.equal(sceneRef.lastCall.args[0]); expect(lastCall.args[1], "Camera from element should have been used") .to.equal(camera); ReactThreeRenderer.unmountComponentAtNode(testDiv, done); }); }); it("should trigger a render when a visible element is added or removed", (done) => { mockConsole.expectLog("THREE.WebGLRenderer", "100"); const renderer = new WebGLRenderer(); const renderCallSpy = Sinon.spy(renderer, "render"); let setChildren: ((childCount: number, callback: () => void) => void) | null = null; class TestContainer extends React.Component<any, { childCount: number }> { constructor(props: any, context: any) { super(props, context); this.state = { childCount: 0, }; setChildren = (childCount: number, callback: () => void) => { this.setState({ childCount, }, () => { requestAnimationFrame(callback); }); }; } public render() { const children = []; for (let i = 0; i < this.state.childCount; ++i) { children.push(<object3D key={`${i}`}/>); } return <object3D> {children} </object3D>; } } ReactThreeRenderer.render(<render camera={<perspectiveCamera/>} scene={<scene> <TestContainer/> </scene>} />, renderer); if (setChildren == null) { return; } const updateChildren: ((childCount: number, callback: () => void) => void) = setChildren; requestAnimationFrame(() => { expect(renderCallSpy.callCount).to.equal(1); requestAnimationFrame(() => { // nothing has changed! expect(renderCallSpy.callCount).to.equal(1); // add a child updateChildren(1, () => { // it should render expect(renderCallSpy.callCount).to.equal(2); // do not add a child updateChildren(1, () => { // should not have rendered! expect(renderCallSpy.callCount).to.equal(2); // add another child updateChildren(2, () => { // should have rendered! expect(renderCallSpy.callCount).to.equal(3); // remove children updateChildren(0, () => { // should have rendered! expect(renderCallSpy.callCount).to.equal(4); ReactThreeRenderer.unmountComponentAtNode(testDiv, done); }); }); }); }); }); }); }); it("should trigger a render only when a visible property is updated", (done) => { mockConsole.expectLog("THREE.WebGLRenderer", "100"); const renderer = new WebGLRenderer(); let nameChangeEvent: any = null; let positionChangeEvent: any = null; class ObjectStateChanger extends React.Component<any, { name: string, position: Vector3, }> { constructor(props: any, context: any) { super(props, context); this.state = { name: "test", position: new Vector3(), }; } public componentDidMount() { nameChangeEvent = (newName: string, callback: () => {}) => { this.setState({ name: newName, }, callback); }; positionChangeEvent = (newPosition: Vector3, callback: () => {}) => { this.setState({ position: newPosition, }, callback); }; } public render() { return <object3D position={this.state.position} name={this.state.name} />; } } const changerSpy = Sinon.spy(); const renderRef = Sinon.spy(); ReactThreeRenderer.render(<render ref={renderRef} camera={<perspectiveCamera/>} scene={<scene> <ObjectStateChanger ref={changerSpy}/> </scene>}/>, renderer); const render: RenderAction = renderRef.lastCall.args[0]; const renderCallSpy = Sinon.spy(render, "triggerRender"); expect(renderCallSpy.callCount).to.equal(0); const obj: Object3D = ReactThreeRenderer.findTHREEObject(changerSpy.lastCall.args[0]); positionChangeEvent(new Vector3(1, 2, 3), () => { expect(renderCallSpy.callCount).to.equal(1); expect(obj.position.equals(new Vector3(1, 2, 3))).to.equal(true); nameChangeEvent("new name", () => { expect(renderCallSpy.callCount).to.equal(1); expect(obj.name).to.equal("new name"); positionChangeEvent(new Vector3(3, 2, 1), () => { expect(renderCallSpy.callCount).to.equal(2); expect(obj.position.equals(new Vector3(3, 2, 1))).to.equal(true); nameChangeEvent("newer name", () => { expect(renderCallSpy.callCount).to.equal(2); expect(obj.name).to.equal("newer name"); ReactThreeRenderer.unmountComponentAtNode(renderer, () => { done(); }); }); }); }); }); }); });
the_stack
import React from 'react'; import { FormattedMessage, injectIntl } from 'react-intl'; import { Link } from 'gatsby'; import { AppstoreAddOutlined, HomeOutlined, MenuOutlined, NotificationOutlined, PlayCircleOutlined, ReadOutlined, SearchOutlined, ZhihuOutlined, TwitterOutlined, YuqueOutlined } from '@ant-design/icons'; import { Row, Col, Select, Input, Menu, Popover, Button } from 'antd'; import * as utils from '../utils'; import { version } from '../../../siteconfig.json'; import { Icon } from './Icon'; const { Option } = Select; const LOGO_URL = 'https://gw.alipayobjects.com/mdn/rms_d27172/afts/img/A*w3sZQpMix18AAAAAAAAAAAAAARQnAQ'; let docSearch: (config: any) => void; if (typeof window !== 'undefined') { // eslint-disable-next-line global-require docSearch = require('docsearch.js'); } function initDocSearch() { if (!docSearch) { return; } docSearch({ apiKey: '6cea501a58304e81c8e9d028a1d995e9', indexName: 'oasisengine', inputSelector: '#search-box input', algoliaOptions: { facetFilters: [ `version:${version}` ] }, transformData( hits: { url: string; }[], ) { hits.forEach((hit) => { // eslint-disable-next-line no-param-reassign hit.url = hit.url.replace('oasisengine.cn', window.location.host); // eslint-disable-next-line no-param-reassign hit.url = hit.url.replace('https:', window.location.protocol); }); return hits; }, debug: false, // Set debug to true if you want to inspect the dropdown }); } interface HeaderProps { isMobile: boolean; intl: any; location: { pathname: string; }; showVersion?: boolean; } interface HeaderState { inputValue?: string; menuVisible: boolean; menuMode?: 'vertical' | 'vertical-left' | 'vertical-right' | 'horizontal' | 'inline'; searchOption?: any[]; searching?: boolean; versions?: string[] } class Header extends React.Component<HeaderProps, HeaderState> { searchInput: Input | null | undefined; timer: number; constructor(props) { super(props); this.state = { menuVisible: false, menuMode: props.isMobile ? 'inline' : 'horizontal', versions: [] }; } async componentDidMount() { const { searchInput } = this; const { intl: { locale } } = this.props; this.redirect(); document.addEventListener('keyup', (event) => { if (event.keyCode === 83 && event.target === document.body) { if (searchInput) { searchInput.focus(); } } }); initDocSearch(locale === 'zh-CN' ? 'cn' : 'en'); // Fetch version from remote config const versionConfig = 'https://render.alipay.com/p/h5data/oasis-version_site-doc-versions-h5data.json'; const versions = await fetch(versionConfig).then((e) => e.json()); if (versions) { this.setState({ versions: versions.map((v) => v.version) }) } } componentDidUpdate(preProps: HeaderProps) { const { isMobile } = this.props; if (isMobile !== preProps.isMobile) { this.setMenuMode(isMobile); } } redirect() { const { pathname } = window.location; const isPathNameZhCN = /-cn\/?$/.test(pathname); const isZhCN = utils.isZhCN(); if (this.isNotMarkdownPage(pathname)) { return; } if (isZhCN !== isPathNameZhCN) { this.replacePathName(pathname, isZhCN); } } setMenuMode = (isMobile: boolean) => { this.setState({ menuMode: isMobile ? 'inline' : 'horizontal' }); }; handleHideMenu = () => { this.setState({ menuVisible: false, }); }; handleShowMenu = () => { this.setState({ menuVisible: true, }); }; onMenuVisibleChange = (visible: boolean) => { this.setState({ menuVisible: visible, }); }; handleSelect = (value: string) => { window.location.href = value; }; replacePathName = (pathname: string, isZhCN: boolean) => { const currentProtocol = `${window.location.protocol}//`; const currentHref = window.location.href.substr(currentProtocol.length); window.location.href = currentProtocol + currentHref.replace( window.location.pathname, utils.getLocalizedPathname(pathname, isZhCN), ) } isNotMarkdownPage(pathname: string) { return pathname === '/' || /api/.test(pathname) || /gltf-viewer/.test(pathname) || /examples/.test(pathname); } handleLangChange = () => { const { location: { pathname }, } = this.props; const isPathNameZhCN = /-cn\/?$/.test(pathname); const isZhCN = utils.isZhCN(); window.localStorage.setItem('locale', isZhCN ? 'en-US' : 'zh-CN'); if (this.isNotMarkdownPage(pathname)) { window.location.reload(); return; } if (isZhCN && isPathNameZhCN) { this.replacePathName(pathname, false); return; } if (!isZhCN && !isPathNameZhCN) { this.replacePathName(pathname, true); } }; onVersionChange = (value: string) => { const versionReg = /\/(\d+[.]\d+[^/]*)\//; const matchedResult = window.location.href.match(versionReg); if (matchedResult && matchedResult[1]) { window.location.href = window.location.href.replace(matchedResult[1], value); } }; render() { const { menuMode, menuVisible } = this.state; const { location, intl } = this.props; const path = location.pathname; const { formatMessage } = intl; const module = location.pathname .replace(/(^\/|\/$)/g, '') .split('/') .slice(0, -1) .join('/'); let activeMenuItem = module || 'home'; if (/docs/.test(path)) { if (/docs\/editor[-]/.test(path)) { activeMenuItem = 'editor-docs'; } else if (/docs\/artist[-]/.test(path)) { activeMenuItem = 'artist-docs'; } else { activeMenuItem = 'engine-docs'; } } else if (/api/.test(path)) { activeMenuItem = 'api'; } else if (/examples/.test(path)) { activeMenuItem = 'examples'; } else if (/gltf-viewer/.test(path)) { activeMenuItem = 'gltfviewer'; } else if (path === '/') { activeMenuItem = 'home'; } const isZhCN = intl.locale === 'zh-CN'; const menu = [ <Menu mode={menuMode} selectedKeys={[activeMenuItem]} id="nav" key="nav"> <Menu.Item key="home" icon={<HomeOutlined />}> <Link to="/"> <FormattedMessage id="app.header.menu.home" /> </Link> </Menu.Item> <Menu.SubMenu key="docs" icon={<ReadOutlined />} title={formatMessage({ id: "app.header.menu.docs" })}> <Menu.ItemGroup title={formatMessage({ id: "app.header.menu.engine" })}> <Menu.Item key="engine-docs"> <Link to={utils.getLocalizedPathname(`${version}/docs/install`, isZhCN)}> {formatMessage({ id: "app.header.menu.engine.docs" })} </Link> </Menu.Item> <Menu.Item key="api"> <Link to={`/${version}/api/core/index`}> API </Link> </Menu.Item> </Menu.ItemGroup> <Menu.ItemGroup title={formatMessage({ id: "app.header.menu.artist" })}> <Menu.Item key="artist-docs"> <Link to={utils.getLocalizedPathname(`/${version}/docs/artist-bake`, isZhCN)}> {formatMessage({ id: "app.header.menu.artist.docs" })} </Link> </Menu.Item> </Menu.ItemGroup> {isZhCN && <Menu.ItemGroup title={formatMessage({ id: "app.header.menu.editor" })}> <Menu.Item key="editor-docs"> <Link to={utils.getLocalizedPathname(`/${version}/docs/editor`, isZhCN)}> {formatMessage({ id: "app.header.menu.editor.docs" })} </Link> </Menu.Item> </Menu.ItemGroup> } </Menu.SubMenu> <Menu.Item key="examples" icon={<PlayCircleOutlined />}> <Link to={`/${version}/examples`}> <FormattedMessage id="app.header.menu.engine.examples" /> </Link> </Menu.Item> <Menu.SubMenu key="ecosystem" icon={<AppstoreAddOutlined />} title={formatMessage({ id: "app.header.menu.ecosystem" })}> <Menu.ItemGroup title={formatMessage({ id: "app.header.menu.ecosystem.tool" })}> <Menu.Item key="miniprogram"> <Link to={utils.getLocalizedPathname(`/${version}/docs/miniprogram`, isZhCN)}> {formatMessage({ id: "app.header.menu.ecosystem.miniprogram" })} </Link> </Menu.Item> <Menu.Item key="gltfviewer"> <Link to={`/gltf-viewer`}> {formatMessage({ id: "app.header.menu.ecosystem.gltfviewer" })} </Link> </Menu.Item> <Menu.Item key="createapp"> <Link to="https://github.com/oasis-engine/create-oasis-app" target="_blank"> {formatMessage({ id: "app.header.menu.ecosystem.createapp" })} </Link> </Menu.Item> {isZhCN && <Menu.Item key="editor"> <Link to="https://oasis.alipay.com/editor" target="_blank"> {formatMessage({ id: "app.header.menu.ecosystem.editor" })} </Link> </Menu.Item> } </Menu.ItemGroup> <Menu.ItemGroup title={formatMessage({ id: "app.header.menu.ecosystem.animation" })}> <Menu.Item key="spine"> <Link to={utils.getLocalizedPathname(`/${version}/docs/spine`, isZhCN)}> Spine </Link> </Menu.Item> <Menu.Item key="lottie"> <Link to={utils.getLocalizedPathname(`/${version}/docs/lottie`, isZhCN)}> Lottie </Link> </Menu.Item> </Menu.ItemGroup> </Menu.SubMenu> <Menu.SubMenu key="community" icon={<NotificationOutlined />} title={formatMessage({ id: "app.header.menu.community" })}> <Menu.Item key="zhihu" icon={<ZhihuOutlined />}> <a target="_blank" rel="noopener noreferrer" href="https://www.zhihu.com/column/c_1369047387231592448"> <FormattedMessage id="app.community.zhihu" /> </a> </Menu.Item> <Menu.Item key="juejin" icon={<Icon type="icon-juejin" />}> <a target="_blank" rel="noopener noreferrer" href="https://juejin.cn/team/6930507995474313230/posts"> <FormattedMessage id="app.community.juejin" /> </a> </Menu.Item> <Menu.Item key="yuque" icon={<YuqueOutlined />}> <a target="_blank" rel="noopener noreferrer" href="https://www.yuque.com/oasis-engine/blog"> <FormattedMessage id="app.community.yuque" /> </a> </Menu.Item> <Menu.Item key="twitter" icon={<TwitterOutlined />}> <a target="_blank" rel="noopener noreferrer" href="https://twitter.com/OasisEngine"> <FormattedMessage id="app.community.twitter" /> </a> </Menu.Item> </Menu.SubMenu> </Menu> ]; return ( <div> <div id="header" className="header"> {menuMode === 'inline' ? ( <Popover overlayClassName="popover-menu" placement="bottomRight" content={menu} trigger="click" visible={menuVisible} arrowPointAtCenter onVisibleChange={this.onMenuVisibleChange} > <MenuOutlined className="nav-phone-icon" onClick={this.handleShowMenu} /> </Popover> ) : null} <Row> <Col xxl={4} xl={5} lg={8} md={8} sm={24} xs={24}> <Link id="logo" to="/"> <img src={LOGO_URL} alt="Oasis Engine" /> </Link> </Col> <Col xxl={20} xl={19} lg={16} md={16} sm={0} xs={0}> <div id="search-box"> <SearchOutlined /> <Input ref={(ref) => { this.searchInput = ref; }} placeholder={intl.formatMessage({ id: 'app.header.search' })} /> </div> <div className="header-meta"> <div className="right-header"> <div id="lang"> <Button onClick={this.handleLangChange} size="small"> <FormattedMessage id="app.header.lang" /> </Button> </div> {(this.state.versions.length && this.props.showVersion) ? <Select size="small" onChange={this.onVersionChange} value={version}> {this.state.versions.map((v) => { return <Option value={v} key={v}>{`v${v}`}</Option> })} </Select> : null} </div> {menuMode === 'horizontal' ? <div id="menu">{menu}</div> : null} </div> </Col> </Row> </div> </div> ); } } export default injectIntl(Header);
the_stack
export class Encoding { private emitBOM: boolean = true; private encodingType: EncodingType = 'Ansi'; /** * Gets a value indicating whether to write a Unicode byte order mark * @returns boolean- true to specify that a Unicode byte order mark is written; otherwise, false */ get includeBom(): boolean { return this.emitBOM; } /** * Gets the encoding type. * @returns EncodingType */ get type(): EncodingType { return this.encodingType; } /** * Sets the encoding type. * @param {EncodingType} value */ set type(value: EncodingType) { this.encodingType = value; } /** * Initializes a new instance of the Encoding class. A parameter specifies whether to write a Unicode byte order mark * @param {boolean} includeBom?-true to specify that a Unicode byte order mark is written; otherwise, false. */ constructor(includeBom?: boolean) { this.initBOM(includeBom); } /** * Initialize the includeBom to emit BOM or Not * @param {boolean} includeBom */ private initBOM(includeBom: boolean): void { if (includeBom === undefined || includeBom === null) { this.emitBOM = true; } else { this.emitBOM = includeBom; } } /** * Calculates the number of bytes produced by encoding the characters in the specified string * @param {string} chars - The string containing the set of characters to encode * @returns {number} - The number of bytes produced by encoding the specified characters */ public getByteCount(chars: string): number { let byteCount: number = 0; validateNullOrUndefined(chars, 'string'); if (chars === '') { let byte: number = this.utf8Len(chars.charCodeAt(0)); return byte; } if (this.type === null || this.type === undefined) { this.type = 'Ansi'; } return this.getByteCountInternal(chars, 0, chars.length); } /** * Return the Byte of character * @param {number} codePoint * @returns {number} */ private utf8Len(codePoint: number): number { let bytes: number = codePoint <= 0x7F ? 1 : codePoint <= 0x7FF ? 2 : codePoint <= 0xFFFF ? 3 : codePoint <= 0x1FFFFF ? 4 : 0; return bytes; } /** * for 4 byte character return surrogate pair true, otherwise false * @param {number} codeUnit * @returns {boolean} */ private isHighSurrogate(codeUnit: number): boolean { return codeUnit >= 0xD800 && codeUnit <= 0xDBFF; } /** * for 4byte character generate the surrogate pair * @param {number} highCodeUnit * @param {number} lowCodeUnit */ private toCodepoint(highCodeUnit: number, lowCodeUnit: number): number { highCodeUnit = (0x3FF & highCodeUnit) << 10; let u: number = highCodeUnit | (0x3FF & lowCodeUnit); return u + 0x10000; } /** * private method to get the byte count for specific charindex and count * @param {string} chars * @param {number} charIndex * @param {number} charCount */ private getByteCountInternal(chars: string, charIndex: number, charCount: number): number { let byteCount: number = 0; if (this.encodingType === 'Utf8' || this.encodingType === 'Unicode') { let isUtf8: boolean = this.encodingType === 'Utf8'; for (let i: number = 0; i < charCount; i++) { let charCode: number = chars.charCodeAt(isUtf8 ? charIndex : charIndex++); if (this.isHighSurrogate(charCode)) { if (isUtf8) { let high: number = charCode; let low: number = chars.charCodeAt(++charIndex); byteCount += this.utf8Len(this.toCodepoint(high, low)); } else { byteCount += 4; ++i; } } else { if (isUtf8) { byteCount += this.utf8Len(charCode); } else { byteCount += 2; } } if (isUtf8) { charIndex++; } } return byteCount; } else { byteCount = charCount; return byteCount; } } /** * Encodes a set of characters from the specified string into the ArrayBuffer. * @param {string} s- The string containing the set of characters to encode * @param {number} charIndex-The index of the first character to encode. * @param {number} charCount- The number of characters to encode. * @returns {ArrayBuffer} - The ArrayBuffer that contains the resulting sequence of bytes. */ public getBytes(s: string, charIndex: number, charCount: number): ArrayBuffer { validateNullOrUndefined(s, 'string'); validateNullOrUndefined(charIndex, 'charIndex'); validateNullOrUndefined(charCount, 'charCount'); if (charIndex < 0 || charCount < 0) { throw new RangeError('Argument Out Of Range Exception: charIndex or charCount is less than zero'); } if (s.length - charIndex < charCount) { throw new RangeError('Argument Out Of Range Exception: charIndex and charCount do not denote a valid range in string'); } let bytes: ArrayBuffer; if (s === '') { bytes = new ArrayBuffer(0); return bytes; } if (this.type === null || this.type === undefined) { this.type = 'Ansi'; } let byteCount: number = this.getByteCountInternal(s, charIndex, charCount); switch (this.type) { case 'Utf8': bytes = this.getBytesOfUtf8Encoding(byteCount, s, charIndex, charCount); return bytes; case 'Unicode': bytes = this.getBytesOfUnicodeEncoding(byteCount, s, charIndex, charCount); return bytes; default: bytes = this.getBytesOfAnsiEncoding(byteCount, s, charIndex, charCount); return bytes; } } /** * Decodes a sequence of bytes from the specified ArrayBuffer into the string. * @param {ArrayBuffer} bytes- The ArrayBuffer containing the sequence of bytes to decode. * @param {number} index- The index of the first byte to decode. * @param {number} count- The number of bytes to decode. * @returns {string} - The string that contains the resulting set of characters. */ public getString(bytes: ArrayBuffer, index: number, count: number): string { validateNullOrUndefined(bytes, 'bytes'); validateNullOrUndefined(index, 'index'); validateNullOrUndefined(count, 'count'); if (index < 0 || count < 0) { throw new RangeError('Argument Out Of Range Exception: index or count is less than zero'); } if (bytes.byteLength - index < count) { throw new RangeError('Argument Out Of Range Exception: index and count do not denote a valid range in bytes'); } if (bytes.byteLength === 0 || count === 0) { return ''; } if (this.type === null || this.type === undefined) { this.type = 'Ansi'; } let out: string = ''; let byteCal: Uint8Array = new Uint8Array(bytes); switch (this.type) { case 'Utf8': let s: string = this.getStringOfUtf8Encoding(byteCal, index, count); return s; case 'Unicode': let byteUnicode: Uint16Array = new Uint16Array(bytes); out = this.getStringofUnicodeEncoding(byteUnicode, index, count); return out; default: let j: number = index; for (let i: number = 0; i < count; i++) { let c: number = byteCal[j]; out += String.fromCharCode(c); // 1 byte(ASCII) character j++; } return out; } } private getBytesOfAnsiEncoding(byteCount: number, s: string, charIndex: number, charCount: number): ArrayBuffer { let bytes: ArrayBuffer = new ArrayBuffer(byteCount); let bufview: Uint8Array = new Uint8Array(bytes); let k: number = 0; for (let i: number = 0; i < charCount; i++) { let charcode: number = s.charCodeAt(charIndex++); if (charcode < 0x800) { bufview[k] = charcode; } else { bufview[k] = 63; //replacement character '?' } k++; } return bytes; } private getBytesOfUtf8Encoding(byteCount: number, s: string, charIndex: number, charCount: number): ArrayBuffer { let bytes: ArrayBuffer = new ArrayBuffer(byteCount); let uint: Uint8Array = new Uint8Array(bytes); let index: number = charIndex; let j: number = 0; for (let i: number = 0; i < charCount; i++) { let charcode: number = s.charCodeAt(index); if (charcode <= 0x7F) { // 1 byte character 2^7 uint[j] = charcode; } else if (charcode < 0x800) { // 2 byte character 2^11 uint[j] = 0xc0 | (charcode >> 6); uint[++j] = 0x80 | (charcode & 0x3f); } else if ((charcode < 0xd800 || charcode >= 0xe000)) { // 3 byte character 2^16 uint[j] = 0xe0 | (charcode >> 12); uint[++j] = 0x80 | ((charcode >> 6) & 0x3f); uint[++j] = 0x80 | (charcode & 0x3f); } else { uint[j] = 0xef; uint[++j] = 0xbf; uint[++j] = 0xbd; // U+FFFE "replacement character" } ++j; ++index; } return bytes; } private getBytesOfUnicodeEncoding(byteCount: number, s: string, charIndex: number, charCount: number): ArrayBuffer { let bytes: ArrayBuffer = new ArrayBuffer(byteCount); let uint16: Uint16Array = new Uint16Array(bytes); for (let i: number = 0; i < charCount; i++) { let charcode: number = s.charCodeAt(i); uint16[i] = charcode; } return bytes; } private getStringOfUtf8Encoding(byteCal: Uint8Array, index: number, count: number): string { let j: number = 0; let i: number = index; let s: string = ''; for (j; j < count; j++) { let c: number = byteCal[i++]; while (i > byteCal.length) { return s; } if (c > 127) { if (c > 191 && c < 224 && i < count) { c = (c & 31) << 6 | byteCal[i] & 63; } else if (c > 223 && c < 240 && i < byteCal.byteLength) { c = (c & 15) << 12 | (byteCal[i] & 63) << 6 | byteCal[++i] & 63; } else if (c > 239 && c < 248 && i < byteCal.byteLength) { c = (c & 7) << 18 | (byteCal[i] & 63) << 12 | (byteCal[++i] & 63) << 6 | byteCal[++i] & 63; } ++i; } s += String.fromCharCode(c); // 1 byte(ASCII) character } return s; } private getStringofUnicodeEncoding(byteUni: Uint16Array, index: number, count: number): string { if (count > byteUni.length) { throw new RangeError('ArgumentOutOfRange_Count'); } let byte16: Uint16Array = new Uint16Array(count); let out: string = ''; for (let i: number = 0; i < count && i < byteUni.length; i++) { byte16[i] = byteUni[index++]; } out = String.fromCharCode.apply(null, byte16); return out; } /** * To clear the encoding instance * @return {void} */ public destroy(): void { this.emitBOM = undefined; this.encodingType = undefined; } } /** * EncodingType : Specifies the encoding type */ export type EncodingType = /** * Specifies the Ansi encoding */ 'Ansi' | /** * Specifies the utf8 encoding */ 'Utf8' | /** * Specifies the Unicode encoding */ 'Unicode'; /** * To check the object is null or undefined and throw error if it is null or undefined * @param {Object} value - object to check is null or undefined * @return {boolean} * @throws {ArgumentException} - if the value is null or undefined * @private */ export function validateNullOrUndefined(value: Object, message: string): void { if (value === null || value === undefined) { throw new Error('ArgumentException: ' + message + ' cannot be null or undefined'); } }
the_stack
import {readFileSync} from "fs"; import {resolve, URL} from "url"; // tslint:disable-next-line:no-var-requires const validator = require("amphtml-validator").newInstance( // Let's not fetch over the network on every run. // Use `npm run update-data` to update. // tslint:disable-next-line:no-var-requires readFileSync(`${__dirname}/validator.js`).toString(), ); import createCacheUrl = require("amp-toolbox-cache-url"); import * as cheerio from "cheerio"; import throat = require("throat"); import {default as fetch, Request, RequestInit, Response} from "node-fetch"; import {basename} from "path"; import * as probe from "probe-image-size"; import * as punycode from "punycode"; import * as readline from "readline"; const CONCURRENCY = 8; const UA_GOOGLEBOT_MOBILE = [ "Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36", "(KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36", "(compatible; Googlebot/2.1; +http://www.google.com/bot.html)", ].join(" "); export interface ActualExpected { readonly actual: string|undefined; readonly expected: string; } export interface Message { readonly status: string; readonly message?: string|ActualExpected; } export interface Context { readonly url: string; readonly $: CheerioStatic; readonly headers: { [key: string]: string; }; } export interface Test { (context: Context): Promise<Message>; } export interface TestList { (context: Context): Promise<Message[]>; } interface InlineMetadata { "title": string; "publisher": string; "publisher-logo-src": string; "poster-portrait-src": string; "poster-square-src"?: string; "poster-landscape-src"?: string; } const S_PASS = "PASS"; const S_FAIL = "FAIL"; const S_WARN = "WARN"; const S_INFO = "INFO"; export const PASS = (): Promise<Message> => Promise.resolve({status: S_PASS}); export const FAIL = (s: string|ActualExpected) => { return Promise.resolve({status: S_FAIL, message: s}); }; export const WARN = (s: string|ActualExpected) => { return Promise.resolve({status: S_WARN, message: s}); }; export const INFO = (s: string|ActualExpected) => { return Promise.resolve({status: S_INFO, message: s}); }; const isPass = (m: Message): boolean => { return m.status === S_PASS; }; const notPass = (m: Message): boolean => { return m.status !== S_PASS; }; const getBody = throat(CONCURRENCY, (context: Context, s: string|Request, init = {}) => { if (!("headers" in init)) { init.headers = {}; } // Might be able to use type guards to avoid the cast somehow... (init.headers as {[key: string]: string})["user-agent"] = UA_GOOGLEBOT_MOBILE; return fetch(s, init); // return res.ok ? res.text() : new Error(res); }, ); const getUrl = throat(CONCURRENCY, async (context: Context, s: string|Request) => { const res = await fetch(s, {headers: context.headers }); return res.url; }, ); const getContentLength = throat(CONCURRENCY, async (context: Context, s: string|Request) => { const options = Object.assign( {}, { method: "HEAD" }, { headers: context.headers } ); const res = await fetch(s, options); if (!res.ok) { return Promise.reject(res); } const contentLength = res.headers.get("content-length"); return contentLength ? contentLength : 0; }, ); const absoluteUrl = (s: string|undefined, base: string|undefined) => { if (typeof s !== "string" || typeof base !== "string") { return undefined; } else { return resolve(base, s); } }; const getSchemaMetadata = ($: CheerioStatic) => { const metadata = JSON.parse($('script[type="application/ld+json"]').html() as string); return metadata ? metadata : {}; }; function getInlineMetadata($: CheerioStatic) { const e = $("amp-story"); const inlineMetadata: InlineMetadata = { "poster-landscape-src": e.attr("poster-landscape-src"), // optional "poster-portrait-src": e.attr("poster-portrait-src"), "poster-square-src": e.attr("poster-square-src"), // optional "publisher": e.attr("publisher"), "publisher-logo-src": e.attr("publisher-logo-src"), "title": e.attr("title"), }; return inlineMetadata; } function getImageSize(context: Context, url: string): Promise<{width: number, height: number, mime: string, [k: string]: any}> { // probe-image size can't handle encoded streams: // https://github.com/nodeca/probe-image-size/issues/28 const headers = Object.assign({}, context.headers); delete headers["accept-encoding"]; return probe(absoluteUrl(url, context.url), { headers }); } const getCorsEndpoints = ($: CheerioStatic) => { return ([] as string[]).concat( $("amp-list[src]").map((_, e) => $(e).attr("src")).get(), $("amp-story amp-story-bookend").attr("src"), $("amp-story").attr("bookend-config-src"), ).filter(s => !!s); }; function fetchToCurl(url: string, init: { headers?: { [k: string]: string } } = { headers: {} }) { const headers = init.headers || {}; const h = Object.keys(headers).map(k => `-H '${k}: ${headers[k]}'`).join(" "); return `curl -i ${h} '${url}'`; } const testValidity: Test = ({$}) => { const res = validator.validateString($.html()); return Promise.resolve(res.status === "PASS" ? PASS() : res); }; const testCanonical: Test = (context) => { const {$, url} = context; const href = $('link[rel="canonical"]').attr("href"); if (!href) { return FAIL("<link rel=canonical> not specified"); } const canonical = absoluteUrl(href, url); if (url !== canonical) { return FAIL({ actual: canonical, expected: url, }); } return getUrl(context, canonical).then((s) => { if (s === canonical) { return PASS(); } else { return FAIL({ actual: s, expected: canonical, }); } }, ).catch(() => { return FAIL(`couldn't retrieve canonical ${canonical}`); }); }; const testSchemaMetadataType: Test = ({$}) => { const metadata = getSchemaMetadata($); const type = metadata["@type"]; if (type !== "Article" && type !== "NewsArticle" && type !== "ReportageNewsArticle") { return WARN(`@type is not 'Article' or 'NewsArticle' or 'ReportageNewsArticle'`); } else { return PASS(); } }; const testSchemaMetadataRecent: Test = ({$}) => { const inLastMonth = (time: number) => { return (time > Date.now() - (30 * 24 * 60 * 60 * 1000)) && (time < Date.now()); }; const metadata = getSchemaMetadata($); const datePublished = metadata.datePublished; const dateModified = metadata.dateModified; if (!datePublished || !dateModified) { return FAIL(`datePublished or dateModified not found`); } const timePublished = Date.parse(datePublished); const timeModified = Date.parse(dateModified); if (isNaN(timePublished) || isNaN(timeModified)) { return FAIL(`couldn't parse datePublished [${datePublished}] or dateModified [${dateModified}]`); } if (timeModified < timePublished) { return FAIL(`dateModified [${dateModified}] is earlier than datePublished [${datePublished}]`); } if (inLastMonth(timePublished) && inLastMonth(timeModified)) { return PASS(); } else { return WARN(`datePublished [${datePublished}] or dateModified [${dateModified}] is old or in the future`); } }; const testAmpStory: Test = ({$}) => { if ($("body amp-story[standalone]").length === 1) { return PASS(); } else { return FAIL(`couldn't find <amp-story standalone> component`); } }; const testVideoSize: Test = (context) => { const {$} = context; return Promise.all($(`amp-video source[type="video/mp4"][src], amp-video[src]`).map(async (i, e) => { const url = absoluteUrl($(e).attr("src"), context.url); const length = await getContentLength(context, url!); return { url, length }; }).get() as any as Array<Promise<{ url: string, length: number }>>).then((args) => { // TODO(stillers): switch to Map return args.reduce((a, v) => { a[v.url] = v.length; return a; }, {} as {[url: string]: number}); }).then((videos) => { const large = Object.keys(videos).filter((v) => videos[v] > 4000000); if (large.length > 0) { return FAIL(`videos over 4MB: [${large.join(",")}]`); } else { return PASS(); } }); }; /** * Adds `__amp_source_origin` query parameter to URL. * * @param url * @param sourceOrigin */ function addSourceOrigin(url: string, sourceOrigin: string) { const {parse, format} = require("url"); // use old API to work with node 6+ const obj = parse(url, true); obj.query.__amp_source_origin = sourceOrigin; obj.search = require("querystring").stringify(obj.query); return format(obj); } function isJson(res: Response): Promise<Response> { const contentType = (() => { if (!res.headers) { return ""; } const s = res.headers.get("content-type") || ""; return s.toLowerCase().split(";")[0]; })(); if (contentType !== "application/json") { throw new Error(`expected content-type: [application/json]; actual: [${contentType}]`); } return res.text().then((text) => { try { JSON.parse(text); } catch (e) { throw new Error(`couldn't parse body as JSON: ${text.substring(0, 100)}`); } return res; }); } function isStatusNotOk(res: Response) { if (!res.ok) { return res; } else { throw new Error(`expected status code: [1xx, 3xx, 4xx, 5xx], actual [${res.status}]`); } } function isStatusOk(res: Response) { if (res.ok) { return res; } else { throw new Error(`expected status code: [2xx], actual [${res.status}]`); } } function isAccessControlHeaders(origin: string, sourceOrigin: string): (res: Response) => Response { return (res) => { const h1 = res.headers.get("access-control-allow-origin") || ""; if ((h1 !== origin) && (h1 !== "*")) { throw new Error( `access-control-allow-origin header is [${h1}], expected [${origin}]`, ); } // The AMP docs specify that the AMP-Access-Control-Allow-Source-Origin and // Access-Control-Expose-Headers headers must be returned, but this is not // in true: the runtime does check this header, but only if the // requireAmpResponseSourceOrigin flag is true, and amp-story sets this to // false. // // https://www.ampproject.org/docs/fundamentals/amp-cors-requests#ensuring-secure-responses /* const h2 = res.headers.get('amp-access-control-allow-source-origin') || ''; if (h2 !== sourceOrigin) throw new Error( `amp-access-control-allow-source-origin header is [${h2}], expected [${sourceOrigin}]` ); const h3 = res.headers.get('access-control-expose-headers') || ''; if (h3 !== 'AMP-Access-Control-Allow-Source-Origin') throw new Error( `access-control-expose-headers is [${h3}], expected [AMP-Access-Control-Allow-Source-Origin]` ); */ return res; }; } function buildSourceOrigin(url: string) { const {parse} = require("url"); // use old API to work with node 6+ const obj = parse(url, true); return `${obj.protocol}//${obj.host}`; } function canXhrSameOrigin(context: Context, xhrUrl: string) { xhrUrl = absoluteUrl(xhrUrl, context.url)!; const sourceOrigin = buildSourceOrigin(context.url); const headers = Object.assign( {}, {"amp-same-origin": "true"}, context.headers ); const curl = fetchToCurl(addSourceOrigin(xhrUrl, sourceOrigin), { headers }); return fetch(addSourceOrigin(xhrUrl, sourceOrigin), {headers}) .then(isStatusOk) .then(isJson) .then(PASS, (e: Error) => FAIL(`can't XHR [${xhrUrl}]: ${e.message} [debug: ${curl}]`)); } async function canXhrCache(context: Context, xhrUrl: string, cacheSuffix: string) { const sourceOrigin = buildSourceOrigin(context.url); const url = await createCacheUrl(cacheSuffix, context.url); const {parse} = require("url"); // use old API to work with node 6+ const obj = parse(url); const origin = `${obj.protocol}//${obj.host}`; const headers = Object.assign( {}, {origin}, context.headers ); const curl = fetchToCurl(addSourceOrigin(xhrUrl, sourceOrigin), { headers }); return fetch(addSourceOrigin(xhrUrl, sourceOrigin), {headers}) .then(isStatusOk) .then(isAccessControlHeaders(origin, sourceOrigin)) .then(isJson) .then(PASS, (e) => FAIL(`can't XHR [${xhrUrl}]: ${e.message} [debug: ${curl}]`)); } const testBookendSameOrigin: Test = (context) => { const {$, url} = context; const s1 = $("amp-story amp-story-bookend").attr("src"); const s2 = $("amp-story").attr("bookend-config-src"); const bookendSrc = s1 || s2; if (!bookendSrc) { return WARN("amp-story-bookend missing"); } const bookendUrl = absoluteUrl(bookendSrc, url); return canXhrSameOrigin(context, bookendUrl!); }; const testBookendCache: Test = (context) => { const {$, url} = context; const s1 = $("amp-story amp-story-bookend").attr("src"); const s2 = $("amp-story").attr("bookend-config-src"); const bookendSrc = s1 || s2; if (!bookendSrc) { return WARN("amp-story-bookend missing"); } const bookendUrl = absoluteUrl(bookendSrc, url); return canXhrCache(context, bookendUrl!, "cdn.ampproject.org"); }; const testVideoSource: Test = ({$}) => { if ($("amp-video[src]").length > 0) { return FAIL("<amp-video src> used instead of <amp-video><source/></amp-video>"); } else { return PASS(); } }; const testAmpStoryV1: Test = ({$}) => { const isV1 = $("script[src='https://cdn.ampproject.org/v0/amp-story-1.0.js']").length > 0; return isV1 ? PASS() : WARN("amp-story-1.0.js not used (probably 0.1?)"); }; const testAmpStoryV1Metadata: Test = ({$}) => { const isV1 = $("script[src='https://cdn.ampproject.org/v0/amp-story-1.0.js']").length > 0; if (!isV1) { return PASS(); } const attr: string[] = [ "title", "publisher", "publisher-logo-src", "poster-portrait-src" ] .map(a => $(`amp-story[${a}]`).length > 0 ? false : a) .filter(Boolean) as string[]; if (attr.length > 0) { return WARN(`<amp-story> is missing attribute(s) that will soon be mandatory: [${attr.join(", ")}]`); } else { return PASS(); } }; const testMetaCharsetFirst: Test = ({$}) => { const firstChild = $("head *:first-child"); const charset = firstChild.attr("charset"); return !charset ? FAIL(`<meta charset> not the first <meta> tag`) : PASS(); }; const testRuntimePreloaded: Test = ({$}) => { const attr = [ "href='https://cdn.ampproject.org/v0.js'", "rel='preload'", "as='script'" ].map(s => `[${s}]`).join(""); const isPreloaded = $(`link${attr}`).length > 0; return isPreloaded ? PASS() : WARN("<link href=https://cdn.ampproject.org/v0.js rel=preload> is missing"); }; const testMostlyText: Test = ({$}) => { const text = $("amp-story").text(); if (text.length > 100) { return PASS(); } else { return WARN(`minimal text in the story [${text}]`); } }; const testThumbnails: TestList = async (context) => { const $ = context.$; async function isSquare(url: string|undefined) { if (!url) { return false; } const {width, height} = await getImageSize(context, absoluteUrl(url, context.url)!); return width === height; } async function isPortrait(url: string|undefined) { if (!url) { return false; } const {width, height} = await getImageSize(context, absoluteUrl(url, context.url)!); return (width > (0.74 * height)) && (width < (0.76 * height)); } async function isLandscape(url: string|undefined) { if (!url) { return false; } const {width, height} = await getImageSize(context, absoluteUrl(url, context.url)!); return (height > (0.74 * width)) && (height < (0.76 * width)); } const inlineMetadata = getInlineMetadata($); const res: Array<Promise<Message>> = []; res.push((() => { const k = "publisher-logo-src"; const v = inlineMetadata[k]; return isSquare(v).then( r => r ? PASS() : FAIL(`[${k}] (${v}) is missing or not square (1:1)`), e => FAIL(`[${k}] (${v}) status not 200`) ); })()); res.push((() => { const k = "poster-portrait-src"; const v = inlineMetadata[k]; return isPortrait(v).then( r => r ? PASS() : FAIL(`[${k}] (${v}) is missing or not portrait (3:4)`), e => FAIL(`[${k}] (${v}) status not 200`) ); })()); (() => { const k = "poster-square-src"; const v = inlineMetadata[k]; if (v) { res.push(isSquare(v).then( r => r ? PASS() : FAIL(`[${k}] (${v}) is not square (1x1)`), e => FAIL(`[${k}] (${v}) status not 200`) )); } })(); (() => { const k = "poster-landscape-src"; const v = inlineMetadata[k]; if (v) { res.push(isLandscape(v).then( r => r ? PASS() : FAIL(`[${k}] (${v}) is not landscape (4:3)`), e => FAIL(`[${k}] (${v}) status not 200`) )); } })(); return (await Promise.all(res)).filter(notPass); }; const testSingleAmpImg = ( context: Context, { src, expectedWidth, expectedHeight }: { src: string, expectedWidth: number, expectedHeight: number } ): Promise<Message> => { const success = ({height, width}: {height: number, width: number}): Promise<Message> => { const actualHeight = height; const actualWidth = width; const actualRatio = Math.floor(actualWidth * 100 / actualHeight) / 100; const expectedRatio = Math.floor(expectedWidth * 100 / expectedHeight) / 100; if (Math.abs(actualRatio - expectedRatio) > 0.015) { const actualString = `${actualWidth}/${actualHeight} = ${actualRatio}`; const expectedString = `${expectedWidth}/${expectedHeight} = ${expectedRatio}`; return FAIL(`[${src}]: actual ratio [${actualString}] does not match specified [${expectedString}]`); } const actualVolume = actualWidth * actualHeight; const expectedVolume = expectedWidth * expectedHeight; if (expectedVolume < (0.25 * actualVolume)) { const actualString = `${actualWidth}x${actualHeight}`; const expectedString = `${expectedWidth}x${expectedHeight}`; return WARN(`[${src}]: actual dimensions [${actualString}] are much larger than specified [${expectedString}]`); } if (expectedVolume > (1.5 * actualVolume)) { const actualString = `${actualWidth}x${actualHeight}`; const expectedString = `${expectedWidth}x${expectedHeight}`; return WARN(`[${src}]: actual dimensions [${actualString}] are much smaller than specified [${expectedString}]`); } return PASS(); }; const fail = (e: {statusCode: number}) => { if (e.statusCode === undefined) { return FAIL(`[${src}] ${JSON.stringify(e)}`); } else { return FAIL(`[${src}] returned status ${e.statusCode}`); } }; return getImageSize(context, absoluteUrl(src, context.url)!).then(success, fail); }; const testAmpImg: TestList = async (context) => { const $ = context.$; return (await Promise.all($("amp-img").map((_, e) => { const src = $(e).attr("src"); const expectedHeight = parseInt($(e).attr("height"), 10); const expectedWidth = parseInt($(e).attr("width"), 10); return testSingleAmpImg(context, { src, expectedHeight, expectedWidth }); }).get() as any as Array<Promise<Message>>)).filter(notPass); }; const testCorsSameOrigin: TestList = async (context) => { const corsEndpoints = getCorsEndpoints(context.$); return (await Promise.all(corsEndpoints.map(s => canXhrSameOrigin(context, s)))).filter(notPass); }; const testCorsCache: TestList = async (context) => { // Cartesian product from https://stackoverflow.com/a/43053803/11543 const cartesian = (a: any, b: any) => [].concat(...a.map((d: any) => b.map((e: any) => [].concat(d, e)))); const corsEndpoints = getCorsEndpoints(context.$); const caches = (require("./caches.json").caches as Array<{ cacheDomain: string }>).map(c => c.cacheDomain); const product = cartesian(corsEndpoints, caches); return (await Promise.all( product.map(([xhrUrl, cacheSuffix]) => canXhrCache(context, xhrUrl, cacheSuffix)) )).filter(notPass); }; const testAll = async (context: Context): Promise<{[key: string]: Message}> => { const tests = [ testValidity, testCanonical, testAmpStory, testAmpStoryV1, testAmpStoryV1Metadata, testSchemaMetadataRecent, testSchemaMetadataType, testBookendSameOrigin, testBookendCache, testVideoSource, testVideoSize, testMostlyText, testRuntimePreloaded, testThumbnails, testMetaCharsetFirst, testAmpImg, testCorsSameOrigin, testCorsCache, ]; const res = await Promise.all(tests.map(async (testFn) => { const v = await testFn(context); return [ testFn.name.substring("test".length).toLowerCase(), // key v, // value ]; })) as Array<[string, Message]>; // not sure why this cast is necessary, but... return res.reduce((a: {[key: string]: Message}, kv: [string, Message]) => { a[kv[0]] = kv[1]; return a; }, {}); }; export { testAll, testAmpStory, testAmpStoryV1, testAmpStoryV1Metadata, testBookendCache, testBookendSameOrigin, testCanonical, testSchemaMetadataType, testSchemaMetadataRecent, testMostlyText, testValidity, testVideoSize, testVideoSource, testMetaCharsetFirst, testRuntimePreloaded, testThumbnails, testAmpImg, testCorsSameOrigin, testCorsCache, fetchToCurl, // "private" functions get prefixed getBody as _getBody, getSchemaMetadata as _getSchemaMetadata, getInlineMetadata as _getInlineMetadata, getImageSize as _getImageSize, getCorsEndpoints as _getCorsEndpoints, }; if (require.main === module) { // invoked directly? if (process.argv.length <= 2) { console.error(`usage: ${basename(process.argv[0])} ${basename(process.argv[1])} URL|copy_as_cURL`); process.exit(1); } const url = process.argv[2] === "-" ? "-" : process.argv.filter(s => s.match(/^http/))[0]; function seq(first: number, last: number): number[] { if (first < last) { return [first].concat(seq(first + 1, last)); } else if (first > last) { return [last].concat(seq(first, last - 1)); } else { return [first]; } } const headers = seq(2, process.argv.length - 1) .filter(n => process.argv[n] === "-H") .map(n => process.argv[n + 1]) .map(s => { const [h, ...v] = s.split(": "); return [h, v.join("")]; }) .reduce((a: {[key: string]: any}, kv) => { a[kv[0]] = kv[1]; return a; }, {}); // console.log({url, headers}); const body = (() => { if (url === "-") { return Promise.resolve(readFileSync("/dev/stdin").toString()); } else { return fetch(url, { headers }).then( r => r.ok ? r.text() : Promise.reject(`couldn't load [${url}]: ${r.statusText}`) ); } })(); body .then(b => cheerio.load(b)) .then($ => testAll({$, headers, url})) .then(r => console.log(JSON.stringify(r, null, 2))) .then(() => process.exit(0)) .catch((e) => console.error(`error: ${e}`)); }
the_stack
import selector from '../fixtures/selectors.json'; import cypressJson from '../../cypress.json'; const setup = [ { width: 1440, height: 900, viewport: 'macbook-15' as const, device: 'Laptop', }, { width: 375, height: 667, viewport: 'iphone-6' as const, device: 'Mobile' }, { width: 768, height: 1024, viewport: 'ipad-2' as const, device: 'Tablet' }, ]; describe('Single Select', () => { before(() => { cy.visit(cypressJson.baseUrl); cy.title().should('equal', 'React-Select'); cy.get('h1').should('contain', 'Test Page for Cypress'); }); for (let config of setup) { const { viewport } = config; context(`Basic in view: ${viewport}`, () => { before(() => { cy.viewport(viewport); }); beforeEach(() => { cy.reload(); }); // TODO: // This test seems to fail when cypress tab is focused. // Also, manual testing does not confirm the desired behavior. it.skip(`Should not display the options menu when touched and dragged in view: ${viewport}`, () => { cy.get(selector.toggleMenuSingle) .click() .click() .get(selector.menuSingle) .should('not.be.visible') // to be sure it says focus and the menu is closed .get(selector.singleSelectSingleInput) .trigger('mousedown') .get(selector.menuSingle) .should('not.be.visible'); }); it(`Should display a default value in view: ${viewport}`, () => { cy.get(selector.singleBasicSelect) .find(selector.singleValue) .should('contain', 'Ocean'); }); it(`Should expand the menu when expand icon is clicked in view: ${viewport}`, () => { cy // Menu is not yet open .get(selector.singleBasicSelect) .find(selector.menu) .should('not.exist') // A dropdown icon is shown .get(selector.singleBasicSelect) .find(selector.indicatorDropdown) .should('be.visible') // Click the icon to open the menu .click() .get(selector.singleBasicSelect) .find(selector.menu) .should('exist') .should('be.visible') .contains('Green'); }); it(`Should close the menu after selecting an option in view: ${viewport}`, () => { cy.get(selector.singleBasicSelect) .find(selector.indicatorDropdown) .click() .get(selector.singleBasicSelect) .find(selector.menu) .should('contain', 'Green') .contains('Green') .click() // Value has updated .get(selector.singleBasicSelect) .find(selector.singleValue) .should('contain', 'Green') // Menu has closed .get(selector.singleBasicSelect) .find(selector.menu) .should('not.exist'); }); it(`Should be disabled once disabled is checked in view: ${viewport}`, () => { cy // Does not start out disabled .get(selector.singleBasicSelect) // .click() .find('input') .should('exist') .should('not.be.disabled') // Disable the select component .get(selector.singleBasic) .find(selector.checkboxDisable) .click() // Now the input should be disabled .get(selector.singleBasicSelect) .click({ force: true }) .find('input') .should('exist') .should('be.disabled'); }); it(`Should filter options when searching in view: ${viewport}`, () => { cy.get(selector.singleBasicSelect) .click() .find('input') .type('For', { force: true }) .get(selector.singleBasicSelect) .find(selector.menu) .should('contain', 'Forest') .find(selector.menuOption) .should('have.length', 1); }); it(`Should show "No options" if searched value is not found in view: ${viewport}`, () => { cy.get(selector.singleBasicSelect) .click() .find('input') .type('/', { force: true }) .get(selector.noOptionsValue) .should('contain', 'No options'); }); it(`Should not clear the value when backspace is pressed in view: ${viewport}`, () => { cy.get(selector.singleBasicSelect) .click() .find('input') .type('{backspace}', { force: true }) .get(selector.singleBasicSelect) .find(selector.placeholder) .should('not.be.visible'); }); }); context(`Grouped in view: ${viewport}`, () => { before(() => { cy.viewport(viewport); }); beforeEach(() => { cy.reload(); }); it(`Should display a default value in view: ${viewport}`, () => { cy.get(selector.singleGroupedSelect) .find(selector.singleValue) .should('contain', 'Blue'); }); it(`Should display group headings in the menu in view: ${viewport}`, () => { cy.get(selector.singleGroupedSelect) .find(selector.indicatorDropdown) .click() .get(selector.singleGroupedSelect) .find(selector.menu) .should('be.visible') .find(selector.groupHeading) .should('have.length', 2); }); it(`Should focus next option on down arrow key press: ${viewport}`, () => { cy.get(selector.singleGroupedSelect) .click() .find('input') .type('{downarrow}', { force: true }) .get(selector.focusedOption) .should('exist'); }); it(`Should focus next option on down arrow key press after filtering: ${viewport}`, () => { cy.get(selector.singleGroupedSelect) .click() .find('input') .type('o', { force: true }) .type('{downarrow}', { force: true }) .get(selector.focusedOption) .should('exist'); }); }); context(`Clearable in view: ${viewport}`, () => { before(() => { cy.viewport(viewport); }); beforeEach(() => { cy.reload(); }); it(`Should display a default value in view: ${viewport}`, () => { cy.get(selector.singleClearableSelect) .find(selector.singleValue) .should('contain', 'Blue'); }); it(`Should display a clear indicator in view: ${viewport}`, () => { cy.get(selector.singleClearableSelect) .find(selector.indicatorClear) .should('be.visible'); }); it(`Should clear the default value when clear is clicked in view: ${viewport}`, () => { cy.get(selector.singleClearableSelect) .find(selector.indicatorClear) .click() .get(selector.singleClearableSelect) .find(selector.placeholder) .should('be.visible') .should('contain', 'Select...'); }); // 'backspaceRemovesValue' is true by default it(`Should clear the value when backspace is pressed in view: ${viewport}`, () => { cy.get(selector.singleClearableSelect) .click() .find('input') .type('{backspace}', { force: true }) .get(selector.singleClearableSelect) .find(selector.placeholder) .should('be.visible') .should('contain', 'Select...'); }); // 'backspaceRemovesValue' is true by default, and delete is included it(`Should clear the value when delete is pressed in view: ${viewport}`, () => { cy.get(selector.singleClearableSelect) .click() .find('input') .type('{del}', { force: true }) .get(selector.singleClearableSelect) .find(selector.placeholder) .should('be.visible') .should('contain', 'Select...'); }); it(`Should not open the menu when a value is cleared with backspace in view: ${viewport}`, () => { cy.get(selector.singleClearableSelect) .click() .find('input') // Close the menu, but leave focused .type('{esc}', { force: true }) .get(selector.singleClearableSelect) .find(selector.menu) .should('not.be.visible') // Clear the value, verify menu doesn't pop .get(selector.singleClearableSelect) .find('input') .type('{backspace}', { force: true }) .get(selector.singleClearableSelect) .find(selector.menu) .should('not.be.visible'); }); it(`Should clear the value when escape is pressed if escapeClearsValue and menu is closed in view: ${viewport}`, () => { cy // nothing happens if escapeClearsValue is false .get(selector.singleClearableSelect) .click() .find('input') // Escape once to close the menu .type('{esc}', { force: true }) .get(selector.singleBasicSelect) .find(selector.menu) .should('not.be.visible') // Escape again to verify value is not cleared .get(selector.singleClearableSelect) .find('input') .type('{esc}', { force: true }) .get(selector.singleClearableSelect) .find(selector.placeholder) .should('not.be.visible') // Enable escapeClearsValue and try again, it should clear the value .get(selector.singleClearable) .find(selector.checkboxEscapeClearsValue) .click() .get(selector.singleClearableSelect) .click() .find('input') // Escape once to close the menu .type('{esc}', { force: true }) .get(selector.singleBasicSelect) .find(selector.menu) .should('not.be.visible') // Escape again to clear value .get(selector.singleClearableSelect) .find('input') .type('{esc}', { force: true }) .get(selector.singleClearableSelect) .find(selector.placeholder) .should('be.visible'); }); }); } });
the_stack
import assert from 'assert'; import Ajv from 'ajv'; import { Route, normalizeRoutes, isHandler, routesSchema, rewritesSchema, redirectsSchema, headersSchema, cleanUrlsSchema, trailingSlashSchema, getTransformedRoutes, } from '../src'; const ajv = new Ajv(); const assertValid = (data: unknown, schema: object = routesSchema) => { const validate = ajv.compile(schema); const valid = validate(data); if (!valid) console.log(validate.errors); assert.equal(valid, true); }; const assertError = ( data: unknown, errors: Ajv.ErrorObject[], schema: object = routesSchema ) => { const validate = ajv.compile(schema); const valid = validate(data); assert.equal(valid, false); assert.deepEqual(validate.errors, errors); }; describe('normalizeRoutes', () => { test('should return routes null if provided routes is null', () => { const actual = normalizeRoutes(null); assert.equal(actual.routes, null); }); test('accepts valid routes', () => { const routes: Route[] = [ { src: '^(?:/(?<value>en|fr))?(?<path>/.*)$', locale: { // @ts-expect-error `value` is not defined… is this a bug or should this prop be added to the type? value: '$value', path: '$path', default: 'en', cookie: 'NEXT_LOCALE', }, }, { src: '^/(?:en/?|fr/?)$', locale: { redirect: { en: '/en', fr: '/fr' }, }, }, { src: '^/about$' }, { src: '^/about$', middleware: 0 }, { src: '^/about$', middlewarePath: 'pages/_middleware' }, { src: '^/blog$', methods: ['GET'], headers: { 'Cache-Control': 'no-cache' }, dest: '/blog', }, { src: '^/.*$', middleware: 0, }, { handle: 'filesystem' }, { src: '^/(?<slug>[^/]+)$', dest: 'blog?slug=$slug' }, { handle: 'hit' }, { src: '^/hit-me$', headers: { 'Cache-Control': 'max-age=20' }, continue: true, }, { handle: 'miss' }, { src: '^/missed-me$', dest: '/api/missed-me', check: true }, { src: '^/missed-me$', headers: { 'Cache-Control': 'max-age=10' }, continue: true, important: true, }, { handle: 'rewrite' }, { src: '^.*$', dest: '/somewhere' }, { handle: 'error' }, { src: '^.*$', dest: '/404', status: 404, }, { src: '^/hello$', dest: '/another', has: [ { type: 'header', key: 'x-rewrite' }, { type: 'cookie', key: 'loggedIn', value: 'yup' }, { type: 'query', key: 'authorized', value: 'yup' }, { type: 'host', value: 'vercel.com' }, ], missing: [ { type: 'header', key: 'x-middleware-subrequest', value: 'secret' }, ], }, ]; assertValid(routes); const normalized = normalizeRoutes(routes); assert.equal(normalized.error, null); assert.deepStrictEqual(normalized.routes, routes); }); test('normalizes src', () => { const expected = '^/about$'; const sources = [ { src: '/about' }, { src: '/about$' }, { src: '\\/about' }, { src: '\\/about$' }, { src: '^/about' }, { src: '^/about$' }, { src: '^\\/about' }, { src: '^\\/about$' }, ]; assertValid(sources); const normalized = normalizeRoutes(sources); assert.equal(normalized.error, null); assert.notEqual(normalized.routes, null); if (normalized.routes) { normalized.routes.forEach(route => { if (isHandler(route)) { assert.fail( `Normalizer returned: { handle: ${route.handle} } instead of { src: ${expected} }` ); } else { assert.strictEqual(route.src, expected); } }); } }); test('returns if null', () => { const input = null; const { error, routes } = normalizeRoutes(input); assert.strictEqual(error, null); assert.strictEqual(routes, input); }); test('returns if empty', () => { const input: Route[] = []; const { error, routes } = normalizeRoutes(input); assert.strictEqual(error, null); assert.strictEqual(routes, input); }); test('fails if route has unknown `handle` value', () => { // @ts-expect-error - intentionally passing invalid "handle" const input: Route[] = [{ handle: 'doesnotexist' }]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 0 has unknown handle value `handle: doesnotexist`.' ); }); test('fails if route has additional properties with `handle` property', () => { // @ts-expect-error - intentionally passing invalid property const input: Route[] = [{ handle: 'filesystem', illegal: true }]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 0 has unknown property `illegal`.' ); }); test('fails if route has a duplicate `handle` value', () => { const input: Route[] = [{ handle: 'filesystem' }, { handle: 'filesystem' }]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 1 is a duplicate. Please use one `handle: filesystem` at most.' ); }); test('fails if route has a invalid regex', () => { const input: Route[] = [{ src: '^/(broken]$' }]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 0 has invalid `src` regular expression "^/(broken]$".' ); }); test('fails if route does not define `handle` or `src` property', () => { // @ts-expect-error - intentionally passing invalid property const input: Route[] = [{ fake: 'foo' }]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 0 must define either `handle` or `src` property.' ); }); test('fails if over 1024 routes', () => { assertError('string', [ { dataPath: '', keyword: 'type', message: 'should be array', params: { type: 'array', }, schemaPath: '#/type', }, ]); const arr = new Array(1026); arr.fill(true); assertError(arr, [ { dataPath: '', keyword: 'maxItems', message: 'should NOT have more than 1024 items', params: { limit: '1024', }, schemaPath: '#/maxItems', }, ]); }); test('fails is src is not string', () => { assertError( [ { src: false, }, ], [ { keyword: 'type', dataPath: '[0].src', schemaPath: '#/items/anyOf/0/properties/src/type', params: { type: 'string' }, message: 'should be string', }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'src' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if dest is not string', () => { assertError( [ // @ts-ignore { dest: false, }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'dest' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if methods is not array', () => { assertError( [ // @ts-ignore { methods: false, }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'methods' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if methods is not string', () => { assertError( [ // @ts-ignore { methods: [false], }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'methods' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if headers is not an object', () => { assertError( [ // @ts-ignore { headers: false, }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'headers' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if header is not a string', () => { assertError( [ // @ts-ignore { headers: { test: false, }, }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'headers' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if handle is not string', () => { assertError( [ // @ts-ignore { handle: false, }, ], [ { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/0/additionalProperties', params: { additionalProperty: 'handle' }, message: 'should NOT have additional properties', }, { keyword: 'type', dataPath: '[0].handle', schemaPath: '#/items/anyOf/1/properties/handle/type', params: { type: 'string' }, message: 'should be string', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if continue is not boolean', () => { assertError( [ // @ts-ignore { continue: 'false', }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'continue' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if check is not boolean', () => { assertError( [ // @ts-ignore { check: 'false', }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'check' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if status is not number', () => { assertError( [ // @ts-ignore { status: '404', }, ], [ { keyword: 'required', dataPath: '[0]', schemaPath: '#/items/anyOf/0/required', params: { missingProperty: 'src' }, message: "should have required property 'src'", }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'status' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if property does not exist', () => { assertError( [ { // @ts-ignore doesNotExist: false, }, ], [ { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/0/additionalProperties', params: { additionalProperty: 'doesNotExist' }, message: 'should NOT have additional properties', }, { keyword: 'additionalProperties', dataPath: '[0]', schemaPath: '#/items/anyOf/1/additionalProperties', params: { additionalProperty: 'doesNotExist' }, message: 'should NOT have additional properties', }, { keyword: 'anyOf', dataPath: '[0]', schemaPath: '#/items/anyOf', params: {}, message: 'should match some schema in anyOf', }, ] ); }); test('fails if redirects permanent is not a boolean', () => { assertError( [ { source: '/foo', destination: '/bar', permanent: 301, }, ], [ { dataPath: '[0].permanent', keyword: 'type', message: 'should be boolean', params: { type: 'boolean', }, schemaPath: '#/items/properties/permanent/type', }, ], redirectsSchema ); }); test('fails if redirects statusCode is not a number', () => { assertError( [ { source: '/foo', destination: '/bar', statusCode: '301', }, ], [ { dataPath: '[0].statusCode', keyword: 'type', message: 'should be integer', params: { type: 'integer', }, schemaPath: '#/items/properties/statusCode/type', }, ], redirectsSchema ); }); test('fails if routes after `handle: hit` use `dest`', () => { const input: Route[] = [ { handle: 'hit', }, { src: '^/user$', dest: '^/api/user$', }, ]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 1 cannot define `dest` after `handle: hit`.' ); }); test('fails if routes after `handle: hit` do not use `continue: true`', () => { const input: Route[] = [ { handle: 'hit', }, { src: '^/user$', headers: { 'Cache-Control': 'no-cache' }, }, ]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 1 must define `continue: true` after `handle: hit`.' ); }); test('fails if routes after `handle: hit` use `status', () => { const input: Route[] = [ { handle: 'hit', }, { src: '^/(.*)$', status: 404, continue: true, }, ]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 1 cannot define `status` after `handle: hit`.' ); }); test('fails if routes after `handle: miss` do not use `check: true`', () => { const input: Route[] = [ { handle: 'miss', }, { src: '^/user$', dest: '^/api/user$', }, ]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 1 must define `check: true` after `handle: miss`.' ); }); test('fails if routes after `handle: miss` do not use `continue: true`', () => { const input: Route[] = [ { handle: 'miss', }, { src: '^/user$', headers: { 'Cache-Control': 'no-cache' }, }, ]; const { error } = normalizeRoutes(input); assert.deepEqual(error?.code, 'invalid_route'); assert.deepEqual( error?.message, 'Route at index 1 must define `continue: true` after `handle: miss`.' ); }); }); describe('getTransformedRoutes', () => { test('should normalize nowConfig.routes', () => { const nowConfig = { routes: [{ src: '/page', dest: '/page.html' }] }; const actual = getTransformedRoutes({ nowConfig }); const expected = normalizeRoutes(nowConfig.routes); assert.deepEqual(actual, expected); assertValid(actual.routes); }); test('should not error when routes is null and cleanUrls is true', () => { const nowConfig = { cleanUrls: true, routes: null }; // @ts-expect-error intentionally passing invalid `routes: null` here const actual = getTransformedRoutes({ nowConfig }); assert.equal(actual.error, null); assertValid(actual.routes); }); test('should not error when has segment is used in destination', () => { const nowConfig = { redirects: [ { source: '/redirect', destination: '/:url', has: [ { type: 'query', key: 'url', value: '(?<url>.*)', }, ], }, ], }; // @ts-expect-error not sure if this one is an error or not… const actual = getTransformedRoutes({ nowConfig }); assert.equal(actual.error, null); assertValid(actual.routes); }); test('should error when routes is defined and cleanUrls is true', () => { const nowConfig = { cleanUrls: true, routes: [{ src: '/page', dest: '/file.html' }], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_mixed_routes'); assert.equal( error?.message, 'If `rewrites`, `redirects`, `headers`, `cleanUrls` or `trailingSlash` are used, then `routes` cannot be present.' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when redirects is invalid regex', () => { const nowConfig = { redirects: [{ source: '^/(*.)\\.html$', destination: '/file.html' }], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_redirect'); assert.equal( error?.message, 'Redirect at index 0 has invalid `source` regular expression "^/(*.)\\.html$".' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when redirects is invalid pattern', () => { const nowConfig = { redirects: [{ source: '/:?', destination: '/file.html' }], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_redirect'); assert.equal( error?.message, 'Redirect at index 0 has invalid `source` pattern "/:?".' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when redirects defines both permanent and statusCode', () => { const nowConfig = { redirects: [ { source: '^/both$', destination: '/api/both', permanent: false, statusCode: 302, }, ], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_redirect'); assert.equal( error?.message, 'Redirect at index 0 cannot define both `permanent` and `statusCode` properties.' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when headers is invalid regex', () => { const nowConfig = { headers: [ { source: '^/(*.)\\.html$', headers: [ { key: 'Cache-Control', value: 'public, max-age=0, must-revalidate', }, ], }, ], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_header'); assert.equal( error?.message, 'Header at index 0 has invalid `source` regular expression "^/(*.)\\.html$".' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when headers is invalid pattern', () => { const nowConfig = { headers: [ { source: '/:?', headers: [{ key: 'x-hello', value: 'world' }] }, ], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_header'); assert.equal( error?.message, 'Header at index 0 has invalid `source` pattern "/:?".' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when rewrites is invalid regex', () => { const nowConfig = { rewrites: [{ source: '^/(*.)\\.html$', destination: '/file.html' }], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_rewrite'); assert.equal( error?.message, 'Rewrite at index 0 has invalid `source` regular expression "^/(*.)\\.html$".' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should error when rewrites is invalid pattern', () => { const nowConfig = { rewrites: [{ source: '/:?', destination: '/file.html' }], }; const { error } = getTransformedRoutes({ nowConfig }); assert.notEqual(error, null); assert.equal(error?.code, 'invalid_rewrite'); assert.equal( error?.message, 'Rewrite at index 0 has invalid `source` pattern "/:?".' ); assert.ok(error?.link); assert.ok(error?.action); }); test('should normalize all redirects before rewrites', () => { const nowConfig = { cleanUrls: true, rewrites: [{ source: '/v1', destination: '/v2/api.py' }], redirects: [ { source: '/help', destination: '/support', statusCode: 302 }, { source: '/bug', destination: 'https://example.com/bug', statusCode: 308, }, ], }; const { error, routes } = getTransformedRoutes({ nowConfig }); const expected = [ { src: '^/(?:(.+)/)?index(?:\\.html)?/?$', headers: { Location: '/$1' }, status: 308, }, { src: '^/(.*)\\.html/?$', headers: { Location: '/$1' }, status: 308, }, { src: '^/help$', headers: { Location: '/support' }, status: 302, }, { src: '^/bug$', headers: { Location: 'https://example.com/bug' }, status: 308, }, { handle: 'filesystem' }, { src: '^/v1$', dest: '/v2/api.py', check: true }, ]; assert.deepEqual(error, null); assert.deepEqual(routes, expected); assertValid(routes, routesSchema); }); test('should validate schemas', () => { const nowConfig = { cleanUrls: true, rewrites: [ { source: '/page', destination: '/page.html' }, { source: '/home', destination: '/index.html' }, { source: '/home', destination: '/another', has: [ { type: 'header', key: 'x-rewrite' }, { type: 'cookie', key: 'loggedIn', value: 'yup' }, { type: 'query', key: 'authorized', value: 'yup' }, { type: 'host', value: 'vercel.com' }, ], }, ], redirects: [ { source: '/version1', destination: '/api1.py' }, { source: '/version2', destination: '/api2.py', statusCode: 302 }, { source: '/version3', destination: '/api3.py', permanent: true }, { source: '/version4', destination: '/api4.py', has: [ { type: 'header', key: 'x-redirect' }, { type: 'cookie', key: 'loggedIn', value: 'yup' }, { type: 'query', key: 'authorized', value: 'yup' }, { type: 'host', value: 'vercel.com' }, ], permanent: false, }, ], headers: [ { source: '/(.*)', headers: [ { key: 'Access-Control-Allow-Origin', value: '*', }, ], }, { source: '/404', headers: [ { key: 'Cache-Control', value: 'max-age=300', }, { key: 'Set-Cookie', value: 'error=404', }, ], }, { source: '/add-header', has: [ { type: 'header', key: 'x-header' }, { type: 'cookie', key: 'loggedIn', value: 'yup' }, { type: 'query', key: 'authorized', value: 'yup' }, { type: 'host', value: 'vercel.com' }, ], headers: [ { key: 'Cache-Control', value: 'max-age=forever', }, ], }, ], trailingSlashSchema: false, }; assertValid(nowConfig.cleanUrls, cleanUrlsSchema); assertValid(nowConfig.rewrites, rewritesSchema); assertValid(nowConfig.redirects, redirectsSchema); assertValid(nowConfig.headers, headersSchema); assertValid(nowConfig.trailingSlashSchema, trailingSlashSchema); }); test('should return null routes if no transformations are performed', () => { const nowConfig = { routes: null }; // @ts-expect-error intentionally passing invalid `routes: null` const { routes } = getTransformedRoutes({ nowConfig }); assert.equal(routes, null); }); test('should error when segment is defined in `destination` but not `source`', () => { const nowConfig = { redirects: [ { source: '/iforgot/:id', destination: '/:another', }, ], }; const { routes, error } = getTransformedRoutes({ nowConfig }); assert.deepEqual(routes, null); assert.ok( error?.message.includes( 'in `destination` property but not in `source` or `has` property' ), error?.message ); }); test('should error when segment is defined in HTTPS `destination` but not `source`', () => { const nowConfig = { redirects: [ { source: '/iforgot/:id', destination: 'https://example.com/:another', }, ], }; const { routes, error } = getTransformedRoutes({ nowConfig }); assert.deepEqual(routes, null); assert.ok( error?.message.includes( 'in `destination` property but not in `source` or `has` property' ), error?.message ); }); test('should error when segment is defined in `destination` query string but not `source`', () => { const nowConfig = { redirects: [ { source: '/iforgot/:id', destination: '/api/login?id=123&name=:name', }, ], }; const { routes, error } = getTransformedRoutes({ nowConfig }); assert.deepEqual(routes, null); assert.ok( error?.message.includes( 'in `destination` property but not in `source` or `has` property' ), error?.message ); }); test('should error when segment is defined in HTTPS `destination` query string but not `source`', () => { const nowConfig = { redirects: [ { source: '/iforgot/:id', destination: 'https://example.com/api/login?id=123&name=:name', }, ], }; const { routes, error } = getTransformedRoutes({ nowConfig }); assert.deepEqual(routes, null); assert.ok( error?.message.includes( 'in `destination` property but not in `source` or `has` property' ), error?.message ); }); test('should work with content-security-policy header containing URL', () => { const nowConfig = { headers: [ { source: '/(.*)', headers: [ { key: 'content-security-policy', value: "default-src 'self'; script-src 'self'; img-src 'self' https://*.example.com; style-src 'self' 'unsafe-inline'; connect-src 'self' https://*.examplpe.com wss://gateway.example.com; form-action 'self'", }, { key: 'feature-policy', value: "accelerometer 'none'; camera 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; payment 'none'; usb 'none'", }, { key: 'referrer-policy', value: 'strict-origin-when-cross-origin', }, { key: 'strict-transport-security', value: 'max-age=31536000; includesubdomains; preload', }, { key: 'x-content-type-options', value: 'nosniff', }, { key: 'x-frame-options', value: 'sameorigin', }, { key: 'x-xss-protection', value: '1; mode=block', }, ], }, ], }; const actual = getTransformedRoutes({ nowConfig }); assert.deepEqual(actual.routes, [ { continue: true, headers: { 'content-security-policy': "default-src 'self'; script-src 'self'; img-src 'self' https://*.example.com; style-src 'self' 'unsafe-inline'; connect-src 'self' https://*.examplpe.com wss://gateway.example.com; form-action 'self'", 'feature-policy': "accelerometer 'none'; camera 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; payment 'none'; usb 'none'", 'referrer-policy': 'strict-origin-when-cross-origin', 'strict-transport-security': 'max-age=31536000; includesubdomains; preload', 'x-content-type-options': 'nosniff', 'x-frame-options': 'sameorigin', 'x-xss-protection': '1; mode=block', }, src: '^(?:/(.*))$', }, ]); }); });
the_stack
module LightSpeed { export class LoaderResult { engine: BABYLON.Engine; scene: BABYLON.Scene; camera: BABYLON.ArcRotateCamera; playerGraphic: BABYLON.AbstractMesh; particleTexture: BABYLON.Texture; radar: BABYLON.Mesh; enemywing: BABYLON.Mesh; enemywing2: BABYLON.Mesh; wingconnector: BABYLON.Mesh; wingconnector2: BABYLON.Mesh; enemyship: BABYLON.Mesh; bulletobj: BABYLON.Mesh; bulletobj2: BABYLON.Mesh; bulletobj3: BABYLON.Mesh; bulletpart: BABYLON.ParticleSystem; bulletpart2: BABYLON.ParticleSystem; rock: BABYLON.AbstractMesh; rock2: BABYLON.AbstractMesh; mine: BABYLON.AbstractMesh; } export class Loader { public isLoaded: boolean = true; public load(canvas: HTMLCanvasElement, loaded: (LoaderResult) => void, notSupported: () => void) { if (!BABYLON.Engine.isSupported()) { notSupported(); return; } var e = new LightSpeed.LoaderResult(); this.isLoaded = false; e.engine = new BABYLON.Engine(canvas, false) e.scene = new BABYLON.Scene(e.engine); e.scene.clearColor = new BABYLON.Color3(0, 0, 0); e.camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 500, new BABYLON.Vector3(0, 0, 0), e.scene); e.camera.maxZ = 20000; time = 0; var backgroundLoad = document.createElement("img"); backgroundLoad.src = "images/starb.png"; var light0 = new BABYLON.HemisphericLight("Omni", new BABYLON.Vector3(0, 0, -10), e.scene); // e.scene.activeCamera.attachControl(canvas); BABYLON.SceneLoader.ImportMesh("", "", "Spaceship.babylon", e.scene, (newMeshes, particleSystems) => { newMeshes[0].scaling.x = .015; newMeshes[0].scaling.y = .015; newMeshes[0].scaling.z = .015; // space ship mesh e.playerGraphic = newMeshes[0]; var backmaterial = new BABYLON.StandardMaterial("texture1", e.scene); backmaterial.diffuseTexture = new BABYLON.Texture(backgroundLoad.src, e.scene); // texture of flare e.particleTexture = new BABYLON.Texture("images/Flare.png", e.scene); //radar e.radar = BABYLON.Mesh.CreateCylinder("12", .1, 300, 300, 55, 1, e.scene); e.radar.position.x = 15000; e.radar.position.z = 15000; e.radar.rotation.x = Math.PI / 2; e.radar.rotation.z = Math.PI * 1.5; var radarmaterial = new BABYLON.StandardMaterial("shieldMaterial", e.scene); radarmaterial.opacityTexture = new BABYLON.Texture("images/radarcircle.png", e.scene); radarmaterial.opacityTexture.hasAlpha = true; radarmaterial.alpha = 0.1; e.radar.material = radarmaterial; var enemyShipmaterial = new BABYLON.StandardMaterial("enemymaterial", e.scene); enemyShipmaterial.diffuseTexture = new BABYLON.Texture("images/Micro.png", e.scene); enemyShipmaterial.bumpTexture = new BABYLON.Texture("images/grate0_normal.png", e.scene); e.enemywing = BABYLON.Mesh.CreateCylinder("12", 3, 60, 60, 5, 1, e.scene); e.wingconnector = BABYLON.Mesh.CreateCylinder("12", 15, 5, 10, 10, 1, e.scene); e.wingconnector2 = e.wingconnector.clone("connector2", null); e.wingconnector2.rotation.x = Math.PI; e.enemywing.rotation.x = Math.PI / 2; e.enemywing2 = e.enemywing.clone("wing2", null); e.enemywing.material = enemyShipmaterial; e.enemywing2.material = enemyShipmaterial; e.enemyship = BABYLON.Mesh.CreateSphere("12", 10, 30, e.scene); e.enemywing.parent = e.enemyship; e.enemywing2.parent = e.enemyship; e.wingconnector.parent = e.enemywing; e.wingconnector2.parent = e.enemywing2; e.enemywing.position.z = 25; e.enemywing2.position.z = -25; e.wingconnector.position.y = -7; e.wingconnector2.position.y = 7; e.enemyship.material = enemyShipmaterial; e.enemyship.position.x = 2000; e.enemyship.position.z = 2000; // enemywing.rotation.z = Math.PI *.5; // enemywing.rotation.y = Math.PI; e.bulletobj = BABYLON.Mesh.CreateSphere("bulletmain", 1, 1, e.scene); e.bulletobj.position.y = -500; e.bulletobj.isVisible = false; e.bulletobj2 = BABYLON.Mesh.CreateSphere("bulletmain2", 4, 3, e.scene); e.bulletobj2.position.x = 15000; e.bulletobj2.position.z = 15000; e.bulletpart = new BABYLON.ParticleSystem("bulletPart", 10, e.scene); e.bulletpart.particleTexture = new BABYLON.Texture("images/laser.png", e.scene); e.bulletpart.emitter = e.bulletobj2; e.bulletpart.minEmitBox = new BABYLON.Vector3(0, 1, 0); // Starting all From e.bulletpart.maxEmitBox = new BABYLON.Vector3(0, 1, 0); // To... e.bulletpart.direction1 = new BABYLON.Vector3(-2, -1, -2); e.bulletpart.direction2 = new BABYLON.Vector3(2, 1, 2); e.bulletpart.minLifeTime = .01; e.bulletpart.maxLifeTime = .1; e.bulletpart.maxSize = 5.5; e.bulletpart.emitRate = 100; e.bulletpart.minEmitPower = 10; e.bulletpart.maxEmitPower = 30; e.bulletpart.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE; e.bulletpart.targetStopDuration = 0; e.bulletpart.disposeOnStop = true; e.bulletobj3 = BABYLON.Mesh.CreateSphere("bulletmain2", 4, 3, e.scene); e.bulletobj3.position.x = 15000; e.bulletobj3.position.z = 15000; e.bulletpart2 = new BABYLON.ParticleSystem("bulletPart", 10, e.scene); e.bulletpart2.particleTexture = new BABYLON.Texture("images/laserred.png", e.scene); e.bulletpart2.emitter = e.bulletobj3; e.bulletpart2.minEmitBox = new BABYLON.Vector3(0, 1, 0); // Starting all From e.bulletpart2.maxEmitBox = new BABYLON.Vector3(0, 1, 0); // To... e.bulletpart2.direction1 = new BABYLON.Vector3(-2, -1, -2); e.bulletpart2.direction2 = new BABYLON.Vector3(2, 1, 2); e.bulletpart2.minLifeTime = .01; e.bulletpart2.maxLifeTime = .1; e.bulletpart2.maxSize = 5.5; e.bulletpart2.emitRate = 100; e.bulletpart2.minEmitPower = 10; e.bulletpart2.maxEmitPower = 30; e.bulletpart2.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE; e.bulletpart2.targetStopDuration = 0; e.bulletpart2.disposeOnStop = true; var rockmaterial = new BABYLON.StandardMaterial("rockmaterial", e.scene); rockmaterial.diffuseTexture = new BABYLON.Texture("images/marble.jpg", e.scene); rockmaterial.bumpTexture = new BABYLON.Texture("images/Rocknormal.jpg", e.scene); rockmaterial.specularColor = new BABYLON.Color3(0, 0, 0); rockmaterial.diffuseTexture.wrapU = .5; rockmaterial.diffuseTexture.wrapV = .5; var minematerial = new BABYLON.StandardMaterial("rockmaterial", e.scene); minematerial.diffuseTexture = new BABYLON.Texture("images/bunker_galvanized.jpg", e.scene); minematerial.bumpTexture = new BABYLON.Texture("images/concrete01_norm.jpg", e.scene); //minematerial.specularColor = new BABYLON.Color3(0, 0, 0); minematerial.diffuseTexture.wrapU = .5; minematerial.diffuseTexture.wrapV = .5; var backgroundSystem = BABYLON.Mesh.CreatePlane("background", 3000, e.scene); backgroundSystem.material = backmaterial;//new BABYLON.StandardMaterial("backgroundmat", e.scene); backgroundSystem.rotation.y = Math.PI; backgroundSystem.rotation.x = Math.PI / 2; backgroundSystem.rotation.z = Math.PI * 1.5; backgroundSystem.position.y = -700; //player = new Player(); //camera.target = player.BoundingBox.position; BABYLON.SceneLoader.ImportMesh("", "", "assets/a6.babylon", e.scene, (newMeshes, particleSystems) => { e.rock = newMeshes[0]; e.rock.position.x = 850; e.rock.position.z = 850; e.rock.material = rockmaterial; BABYLON.SceneLoader.ImportMesh("", "", "assets/a5.babylon", e.scene, (newMeshes, particleSystems) =>{ e.rock2 = newMeshes[0]; e.rock2.position.x = 850; e.rock2.position.z = 850; e.rock2.material = rockmaterial; BABYLON.SceneLoader.ImportMesh("", "", "assets/mine1-2.babylon", e.scene, (newMeshes, particleSystems) => { e.mine = newMeshes[0]; e.mine.position.x = 850; e.mine.position.z = 850; e.mine.rotation.y = Math.PI; e.mine.rotation.x = Math.PI / 2; e.mine.rotation.z = Math.PI * 1.5; e.mine.material = minematerial; this.isLoaded = true; loaded(e); }); }); }); }); } } }
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import DataContext from 'context/Data'; import ScalerContext from 'context/Scaler'; import GriffPropTypes, { seriesPropType } from 'utils/proptypes'; import Axes, { Domains } from 'utils/Axes'; import { Domain, Series, Collection } from 'external'; import { Item } from 'internal'; import { withDisplayName } from 'utils/displayName'; // TODO: Move this to DataProvider. type OnTimeSubDomainChanged = (timeSubDomain: Domain) => void; // TODO: Move this to DataProvider. type LimitTimeSubDomain = (timeSubDomain: Domain) => Domain; // TODO: Move this to DataProvider. type OnUpdateDomains = (subDomains: DomainsByItemId) => void; // TODO: Move this to DataProvider. interface DataContext { timeDomain: Domain; timeSubDomain: Domain; timeSubDomainChanged: OnTimeSubDomainChanged; limitTimeSubDomain: LimitTimeSubDomain | undefined; externalXSubDomain: Domain | undefined; series: Series[]; collections: Collection[]; onUpdateDomains: OnUpdateDomains; } export interface Props { children: React.ReactChild | React.ReactChild[]; dataContext: DataContext; } export interface DomainsByItemId { [itemId: string]: Domains; } interface State { domainsByItemId: DomainsByItemId; subDomainsByItemId: DomainsByItemId; } export interface OnDomainsUpdated extends Function {} type DomainAxis = 'time' | 'x' | 'y'; interface StateUpdates { domainsByItemId: DomainsByItemId; subDomainsByItemId: DomainsByItemId; } // If the timeSubDomain is within this margin, consider it to be attached to // the leading edge of the timeDomain. const FRONT_OF_WINDOW_THRESHOLD = 0.05; /** * Provide a placeholder domain so that we can test for validity later, but * it can be safely operated on like a real domain. */ export const placeholder = (min: number, max: number): Domain => { const domain: Domain = [min, max]; domain.placeholder = true; return domain; }; const haveDomainsChanged = (before: Item, after: Item) => !isEqual(before.timeDomain, after.timeDomain) || !isEqual(before.timeSubDomain, after.timeSubDomain) || !isEqual(before.xDomain, after.xDomain) || !isEqual(before.xSubDomain, after.xSubDomain) || !isEqual(before.yDomain, after.yDomain) || !isEqual(before.ySubDomain, after.ySubDomain); const findItemsWithChangedDomains = ( previousItems: Item[], currentItems: Item[] ) => { const previousItemsById: { [itemId: string]: Item } = previousItems.reduce( (acc, s) => ({ ...acc, [s.id]: s, }), {} ); return currentItems.reduce((acc: Item[], s) => { if ( !previousItemsById[s.id] || haveDomainsChanged(previousItemsById[s.id] || {}, s) ) { return [...acc, s]; } return acc; }, []); }; const isEqual = (a: Domain | undefined, b: Domain | undefined): boolean => { if (a === b) { return true; } if (!a || !b) { return false; } return a[0] === b[0] && a[1] === b[1]; }; export const firstResolvedDomain = ( domain: Domain | undefined, // tslint:disable-next-line ...domains: (undefined | Domain)[] ): Domain | undefined => { if (domain && domain.placeholder !== true) { return [...domain] as Domain; } if (domains.length === 0) { return undefined; } return firstResolvedDomain(domains[0], ...(domains.splice(1) as Domain[])); }; /** * The scaler is the source of truth for all things related to the domains and * subdomains for all of the items within Griff. Note that an item can be either * a series or a collection, and domains are flexible. As of this writing, there * are three axes: * time: The timestamp of a datapoint * x: The x-value of a datapoint * y: The y-value of a datapoint. * * These axes all have separate domains and subdomains. The domain is the range * of that axis, and the subdomain is the currently-visible region of that * range. * * These are manipulated with the {@link #updateDomains} function, which is * made available through the {@link ScalerContext}. */ class Scaler extends React.Component<Props, State> { // eslint-disable-next-line react/static-property-placement static propTypes = { children: PropTypes.node.isRequired, dataContext: PropTypes.shape({ timeDomain: PropTypes.arrayOf(PropTypes.number).isRequired, timeSubDomain: PropTypes.arrayOf(PropTypes.number).isRequired, timeSubDomainChanged: PropTypes.func.isRequired, limitTimeSubDomain: PropTypes.func, externalXSubDomain: PropTypes.arrayOf(PropTypes.number), series: seriesPropType.isRequired, collections: GriffPropTypes.collections.isRequired, }).isRequired, }; // eslint-disable-next-line react/static-property-placement static defaultProps = {}; static getDerivedStateFromProps( { dataContext: { timeDomain, timeSubDomain, series, collections } }: Props, state: State ) { // Make sure that all items in the props are present in the domainsByItemId // and subDomainsByItemId state objects. const { domainsByItemId, subDomainsByItemId } = state; let updated = false; const stateUpdates = series.concat(collections).reduce( (acc: StateUpdates, item: Item): StateUpdates => { const updates: StateUpdates = { ...acc }; if (!domainsByItemId[item.id]) { updated = true; updates.domainsByItemId = { ...updates.domainsByItemId, [item.id]: { time: [...timeDomain] as Domain, x: firstResolvedDomain(item.xDomain) || placeholder(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER), y: firstResolvedDomain(item.yDomain) || placeholder(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER), }, }; } if (!subDomainsByItemId[item.id]) { updated = true; updates.subDomainsByItemId = { ...updates.subDomainsByItemId, [item.id]: { time: [...timeSubDomain] as Domain, x: firstResolvedDomain(item.xSubDomain) || placeholder(0, 1), y: firstResolvedDomain(item.ySubDomain) || placeholder(0, 1), }, }; } return updates; }, { domainsByItemId, subDomainsByItemId } ); return updated ? stateUpdates : null; } state: State = { domainsByItemId: {}, subDomainsByItemId: {}, }; componentDidUpdate(prevProps: Props) { const { dataContext } = this.props; const { domainsByItemId: oldDomainsByItemId, subDomainsByItemId: oldSubDomainsByItemId, } = this.state; const changedSeries = findItemsWithChangedDomains( prevProps.dataContext.series, dataContext.series ); const changedCollections = findItemsWithChangedDomains( prevProps.dataContext.collections, dataContext.collections ); if (changedSeries.length > 0 || changedCollections.length > 0) { const domainsByItemId = { ...oldDomainsByItemId }; const subDomainsByItemId = { ...oldSubDomainsByItemId }; [...changedSeries, ...changedCollections].forEach(item => { domainsByItemId[item.id] = { time: firstResolvedDomain( dataContext.timeDomain, item.timeDomain, Axes.time(oldDomainsByItemId[item.id]) ) || placeholder(0, Date.now()), x: firstResolvedDomain( item.xDomain, Axes.x(oldDomainsByItemId[item.id]) ) || // Set a large range because this is a domain. placeholder(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER), y: firstResolvedDomain( item.yDomain, Axes.y(oldDomainsByItemId[item.id]) ) || // Set a large range because this is a domain. placeholder(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER), }; subDomainsByItemId[item.id] = { time: firstResolvedDomain( dataContext.timeSubDomain || item.timeSubDomain || Axes.time(oldSubDomainsByItemId[item.id]) ) || // Set a large range because this is a subdomain. placeholder(0, Date.now()), x: firstResolvedDomain( item.xSubDomain, Axes.x(oldSubDomainsByItemId[item.id]) ) || // Set a small range because this is a subdomain. placeholder(0, 1), y: firstResolvedDomain( item.ySubDomain || Axes.y(oldSubDomainsByItemId[item.id]) ) || // Set a small range because this is a subdomain. placeholder(0, 1), }; }); // eslint-disable-next-line react/no-did-update-set-state this.setState({ subDomainsByItemId, domainsByItemId }); return; } if (!isEqual(prevProps.dataContext.timeDomain, dataContext.timeDomain)) { const { timeDomain: prevTimeDomain } = prevProps.dataContext; const { timeDomain: nextTimeDomain } = dataContext; // When timeDomain changes, we need to update everything downstream. const domainsByItemId = { ...oldDomainsByItemId }; Object.keys(domainsByItemId).forEach(itemId => { domainsByItemId[itemId].time = nextTimeDomain; }); const subDomainsByItemId = { ...oldSubDomainsByItemId }; Object.keys(subDomainsByItemId).forEach(itemId => { const { time: timeSubDomain } = oldSubDomainsByItemId[itemId]; subDomainsByItemId[itemId] = { ...oldSubDomainsByItemId[itemId], }; const dt = timeSubDomain[1] - timeSubDomain[0]; if ( Math.abs((timeSubDomain[1] - prevTimeDomain[1]) / dt) <= FRONT_OF_WINDOW_THRESHOLD ) { // Looking at the front of the window -- continue to track that. subDomainsByItemId[itemId].time = [ nextTimeDomain[1] - dt, nextTimeDomain[1], ]; } else if (timeSubDomain[0] <= prevTimeDomain[0]) { // Looking at the back of the window -- continue to track that. subDomainsByItemId[itemId].time = [ prevTimeDomain[0], prevTimeDomain[0] + dt, ]; } }); // eslint-disable-next-line react/no-did-update-set-state this.setState({ domainsByItemId, subDomainsByItemId }); } if ( !isEqual(prevProps.dataContext.timeSubDomain, dataContext.timeSubDomain) ) { // When timeSubDomain changes, we need to update everything downstream. const newSubDomainsByItemId: DomainsByItemId = {}; Object.keys(oldSubDomainsByItemId).forEach(itemId => { newSubDomainsByItemId[itemId] = { ...oldSubDomainsByItemId[itemId], time: dataContext.timeSubDomain, }; }); // eslint-disable-next-line react/no-did-update-set-state this.setState({ subDomainsByItemId: newSubDomainsByItemId }); } } /** * Update the subdomains for the given items. This is a patch update and will * be merged with the current state of the subdomains. An example payload * will resemble: * <code> * { * "series-1": { * "y": [0.5, 0.75], * }, * "series-2": { * "y": [1.0, 2.0], * } * } * </code> * * After this is complete, {@code callback} will be called with this patch * object. */ updateDomains = ( changedDomainsById: DomainsByItemId, callback: OnDomainsUpdated ) => { // FIXME: This is not multi-series aware. let newTimeSubDomain = null; const { dataContext } = this.props; const { domainsByItemId, subDomainsByItemId } = this.state; const newSubDomains = { ...subDomainsByItemId }; Object.keys(changedDomainsById).forEach(itemId => { newSubDomains[itemId] = { ...(subDomainsByItemId[itemId] || {}) }; Object.keys(changedDomainsById[itemId]).forEach(uncastAxis => { const axis: DomainAxis = uncastAxis as DomainAxis; let newSubDomain = changedDomainsById[itemId][axis]; if (axis === String(Axes.time)) { if (dataContext.limitTimeSubDomain) { newSubDomain = dataContext.limitTimeSubDomain(newSubDomain); } } const newSpan = newSubDomain[1] - newSubDomain[0]; const existingSubDomain = subDomainsByItemId[itemId][axis] || newSubDomain; const existingSpan = existingSubDomain[1] - existingSubDomain[0]; const limits = firstResolvedDomain( ((domainsByItemId || {})[itemId] || {})[axis], axis === String(Axes.time) ? // FIXME: Phase out this single timeDomain thing. dataContext.timeDomain : undefined ) || // Set a large range because this is a limiting range. placeholder(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); if (newSpan === existingSpan) { // This is a translation; check the bounds. if (newSubDomain[0] <= limits[0]) { newSubDomain = [limits[0], limits[0] + newSpan]; } if (newSubDomain[1] >= limits[1]) { newSubDomain = [limits[1] - newSpan, limits[1]]; } } else { newSubDomain = [ Math.max(limits[0], newSubDomain[0]), Math.min(limits[1], newSubDomain[1]), ]; } newSubDomains[itemId][axis] = newSubDomain; if (axis === String(Axes.time)) { newTimeSubDomain = newSubDomain; } }); }); // expose newSubDomains to DataProvider if (dataContext.onUpdateDomains) { dataContext.onUpdateDomains(newSubDomains); } this.setState( { subDomainsByItemId: newSubDomains }, callback ? () => callback(changedDomainsById) : undefined ); if (newTimeSubDomain) { dataContext.timeSubDomainChanged(newTimeSubDomain); } }; render() { const { domainsByItemId, subDomainsByItemId } = this.state; const { children, dataContext: { collections, series }, } = this.props; const finalContext = { // Pick what we need out of the dataContext instead of spreading the // entire object into the context. collections, series, updateDomains: this.updateDomains, domainsByItemId, subDomainsByItemId, }; return ( <ScalerContext.Provider value={finalContext as any}> {children} </ScalerContext.Provider> ); } } export default withDisplayName('Scaler', (props: Props) => ( <DataContext.Consumer> {dataContext => ( <Scaler {...props} dataContext={(dataContext as unknown) as DataContext} /> )} </DataContext.Consumer> ));
the_stack
"use strict"; // uuid: e8f361d2-c6fe-4649-9fde-fe6f24fa043a // ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ /** @module end-user | The lines bellow convey information for the end-user */ /** * ## Description * * An **expression** is a textual value that starts with `=`. * Expressions unlike [Code Handlers](code handler) can be defined on the `.json` * config file and support teleporting. * * ABeamer supports: * * - binary operators: `+`, `-`, `*`, `/`, `%` (modulus). * Work both with numbers and arrays. * `+` operator also concatenates textual values. * * - equality and comparison operators: `==`, `!=`, `<`, `>`, `<=`, `>=`. * - logical comparison: `and`, `or`. * These operators transform the 2 numerical values into 0 (false) or 1 (true). * * - parenthesis: `(`, `)`. * - [](functions). * - textual values: delimited by single quotes. * the following character strings have a special meaning: * - `\'` - defines a single quote * - `\n` - defines new line * - numerical values. * - numerical arrays: [x,y,z]. * - variables: numerical, textual, numerical arrays, objects. * - variable array one-dimension indices. * * ## Built-in Variables * * ABeamer has the following built-in variables: * * `e` - mathematical constant 'e'. * `pi` - mathematical constant 'pi'. * `deg2rad` - `=pi/180`. * `rad2deg` - `=180/pi`. * * `fps` - frames per second. * `frameWidth` - frame output width = generated file image width. * `frameHeight` - frame output height = generated file image height. * * `isTeleporting` - Is True, if it's teleporting. * * `v0` - Computed Numerical `valueStart`. * `v1` - Computed Numerical `value`. * `vd` - Computed Numerical difference `value` - `valueStart`. * `vt` - Computed Numerical value injected to the easing function. * `vot` - Computed Numerical value injected to the oscillator function. * `vpt` - Computed Numerical value injected to the path function. * `t` - `t` used to interpolate an easing, oscillator or path via expression. * ## Examples * * `= 'A' + 'Beamer'`. * `= round(12.4 + ceil(50.5) / 2 * (60 % 4))`. * `= cos(60*deg2rad) * random()`. * `= iff(fps < 20, 'too few frames', 'lots of frames')`. * `=[2, 3] + [4, 5]`. * `=chart.labelsY.marginAfter`. * `=foo[x-y+z]`. */ namespace ABeamer { // #generate-group-section // ------------------------------------------------------------------------ // Expressions // ------------------------------------------------------------------------ // The following section contains data for the end-user // generated by `gulp build-definition-files` // ------------------------------- // #export-section-start: release export type VarType = number | string | boolean | number[] | object; export interface Vars { e: number; pi: number; /** =pi/180 */ deg2rad: number; /** =180/pi */ rad2deg: number; /** Frames per second. */ fps?: uint; /** Frame output width = generated file image width. */ frameWidth?: uint; /** Frame output height = generated file image height. */ frameHeight?: uint; /** Is True, if it's teleporting. */ isTeleporting?: boolean; /** Element index of the active adapter */ elIndex?: uint; /** Number of elements inside defined by the active adapter */ elCount?: uint; /** Computed Numerical `valueStart`. */ v0?: number; /** Computed Numerical `value`. */ v1?: number; /** Computed Numerical difference `value` - `valueStart`. */ vd?: number; /** Computed Numerical value injected to the easing function. */ vt?: number; /** Computed Numerical value injected to the oscillator function. */ vot?: number; /** Computed Numerical value injected to the path function. */ vpt?: number; /** `t` used to interpolate an easing, oscillator or path via expression. */ t?: number; /** Generic value. Used in Charts. */ v?: number; /** Generic iterator. Used in Factories. */ i?: int; /** Generic number of items/points/elements. Used in Charts. */ n?: int; [name: string]: VarType; } export const enum ExprType { NotExpr, CalcOnce, CalcMany, } export type ExprResult = string | number | number[]; export type ExprString = string; // #export-section-end: release // ------------------------------- // ------------------------------------------------------------------------ // Implementation // ------------------------------------------------------------------------ /** * Initializes the default global expression variables. * Code outside the core library should access this const. * It should use instead `getVars()`. */ export const _vars: Vars = { e: Math.E, pi: Math.PI, deg2rad: Math.PI / 180, rad2deg: 180 / Math.PI, }; /** * Returns the global expression variables. * Plugins who want to add init variables, should use this function. * The usage of _vars is discourage to be used outside the scope adding init vars * for plugins. * Use `args.vars` instead. */ export function getVars(): Vars { return _vars; } /** * Defines the code range for characters. * By default only includes the latin alphabet * but if functions are mapped into another characters systems, * it must add to this list the extra character code ranges. * */ export const CharRanges = [ ['A'.charCodeAt(0), 'Z'.charCodeAt(0)], ['a'.charCodeAt(0), 'z'.charCodeAt(0)], ]; /** * Utility function to test if `ch` is a character. * It might include non-latin characters. It depends on `CharRanges`. * Used by developers and plugin creators. * */ export function isCharacter(ch: string | undefined, pos: uint = 0): boolean { if (ch === undefined || ch[pos] === undefined) { return false; } const codePoint = ch.codePointAt(pos); return CharRanges.findIndex(rg => codePoint >= rg[0] && codePoint <= rg[1]) !== -1; } /** * Utility function to test if it's a digit. * Used by developers and plugin creators. * */ export function isDigit(ch: string): boolean { return ch >= '0' && ch <= '9'; } /** * Utility function to test if it's a digit or character. * It might include non-latin characters. It depends on `CharRanges`. * Used by developers and plugin creators. * */ export function isCharacterOrNum(ch: string): boolean { return isDigit(ch) || isCharacter(ch); } /** * Tests if `text` is an expression. * Used by developers and plugin creators. */ export function isExpr(text: string): boolean { return text !== undefined && text[0] === '='; } // ------------------------------------------------------------------------ // ExprParser // ------------------------------------------------------------------------ const enum TokenType { None, Function, ArrayOpen, ArrayClose, Comma, ParamOpen, ParamClose, Value, Plus, Minus, Multiply, Divide, Mod, Equal, Different, Lesser, Greater, LessEqual, GreaterEqual, LogicalAnd, LogicalOr, LogicalNot, } const enum TokenClass { None, Function, ArrayOpen, ArrayClose, Value, ParamOpen, ParamClose, Unary, LogicalUnary, Binary, Comma, } enum Str2TokenType { '[' = TokenType.ArrayOpen, ']' = TokenType.ArrayClose, '(' = TokenType.ParamOpen, ')' = TokenType.ParamClose, '+' = TokenType.Plus, '-' = TokenType.Minus, '*' = TokenType.Multiply, '/' = TokenType.Divide, '%' = TokenType.Mod, ',' = TokenType.Comma, '==' = TokenType.Equal, '!=' = TokenType.Different, '<' = TokenType.Lesser, '>' = TokenType.Greater, '<=' = TokenType.LessEqual, '>=' = TokenType.GreaterEqual, } interface Token extends ExFuncParam { tkType?: TokenType; tkClass?: TokenClass; canBinOp?: boolean; funcParams?: ExprFuncParams; } /** * List of operator precedence. * Taken from the JavaScript operator precedence. */ const opPriority: uint[] = [ 0, // None, 19, // Function, 19, // ArrayOpen, 19, // ArrayClose, 19, // Comma, 20, // ParamOpen, 20, // ParamClose, 1, // Value, 13, // Plus, 13, // Minus, 14, // Multiply, 14, // Divide, 14, // Mod, 10, // Equal, 10, // Different, 11, // Lesser, 11, // Greater, 11, // LessEqual, 11, // GreaterEqual, 6, // LogicalAnd 5, // LogicalOr 16, // LogicalNot ]; const Type2Class: TokenClass[] = [ TokenClass.None, TokenClass.Function, TokenClass.ArrayOpen, TokenClass.ArrayClose, TokenClass.Comma, TokenClass.ParamOpen, TokenClass.ParamClose, TokenClass.Value, TokenClass.Unary, TokenClass.Unary, TokenClass.Binary, TokenClass.Binary, TokenClass.Binary, // equality operators TokenClass.Binary, TokenClass.Binary, // conditional Operators TokenClass.Binary, TokenClass.Binary, TokenClass.Binary, TokenClass.Binary, // Logical operators TokenClass.Binary, TokenClass.Binary, TokenClass.LogicalUnary, ]; // ------------------------------------------------------------------------ // parser // ------------------------------------------------------------------------ interface ParseParams extends ExFuncReq { expr: string; pos: uint; token?: Token; } function _isId(ch: string | undefined, isFirst: boolean): boolean { return ch === undefined ? false : (ch === '_' ? true : isFirst ? isCharacter(ch) : isCharacterOrNum(ch)); } function _parseVars(p: ParseParams, varValue: VarType, varName: string, expr: string, pos: uint): uint { const varTypeOf = typeof varValue; if (varValue === undefined) { err(p, `Unknown variable ${varName}`); } if (varTypeOf === 'string') { p.token.paType = ExFuncParamType.String; p.token.sValue = varValue as string; } else if (varTypeOf === 'number') { p.token.paType = ExFuncParamType.Number; p.token.numValue = varValue as number; p.token.sValue = undefined; p.token.arrayValue = undefined; } else if (varTypeOf === 'object') { if (Array.isArray(varValue)) { p.token.paType = ExFuncParamType.Array; p.token.arrayValue = varValue as number[]; p.token.sValue = undefined; p.token.numValue = undefined; } else if (expr[pos] === '.') { const varPropStart = ++pos; while (_isId(expr[pos], varPropStart === pos)) { pos++; } const varProp = expr.substring(varPropStart, pos); if (!varProp) { err(p, `Invalid object variable ${varName}`); } pos = _parseVars(p, varValue[varProp], varName + '.' + varProp, expr, pos); } if (expr[pos] === '[') { const varPropStart = ++pos; let bracketCount = 1; while (bracketCount > 0) { switch (expr[pos]) { case '[': bracketCount++; break; case ']': bracketCount--; break; case undefined: err(p, `Invalid variable indexing ${varName}`); } pos++; } const indexExpr = '=' + expr.substring(varPropStart, pos - 1); const indexValue = calcExpr(indexExpr, p.args); const arrayItem = (varValue as any[])[parseInt(indexValue as any)]; _parseVars(p, arrayItem, varName, indexExpr, 1); pos++; } } else if (varTypeOf === 'boolean') { p.token.paType = ExFuncParamType.Number; p.token.numValue = (varValue as boolean) ? 1 : 0; p.token.sValue = undefined; p.token.arrayValue = undefined; } else { err(p, `Unsupported type of ${varName}`); } return pos; } function _parser(p: ParseParams, checkSign: boolean): TokenClass { let startPos; function setToken(aType: TokenType): void { p.token.sValue = expr.substring(startPos, pos); p.token.tkType = aType; p.token.tkClass = Type2Class[aType]; } const expr = p.expr; let pos = p.pos; p.token.tkClass = TokenClass.None; do { let ch = expr[pos]; while (ch === ' ') { ch = expr[++pos]; } startPos = pos; if (ch === undefined) { break; } // vars, functions, named operators if (ch === '_' || isCharacter(ch)) { while (_isId(expr[++pos], false)) { } if (expr[pos] === '(') { setToken(TokenType.Function); const funcName = p.token.sValue; if (funcName === 'not') { p.token.tkType = TokenType.LogicalNot; p.token.tkClass = TokenClass.LogicalUnary; } else { pos++; } } else { setToken(TokenType.Value); const varName = p.token.sValue; const opNameIndex = ['not', 'and', 'or'].indexOf(varName); if (opNameIndex !== -1) { // named operators p.token.tkType = [TokenType.LogicalNot, TokenType.LogicalAnd, /**/ TokenType.LogicalOr][opNameIndex]; p.token.tkClass = opNameIndex !== 0 ? TokenClass.Binary : TokenClass.LogicalUnary; } else { // variables pos = _parseVars(p, p.args.vars[varName], varName, expr, pos); } } break; } // number sign if (checkSign && ((ch === '-' || ch === '+') && isDigit(expr[pos + 1]))) { ch = expr[++pos]; } // numbers if (isDigit(ch)) { do { ch = expr[++pos]; } while (ch && (isDigit(ch) || ch === '.')); setToken(TokenType.Value); p.token.paType = ExFuncParamType.Number; p.token.numValue = parseFloat(p.token.sValue); p.token.sValue = undefined; break; } // strings if (ch === "'") { let prevCh: string; do { prevCh = ch; ch = expr[++pos]; } while ((ch !== "'" || prevCh === '\\') && ch !== undefined); startPos++; setToken(TokenType.Value); p.token.sValue = p.token.sValue.replace(/\\([n'])/g, (_all, meta) => { switch (meta) { case 'n': return '\n'; case "'": return "'"; } }); p.token.paType = ExFuncParamType.String; pos++; break; } // equality and comparison if ('=!<>'.indexOf(ch) !== -1 && expr[pos + 1] === '=') { ch = ch + '='; pos++; } // symbols const type = Str2TokenType[ch] || TokenType.None; if (type === TokenType.None) { err(p, `Unknown token ${ch} in position ${pos}`, p.token); } pos++; setToken(type); break; } while (true); const tkClass = p.token.tkClass; p.pos = pos; // @ts-ignore TypeScript bug :-( p.token.canBinOp = tkClass === TokenClass.Unary || tkClass === TokenClass.Binary; return tkClass; } // ------------------------------------------------------------------------ // Execute Expression Function // ------------------------------------------------------------------------ function _execExprFunction(p: ParseParams, funcToken: Token): Token { const funcName = funcToken.sValue; const func = _exFunctions[funcName]; if (!func) { err(p, `Unknown function: ${funcName}`, funcToken); } const res: Token = { canBinOp: false, tkClass: TokenClass.Value, tkType: TokenType.Value, }; p.res = res; p.token = funcToken; func(funcToken.funcParams, p); return res; } // ------------------------------------------------------------------------ // Execute Array // ------------------------------------------------------------------------ function _execArray(_p: ParseParams, funcToken: Token): Token { const res: Token = { paType: ExFuncParamType.Array, sValue: undefined, numValue: undefined, arrayValue: funcToken.funcParams.map(param => { return param.numValue; }), canBinOp: false, tkClass: TokenClass.Value, tkType: TokenType.Value, }; return res; } // ------------------------------------------------------------------------ // State Machine // ------------------------------------------------------------------------ // @TODO: Implement logical Not function _stateMachine(p: ParseParams): ExprResult { const enum States { IdAndUnary, NoUnary, Binary, } const stack: Token[] = []; let state = States.IdAndUnary; let token: Token; let op: Token; /** stack.length - 1 */ let stackLast = -1; /** startPoints[startPoints.length-1] */ let startPoint: uint = 0; /** list of indexes to the stack element after for each 'func', '(' and ',' */ const startPoints: uint[] = []; p.req = p; function push(): void { stack.push(token); stackLast++; } function pop(): Token { const tk = stack[stackLast]; stack.length = stackLast; stackLast--; return tk; } function calcStackLeft(): void { // startPoint = 0; while (stackLast > 1 && stackLast > startPoint + 1) { op = stack[startPoint + 1]; if (!op.canBinOp) { break; } const t1 = stack[startPoint]; const t2 = stack[startPoint + 2]; _calcBinary(p, op, t1, t2); stack.splice(startPoint + 1, 2); stackLast -= 2; } } function calcStackRight(): void { while (stackLast > 2) { op = stack[stackLast - 1]; if (!op.canBinOp) { break; } const t1 = stack[stackLast - 2]; const t2 = stack[stackLast]; const prevOp = stack[stackLast - 3]; if (_comparePriority(op, prevOp)) { _calcBinary(p, op, t1, t2); stack.length = stackLast - 1; stackLast -= 2; } else { break; } } } function onCloseParamOrArrayOrFunc(): void { calcStackLeft(); if (startPoint !== stackLast) { err(p, '', token); } token = stack.pop(); stackLast--; } do { p.token = {}; const thisTkClass = _parser(p, state !== States.Binary); token = p.token; if (thisTkClass === TokenClass.None) { break; } switch (thisTkClass) { case TokenClass.Value: if (state === States.Binary) { err(p, '', token); } else if (state === States.NoUnary && [TokenClass.Unary, TokenClass.LogicalUnary].indexOf(stack[stackLast].tkClass) !== -1 && (stackLast === 0 || stack[stackLast - 1].tkClass !== TokenClass.Value)) { state = States.IdAndUnary; op = pop(); _calcUnary(p, op, token); } state = States.Binary; push(); calcStackRight(); break; case TokenClass.ArrayOpen: // flows to TokenClass.Function case TokenClass.Function: token.funcParams = []; // flows to TokenClass.ParamOpen case TokenClass.ParamOpen: if (state === States.Binary) { err(p, '', token); } push(); startPoint = stackLast + 1; startPoints.push(startPoint); state = States.IdAndUnary; break; case TokenClass.Comma: case TokenClass.ParamClose: case TokenClass.ArrayClose: if (!startPoint) { err(p, `Missing starting parenthesis`, token); } const funcToken = stack[startPoint - 1]; const isTokenComma = thisTkClass === TokenClass.Comma; const isFunc = funcToken.tkClass === TokenClass.Function; const isArray = funcToken.tkClass === TokenClass.ArrayOpen; if (isTokenComma && !isFunc && !isArray) { err(p, `Missing function`, token); } if ((isFunc || isArray) && !isTokenComma) { // function code if (startPoint !== stackLast + 1) { // in case there are 0 parameters onCloseParamOrArrayOrFunc(); funcToken.funcParams.push(token); } if (isFunc) { token = _execExprFunction(p, funcToken); } else { token = _execArray(p, funcToken); } } else { // not a function onCloseParamOrArrayOrFunc(); } if (!isTokenComma) { stack[stackLast] = token; startPoints.pop(); startPoint = startPoints[startPoints.length - 1] || 0; state = States.Binary; } else { funcToken.funcParams.push(token); state = States.IdAndUnary; } break; case TokenClass.LogicalUnary: case TokenClass.Unary: if (state === States.IdAndUnary) { if (thisTkClass === TokenClass.Unary) { state = States.NoUnary; } push(); break; } // it flows to TokenClass.Binary case TokenClass.Binary: if (state !== States.Binary) { err(p, '', token); } if (stackLast > 0 && stack[stackLast].tkClass === TokenClass.Value) { op = stack[stackLast - 1]; if (op.canBinOp && _comparePriority(op, token)) { calcStackLeft(); } } state = States.NoUnary; push(); break; } } while (true); calcStackLeft(); // #debug-start if (p.args.isVerbose) { token = stack.length > 0 ? stack[0] : { paType: ExFuncParamType.String }; const v = _valueOfToken(token); p.args.story.logFrmt('expression', [ ['expression', p.expr], ['value', v.toString()], ['stack.length', stack.length], ['stack', JSON.stringify(stack, undefined, 2)]]); } // #debug-end if (stack.length !== 1) { err(p, `Stack not empty`); } token = stack[0]; if (stack[stackLast].tkClass !== TokenClass.Value) { err(p, 'Not a value'); } return _valueOfToken(token); } function _valueOfToken(token: Token): ExprResult { return token.paType === ExFuncParamType.String ? token.sValue : token.paType === ExFuncParamType.Array ? token.arrayValue : token.numValue; } // ------------------------------------------------------------------------ // Error Handling // ------------------------------------------------------------------------ /** Throws a localized error */ function err(p: ParseParams, msg?: string, _value?: Token): void { throwI8n(Msgs.ExpHasErrors, { e: p.expr, err: msg || '' }); } /** * Checks if the function parameter count matches the parameters expected, * and if their types match the expected. */ function _checkFuncParams(req: ParseParams, paramCount: uint, paramTypes?: ExFuncParamType[]): void { const params = req.token.funcParams; if (paramCount >= 0 && params.length !== paramCount) { err(req, i8nMsg(Msgs.WrongNrParams, { p: req.token.sValue })); } if (paramTypes) { paramTypes.forEach((paramType, index) => { const pi = params[index]; if (!pi || (pi.paType !== paramType && paramType !== ExFuncParamType.Any)) { err(req, i8nMsg(Msgs.WrongParamType, { p: req.token.sValue, i: index })); } }); } } // ------------------------------------------------------------------------ // Function Tools // ------------------------------------------------------------------------ /** * Provides services for functions where the input can be N numerical parameters, * or an array of numerical values. * * Supported cases: * - `paramCount=1; arrayLength=undefined;` * - if it's an array, it will exec the `func` on each index, and set output to an array. * - if it's 1 numerical parameter, it will execute the `func` and set output a number. * * - `paramCount=undefined; arrayLength=undefined;` * - it calls the `func` with an array, the result value type * is the same as the one returned by the `func`. * */ export function arrayInputHelper(params: ExprFuncParams, req: ExFuncReq, paramCount: uint | undefined, arrayLength: uint | undefined, func: (inpArray: any) => any): void { let inpArray: number[]; if (params.length === 1 && params[0].paType === ExFuncParamType.Array) { // if the input value is a numerical array inpArray = params[0].arrayValue; if (arrayLength && inpArray.length !== arrayLength) { err(req as ParseParams, i8nMsg(Msgs.WrongNrParams, { p: (req as ParseParams).token.sValue })); } if (paramCount !== arrayLength) { inpArray.forEach((el, index) => { inpArray[index] = func(el); }); req.res.paType = ExFuncParamType.Array; req.res.arrayValue = inpArray; return; } } else { // if the input is a list of numerical parameters if (paramCount >= 0 && params.length !== paramCount) { err(req as ParseParams, i8nMsg(Msgs.WrongNrParams, { p: (req as ParseParams).token.sValue })); } inpArray = params.map((param, index) => { if (param.paType !== ExFuncParamType.Number) { err(req as ParseParams, i8nMsg(Msgs.WrongParamType, { p: (req as ParseParams).token.sValue, i: index })); } return param.numValue; }); if (paramCount === 1) { req.res.paType = ExFuncParamType.Number; req.res.numValue = func(inpArray[0]); return; } } const resValue = func(inpArray); if (typeof resValue === 'number') { req.res.paType = ExFuncParamType.Number; req.res.numValue = resValue; } else { req.res.paType = ExFuncParamType.Array; req.res.arrayValue = resValue; } } // ------------------------------------------------------------------------ // Tools // ------------------------------------------------------------------------ /** Compares operators priority. */ function _comparePriority(op1: Token, op2: Token): boolean { return opPriority[op1.tkType] >= opPriority[op2.tkType]; } // ------------------------------------------------------------------------ // Compute // ------------------------------------------------------------------------ /** Computes unary operators. */ function _calcUnary(p: ParseParams, op: Token, value: Token): void { if (value.paType !== ExFuncParamType.Number) { err(p, Msgs.UnaryErr, op); } if (op.tkType === TokenType.Minus) { value.numValue = -value.numValue; } else if (op.tkType === TokenType.LogicalNot) { value.numValue = value.numValue ? 0 : 1; } } /** Computes binary operators. */ function _calcBinary(p: ParseParams, op: Token, value1: Token, value2: Token): void { const AnyNotNumber = value1.paType !== ExFuncParamType.Number || value2.paType !== ExFuncParamType.Number; const is1stArray = value1.paType === ExFuncParamType.Array; const is2ndArray = value2.paType === ExFuncParamType.Array; function NumbersOnly() { if (AnyNotNumber) { err(p, 'This op only supports numbers', value1); } } let v: number; function execOp(f: (a: number, b: number) => number, allowOther?: boolean): boolean { if (is1stArray || is2ndArray) { if (!is1stArray || !is2ndArray) { throwErr(`Can only add 2 arrays`); } if (value1.arrayValue.length !== value2.arrayValue.length) { throwErr(`Both arrays must have the same value`); } value1.arrayValue.forEach((v1, index) => { value1.arrayValue[index] = f(v1, value2.arrayValue[index]); }); value1.paType = ExFuncParamType.Array; v = undefined; } else { if (AnyNotNumber) { if (allowOther) { return false; } else { NumbersOnly(); } } else { v = f(value1.numValue, value2.numValue); } } return true; } switch (op.tkType) { case TokenType.Plus: if (!execOp((a, b) => a + b, true)) { value1.sValue = (value1.paType === ExFuncParamType.Number ? value1.numValue.toString() : value1.sValue) + (value2.paType === ExFuncParamType.Number ? value2.numValue.toString() : value2.sValue); value1.paType = ExFuncParamType.String; return; } break; case TokenType.Minus: execOp((a, b) => a - b); break; case TokenType.Multiply: execOp((a, b) => a * b); break; case TokenType.Divide: execOp((a, b) => a / b); break; case TokenType.Mod: execOp((a, b) => a % b); break; case TokenType.Equal: NumbersOnly(); v = value1.numValue === value2.numValue ? 1 : 0; break; case TokenType.Different: NumbersOnly(); v = value1.numValue !== value2.numValue ? 1 : 0; break; case TokenType.Lesser: NumbersOnly(); v = value1.numValue < value2.numValue ? 1 : 0; break; case TokenType.Greater: NumbersOnly(); v = value1.numValue > value2.numValue ? 1 : 0; break; case TokenType.LessEqual: NumbersOnly(); v = value1.numValue <= value2.numValue ? 1 : 0; break; case TokenType.GreaterEqual: NumbersOnly(); v = value1.numValue >= value2.numValue ? 1 : 0; break; case TokenType.LogicalAnd: NumbersOnly(); v = value1.numValue && value2.numValue ? 1 : 0; break; case TokenType.LogicalOr: NumbersOnly(); v = value1.numValue || value2.numValue ? 1 : 0; break; } value1.numValue = v; } // ------------------------------------------------------------------------ // Public Functions // ------------------------------------------------------------------------ /** * Calculates an expression. * Expects the input to be an expression. * Used mostly by plugin creators and developers. */ export function calcExpr(expr: string, args: ABeamerArgs): ExprResult { return _stateMachine({ args, checkParams: _checkFuncParams, expr, pos: 1, }); } /** * If it's an expression, it computes its value. * Returns undefined if it's not an expression. * Used mostly by plugin creators and developers. */ export function ifExprCalc(expr: string, args: ABeamerArgs): ExprResult | undefined { return isExpr(expr) ? calcExpr(expr, args) : undefined; } /** * If it's an expression, it computes its value and returns its numerical value. * Returns `defNumber` if it's not an expression. * Used mostly by plugin creators and developers. */ export function ifExprCalcNum(expr: string, defNumber: number | undefined, args: ABeamerArgs): number | undefined { if (!isExpr(expr)) { return defNumber; } const exprValue = calcExpr(expr, args); if (args.isStrict && exprValue !== undefined && typeof exprValue !== 'number') { throwI8n(Msgs.MustBeANumber, { p: expr }); } return exprValue !== undefined ? parseFloat(exprValue as string) : defNumber; } /** * Computes the expression and returns the value. * If isStrict, checks if the return value is textual, if not throws error. */ export function calcStr(expr: string, args: ABeamerArgs): string { const exprValue = calcExpr(expr, args); if (args.isStrict && (exprValue === undefined || typeof exprValue !== 'string')) { throwI8n(Msgs.MustBeAString, { p: expr }); } return exprValue as string; } /** * If it's an expression, it computes its value and returns its numerical value. * Returns `defNumber` if it's not an expression. * Used mostly by plugin creators and developers. */ export function ifExprCalcStr(expr: string, defString: string | undefined, args: ABeamerArgs): string | undefined { if (!isExpr(expr)) { return defString; } const exprValue = calcExpr(expr, args); if (args.isStrict && exprValue !== undefined && typeof exprValue !== 'string') { throwI8n(Msgs.MustBeAString, { p: expr }); } return exprValue !== undefined ? exprValue as string : defString; } /** * Checks if it's an expression, if it is, it computes and returns * the value as a number. Otherwise, returns the parameter as a number. * Used mostly by plugin creators and developers. */ export function ExprOrNumToNum(param: ExprString | number, defValue: number | undefined, args: ABeamerArgs): number | undefined { if (args.isStrict && param !== undefined) { const typeofP = typeof param; if (typeofP !== 'string' && typeofP !== 'number') { throwI8n(Msgs.MustBeANumberOrExpr, { p: param }); } } return ifExprCalcNum(param as string, param !== undefined ? param as number : defValue, args); } /** * Checks if it's an expression, if it is, it computes and returns * the value as a number. Otherwise, returns the parameter as a number. * Used mostly by plugin creators and developers. */ export function ExprOrStrToStr(param: ExprString | string, defValue: string | undefined, args: ABeamerArgs): string | undefined { if (args.isStrict && param !== undefined) { const typeofP = typeof param; if (typeofP !== 'string') { throwI8n(Msgs.MustBeAStringOrExpr, { p: param }); } } return ifExprCalcStr(param as string, param !== undefined ? param as string : defValue, args); } }
the_stack
import { parseJsonAndExpectOnlyFlowNodes, verifyShape } from './JsonTestUtils'; import { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement'; import { ShapeBpmnElementKind, ShapeBpmnEventBasedGatewayKind } from '../../../../../src/model/bpmn/internal'; import { ShapeBpmnEventBasedGateway } from '../../../../../src/model/bpmn/internal/shape/ShapeBpmnElement'; describe.each([ ['task', ShapeBpmnElementKind.TASK], ['serviceTask', ShapeBpmnElementKind.TASK_SERVICE], ['userTask', ShapeBpmnElementKind.TASK_USER], ['receiveTask', ShapeBpmnElementKind.TASK_RECEIVE], ['sendTask', ShapeBpmnElementKind.TASK_SEND], ['manualTask', ShapeBpmnElementKind.TASK_MANUAL], ['businessRuleTask', ShapeBpmnElementKind.TASK_BUSINESS_RULE], ['scriptTask', ShapeBpmnElementKind.TASK_SCRIPT], ['exclusiveGateway', ShapeBpmnElementKind.GATEWAY_EXCLUSIVE], ['inclusiveGateway', ShapeBpmnElementKind.GATEWAY_INCLUSIVE], ['parallelGateway', ShapeBpmnElementKind.GATEWAY_PARALLEL], ['eventBasedGateway', ShapeBpmnElementKind.GATEWAY_EVENT_BASED], // ['complexGateway', ShapeBpmnElementKind.GATEWAY_COMPLEX], ])('parse bpmn as json for %s', (bpmnKind: string, expectedShapeBpmnElementKind: ShapeBpmnElementKind) => { const processWithFlowNodeAsObject = {} as TProcess; processWithFlowNodeAsObject[`${bpmnKind}`] = { id: `${bpmnKind}_id_0`, name: `${bpmnKind} name`, }; it.each([ ['object', processWithFlowNodeAsObject], ['array', [processWithFlowNodeAsObject]], ])(`should convert as Shape, when a ${bpmnKind} is an attribute (as object) of 'process' (as %s)`, (title: string, processJson: TProcess) => { const json = { definitions: { targetNamespace: '', process: processJson, BPMNDiagram: { name: 'process 0', BPMNPlane: { BPMNShape: { id: `shape_${bpmnKind}_id_0`, bpmnElement: `${bpmnKind}_id_0`, Bounds: { x: 362, y: 232, width: 36, height: 45 }, }, }, }, }, }; const model = parseJsonAndExpectOnlyFlowNodes(json, 1); verifyShape(model.flowNodes[0], { shapeId: `shape_${bpmnKind}_id_0`, bpmnElementId: `${bpmnKind}_id_0`, bpmnElementName: `${bpmnKind} name`, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 362, y: 232, width: 36, height: 45, }, }); }); it(`should convert as Shape, when a ${bpmnKind} (with/without name) is an attribute (as array) of 'process'`, () => { const json = { definitions: { targetNamespace: '', process: {}, BPMNDiagram: { name: 'process 0', BPMNPlane: { BPMNShape: [ { id: `shape_${bpmnKind}_id_0`, bpmnElement: `${bpmnKind}_id_0`, Bounds: { x: 362, y: 232, width: 36, height: 45 }, }, { id: `shape_${bpmnKind}_id_1`, bpmnElement: `${bpmnKind}_id_1`, Bounds: { x: 365, y: 235, width: 35, height: 46 }, }, ], }, }, }, }; (json.definitions.process as TProcess)[`${bpmnKind}`] = [ { id: `${bpmnKind}_id_0`, name: `${bpmnKind} name`, }, { id: `${bpmnKind}_id_1`, }, ]; const model = parseJsonAndExpectOnlyFlowNodes(json, 2); verifyShape(model.flowNodes[0], { shapeId: `shape_${bpmnKind}_id_0`, bpmnElementId: `${bpmnKind}_id_0`, bpmnElementName: `${bpmnKind} name`, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 362, y: 232, width: 36, height: 45, }, }); verifyShape(model.flowNodes[1], { shapeId: `shape_${bpmnKind}_id_1`, bpmnElementId: `${bpmnKind}_id_1`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 365, y: 235, width: 35, height: 46, }, }); }); if (expectedShapeBpmnElementKind === ShapeBpmnElementKind.TASK_RECEIVE) { it(`should convert as Shape, when a ${bpmnKind} (with/without instantiate) is an attribute (as array) of 'process'`, () => { const json = { definitions: { targetNamespace: '', process: {}, BPMNDiagram: { name: 'process 0', BPMNPlane: { BPMNShape: [ { id: `shape_${bpmnKind}_id_0`, bpmnElement: `${bpmnKind}_id_0`, Bounds: { x: 362, y: 232, width: 36, height: 45 }, }, { id: `shape_${bpmnKind}_id_1`, bpmnElement: `${bpmnKind}_id_1`, Bounds: { x: 365, y: 235, width: 35, height: 46 }, }, ], }, }, }, }; (json.definitions.process as TProcess)[`${bpmnKind}`] = [ { id: `${bpmnKind}_id_0`, }, { id: `${bpmnKind}_id_1`, instantiate: true, }, ]; const model = parseJsonAndExpectOnlyFlowNodes(json, 2); verifyShape(model.flowNodes[0], { shapeId: `shape_${bpmnKind}_id_0`, bpmnElementId: `${bpmnKind}_id_0`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 362, y: 232, width: 36, height: 45, }, }); expect(model.flowNodes[0].bpmnElement.instantiate).toBeFalsy(); verifyShape(model.flowNodes[1], { shapeId: `shape_${bpmnKind}_id_1`, bpmnElementId: `${bpmnKind}_id_1`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 365, y: 235, width: 35, height: 46, }, }); expect(model.flowNodes[1].bpmnElement.instantiate).toBeTruthy(); }); } if (expectedShapeBpmnElementKind === ShapeBpmnElementKind.GATEWAY_EVENT_BASED) { it(`should convert as Shape, when a ${bpmnKind} (with/without instantiate) is an attribute (as array) of 'process'`, () => { const json = { definitions: { targetNamespace: '', process: {}, BPMNDiagram: { name: 'process 0', BPMNPlane: { BPMNShape: [ { id: `shape_${bpmnKind}_id_1`, bpmnElement: `${bpmnKind}_id_1`, Bounds: { x: 362, y: 232, width: 36, height: 45 }, }, { id: `shape_${bpmnKind}_id_2`, bpmnElement: `${bpmnKind}_id_2`, Bounds: { x: 462, y: 232, width: 36, height: 45 }, }, { id: `shape_${bpmnKind}_id_3`, bpmnElement: `${bpmnKind}_id_3`, Bounds: { x: 562, y: 232, width: 36, height: 45 }, }, { id: `shape_${bpmnKind}_id_11`, bpmnElement: `${bpmnKind}_id_11`, Bounds: { x: 365, y: 235, width: 35, height: 46 }, }, { id: `shape_${bpmnKind}_id_12`, bpmnElement: `${bpmnKind}_id_12`, Bounds: { x: 365, y: 335, width: 34, height: 47 }, }, { id: `shape_${bpmnKind}_id_13`, bpmnElement: `${bpmnKind}_id_13`, Bounds: { x: 375, y: 245, width: 34, height: 47 }, }, ], }, }, }, }; (json.definitions.process as TProcess)[`${bpmnKind}`] = [ { id: `${bpmnKind}_id_1`, }, { id: `${bpmnKind}_id_2`, eventGatewayType: 'Exclusive', }, { id: `${bpmnKind}_id_3`, eventGatewayType: 'Parallel', // forbidden by the BPMN spec, only valid when 'instantiate: true' }, { id: `${bpmnKind}_id_11`, instantiate: true, }, { id: `${bpmnKind}_id_12`, instantiate: true, eventGatewayType: 'Exclusive', }, { id: `${bpmnKind}_id_13`, instantiate: true, eventGatewayType: 'Parallel', }, ]; const model = parseJsonAndExpectOnlyFlowNodes(json, 6); // Non 'instantiate' elements verifyShape(model.flowNodes[0], { shapeId: `shape_${bpmnKind}_id_1`, bpmnElementId: `${bpmnKind}_id_1`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 362, y: 232, width: 36, height: 45, }, }); let currentEventBasedGateway = model.flowNodes[0].bpmnElement as ShapeBpmnEventBasedGateway; expect(currentEventBasedGateway.instantiate).toBeFalsy(); expect(currentEventBasedGateway.gatewayKind).toEqual(ShapeBpmnEventBasedGatewayKind.None); verifyShape(model.flowNodes[1], { shapeId: `shape_${bpmnKind}_id_2`, bpmnElementId: `${bpmnKind}_id_2`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 462, y: 232, width: 36, height: 45, }, }); currentEventBasedGateway = model.flowNodes[1].bpmnElement as ShapeBpmnEventBasedGateway; expect(currentEventBasedGateway.instantiate).toBeFalsy(); expect(currentEventBasedGateway.gatewayKind).toEqual(ShapeBpmnEventBasedGatewayKind.Exclusive); verifyShape(model.flowNodes[2], { shapeId: `shape_${bpmnKind}_id_3`, bpmnElementId: `${bpmnKind}_id_3`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 562, y: 232, width: 36, height: 45, }, }); currentEventBasedGateway = model.flowNodes[2].bpmnElement as ShapeBpmnEventBasedGateway; expect(currentEventBasedGateway.instantiate).toBeFalsy(); expect(currentEventBasedGateway.gatewayKind).toEqual(ShapeBpmnEventBasedGatewayKind.Parallel); // 'instantiate' elements verifyShape(model.flowNodes[3], { shapeId: `shape_${bpmnKind}_id_11`, bpmnElementId: `${bpmnKind}_id_11`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 365, y: 235, width: 35, height: 46, }, }); currentEventBasedGateway = model.flowNodes[3].bpmnElement as ShapeBpmnEventBasedGateway; expect(currentEventBasedGateway.instantiate).toBeTruthy(); expect(currentEventBasedGateway.gatewayKind).toEqual(ShapeBpmnEventBasedGatewayKind.None); verifyShape(model.flowNodes[4], { shapeId: `shape_${bpmnKind}_id_12`, bpmnElementId: `${bpmnKind}_id_12`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 365, y: 335, width: 34, height: 47, }, }); currentEventBasedGateway = model.flowNodes[4].bpmnElement as ShapeBpmnEventBasedGateway; expect(currentEventBasedGateway.instantiate).toBeTruthy(); expect(currentEventBasedGateway.gatewayKind).toEqual(ShapeBpmnEventBasedGatewayKind.Exclusive); verifyShape(model.flowNodes[5], { shapeId: `shape_${bpmnKind}_id_13`, bpmnElementId: `${bpmnKind}_id_13`, bpmnElementName: undefined, bpmnElementKind: expectedShapeBpmnElementKind, bounds: { x: 375, y: 245, width: 34, height: 47, }, }); currentEventBasedGateway = model.flowNodes[5].bpmnElement as ShapeBpmnEventBasedGateway; expect(currentEventBasedGateway.instantiate).toBeTruthy(); expect(currentEventBasedGateway.gatewayKind).toEqual(ShapeBpmnEventBasedGatewayKind.Parallel); }); } });
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQueryUI plugin that can manage the detail panel for an aircraft. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.aircraftInfoWindowClass = VRS.globalOptions.aircraftInfoWindowClass || 'vrsAircraftInfoWindow'; // The class for the info window panel. VRS.globalOptions.aircraftInfoWindowEnabled = VRS.globalOptions.aircraftInfoWindowEnabled !== undefined ? VRS.globalOptions.aircraftInfoWindowEnabled : true; // True if the info window is enabled by default VRS.globalOptions.aircraftInfoWindowItems = VRS.globalOptions.aircraftInfoWindowItems || [ // The array of items that are rendered into the info window. VRS.RenderProperty.Icao, VRS.RenderProperty.Registration, VRS.RenderProperty.ModelIcao, VRS.RenderProperty.Operator, VRS.RenderProperty.Model, VRS.RenderProperty.Callsign, VRS.RenderProperty.RouteShort, VRS.RenderProperty.Speed, VRS.RenderProperty.Altitude ]; VRS.globalOptions.aircraftInfoWindowShowUnits = VRS.globalOptions.aircraftInfoWindowShowUnits !== undefined ? VRS.globalOptions.aircraftInfoWindowShowUnits : true; // True if units should be shown in the info window. VRS.globalOptions.aircraftInfoWindowFlagUncertainCallsigns = VRS.globalOptions.aircraftInfoWindowFlagUncertainCallsigns !== undefined ? VRS.globalOptions.aircraftInfoWindowFlagUncertainCallsigns : true; // True if uncertain callsigns are to be flagged as such. VRS.globalOptions.aircraftInfoWindowDistinguishOnGround = VRS.globalOptions.aircraftInfoWindowDistinguishOnGround !== undefined ? VRS.globalOptions.aircraftInfoWindowDistinguishOnGround : true; // True if aircraft on the ground should show an altitude of GND. VRS.globalOptions.aircraftInfoWindowAllowConfiguration = VRS.globalOptions.aircraftInfoWindowAllowConfiguration !== undefined ? VRS.globalOptions.aircraftInfoWindowAllowConfiguration : true; // True if the user can configure the infowindow settings. VRS.globalOptions.aircraftInfoWindowEnablePanning = VRS.globalOptions.aircraftInfoWindowEnablePanning !== undefined ? VRS.globalOptions.aircraftInfoWindowEnablePanning : true; // True if the map should pan to the info window when it opens. /** * The options that the AircraftInfoWindowPlugin honours. */ export interface AircraftInfoWindowPlugin_Options { /** * The name to use when storing settings. */ name?: string; /** * The aircraft list that the plugin will listen to. */ aircraftList?: AircraftList; /** * The object that holds onto the markers for the map we'll be using. */ aircraftPlotter?: AircraftPlotter; /** * The unit display preferences to use when showing aircraft detail. */ unitDisplayPreferences: UnitDisplayPreferences; /** * True if the info window is to be shown, false otherwise. */ enabled?: boolean; /** * True if the info window should override the options with those saved by the user. */ useStateOnOpen?: boolean; /** * The items to display in the info window. */ items?: RenderPropertyEnum[]; /** * True if units should be shown. */ showUnits?: boolean; /** * True if uncertain callsigns are to be highlighted. */ flagUncertainCallsigns?: boolean; /** * True if aircraft on the ground should show an altitude of GND. */ distinguishOnGround?: boolean; /** * True if the map should pan to the info window when it opens. */ enablePanning?: boolean; } /** * The state held by the AircraftInfoWindowPlugin. */ class AircraftInfoWindowPlugin_State { /** * The jQuery element for the container that the items are rendered into. */ containerElement: JQuery = null; /** * The jQuery element for the items container. */ itemsContainerElement: JQuery = null; /** * An associative array of jQuery elements that hold values against the render properties that will be rendered into them. */ itemElements: { [index: string]: JQuery } = {}; /** * The map info window that gets us displayed on the map. */ mapInfoWindow: IMapInfoWindow = null; /** * The aircraft whose details we are displaying. */ aircraft: Aircraft = null; /** * The aircraft that the info window is anchored to. */ anchoredAircraft: Aircraft = null; /** * True if updates have been suspended. */ suspended = false; /** * True if the user closed an open InfoWindow. If they closed a window then we don't open any new ones unless * they specifically request it by clicking a map marker - that will clear this flag and we then resume showing * info windows for all selections. */ closedByUser = false; /** * The object that manages the link to the aircraft detail page. */ jumpToAircraftDetailLinkRenderer: JumpToAircraftDetailPageRenderHandler = null; /** * The jQuery element that holds the links. */ linksElement: JQuery = null; /** * The direct reference to the aircraft links manager. */ linksPlugin: AircraftLinksPlugin = null; /** * The hook result from an aircraft list updated event. */ aircraftListUpdatedHookResult: IEventHandle = null; /** * The hook result from a info window closed by the user event. */ infoWindowClosedByUserHookResult: IEventHandleJQueryUI = null; /** * The hook result from a marker clicked event. */ markerClickedHookResult: IEventHandleJQueryUI = null; /** * The hook result from a selected aircraft changed event. */ selectedAircraftChangedHook: IEventHandle = null; /** * The hook result from the unit display preferences unit changed event. */ unitChangedHookResult: IEventHandle = null; /** * The hook result for the change of language event. */ localeChangedHookResult: IEventHandle = null; } /** * The settings that an AircraftInfoWindowPlugin can persist between sessions. */ export interface AircraftInfoWindowPlugin_SaveState { enabled: boolean; items: RenderPropertyEnum[]; showUnits: boolean; } /* * jQueryUIHelper */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getAircraftInfoWindowPlugin = function(jQueryElement: JQuery) : AircraftInfoWindowPlugin { return <AircraftInfoWindowPlugin>jQueryElement.data('vrsVrsAircraftInfoWindow'); } VRS.jQueryUIHelper.getAircraftInfoWindowOptions = function(overrides?: AircraftInfoWindowPlugin_Options) : AircraftInfoWindowPlugin_Options { return $.extend({ name: 'default', aircraftList: null, aircraftPlotter: null, unitDisplayPreferences: null, enabled: VRS.globalOptions.aircraftInfoWindowEnabled, useStateOnOpen: true, items: VRS.globalOptions.aircraftInfoWindowItems, showUnits: VRS.globalOptions.aircraftInfoWindowShowUnits, flagUncertainCallsigns: VRS.globalOptions.aircraftInfoWindowFlagUncertainCallsigns, distinguishOnGround: VRS.globalOptions.aircraftInfoWindowDistinguishOnGround, enablePanning: VRS.globalOptions.aircraftInfoWindowEnablePanning }, overrides); } /** * A widget that can show details from the selected aircraft in a map's info window. */ export class AircraftInfoWindowPlugin extends JQueryUICustomWidget implements ISelfPersist<AircraftInfoWindowPlugin_SaveState> { options: AircraftInfoWindowPlugin_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getAircraftInfoWindowOptions(); } private _getState() : AircraftInfoWindowPlugin_State { var result = this.element.data('aircraftInfoWindowState'); if(result === undefined) { result = new AircraftInfoWindowPlugin_State(); this.element.data('aircraftInfoWindowState', result); } return result; } _create() { var state = this._getState(); var options = this.options; var map = options.aircraftPlotter.getMap(); if(options.useStateOnOpen) { this.loadAndApplyState(); } this.element.addClass(VRS.globalOptions.aircraftInfoWindowClass); state.containerElement = $('<div/>') .appendTo(this.element); state.itemsContainerElement = $('<ul/>') .appendTo(state.containerElement); this._buildItems(state); state.jumpToAircraftDetailLinkRenderer = new VRS.JumpToAircraftDetailPageRenderHandler(); state.linksElement = $('<div/>') .addClass('links') .vrsAircraftLinks(VRS.jQueryUIHelper.getAircraftLinksOptions({ linkSites: [ state.jumpToAircraftDetailLinkRenderer ] })) .appendTo(state.containerElement); state.linksPlugin = VRS.jQueryUIHelper.getAircraftLinksPlugin(state.linksElement); state.mapInfoWindow = map.addInfoWindow(map.getUnusedInfoWindowId(), { content: this.element[0], disableAutoPan: !options.enablePanning }); state.infoWindowClosedByUserHookResult = map.hookInfoWindowClosedByUser(this._infoWindowClosedByUser, this); state.aircraftListUpdatedHookResult = options.aircraftList.hookUpdated(this._aircraftListUpdated, this); state.selectedAircraftChangedHook = options.aircraftList.hookSelectedAircraftChanged(this._selectedAircraftChanged, this); state.markerClickedHookResult = map.hookMarkerClicked(this._markerClicked, this); state.unitChangedHookResult = options.unitDisplayPreferences.hookUnitChanged(this._displayUnitChanged, this); state.localeChangedHookResult = VRS.globalisation.hookLocaleChanged(this._localeChanged, this); this.showForAircraft(options.aircraftList.getSelectedAircraft()); } _destroy() { var state = this._getState(); var options = this.options; // Unhook all of the events if(state.aircraftListUpdatedHookResult) options.aircraftList.unhook(state.aircraftListUpdatedHookResult); state.aircraftListUpdatedHookResult = null; if(state.selectedAircraftChangedHook) options.aircraftList.unhook(state.selectedAircraftChangedHook); state.selectedAircraftChangedHook = null; if(state.infoWindowClosedByUserHookResult) options.aircraftPlotter.getMap().unhook(state.infoWindowClosedByUserHookResult); state.infoWindowClosedByUserHookResult = null; if(state.markerClickedHookResult) options.aircraftPlotter.getMap().unhook(state.markerClickedHookResult); state.markerClickedHookResult = null; if(state.unitChangedHookResult) options.unitDisplayPreferences.unhook(state.unitChangedHookResult); state.unitChangedHookResult = null; if(state.localeChangedHookResult) VRS.globalisation.unhook(state.localeChangedHookResult); state.localeChangedHookResult = null; // Destroy the links if(state.linksElement) { state.linksPlugin.destroy(); state.linksElement.remove(); } state.linksElement = null; state.jumpToAircraftDetailLinkRenderer = null; // Destroy the items this._destroyItems(state); if(state.itemsContainerElement) state.itemsContainerElement.remove(); state.itemsContainerElement = null; // Destroy the container if(state.containerElement) state.containerElement.remove(); state.containerElement = null; // Remove the class this.element.removeClass(VRS.globalOptions.aircraftInfoWindowClass); // Remove the info window if(state.mapInfoWindow) { options.aircraftPlotter.getMap().destroyInfoWindow(state.mapInfoWindow); } state.mapInfoWindow = null; // Null out anything that's left over state.aircraft = null; } /** * Creates the items list. */ private _buildItems(state: AircraftInfoWindowPlugin_State) { this._destroyItems(state); var options = this.options; var length = options.items.length; for(var i = 0;i < length;++i) { var renderProperty = options.items[i]; var handler = VRS.renderPropertyHandlers[renderProperty]; if(!handler) throw 'Cannot find the render property handler for ' + renderProperty; var listItem = $('<li/>') .appendTo(state.itemsContainerElement); var label = $('<label/>') .text(handler.suppressLabelCallback(VRS.RenderSurface.InfoWindow) ? '' : VRS.globalisation.getText(handler.labelKey) + ':') .appendTo(listItem); state.itemElements[renderProperty] = $('<p/>') .addClass('value') .appendTo(listItem); } } /** * Destroys the items list. * @param {VRS.AircraftInfoWindowState} state * @private */ private _destroyItems(state: AircraftInfoWindowPlugin_State) { state.itemsContainerElement.empty(); state.itemElements = {}; } /** * Saves the current state to persistent storage. */ saveState() { VRS.configStorage.save(this._persistenceKey(), this._createSettings()); } /** * Returns the previously saved state or, if none has been saved, the current state. */ loadState() : AircraftInfoWindowPlugin_SaveState { var savedSettings = VRS.configStorage.load(this._persistenceKey(), {}); var result = $.extend(this._createSettings(), savedSettings); result.items = VRS.renderPropertyHelper.buildValidRenderPropertiesList(result.items, [ VRS.RenderSurface.InfoWindow ]); return result; } /** * Applies the previously saved state to this object. */ applyState(settings: AircraftInfoWindowPlugin_SaveState) { var options = this.options; options.enabled = settings.enabled; options.items = settings.items.slice(); options.showUnits = settings.showUnits; var state = this._getState(); if(state.containerElement) { this._buildItems(state); this.refreshDisplay(); } } /** * Loads and applies the previously saved state. */ loadAndApplyState() { this.applyState(this.loadState()); } /** * Returns the key to use when saving and loading state. */ private _persistenceKey() : string { return 'vrsAircraftInfoWindow-' + this.options.name; } /** * Returns the object that holds the current state. */ private _createSettings() : AircraftInfoWindowPlugin_SaveState { var options = this.options; return { enabled: options.enabled, items: options.items, showUnits: options.showUnits }; } /** * Creates the option pane for configuring the standard options. */ createOptionPane(displayOrder: number) : OptionPane { var result = new VRS.OptionPane({ name: 'infoWindow', titleKey: 'PaneInfoWindow', displayOrder: displayOrder }); var options = this.options; var saveAndApplyState = () => { this.saveState(); var settings = this._createSettings(); this.applyState(settings); }; // Enabled field - users can always turn this off even if they can't configure anything else result.addField(new VRS.OptionFieldCheckBox({ name: 'enable', labelKey: 'EnableInfoWindow', getValue: () => options.enabled, setValue: (value) => options.enabled = value, saveState: saveAndApplyState })); if(VRS.globalOptions.aircraftInfoWindowAllowConfiguration) { result.addField(new VRS.OptionFieldCheckBox({ name: 'showUnits', labelKey: 'ShowUnits', getValue: () => options.showUnits, setValue: (value) => options.showUnits = value, saveState: saveAndApplyState })); VRS.renderPropertyHelper.addRenderPropertiesListOptionsToPane({ pane: result, surface: VRS.RenderSurface.InfoWindow, fieldLabel: 'Columns', getList: () => options.items, setList: (value) => options.items = value, saveState: saveAndApplyState }); } return result; } /** * Suspends or resumes updates. */ suspend(onOff: boolean) { var state = this._getState(); if(state.suspended !== onOff) { state.suspended = onOff; } } /** * Displays information for an aircraft. */ showForAircraft(aircraft: Aircraft) { var state = this._getState(); state.aircraft = aircraft; this._displayDetails(state, true); } /** * Refreshes the display. */ refreshDisplay() { var state = this._getState(); this._displayDetails(state, true); } /** * Displays information for the current aircraft. */ private _displayDetails(state: AircraftInfoWindowPlugin_State, forceRefresh?: boolean) { var options = this.options; if(state.suspended || state.closedByUser) return; if(forceRefresh === undefined) forceRefresh = false; var aircraft = state.aircraft; var map = options.aircraftPlotter.getMap(); var mapMarker = options.aircraftPlotter.getMapMarkerForAircraft(aircraft); var mapInfoWindow = state.mapInfoWindow; if(state.anchoredAircraft !== aircraft) forceRefresh = true; var length = options.items.length; if(options.enabled) { for(var i = 0;i < length;++i) { var renderProperty = options.items[i]; var handler = VRS.renderPropertyHandlers[renderProperty]; if(!handler) throw 'Cannot find the handler for ' + renderProperty; var renderElement = state.itemElements[renderProperty]; if(renderElement) { if(!aircraft) renderElement.text(''); else if(forceRefresh || handler.hasChangedCallback(aircraft)) { handler.renderToJQuery(renderElement, VRS.RenderSurface.InfoWindow, aircraft, options); } } } state.linksPlugin.renderForAircraft(state.aircraft, false); } if(!mapMarker || !options.enabled) { if(mapInfoWindow.isOpen) map.closeInfoWindow(mapInfoWindow); state.anchoredAircraft = null; } else { if(forceRefresh) { if(mapInfoWindow.isOpen) map.closeInfoWindow(mapInfoWindow); map.openInfoWindow(mapInfoWindow, mapMarker); state.anchoredAircraft = aircraft; } } } /** * Called when the selected aircraft changes. */ private _selectedAircraftChanged() { var selectedAircraft = this.options.aircraftList.getSelectedAircraft(); this.showForAircraft(selectedAircraft); } /** * Called when the user clicks a map marker. */ private _markerClicked(event: Event, data: IMapMarkerEventArgs) { var state = this._getState(); var options = this.options; if(state.mapInfoWindow) { var aircraft = options.aircraftPlotter.getAircraftForMarkerId(<number>data.id); if(aircraft) { state.closedByUser = false; if(!state.mapInfoWindow.isOpen || state.aircraft != aircraft) this.showForAircraft(aircraft); } } } /** * Called when the user closes the info window manually. */ private _infoWindowClosedByUser(event: Event, data: IMapInfoWindowEventArgs) { var state = this._getState(); state.closedByUser = true; } /** * Called when the aircraft list has been updated. */ private _aircraftListUpdated() { var state = this._getState(); var options = this.options; if(state.aircraft) { if(!options.aircraftList.findAircraftById(state.aircraft.id)) this.showForAircraft(null); else this._displayDetails(state, false); } } /** * Called when the unit display preferences have been changed. */ private _displayUnitChanged() { var state = this._getState(); if(state.aircraft) this.refreshDisplay(); } /** * Called when the language has been changed. */ private _localeChanged() { var state = this._getState(); if(state.aircraft) this.refreshDisplay(); } } $.widget('vrs.vrsAircraftInfoWindow', new AircraftInfoWindowPlugin()); } declare interface JQuery { vrsAircraftInfoWindow(); vrsAircraftInfoWindow(options: VRS.AircraftInfoWindowPlugin_Options); vrsAircraftInfoWindow(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import { getQueueToken, NO_QUEUE_FOUND } from '@nestjs/bull-shared'; import { Injectable, Logger, OnModuleInit, Type } from '@nestjs/common'; import { createContextId, DiscoveryService, MetadataScanner, ModuleRef, } from '@nestjs/core'; import { Injector } from '@nestjs/core/injector/injector'; import { InstanceWrapper } from '@nestjs/core/injector/instance-wrapper'; import { Module } from '@nestjs/core/injector/module'; import { Processor, Queue, QueueEvents, QueueOptions, Worker, WorkerOptions, } from 'bullmq'; import { BullMetadataAccessor } from './bull-metadata.accessor'; import { OnQueueEventMetadata, OnWorkerEventMetadata } from './decorators'; import { InvalidProcessorClassError, InvalidQueueEventsListenerClassError, } from './errors'; import { QueueEventsHost, WorkerHost } from './hosts'; import { getSharedConfigToken } from './utils/get-shared-config-token.util'; @Injectable() export class BullExplorer implements OnModuleInit { private static _workerClass: Type = Worker; private readonly logger = new Logger('BullModule'); private readonly injector = new Injector(); static set workerClass(cls: Type) { this._workerClass = cls; } constructor( private readonly moduleRef: ModuleRef, private readonly discoveryService: DiscoveryService, private readonly metadataAccessor: BullMetadataAccessor, private readonly metadataScanner: MetadataScanner, ) {} onModuleInit() { this.registerWorkers(); this.registerQueueEventListeners(); } registerWorkers() { const processors: InstanceWrapper[] = this.discoveryService .getProviders() .filter((wrapper: InstanceWrapper) => this.metadataAccessor.isProcessor( // NOTE: Regarding the ternary statement below, // - The condition `!wrapper.metatype` is because when we use `useValue` // the value of `wrapper.metatype` will be `null`. // - The condition `wrapper.inject` is needed here because when we use // `useFactory`, the value of `wrapper.metatype` will be the supplied // factory function. // For both cases, we should use `wrapper.instance.constructor` instead // of `wrapper.metatype` to resolve processor's class properly. // But since calling `wrapper.instance` could degrade overall performance // we must defer it as much we can. But there's no other way to grab the // right class that could be annotated with `@Processor()` decorator // without using this property. !wrapper.metatype || wrapper.inject ? wrapper.instance?.constructor : wrapper.metatype, ), ); processors.forEach((wrapper: InstanceWrapper) => { const { instance, metatype } = wrapper; const isRequestScoped = !wrapper.isDependencyTreeStatic(); const { name: queueName, configKey } = this.metadataAccessor.getProcessorMetadata( // NOTE: We are relying on `instance.constructor` to properly support // `useValue` and `useFactory` providers besides `useClass`. instance.constructor || metatype, ); const queueToken = getQueueToken(queueName); const queueOpts = this.getQueueOptions(queueToken, queueName, configKey); if (!(instance instanceof WorkerHost)) { throw new InvalidProcessorClassError(instance.constructor?.name); } else { const workerOptions = this.metadataAccessor.getWorkerOptionsMetadata( instance.constructor, ); this.handleProcessor( instance, queueName, queueOpts, wrapper.host, isRequestScoped, workerOptions, ); } this.registerWorkerEventListeners(wrapper); }); } getQueueOptions(queueToken: string, queueName: string, configKey?: string) { try { const queueRef = this.moduleRef.get<Queue>(queueToken, { strict: false }); return queueRef.opts ?? {}; } catch (err) { const sharedConfigToken = getSharedConfigToken(configKey); try { return this.moduleRef.get<QueueOptions>(sharedConfigToken, { strict: false, }); } catch (err) { this.logger.error(NO_QUEUE_FOUND(queueName)); throw err; } } } handleProcessor<T extends WorkerHost>( instance: T, queueName: string, queueOpts: QueueOptions, moduleRef: Module, isRequestScoped: boolean, options: WorkerOptions = {}, ) { const methodKey = 'process'; let processor: Processor<any, void, string>; if (isRequestScoped) { processor = async (...args: unknown[]) => { const contextId = createContextId(); if (this.moduleRef.registerRequestByContextId) { // Additional condition to prevent breaking changes in // applications that use @nestjs/bull older than v7.4.0. const jobRef = args[0]; this.moduleRef.registerRequestByContextId(jobRef, contextId); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, moduleRef.providers, contextId, ); return contextInstance[methodKey].call(contextInstance, ...args); }; } else { processor = instance[methodKey].bind(instance); } const worker = new BullExplorer._workerClass(queueName, processor, { connection: queueOpts.connection, sharedConnection: queueOpts.sharedConnection, prefix: queueOpts.prefix, ...options, }); (instance as any)._worker = worker; } registerWorkerEventListeners(wrapper: InstanceWrapper) { const { instance } = wrapper; this.metadataScanner.scanFromPrototype( instance, Object.getPrototypeOf(instance), (key: string) => { const workerEventHandlerMetadata = this.metadataAccessor.getOnWorkerEventMetadata(instance[key]); if (workerEventHandlerMetadata) { this.handleWorkerEvents(key, wrapper, workerEventHandlerMetadata); } }, ); } handleWorkerEvents( key: string, wrapper: InstanceWrapper, options: OnWorkerEventMetadata, ) { const { instance } = wrapper; if (!wrapper.isDependencyTreeStatic()) { this.logger.warn( `Warning! "${wrapper.name}" class is request-scoped and it defines an event listener ("${wrapper.name}#${key}"). Since event listeners cannot be registered on scoped providers, this handler will be ignored.`, ); return; } instance.worker.on(options.eventName, instance[key].bind(instance)); } registerQueueEventListeners() { const eventListeners: InstanceWrapper[] = this.discoveryService .getProviders() .filter((wrapper: InstanceWrapper) => this.metadataAccessor.isQueueEventsListener( // NOTE: Regarding the ternary statement below, // - The condition `!wrapper.metatype` is because when we use `useValue` // the value of `wrapper.metatype` will be `null`. // - The condition `wrapper.inject` is needed here because when we use // `useFactory`, the value of `wrapper.metatype` will be the supplied // factory function. // For both cases, we should use `wrapper.instance.constructor` instead // of `wrapper.metatype` to resolve processor's class properly. // But since calling `wrapper.instance` could degrade overall performance // we must defer it as much we can. But there's no other way to grab the // right class that could be annotated with `@Processor()` decorator // without using this property. !wrapper.metatype || wrapper.inject ? wrapper.instance?.constructor : wrapper.metatype, ), ); eventListeners.forEach((wrapper: InstanceWrapper) => { const { instance, metatype } = wrapper; if (!wrapper.isDependencyTreeStatic()) { this.logger.warn( `Warning! "${wrapper.name}" class is request-scoped and it is flagged as an event listener. Since event listeners cannot be registered on scoped providers, this handler will be ignored.`, ); return; } const { queueName, queueEventsOptions } = this.metadataAccessor.getQueueEventsListenerMetadata( // NOTE: We are relying on `instance.constructor` to properly support // `useValue` and `useFactory` providers besides `useClass`. instance.constructor || metatype, ); const queueToken = getQueueToken(queueName); const queueOpts = this.getQueueOptions(queueToken, queueName); if (!(instance instanceof QueueEventsHost)) { throw new InvalidQueueEventsListenerClassError( instance.constructor?.name, ); } else { const queueEventsInstance = new QueueEvents(queueName, { connection: queueOpts.connection, prefix: queueOpts.prefix, sharedConnection: queueOpts.sharedConnection, ...queueEventsOptions, }); (instance as any)._queueEvents = queueEventsInstance; this.metadataScanner.scanFromPrototype( instance, Object.getPrototypeOf(instance), (key: string) => { const queueEventHandlerMetadata = this.metadataAccessor.getOnQueueEventMetadata(instance[key]); if (queueEventHandlerMetadata) { this.handleQueueEvents( key, wrapper, queueEventsInstance, queueEventHandlerMetadata, ); } }, ); } }); } handleQueueEvents( key: string, wrapper: InstanceWrapper, queueEventsInstance: QueueEvents, options: OnQueueEventMetadata, ) { const { eventName } = options; const { instance } = wrapper; queueEventsInstance.on(eventName, instance[key].bind(instance)); } }
the_stack
import { ParamField } from '../types'; /** * Formats a multi-value header's value, based on https://tools.ietf.org/html/rfc7230#section-7 * If an argument is a string, or a tuple where the second argument is '', only the key will be serialized. * example: `formatMultiValueHeader(['k1', 'v1'], ['k2', '']) === 'k1=v1, k2' */ export const formatMultiValueHeader = (...keyValuePairs: ReadonlyArray<readonly [string, string] | string>) => { // right now we are assuming that key is a valid token. We might want to implement parsing later. // *token* is defined in RFC 7230, section 3.2.6. return keyValuePairs .map(item => { if (typeof item === 'string') return item; const [key, rawValue] = item; if (!rawValue) return key; const needsQuotes = rawValue.indexOf(',') > -1; const value = needsQuotes ? `"${rawValue}"` : rawValue; return `${key}=${value}`; }) .join(', '); }; // Copied from https://en.wikipedia.org/wiki/List_of_HTTP_header_fields export const allHeaderFields: ParamField[] = [ { name: 'A-IM', description: 'Acceptable instance-manipulations for the request.', example: 'A-IM: feed', }, { name: 'Accept', description: 'Media type(s) that is/are acceptable for the response. See Content negotiation.', example: 'Accept: text/html', }, { name: 'Accept-Charset', description: 'Character sets that are acceptable.', example: 'Accept-Charset: utf-8', }, { name: 'Accept-Encoding', description: 'List of acceptable encodings. See HTTP compression.', example: 'Accept-Encoding: gzip, deflate', }, { name: 'Accept-Language', description: 'List of acceptable human languages for response. See Content negotiation.', example: 'Accept-Language: en-US', }, { name: 'Accept-Datetime', description: 'Acceptable version in time.', example: 'Accept-Datetime: Thu, 31 May 2007 20:35:00 GMT', }, { name: 'Access-Control-Request-Method', description: 'Initiates a request for cross-origin resource sharing with Origin (below).', example: 'Access-Control-Request-Method: GET', }, { name: 'Access-Control-Request-Headers', description: 'Initiates a request for cross-origin resource sharing with Origin (below).', example: '', }, { name: 'Authorization', description: 'Authentication credentials for HTTP authentication.', example: 'Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==', }, { name: 'Cache-Control', description: 'Used to specify directives that must be obeyed by all caching mechanisms along the request-response chain.', example: 'Cache-Control: no-cache', }, { name: 'Connection', description: 'Control options for the current connection and list of hop-by-hop request fields.[12]Must not be used with HTTP/2.[13]', example: 'Connection: keep-aliveConnection: Upgrade', }, { name: 'Content-Length', description: 'The length of the request body in octets (8-bit bytes).', example: 'Content-Length: 348', }, { name: 'Content-MD5', description: 'A Base64-encoded binary MD5 sum of the content of the request body.', example: 'Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==', }, { name: 'Content-Type', description: 'The Media type of the body of the request (used with POST and PUT requests).', example: 'Content-Type: application/x-www-form-urlencoded', }, { name: 'Cookie', description: 'An HTTP cookie previously sent by the server with Set-Cookie (below).', example: 'Cookie: $Version=1; Skin=new;', }, { name: 'Date', description: 'The date and time at which the message was originated (in "HTTP-date" format as defined by RFC 7231 Date/Time Formats).', example: 'Date: Tue, 15 Nov 1994 08:12:31 GMT', }, { name: 'Expect', description: 'Indicates that particular server behaviors are required by the client.', example: 'Expect: 100-continue', }, { name: 'Forwarded', description: 'Disclose original information of a client connecting to a web server through an HTTP proxy.[15]', example: 'Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43Forwarded: for=192.0.2.43, for=198.51.100.17', }, { name: 'From', description: 'The email address of the user making the request.', example: 'From: user@example.com', }, { name: 'Host', description: 'The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. The port number may be omitted if the port is the standard port for the service requested.Mandatory since HTTP/1.1.[16] If the request is generated directly in HTTP/2, it should not be used.[17]', example: 'Host: en.wikipedia.org:8080Host: en.wikipedia.org', }, { name: 'HTTP2-Settings', description: 'A request that upgrades from HTTP/1.1 to HTTP/2 MUST include exactly one HTTP2-Setting header field. The HTTP2-Settings header field is a connection-specific header field that includes parameters that govern the HTTP/2 connection, provided in anticipation of the server accepting the request to upgrade.[18][19]', example: 'HTTP2-Settings: token64', }, { name: 'If-Match', description: 'Only perform the action if the client supplied entity matches the same entity on the server. This is mainly for methods like PUT to only update a resource if it has not been modified since the user last updated it.', example: 'If-Match: "737060cd8c284d8af7ad3082f209582d"', }, { name: 'If-Modified-Since', description: 'Allows a 304 Not Modified to be returned if content is unchanged.', example: 'If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT', }, { name: 'If-None-Match', description: 'Allows a 304 Not Modified to be returned if content is unchanged, see HTTP ETag.', example: 'If-None-Match: "737060cd8c284d8af7ad3082f209582d"', }, { name: 'If-Range', description: 'If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity.', example: 'If-Range: "737060cd8c284d8af7ad3082f209582d"', }, { name: 'If-Unmodified-Since', description: 'Only send the response if the entity has not been modified since a specific time.', example: 'If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT', }, { name: 'Max-Forwards', description: 'Limit the number of times the message can be forwarded through proxies or gateways.', example: 'Max-Forwards: 10', }, { name: 'Origin', description: 'Initiates a request for cross-origin resource sharing (asks server for Access-Control-* response fields).', example: 'Origin: http://www.example-social-network.com', }, { name: 'Pragma', description: 'Implementation-specific fields that may have various effects anywhere along the request-response chain.', example: 'Pragma: no-cache', }, { name: 'Prefer', description: 'Used to request that certain behaviours be employed by a server while processing a request. Used by Prism to control some of the behaviour of the mock server.', example: 'Prefer: code=200', }, { name: 'Proxy-Authorization', description: 'Authorization credentials for connecting to a proxy.', example: 'Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==', }, { name: 'Range', description: 'Request only part of an entity. Bytes are numbered from 0. See Byte serving.', example: 'Range: bytes=500-999', }, { name: 'Referer', description: 'This is the address of the previous web page from which a link to the currently requested page was followed. (The word “referrer” has been misspelled in the RFC as well as in most implementations to the point that it has become standard usage and is considered correct terminology)', example: 'Referer: http://en.wikipedia.org/wiki/Main_Page', }, { name: 'TE', description: 'The transfer encodings the user agent is willing to accept: the same values as for the response header field Transfer-Encoding can be used, plus the "trailers" value (related to the "chunked" transfer method) to notify the server it expects to receive additional fields in the trailer after the last, zero-sized, chunk.Only trailers is supported in HTTP/2.[13]', example: 'TE: trailers, deflate', }, { name: 'User-Agent', description: 'The user agent string of the user agent.', example: 'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/12.0', }, { name: 'Upgrade', description: 'Ask the server to upgrade to another protocol.Must not be used in HTTP/2.[13]', example: 'Upgrade: h2c, HTTPS/1.3, IRC/6.9, RTA/x11, websocket', }, { name: 'Via', description: 'Informs the server of proxies through which the request was sent.', example: 'Via: 1.0 fred, 1.1 example.com (Apache/1.1)', }, { name: 'Warning', description: 'A general warning about possible problems with the entity body.', example: 'Warning: 199 Miscellaneous warning', }, { name: 'Upgrade-Insecure-Requests', description: 'Tells a server which (presumably in the middle of a HTTP -> HTTPS migration) hosts mixed content that the client would prefer redirection to HTTPS and can handle Content-Security-Policy: upgrade-insecure-requestsMust not be used with HTTP/2[13]', example: 'Upgrade-Insecure-Requests: 1', }, { name: 'X-Requested-With', description: 'Mainly used to identify Ajax requests. Most JavaScript frameworks send this field with value of XMLHttpRequest', example: 'X-Requested-With: XMLHttpRequest', }, { name: 'DNT', description: "Requests a web application to disable their tracking of a user. This is Mozilla's version of the X-Do-Not-Track header field (since Firefox 4.0 Beta 11).Safari and IE9 also have support for this field.[22] On March 7, 2011, a draft proposal was submitted to IETF.[23] The W3C Tracking Protection Working Group is producing a specification.[24]", example: 'DNT: 1 (Do Not Track Enabled)DNT: 0 (Do Not Track Disabled)', }, { name: 'X-Forwarded-For', description: 'A de facto standard for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or load balancer. Superseded by Forwarded header.', example: 'X-Forwarded-For: client1, proxy1, proxy2X-Forwarded-For: 129.78.138.66, 129.78.64.103', }, { name: 'X-Forwarded-Host', description: 'A de facto standard for identifying the original host requested by the client in the Host HTTP request header, since the host name and/or port of the reverse proxy (load balancer) may differ from the origin server handling the request. Superseded by Forwarded header.', example: 'X-Forwarded-Host: en.wikipedia.org:8080X-Forwarded-Host: en.wikipedia.org', }, { name: 'X-Forwarded-Proto', description: 'A de facto standard for identifying the originating protocol of an HTTP request, since a reverse proxy (or a load balancer) may communicate with a web server using HTTP even if the request to the reverse proxy is HTTPS. An alternative form of the header (X-ProxyUser-Ip) is used by Google clients talking to Google servers. Superseded by Forwarded header.', example: 'X-Forwarded-Proto: https', }, { name: 'Front-End-Https', description: 'Non-standard header field used by Microsoft applications and load-balancers', example: 'Front-End-Https: on', }, { name: 'X-Http-Method-Override', description: 'Requests a web application to override the method specified in the request (typically POST) with the method given in the header field (typically PUT or DELETE). This can be used when a user agent or firewall prevents PUT or DELETE methods from being sent directly (note that this is either a bug in the software component, which ought to be fixed, or an intentional configuration, in which case bypassing it may be the wrong thing to do).', example: 'X-HTTP-Method-Override: DELETE', }, { name: 'X-ATT-DeviceId', description: 'Allows easier parsing of the MakeModel/Firmware that is usually found in the User-Agent String of AT&T Devices', example: 'X-Att-Deviceid: GT-P7320/P7320XXLPG', }, { name: 'X-Wap-Profile', description: 'Links to an XML file on the Internet with a full description and details about the device currently connecting. In the example to the right is an XML file for an AT&T Samsung Galaxy S2.', example: 'x-wap-profile:http://wap.samsungmobile.com/uaprof/SGH-I777.xml', }, { name: 'Proxy-Connection', description: 'Implemented as a misunderstanding of the HTTP specifications. Common because of mistakes in implementations of early HTTP versions. Has exactly the same functionality as standard Connection field.Must not be used with HTTP/2.[13]', example: 'Proxy-Connection: keep-alive', }, { name: 'X-UIDH', description: 'Server-side deep packet insertion of a unique ID identifying customers of Verizon Wireless; also known as "perma-cookie" or "supercookie"', example: 'X-UIDH: ...', }, { name: 'X-Csrf-Token', description: 'Used to prevent cross-site request forgery. Alternative header names are: X-CSRFToken and X-XSRF-TOKEN', example: 'X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql', }, { name: 'X-Request-ID', description: 'Correlates HTTP requests between a client and server.', example: 'X-Request-ID: f058ebd6-02f7-4d3f-942e-904344e8cde5', }, { name: 'Save-Data', description: 'The Save-Data client hint request header available in Chrome, Opera, and Yandex browsers lets developers deliver lighter, faster applications to users who opt-in to data saving mode in their browser.', example: 'Save-Data: on', }, ];
the_stack
import {MotionController} from 'webxr-input-profiles/packages/motion-controllers/src/motionController'; import {fetchProfile} from 'webxr-input-profiles/packages/motion-controllers/src/profiles'; import {Constants} from 'webxr-input-profiles/packages/motion-controllers/src/constants'; import { XRFrame, XRInputSource } from 'webxr'; import Gltf2Importer from '../foundation/importer/Gltf2Importer'; import ModelConverter from '../foundation/importer/ModelConverter'; import { Is } from '../foundation/misc/Is'; import Entity from '../foundation/core/Entity'; import { Component } from 'webxr-input-profiles/packages/motion-controllers/src/component'; import Quaternion from '../foundation/math/Quaternion'; import Vector3 from '../foundation/math/Vector3'; import { IMutableScalar, IMutableVector3 } from '../foundation/math/IVector'; import WebXRSystem from './WebXRSystem'; import { defaultValue } from '../foundation/misc/MiscUtil'; import { IMutableQuaternion } from '../foundation/math/IQuaternion'; import Matrix33 from '../foundation/math/Matrix33'; import Matrix44 from '../foundation/math/Matrix44'; import MutableVector3 from '../foundation/math/MutableVector3'; import MutableMatrix33 from '../foundation/math/MutableMatrix33'; import MutableScalar from '../foundation/math/MutableScalar'; import MutableMatrix44 from '../foundation/math/MutableMatrix44'; const oculusProfile = require('webxr-input-profiles/packages/registry/profiles/oculus/oculus-touch.json'); const motionControllers:Map<XRInputSource, MotionController> = new Map(); type ComponentValues = { state: Constants.ComponentState; button?: number; xAxis?: number; yAxis?: number }; type ComponentChangeCallback = ({ componentValues, handedness}: {componentValues: ComponentValues, handedness: Constants.Handedness} )=>unknown; const GeneralType = Object.freeze({ TRIGGER: 'trigger', SQUEEZE: 'squeeze', TOUCHPAD: 'touchpad', THUMBSTICK: 'thumbstick', BUTTON_1: 'button_1', BUTTON_2: 'button_2', BUTTON_3: 'button_3', BUTTON_SPECIAL: 'button_special' }); type ComponentFunctionMap = { 'trigger': ComponentChangeCallback; 'squeeze': ComponentChangeCallback; 'touchpad': ComponentChangeCallback; 'thumbstick': ComponentChangeCallback; 'button_1': ComponentChangeCallback; 'button_2': ComponentChangeCallback; 'button_3': ComponentChangeCallback; 'buttonSpecial': ComponentChangeCallback; } type WebXRSystemViewerData = { viewerTranslate: IMutableVector3, viewerScale: MutableVector3, viewerOrientation: IMutableQuaternion, viewerAzimuthAngle: MutableScalar, } const wellKnownMapping = new Map(); wellKnownMapping.set('a_button', GeneralType.BUTTON_1); wellKnownMapping.set('b_button', GeneralType.BUTTON_2); wellKnownMapping.set('x_button', GeneralType.BUTTON_1); wellKnownMapping.set('y_button', GeneralType.BUTTON_2); wellKnownMapping.set('thumbrest', GeneralType.BUTTON_3); wellKnownMapping.set('menu', GeneralType.BUTTON_SPECIAL); wellKnownMapping.set('xr_standard_trigger', GeneralType.TRIGGER); wellKnownMapping.set('xr_standard_squeeze', GeneralType.SQUEEZE); wellKnownMapping.set('xr_standard_thumbstick', GeneralType.THUMBSTICK); wellKnownMapping.set('xr_standard_touchpad', GeneralType.TOUCHPAD); wellKnownMapping.set('trigger', GeneralType.TRIGGER); wellKnownMapping.set('squeeze', GeneralType.SQUEEZE); wellKnownMapping.set('thumbstick', GeneralType.THUMBSTICK); wellKnownMapping.set('touchpad', GeneralType.TOUCHPAD); export async function createMotionController(xrInputSource: XRInputSource, basePath: string, profilePriorities: string[]) { const { profile, assetPath } = await fetchProfile(xrInputSource, basePath, undefined, true, profilePriorities); const motionController = new MotionController(xrInputSource, profile, assetPath!); motionControllers.set(xrInputSource, motionController); const asset = await addMotionControllerToScene(motionController); const modelConverter = ModelConverter.getInstance(); if (Is.exist(asset)) { const rootGroup = modelConverter.convertToRhodoniteObject(asset); return rootGroup; } else { return undefined; } } async function addMotionControllerToScene(motionController: MotionController) { const importer = Gltf2Importer.getInstance(); const asset = await importer.import(motionController.assetUrl); addTouchPointDots(motionController, asset); // MyEngine.scene.add(asset); return asset; } export function updateGamePad(timestamp: number, xrFrame: XRFrame, viewerData: WebXRSystemViewerData) { // Other frame-loop stuff ... Array.from(motionControllers.values()).forEach((motionController: MotionController) => { motionController.updateFromGamepad(); Object.keys(motionController.components).forEach((componentId: string) =>{ const component = motionController.components[componentId]; processInput(component, (motionController.xrInputSource as XRInputSource).handedness, viewerData, timestamp); }) }); // Other frame-loop stuff ... } let lastTimestamp = 0; function processInput(component: Component, handed: string, viewerData: WebXRSystemViewerData, timestamp: number) { const componentName = wellKnownMapping.get(component.rootNodeName); if (Is.not.exist(componentName)) { return; } if (lastTimestamp === 0) { lastTimestamp = timestamp; return; } const deltaSec = (timestamp - lastTimestamp) * 0.000001; switch(componentName) { case GeneralType.TRIGGER: processTriggerInput(component, handed, viewerData, deltaSec); break; case GeneralType.THUMBSTICK: processThumbstickInput(component, handed, viewerData, deltaSec); break; case GeneralType.SQUEEZE: processSqueezeInput(component, handed, viewerData, deltaSec); break; case GeneralType.BUTTON_1: case GeneralType.BUTTON_2: case GeneralType.BUTTON_3: case GeneralType.BUTTON_SPECIAL: processButtonInput(component, handed, viewerData, deltaSec); break; case GeneralType.TOUCHPAD: processTouchpadInput(component, handed, viewerData, deltaSec); break; default: } } const scaleVec3 = MutableVector3.one(); function processTriggerInput(triggerComponent: Component, handed: string, viewerData: WebXRSystemViewerData, deltaSec: number) { let value = 0; const scale = 0.1; const componentName = wellKnownMapping.get(triggerComponent.rootNodeName); if (triggerComponent.values.state === Constants.ComponentState.PRESSED) { console.log(componentName, triggerComponent.values.button, handed); value = defaultValue(0, triggerComponent.values.button) * deltaSec; // Fire ray gun } else if (triggerComponent.values.state === Constants.ComponentState.TOUCHED) { const chargeLevel = triggerComponent.values.button; console.log(componentName, triggerComponent.values.button, handed); value = defaultValue(0, triggerComponent.values.button) * deltaSec; // Show ray gun charging up } if (handed === 'right') { value *= -1; } scaleVec3.x -= value * scale; scaleVec3.y -= value * scale; scaleVec3.z -= value * scale; scaleVec3.x = Math.max(scaleVec3.x, 0.05); scaleVec3.y = Math.max(scaleVec3.y, 0.05); scaleVec3.z = Math.max(scaleVec3.z, 0.05); scaleVec3.x = Math.min(scaleVec3.x, 3.00); scaleVec3.y = Math.min(scaleVec3.y, 3.00); scaleVec3.z = Math.min(scaleVec3.z, 3.00); viewerData.viewerScale.copyComponents(scaleVec3); } function processSqueezeInput(squeezeComponent: Component, handed: string, viewerData: WebXRSystemViewerData, deltaSec: number) { const componentName = wellKnownMapping.get(squeezeComponent.rootNodeName); if (squeezeComponent.values.state === Constants.ComponentState.PRESSED) { console.log(componentName, squeezeComponent.values.button, handed); // Fire ray gun } else if (squeezeComponent.values.state === Constants.ComponentState.TOUCHED) { const chargeLevel = squeezeComponent.values.button; console.log(componentName, squeezeComponent.values.button, handed); // Show ray gun charging up } } function processThumbstickInput(thumbstickComponent: Component, handed: string, viewerData: WebXRSystemViewerData, deltaSec: number) { const componentName = wellKnownMapping.get(thumbstickComponent.rootNodeName); let xAxis = 0; let yAxis = 0; const deltaScaleHorizontal = 0.25; const deltaScaleVertical= 0.10; const deltaScaleAzimuthAngle = 0.15; if (thumbstickComponent.values.state === Constants.ComponentState.PRESSED) { console.log(componentName, thumbstickComponent.values.button, thumbstickComponent.values.state, handed); xAxis = defaultValue(0, thumbstickComponent.values.xAxis) * deltaSec; yAxis = defaultValue(0, thumbstickComponent.values.yAxis) * deltaSec; // Align the world orientation to the user's current orientation } else if (thumbstickComponent.values.state === Constants.ComponentState.TOUCHED) { xAxis = defaultValue(0, thumbstickComponent.values.xAxis) * deltaSec; yAxis = defaultValue(0, thumbstickComponent.values.yAxis) * deltaSec; } xAxis = Math.min(xAxis, 1); yAxis = Math.min(yAxis, 1); const deltaVector = MutableVector3.zero(); if (handed === 'right') { viewerData.viewerAzimuthAngle.x -= xAxis * deltaScaleAzimuthAngle; deltaVector.y -= yAxis * deltaScaleVertical * viewerData.viewerScale.x; } else { deltaVector.x += xAxis * deltaScaleHorizontal * viewerData.viewerScale.x; deltaVector.z += yAxis * deltaScaleHorizontal * viewerData.viewerScale.x; } const orientationMat = new MutableMatrix33(viewerData.viewerOrientation); const rotateMat = orientationMat.multiply(MutableMatrix33.rotateY(viewerData.viewerAzimuthAngle.x)); rotateMat.multiplyVectorTo(deltaVector, deltaVector as MutableVector3); viewerData.viewerTranslate.add(deltaVector); } function processButtonInput(buttonComponent: Component, handed: string, viewerData: WebXRSystemViewerData, deltaSec: number) { const componentName = wellKnownMapping.get(buttonComponent.rootNodeName); if (buttonComponent.values.state === Constants.ComponentState.PRESSED) { console.log(componentName, buttonComponent.values.button, buttonComponent.values.state, handed); } else if (buttonComponent.values.state === Constants.ComponentState.TOUCHED) { console.log(componentName, buttonComponent.values.button, buttonComponent.values.state, handed); } } function processTouchpadInput(thumbstick: Component, handed: string, viewerData: WebXRSystemViewerData, deltaSec: number) { if (thumbstick.values.state === Constants.ComponentState.PRESSED) { // Align the world orientation to the user's current orientation } else if (thumbstick.values.state === Constants.ComponentState.TOUCHED && thumbstick.values.yAxis !== 0) { const scootDistance = thumbstick.values.yAxis;//* scootIncrement; // Scoot the user forward } } function addTouchPointDots(motionController: MotionController, asset: any) { Object.values(motionController.components).forEach((component) => { if (component.touchPointNodeName) { const touchPointRoot = asset.getChildByName(component.touchPointNodeName, true); // const sphereGeometry = new THREE.SphereGeometry(0.001); // const material = new THREE.MeshBasicMaterial({ color: 0x0000FF }); // const touchPointDot = new THREE.Mesh(sphereGeometry, material); // touchPointRoot.add(touchPointDot); } }); } export function updateMotionControllerModel(entity: Entity, motionController: MotionController) { // this codes are from https://immersive-web.github.io/webxr-input-profiles/packages/motion-controllers/#animating-components // Update the 3D model to reflect the button, thumbstick, and touchpad state const map = entity.getTagValue('rnEntitiesByNames'); Object.values(motionController.components).forEach((component: Component) => { for (const visualResponseName in component.visualResponses) { const visualResponse = component.visualResponses[visualResponseName]; // Find the topmost node in the visualization const entity = map.get(visualResponse.valueNodeName); if (Is.not.exist(entity)) { console.warn(`The entity of the controller doesn't exist`) continue; } // Calculate the new properties based on the weight supplied if (visualResponse.valueNodeProperty === 'visibility') { entity.getSceneGraph().isVisible = !!visualResponse.value; } else if (visualResponse.valueNodeProperty === 'transform') { const minNode = map.get(visualResponse.minNodeName!); const maxNode = map.get(visualResponse.maxNodeName!); if (Is.not.exist(minNode) || Is.not.exist(maxNode)) { console.warn(`The min/max Node of the component of the controller doesn't exist`) continue; } const minNodeTransform = minNode.getTransform(); const maxNodeTransform = maxNode.getTransform(); entity.getTransform().quaternion = Quaternion.qlerp( minNodeTransform.quaternionInner, maxNodeTransform.quaternionInner, visualResponse.value as number, ); entity.getTransform().translate = Vector3.lerp( maxNodeTransform.translateInner, minNodeTransform.translateInner, visualResponse.value as number ); } } }); } export function getMotionController(xrInputSource: XRInputSource) { return motionControllers.get(xrInputSource) }
the_stack
import {ipcRenderer} from 'electron'; import {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react'; import {Button, Row, Tabs, Tooltip} from 'antd'; import {ArrowLeftOutlined, ArrowRightOutlined, BookOutlined, CodeOutlined, ContainerOutlined} from '@ant-design/icons'; import { ACTIONS_PANE_FOOTER_HEIGHT, ACTIONS_PANE_TAB_PANE_OFFSET, NAVIGATOR_HEIGHT_OFFSET, TOOLTIP_DELAY, } from '@constants/constants'; import {makeApplyKustomizationText, makeApplyResourceText} from '@constants/makeApplyText'; import { ApplyFileTooltip, ApplyTooltip, DiffTooltip, OpenExternalDocumentationTooltip, SaveUnsavedResourceTooltip, } from '@constants/tooltips'; import {AlertEnum, AlertType} from '@models/alert'; import {K8sResource} from '@models/k8sresource'; import {useAppDispatch, useAppSelector} from '@redux/hooks'; import {setAlert} from '@redux/reducers/alert'; import {openResourceDiffModal} from '@redux/reducers/main'; import {openSaveResourcesToFileFolderModal, setMonacoEditor} from '@redux/reducers/ui'; import { isInPreviewModeSelector, kubeConfigContextSelector, kubeConfigPathSelector, settingsSelector, } from '@redux/selectors'; import {applyFileWithConfirm} from '@redux/services/applyFileWithConfirm'; import {isKustomizationPatch, isKustomizationResource} from '@redux/services/kustomize'; import {isUnsavedResource} from '@redux/services/resource'; import {applyHelmChart} from '@redux/thunks/applyHelmChart'; import {applyResource} from '@redux/thunks/applyResource'; import {selectFromHistory} from '@redux/thunks/selectionHistory'; import FormEditor from '@molecules/FormEditor'; import Monaco from '@molecules/Monaco'; import {MonoPaneTitle, MonoPaneTitleCol} from '@atoms'; import TabHeader from '@atoms/TabHeader'; import Icon from '@components/atoms/Icon'; import HelmChartModalConfirmWithNamespaceSelect from '@components/molecules/HelmChartModalConfirmWithNamespaceSelect'; import ModalConfirmWithNamespaceSelect from '@components/molecules/ModalConfirmWithNamespaceSelect'; import {openExternalResourceKindDocumentation} from '@utils/shell'; import AppContext from '@src/AppContext'; import featureFlags from '@src/feature-flags.json'; import {getResourceKindHandler} from '@src/kindhandlers'; import {getFormSchema, getUiSchema} from '@src/kindhandlers/common/formLoader'; import * as S from './ActionsPane.styled'; import ActionsPaneFooter from './ActionsPaneFooter'; const {TabPane} = Tabs; const ActionsPane = (props: {contentHeight: string}) => { const {contentHeight} = props; const {windowSize} = useContext(AppContext); const windowHeight = windowSize.height; const selectedResourceId = useAppSelector(state => state.main.selectedResourceId); const selectedValuesFileId = useAppSelector(state => state.main.selectedValuesFileId); const helmValuesMap = useAppSelector(state => state.main.helmValuesMap); const helmChartMap = useAppSelector(state => state.main.helmChartMap); const applyingResource = useAppSelector(state => state.main.isApplyingResource); const resourceMap = useAppSelector(state => state.main.resourceMap); const selectedPath = useAppSelector(state => state.main.selectedPath); const fileMap = useAppSelector(state => state.main.fileMap); const previewLoader = useAppSelector(state => state.main.previewLoader); const uiState = useAppSelector(state => state.ui); const currentSelectionHistoryIndex = useAppSelector(state => state.main.currentSelectionHistoryIndex); const selectionHistory = useAppSelector(state => state.main.selectionHistory); const previewType = useAppSelector(state => state.main.previewType); const monacoEditor = useAppSelector(state => state.ui.monacoEditor); const isClusterDiffVisible = useAppSelector(state => state.ui.isClusterDiffVisible); const isActionsPaneFooterExpanded = useAppSelector(state => state.ui.isActionsPaneFooterExpanded); const isInPreviewMode = useAppSelector(isInPreviewModeSelector); const kubeConfigContext = useAppSelector(kubeConfigContextSelector); const kubeConfigPath = useAppSelector(kubeConfigPathSelector); const {kustomizeCommand} = useAppSelector(settingsSelector); const navigatorHeight = useMemo( () => windowHeight - NAVIGATOR_HEIGHT_OFFSET - (isInPreviewMode ? 25 : 0), [windowHeight, isInPreviewMode] ); const [activeTabKey, setActiveTabKey] = useState('source'); const [isApplyModalVisible, setIsApplyModalVisible] = useState(false); const [isButtonShrinked, setButtonShrinkedState] = useState<boolean>(true); const [isHelmChartApplyModalVisible, setIsHelmChartApplyModalVisible] = useState(false); const [selectedResource, setSelectedResource] = useState<K8sResource>(); const dispatch = useAppDispatch(); // Could not get the ref of Tabs Component const tabsList = document.getElementsByClassName('ant-tabs-nav-list'); const extraButton = useRef<any>(); const getDistanceBetweenTwoComponents = useCallback(() => { const tabsListEl = tabsList[0].getBoundingClientRect(); const extraButtonEl = extraButton.current.getBoundingClientRect(); const distance = extraButtonEl.left - tabsListEl.right; if (isButtonShrinked) { // 230px = approx width of not collapsed button if (distance > 350) { setButtonShrinkedState(false); } } // The button has 10px margin-left if (!isButtonShrinked && distance < 40) { setButtonShrinkedState(true); } }, [isButtonShrinked, tabsList]); const editorTabPaneHeight = useMemo(() => { let defaultHeight = parseInt(contentHeight, 10) - ACTIONS_PANE_TAB_PANE_OFFSET; if (!featureFlags.ActionsPaneFooter) { defaultHeight += 20; } if (isActionsPaneFooterExpanded) { return defaultHeight - ACTIONS_PANE_FOOTER_HEIGHT; } return defaultHeight; }, [contentHeight, isActionsPaneFooterExpanded]); const onSaveHandler = () => { if (selectedResource) { dispatch(openSaveResourcesToFileFolderModal([selectedResource.id])); } }; const resourceKindHandler = selectedResource && getResourceKindHandler(selectedResource.kind); const isLeftArrowEnabled = selectionHistory.length > 1 && (currentSelectionHistoryIndex === undefined || (currentSelectionHistoryIndex && currentSelectionHistoryIndex > 0)); const isRightArrowEnabled = selectionHistory.length > 1 && currentSelectionHistoryIndex !== undefined && currentSelectionHistoryIndex < selectionHistory.length - 1; const onClickLeftArrow = () => { selectFromHistory('left', currentSelectionHistoryIndex, selectionHistory, resourceMap, fileMap, dispatch); }; const onClickRightArrow = () => { selectFromHistory('right', currentSelectionHistoryIndex, selectionHistory, resourceMap, fileMap, dispatch); }; const applySelection = useCallback(() => { if (selectedValuesFileId && (!selectedResourceId || selectedValuesFileId === selectedResourceId)) { const helmValuesFile = helmValuesMap[selectedValuesFileId]; if (helmValuesFile) { setIsHelmChartApplyModalVisible(true); } } else if (selectedResource) { setIsApplyModalVisible(true); } else if (selectedPath) { applyFileWithConfirm(selectedPath, fileMap, dispatch, kubeConfigPath, kubeConfigContext); } }, [ selectedResource, fileMap, kubeConfigPath, selectedPath, dispatch, helmValuesMap, selectedValuesFileId, kubeConfigContext, selectedResourceId, ]); useEffect(() => { if (monacoEditor.apply) { applySelection(); dispatch(setMonacoEditor({apply: false})); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [monacoEditor]); const diffSelectedResource = useCallback(() => { if (!kubeConfigContext || kubeConfigContext === '') { const alert: AlertType = { type: AlertEnum.Error, title: 'Diff not available', message: 'No Cluster Configured', }; dispatch(setAlert(alert)); return; } if (selectedResourceId) { dispatch(openResourceDiffModal(selectedResourceId)); } }, [dispatch, selectedResourceId, kubeConfigContext]); const onPerformResourceDiff = useCallback( (_: any, resourceId: string) => { if (resourceId) { dispatch(openResourceDiffModal(resourceId)); } }, [dispatch] ); const isDiffButtonDisabled = useMemo(() => { if (!selectedResource) { return true; } if (isKustomizationPatch(selectedResource) || isKustomizationResource(selectedResource)) { return true; } return false; }, [selectedResource]); const onClickApplyResource = useCallback( (namespace?: string) => { if (!selectedResource) { setIsApplyModalVisible(false); return; } const isClusterPreview = previewType === 'cluster'; applyResource(selectedResource.id, resourceMap, fileMap, dispatch, kubeConfigPath, kubeConfigContext, namespace, { isClusterPreview, kustomizeCommand, }); setIsApplyModalVisible(false); }, [dispatch, fileMap, kubeConfigContext, kubeConfigPath, kustomizeCommand, previewType, resourceMap, selectedResource] ); const onClickApplyHelmChart = useCallback( (namespace?: string, shouldCreateNamespace?: boolean) => { if (!selectedValuesFileId) { setIsHelmChartApplyModalVisible(false); return; } const helmValuesFile = helmValuesMap[selectedValuesFileId]; applyHelmChart( helmValuesFile, helmChartMap[helmValuesFile.helmChartId], fileMap, dispatch, kubeConfigPath, kubeConfigContext, namespace, shouldCreateNamespace ); setIsHelmChartApplyModalVisible(false); }, [dispatch, fileMap, helmChartMap, helmValuesMap, kubeConfigPath, kubeConfigContext, selectedValuesFileId] ); const confirmModalTitle = useMemo(() => { if (!selectedResource) { return ''; } return isKustomizationResource(selectedResource) ? makeApplyKustomizationText(selectedResource.name, kubeConfigContext) : makeApplyResourceText(selectedResource.name, kubeConfigContext); }, [selectedResource, kubeConfigContext]); const helmChartConfirmModalTitle = useMemo(() => { if (!selectedValuesFileId) { return ''; } const helmValuesFile = helmValuesMap[selectedValuesFileId]; return `Install the ${helmChartMap[helmValuesFile.helmChartId].name} Chart using ${ helmValuesFile.name } in cluster [${kubeConfigContext}]?`; }, [helmChartMap, helmValuesMap, kubeConfigContext, selectedValuesFileId]); // called from main thread because thunks cannot be dispatched by main useEffect(() => { ipcRenderer.on('perform-resource-diff', onPerformResourceDiff); return () => { ipcRenderer.removeListener('perform-resource-diff', onPerformResourceDiff); }; }, [onPerformResourceDiff]); useEffect(() => { if (selectedResourceId && resourceMap[selectedResourceId]) { setSelectedResource(resourceMap[selectedResourceId]); } else { setSelectedResource(undefined); } }, [selectedResourceId, resourceMap]); useEffect(() => { if ( (activeTabKey === 'metadataForm' || activeTabKey === 'form') && (!selectedResourceId || !(resourceKindHandler && resourceKindHandler.formEditorOptions)) ) { setActiveTabKey('source'); } }, [selectedResourceId, selectedResource, activeTabKey, resourceKindHandler]); const isSelectedResourceUnsaved = useCallback(() => { if (!selectedResource) { return false; } return isUnsavedResource(selectedResource); }, [selectedResource]); useEffect(() => { if (tabsList && tabsList.length && extraButton.current) { getDistanceBetweenTwoComponents(); } }, [tabsList, uiState.paneConfiguration, windowSize, selectedResource, getDistanceBetweenTwoComponents]); return ( <> <Row> <MonoPaneTitleCol> <MonoPaneTitle> <S.TitleBarContainer> <span>Editor</span> <S.RightButtons> <S.LeftArrowButton onClick={onClickLeftArrow} disabled={!isLeftArrowEnabled} type="link" size="small" icon={<ArrowLeftOutlined />} /> <S.RightArrowButton onClick={onClickRightArrow} disabled={!isRightArrowEnabled} type="link" size="small" icon={<ArrowRightOutlined />} /> {isSelectedResourceUnsaved() && ( <Tooltip mouseEnterDelay={TOOLTIP_DELAY} title={SaveUnsavedResourceTooltip}> <S.SaveButton type="primary" size="small" onClick={onSaveHandler}> Save </S.SaveButton> </Tooltip> )} <Tooltip mouseEnterDelay={TOOLTIP_DELAY} title={selectedPath ? ApplyFileTooltip : ApplyTooltip} placement="bottomLeft" > <Button loading={Boolean(applyingResource)} type="primary" size="small" ghost onClick={applySelection} disabled={ (!selectedResourceId && !selectedPath) || (selectedResource && isKustomizationPatch(selectedResource)) } icon={<Icon name="kubernetes" />} > Deploy </Button> </Tooltip> <Tooltip mouseEnterDelay={TOOLTIP_DELAY} title={DiffTooltip} placement="bottomLeft"> <S.DiffButton size="small" type="primary" ghost onClick={diffSelectedResource} disabled={isDiffButtonDisabled} > Diff </S.DiffButton> </Tooltip> </S.RightButtons> </S.TitleBarContainer> </MonoPaneTitle> </MonoPaneTitleCol> </Row> <S.ActionsPaneContainer $height={navigatorHeight}> <S.TabsContainer> <S.Tabs defaultActiveKey="source" activeKey={activeTabKey} onChange={k => setActiveTabKey(k)} tabBarExtraContent={ selectedResource && resourceKindHandler?.helpLink ? ( <Tooltip mouseEnterDelay={TOOLTIP_DELAY} title={OpenExternalDocumentationTooltip}> <S.ExtraRightButton onClick={() => openExternalResourceKindDocumentation(resourceKindHandler?.helpLink)} type="link" ref={extraButton} > {isButtonShrinked ? '' : `See ${selectedResource?.kind} documentation`} <BookOutlined /> </S.ExtraRightButton> </Tooltip> ) : null } > <TabPane key="source" style={{height: editorTabPaneHeight}} tab={<TabHeader icon={<CodeOutlined />}>Source</TabHeader>} > {uiState.isFolderLoading || previewLoader.isLoading ? ( <S.Skeleton active /> ) : ( !isClusterDiffVisible && (selectedResourceId || selectedPath || selectedValuesFileId) && ( <Monaco applySelection={applySelection} diffSelectedResource={diffSelectedResource} /> ) )} </TabPane> {selectedResource && resourceKindHandler?.formEditorOptions?.editorSchema && ( <TabPane disabled={!selectedResourceId} key="form" style={{height: editorTabPaneHeight}} tab={<TabHeader icon={<ContainerOutlined />}>{selectedResource.kind}</TabHeader>} > {uiState.isFolderLoading || previewLoader.isLoading ? ( <S.Skeleton active /> ) : ( <FormEditor formSchema={resourceKindHandler.formEditorOptions.editorSchema} formUiSchema={resourceKindHandler.formEditorOptions.editorUiSchema} /> )} </TabPane> )} {selectedResource && resourceKindHandler && resourceKindHandler.kind !== 'Kustomization' && ( <TabPane key="metadataForm" style={{height: editorTabPaneHeight}} tab={<TabHeader icon={<ContainerOutlined />}>Metadata</TabHeader>} > {uiState.isFolderLoading || previewLoader.isLoading ? ( <S.Skeleton active /> ) : ( <FormEditor formSchema={getFormSchema('metadata')} formUiSchema={getUiSchema('metadata')} /> )} </TabPane> )} </S.Tabs> </S.TabsContainer> {featureFlags.ActionsPaneFooter && <ActionsPaneFooter />} </S.ActionsPaneContainer> {isApplyModalVisible && ( <ModalConfirmWithNamespaceSelect isVisible={isApplyModalVisible} resources={selectedResource ? [selectedResource] : []} title={confirmModalTitle} onOk={selectedNamespace => onClickApplyResource(selectedNamespace)} onCancel={() => setIsApplyModalVisible(false)} /> )} {isHelmChartApplyModalVisible && ( <HelmChartModalConfirmWithNamespaceSelect isVisible={isHelmChartApplyModalVisible} title={helmChartConfirmModalTitle} onCancel={() => setIsHelmChartApplyModalVisible(false)} onOk={(selectedNamespace, shouldCreateNamespace) => onClickApplyHelmChart(selectedNamespace, shouldCreateNamespace) } /> )} </> ); }; export default ActionsPane;
the_stack
jest.dontMock('axios'); import axios from 'axios'; import { spawn } from 'child_process'; import { Server } from '@hapi/hapi'; import * as http from 'http'; import * as path from 'path'; import { createServer } from './sampleServer'; import * as unexpected from 'unexpected'; import * as url from 'url'; import { promises as fs } from 'fs'; const expect = unexpected.clone(); /** Localhost port numbers for each config */ const configPorts: { [config: string]: number } = { main: 5199, 'temp.gen': 5199 }; let baseUrl = 'http://localhost'; interface ResponseInfo { rawResponse: Buffer; text: string; data?: any; headers: { [name: string]: string | string[] }; statusCode: number; statusMessage?: string; } expect.addAssertion('<string> to provide response <object>', function( expect, path, expected ) { return expect({ method: 'GET', path }, 'to provide response', expected); }); expect.addAssertion('<object> to provide response <object>', function( expect, request, expected ) { const parsedUrl = url.parse(baseUrl + request.path); return expect .promise((resolve, reject) => { const req = http.request( { method: request.method || 'GET', hostname: parsedUrl.hostname, port: parsedUrl.port || 80, path: parsedUrl.path, headers: request.headers }, (res) => { const chunks: Buffer[] = []; res.on('data', (chunk) => { if (typeof chunk === 'string') { chunks.push(Buffer.from(chunk, 'utf-8')); } else { chunks.push(chunk); } }); res.on('error', (e) => { reject(e); }); res.on('end', () => { const rawResponse = Buffer.concat(chunks); // Assuming UTF-8 for everything - we're not supporting everything here const text = rawResponse.toString('utf-8'); // Ignore undefined headers const headers: { [name: string]: string | string[]; } = res.headers as any; const isJson = headers['content-type'] && typeof headers['content-type'] === 'string' && (headers['content-type'] as string).split(';')[0] === 'application/json'; let data = undefined; if (isJson) { try { data = JSON.parse(text); } catch {} } const responseInfo: ResponseInfo = { rawResponse, text, data, headers, statusCode: res.statusCode || 0, statusMessage: res.statusMessage || '' }; resolve(responseInfo); }); } ); req.end(); }) .then((responseInfo) => { expect(responseInfo, 'to satisfy', expected); }); }); function getConfigPath(configName) { if (path.isAbsolute(configName)) { return configName; } return path.join(__dirname, 'configs', configName + '.ts'); } function poll(localPort: number) { return axios.get('http://localhost:' + localPort + '/-/health'); } function startProxy( configName: string, ...args: string[] ): Promise<{ shutdownProxy: () => Promise<void>; waitForUpdate: () => Promise<void>; }> { const proxyProcess = spawn( process.argv[0], ['dist/src/cli.js', 'start', getConfigPath(configName), ...args], { cwd: process.cwd() } ); const debugProxy = !!process.env.DEBUG_PROXY; let updateComplete: (() => void) | null = null; function waitForUpdate() { const wait = new Promise<void>((resolve, resject) => { updateComplete = () => { updateComplete = null; resolve(); }; }); return wait; } proxyProcess.stdout.on('data', (chunk) => { if (debugProxy) { console.log('[PROXY:stdout]', chunk.toString()); } if (updateComplete && /Server config updated/.test(chunk.toString())) { updateComplete(); } }); proxyProcess.stderr.on('data', (chunk) => { if (debugProxy) { console.log('[PROXY:stderr]', chunk.toString()); } }); baseUrl = `http://localhost:${configPorts[configName]}`; const shutdownProxy: () => Promise<void> = () => new Promise((resolve, reject) => { proxyProcess.on('close', () => { // Wait 1s for the process to properly tidy itself up after finishing // This shouldn't be necessary, but it seems that we get the 'close' event before everything is properly cleaned up setTimeout(resolve, 1000); }); proxyProcess.kill('SIGINT'); }); return new Promise((resolve, reject) => { function checkIfStarted() { poll(configPorts[configName]) .then(() => resolve({ shutdownProxy, waitForUpdate })) .catch(() => { setTimeout(checkIfStarted, 100); }); } checkIfStarted(); }); } describe('intervene proxy', () => { let server: Server; beforeAll(() => { server = createServer(); return server.start(); }); afterAll(() => server.stop()); describe('with simple config', () => { let killProxy; beforeAll(() => { axios.defaults.baseURL = 'http://localhost:5199'; return startProxy('main').then( ({ shutdownProxy }) => (killProxy = shutdownProxy) ); }); afterAll(() => killProxy()); it('proxies a simple json call', async () => { return expect('/json', 'to provide response', { data: { static: 'json' } }); }); it('returns with a static response direct from proxy', async () => { return expect('/proxy/static', 'to provide response', { statusCode: 200, data: { fixed: true, jsonResponse: true }, headers: { 'content-type': 'application/json; charset=utf-8' } }); }); it('returns with a static text response direct from proxy', async () => { return expect('/fixedresponse', 'to provide response', { statusCode: 200, text: 'plain text response', headers: { 'content-type': 'text/html; charset=utf-8' } }); }); it('proxies a JSON string response', async () => { return expect('/jsonstring', 'to provide response', { statusCode: 200, text: '"OK"', headers: { 'content-type': 'application/json; charset=utf-8' } }); }); it('modifies a JSON string response', async () => { return expect('/change/jsonstring', 'to provide response', { statusCode: 200, text: '"changed"', data: 'changed', headers: { 'content-type': 'application/json; charset=utf-8' } }); }); it('allows adding a request header', async () => { return expect('/add/requestheader', 'to provide response', { statusCode: 200, data: { testHeader: 'added' } }); }); it('allows patching the URL before proxying', async () => { return expect('/mapped/url', 'to provide response', { data: { location: 'new' } }); }); it('allows patching the querystring before proxying', async () => { return expect('/mapped/query?foo=bar', 'to provide response', { data: { query: { foo: 'changed' } } }); }); it('allows adding an extra response header', async () => { return expect('/add/responseheader', 'to provide response', { headers: { 'x-added-test': 'response-header' } }); }); it('replies for OPTIONS requests', async () => { return expect( { method: 'OPTIONS', path: '/json', headers: { origin: 'http://example.com', 'access-control-request-method': 'POST' } }, 'to provide response', { headers: { 'access-control-allow-headers': 'Accept,Authorization,Content-Type,If-None-Match', 'access-control-allow-methods': 'POST', 'access-control-allow-origin': 'http://example.com', 'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization', 'access-control-allow-credentials': 'true', 'access-control-max-age': '60' } } ); }); it('replies with the passed origin for OPTIONS requests', async () => { return expect( { method: 'OPTIONS', path: '/json', headers: { origin: 'http://foo.invalid:5000', 'access-control-request-method': 'POST' } }, 'to provide response', { headers: { 'access-control-allow-origin': 'http://foo.invalid:5000', 'access-control-allow-credentials': 'true' } } ); }); it('replies for OPTIONS for static intercepted responses', async () => { return expect( { method: 'OPTIONS', path: '/proxy/static', headers: { origin: 'http://example.com', 'access-control-request-method': 'POST' } }, 'to provide response', { headers: { 'access-control-allow-headers': 'Accept,Authorization,Content-Type,If-None-Match', 'access-control-allow-methods': 'POST', 'access-control-allow-origin': 'http://example.com', 'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization', 'access-control-allow-credentials': 'true', 'access-control-max-age': '60' } } ); }); }); describe('updating configs', () => { it('reloads the config after an update', () => { const tmpPath = path.join(__dirname, 'configs', 'temp.gen.ts'); let shutdownProxy: () => Promise<void>; let waitForUpdate: () => Promise<void>; return fs .copyFile(path.join(__dirname, 'configs', 'simple1.ts'), tmpPath) .then(() => startProxy('temp.gen')) .then((result) => { shutdownProxy = result.shutdownProxy; waitForUpdate = result.waitForUpdate; return expect('/foo', 'to provide response', { data: { bar: true } }); }) .then(() => { return expect('/bar', 'to provide response', { statusCode: 404 }); }) .then(() => fs.copyFile(path.join(__dirname, 'configs', 'simple2.ts'), tmpPath) ) .then(() => { return waitForUpdate(); }) .then(() => { return expect('/foo', 'to provide response', { data: { newConfig: true } }); }) .then(() => { return expect('/bar', 'to provide response', { statusCode: 200, data: { newRoute: true } }); }) .then( () => shutdownProxy(), (e) => { return shutdownProxy().then(() => { throw e; }); } ); }); it('reloads the config after multiple updates', () => { const tmpPath = path.join(__dirname, 'configs', 'temp.gen.ts'); let shutdownProxy: () => Promise<void>; let waitForUpdate: () => Promise<void>; return fs .copyFile(path.join(__dirname, 'configs', 'simple1.ts'), tmpPath) .then(() => startProxy('temp.gen')) .then((result) => { shutdownProxy = result.shutdownProxy; waitForUpdate = result.waitForUpdate; return expect('/foo', 'to provide response', { data: { bar: true } }); }) .then(() => { return expect('/bar', 'to provide response', { statusCode: 404 }); }) .then(() => { return fs.copyFile( path.join(__dirname, 'configs', 'simple2.ts'), tmpPath ); }) .then(() => { return waitForUpdate(); }) .then(() => { return expect('/foo', 'to provide response', { data: { newConfig: true } }); }) .then(() => { return expect('/bar', 'to provide response', { statusCode: 200, data: { newRoute: true } }); }) .then(() => { // Go back to initial config return fs.copyFile( path.join(__dirname, 'configs', 'simple1.ts'), tmpPath ); }) .then(() => { return waitForUpdate(); }) .then(() => { return expect('/foo', 'to provide response', { data: { bar: true } }); }) .then( () => shutdownProxy(), (e) => { return shutdownProxy().then(() => { throw e; }); } ); }); }); });
the_stack
import { Trans } from "@lingui/macro"; import PropTypes from "prop-types"; import * as React from "react"; import { Tooltip } from "reactjs-components"; import mixin from "reactjs-mixin"; import { findNestedPropertyInObject, isObject } from "#SRC/js/utils/Util"; import { SET } from "#SRC/js/constants/TransactionTypes"; import AddButton from "#SRC/js/components/form/AddButton"; import FieldAutofocus from "#SRC/js/components/form/FieldAutofocus"; import FieldError from "#SRC/js/components/form/FieldError"; import FieldHelp from "#SRC/js/components/form/FieldHelp"; import FieldInput from "#SRC/js/components/form/FieldInput"; import FieldLabel from "#SRC/js/components/form/FieldLabel"; import FieldSelect from "#SRC/js/components/form/FieldSelect"; import FormGroup from "#SRC/js/components/form/FormGroup"; import FormGroupContainer from "#SRC/js/components/form/FormGroupContainer"; import FormGroupHeading from "#SRC/js/components/form/FormGroupHeading"; import FormGroupHeadingContent from "#SRC/js/components/form/FormGroupHeadingContent"; import FormRow from "#SRC/js/components/form/FormRow"; import InfoTooltipIcon from "#SRC/js/components/form/InfoTooltipIcon"; import MetadataStore from "#SRC/js/stores/MetadataStore"; import Networking from "#SRC/js/constants/Networking"; import StoreMixin from "#SRC/js/mixins/StoreMixin"; import * as ValidatorUtil from "#SRC/js/utils/ValidatorUtil"; import VirtualNetworksStore from "#SRC/js/stores/VirtualNetworksStore"; import SingleContainerPortDefinitions from "../../reducers/serviceForm/FormReducers/SingleContainerPortDefinitionsReducer"; import SingleContainerPortMappings from "../../reducers/serviceForm/FormReducers/SingleContainerPortMappingsReducer"; import { FormReducer as networks } from "../../reducers/serviceForm/FormReducers/Networks"; import ServiceConfigUtil from "../../utils/ServiceConfigUtil"; import VipLabelUtil from "../../utils/VipLabelUtil"; import { getHostPortPlaceholder, isHostNetwork } from "../../utils/NetworkUtil"; import { Overlay } from "#SRC/js/structs/Overlay"; import dcosVersion$ from "#SRC/js/stores/dcos-version"; import { Subscription } from "rxjs"; const { BRIDGE, HOST, CONTAINER } = Networking.type; class NetworkingFormSection extends mixin(StoreMixin) { static defaultProps = { data: {}, errors: {}, onAddItem() {}, onRemoveItem() {}, }; static propTypes = { data: PropTypes.object, errors: PropTypes.object, onAddItem: PropTypes.func, onRemoveItem: PropTypes.func, }; $dcosVersion?: Subscription; state = { hasCalicoNetworking: false }; store_listeners = [{ name: "virtualNetworks", events: ["success"] }]; componentDidMount() { super.componentDidMount?.(); this.$dcosVersion = dcosVersion$.subscribe(({ hasCalicoNetworking }) => { this.setState({ hasCalicoNetworking }); }); } componentWillUnmount() { super.componentWillUnmount?.(); this.$dcosVersion?.unsubscribe(); } onVirtualNetworksStoreSuccess = () => { this.forceUpdate(); }; getHostPortFields(portDefinition, index) { let hostPortValue = portDefinition.hostPort; const { errors, data } = this.props; const hostPortError = findNestedPropertyInObject(errors, `portDefinitions.${index}.port`) || findNestedPropertyInObject( errors, `container.portMappings.${index}.hostPort` ); const isInputDisabled = isHostNetwork(data) ? data.portsAutoAssign : portDefinition.automaticPort; let placeholder; if (isInputDisabled) { placeholder = getHostPortPlaceholder(index); hostPortValue = ""; } const tooltipContent = ( <Trans render="span"> This host port will be accessible as an environment variable called{" "} '$PORT{index}'.{" "} <a href={MetadataStore.buildDocsURI( "/deploying-services/service-ports/" )} target="_blank" > More information </a> . </Trans> ); return [ <FormGroup className="column-3" key="host-port" showError={Boolean(hostPortError)} > <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Host Port</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={tooltipContent} interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldInput disabled={isInputDisabled} placeholder={placeholder} min="0" name={`portDefinitions.${index}.hostPort`} type="number" value={hostPortValue} autoFocus={Boolean(hostPortError)} /> <FieldError>{hostPortError}</FieldError> </FormGroup>, !isHostNetwork(this.props.data) && this.getNonHostNetworkPortsAutoAssignSection(portDefinition, index), ]; } getLoadBalancedServiceAddressField(endpoint, index) { const { errors } = this.props; const { loadBalanced } = endpoint; let vipPortError = null; let loadBalancedError = findNestedPropertyInObject(errors, `portDefinitions.${index}.labels`) || findNestedPropertyInObject( errors, `container.portMappings.${index}.labels` ); if (isObject(loadBalancedError)) { vipPortError = loadBalancedError[VipLabelUtil.defaultVip(index)]; loadBalancedError = null; } const loadBalancerDocsURI = MetadataStore.buildDocsURI( "/deploying-services/service-endpoints/" ); const loadBalancerTooltipContent = ( <Trans render="span"> Load balance the service internally (layer 4), and create a service{" "} address. For external (layer 7) load balancing, create an external load{" "} balancer and attach this service.{" "} <a href={loadBalancerDocsURI} target="_blank"> More Information </a> . </Trans> ); return [ <FormRow key="lb-enable"> <FormGroup className="column-12" showError={Boolean(vipPortError || loadBalancedError)} > <FieldLabel> <FieldInput checked={loadBalanced} name={`portDefinitions.${index}.loadBalanced`} type="checkbox" /> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span"> Enable Load Balanced Service Address </Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={loadBalancerTooltipContent} interactive={true} maxWidth={300} wrapperClassName="tooltip-wrapper text-align-center" wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> </FormGroup> </FormRow>, loadBalanced && this.getLoadBalancedPortField(endpoint, index), ]; } getLoadBalancedPortField(endpoint, index) { const { errors, data: { id, portsAutoAssign }, } = this.props; const { hostPort, containerPort, vip, vipPort } = endpoint; const defaultVipPort = isHostNetwork(this.props.data) ? hostPort : containerPort; // clear placeholder when HOST network portsAutoAssign is true const placeholder = isHostNetwork(this.props.data) && portsAutoAssign ? "" : defaultVipPort; let vipPortError = null; let loadBalancedError = findNestedPropertyInObject(errors, `portDefinitions.${index}.labels`) || findNestedPropertyInObject( errors, `container.docker.portMappings.${index}.labels` ); const tooltipContent = ( <Trans render="span"> This port will be used to load balance this service address internally </Trans> ); if (isObject(loadBalancedError)) { vipPortError = loadBalancedError[VipLabelUtil.defaultVip(index)]; loadBalancedError = null; } let address = vip; let port = ""; if (!portsAutoAssign && !ValidatorUtil.isEmpty(hostPort)) { port = hostPort; } if (!ValidatorUtil.isEmpty(containerPort)) { port = containerPort; } if (!ValidatorUtil.isEmpty(vipPort)) { port = vipPort; } if (address == null) { address = `${id}:${port}`; } const vipMatch = address.match(/(.+):\d+/); if (vipMatch) { address = `${vipMatch[1]}:${port}`; } let hostName = null; if (!vipPortError) { hostName = ServiceConfigUtil.buildHostNameFromVipLabel(address, port); } const helpText = ( <FieldHelp> <Trans render="span"> Load balance this service internally at {hostName} </Trans> </FieldHelp> ); return ( <FormRow key="lb-port"> <FormGroup className="column-12"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Load Balanced Port</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={tooltipContent} interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FormRow> <FormGroup className="column-3" key="vip-port" showError={Boolean(vipPortError)} > <FieldAutofocus> <FieldInput min="1" placeholder={placeholder} name={`portDefinitions.${index}.vipPort`} type="number" value={vipPort} autoFocus={Boolean(vipPortError)} /> </FieldAutofocus> </FormGroup> </FormRow> <FormRow> <FormGroup className="column-12" showError={Boolean(vipPortError)}> <FieldError>{vipPortError}</FieldError> {!vipPortError && helpText} </FormGroup> </FormRow> </FormGroup> </FormRow> ); } getProtocolField(portDefinition, index) { const { errors } = this.props; const protocolError = findNestedPropertyInObject(errors, `portDefinitions.${index}.protocol`) || findNestedPropertyInObject( errors, `container.portMappings.${index}.protocol` ); const assignHelpText = ( <Trans render="span"> Most services will use TCP.{" "} <a href={MetadataStore.buildDocsURI( "/deploying-services/service-ports/" )} target="_blank" > More information </a> . </Trans> ); return ( <FormGroup className="column-3" showError={Boolean(protocolError)}> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Protocol</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={assignHelpText} interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FormRow> <FormGroup className="column-auto"> <FieldLabel matchInputHeight={true}> <FieldInput checked={portDefinition.protocol.udp} name={`portDefinitions.${index}.protocol.udp`} type="checkbox" /> UDP </FieldLabel> </FormGroup> <FormGroup className="column-auto"> <FieldLabel matchInputHeight={true}> <FieldInput checked={portDefinition.protocol.tcp} name={`portDefinitions.${index}.protocol.tcp`} type="checkbox" /> TCP </FieldLabel> </FormGroup> </FormRow> <FieldError>{protocolError}</FieldError> </FormGroup> ); } getContainerPortField(portDefinition, network, errors, index) { if (network == null || network === HOST) { return null; } const containerPortError = findNestedPropertyInObject( errors, `portDefinitions.${index}.containerPort` ) || findNestedPropertyInObject( errors, `container.portMappings.${index}.containerPort` ); return ( <FormGroup className="column-3" showError={Boolean(containerPortError)}> <FieldLabel> <Trans render="span">Container Port</Trans> </FieldLabel> <FieldAutofocus> <FieldInput min="0" name={`portDefinitions.${index}.containerPort`} type="number" value={portDefinition.containerPort} autoFocus={Boolean(containerPortError)} /> </FieldAutofocus> <FieldError>{containerPortError}</FieldError> </FormGroup> ); } /** * This field is actually not present in the appConfig, but is generated by * the reducers, so we empower the user to show and hide fields * @param {Object} portDefinition, the portDefinition to turn port mapping on * and off ofr * @param {String} network, type of network * @param {Number} index, position of port definition in the * portDefinitions array * @return {Component} Checkbox for turning port mapping on and off */ getPortMappingCheckbox(portDefinition, network, index) { if ([BRIDGE, HOST].includes(network)) { return null; } return ( <FormGroup className="column-3"> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Port Mapping</Trans> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldLabel matchInputHeight={true}> <FieldInput checked={portDefinition.portMapping} name={`portDefinitions.${index}.portMapping`} type="checkbox" /> Enabled </FieldLabel> </FormGroup> ); } getServiceEndpoints() { const { errors, data: { networks }, } = this.props; const networkType = findNestedPropertyInObject(networks, "0.mode") || HOST; const endpoints = isHostNetwork(this.props.data) ? this.props.data.portDefinitions : this.props.data.portMappings; const endpointHelpTooltip = ( <Trans render="span"> Name your endpoint to search for it by a meaningful name, rather than{" "} the port number. </Trans> ); return endpoints.map((endpoint, index) => { let portMappingFields = null; const nameError = findNestedPropertyInObject(errors, `portDefinitions.${index}.name`) || findNestedPropertyInObject( errors, `container.portMappings.${index}.name` ); if (endpoint.portMapping || [BRIDGE, HOST].includes(networkType)) { portMappingFields = ( <FormRow> {this.getHostPortFields(endpoint, index)} {this.getProtocolField(endpoint, index)} </FormRow> ); } return ( <FormGroupContainer key={index} onRemove={this.props.onRemoveItem.bind(this, { value: index, path: "portDefinitions", })} > <FormRow> {this.getContainerPortField(endpoint, networkType, errors, index)} <FormGroup className="column-6" showError={Boolean(nameError)}> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Service Endpoint Name</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={endpointHelpTooltip} interactive={true} maxWidth={300} wrapperClassName="tooltip-wrapper text-align-center" wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> <FieldAutofocus> <FieldInput name={`portDefinitions.${index}.name`} type="text" value={endpoint.name} /> </FieldAutofocus> <FieldError>{nameError}</FieldError> </FormGroup> {this.getPortMappingCheckbox(endpoint, networkType, index)} </FormRow> {portMappingFields} {this.getLoadBalancedServiceAddressField(endpoint, index)} </FormGroupContainer> ); }); } getVirtualNetworks() { // Networks with subnet6 should be disabled when "UCR" container type is selected. const isMesosContainer = this.props.data?.container?.type === "MESOS"; const isVirtualNetworkAvailable = (o: Overlay) => o.enabled && (!isMesosContainer || !o.subnet6); return VirtualNetworksStore.overlays .filter(isVirtualNetworkAvailable) .map(({ name }) => ( <Trans id="Virtual Network: {0}" key={name} render={<option value={`${CONTAINER}.${name}`} />} values={{ 0: name }} /> )); } getTypeSelections() { const { mode, name } = this.props.data?.networks?.[0] || {}; const selectedValue = name ? `${mode}.${name}` : mode; const selections = ( <FieldSelect name="networks.0.network" value={selectedValue}> <Trans key="host" id="Host" render={<option value={HOST} />} /> <Trans key="bridge" id="Bridge" render={<option value={BRIDGE} />} /> {this.state.hasCalicoNetworking ? ( <option value={`${CONTAINER}.calico`}>Virtual Network: Calico</option> ) : null} {this.getVirtualNetworks()} </FieldSelect> ); return selections; } getServiceEndpointsSection() { const serviceEndpointsDocsURI = MetadataStore.buildDocsURI( "/deploying-services/service-endpoints/" ); const serviceEndpointsTooltipContent = ( <Trans render="span"> Service endpoints map traffic from a single VIP to multiple IP addresses{" "} and ports.{" "} <a href={serviceEndpointsDocsURI} target="_blank"> More Information </a> . </Trans> ); const heading = ( <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Service Endpoints</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={serviceEndpointsTooltipContent} interactive={true} maxWidth={300} wrapperClassName="tooltip-wrapper text-align-center" wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> ); return ( <div> <h2 className="short-bottom" key="service-endpoints-header"> {heading} </h2> <Trans render="p" key="service-endpoints-description"> DC/OS can automatically generate a Service Address to connect to each of your load balanced endpoints. </Trans> {isHostNetwork(this.props.data) && this.getHostNetworkPortsAutoAssignSection()} {this.getServiceEndpoints()} <FormRow key="service-endpoints-add-button"> <FormGroup className="column-12"> <AddButton onClick={this.props.onAddItem.bind(this, { path: "portDefinitions", })} > <Trans render="span">Add Service Endpoint</Trans> </AddButton> </FormGroup> </FormRow> </div> ); } getHostNetworkPortsAutoAssignSection() { const portsAutoAssignValue = this.props.data.portsAutoAssign; return ( <div> <FieldLabel matchInputHeight={true}> <FieldInput checked={portsAutoAssignValue} name="portsAutoAssign" type="checkbox" /> <Trans render="span">Assign Host Ports Automatically</Trans> </FieldLabel> </div> ); } getNonHostNetworkPortsAutoAssignSection(endpoint, index) { return ( <FormGroup className="column-auto flush-left" key="assign-automatically"> <FieldLabel>&nbsp;</FieldLabel> <FieldLabel matchInputHeight={true}> <FieldInput checked={endpoint.automaticPort} name={`portDefinitions.${index}.automaticPort`} type="checkbox" /> <Trans render="span">Assign Automatically</Trans> </FieldLabel> </FormGroup> ); } render() { const networkError = findNestedPropertyInObject( this.props.errors, "networks" ); let { networks } = this.props.data; const tooltipContent = ( <Trans> Refer to the{" "} <a href={MetadataStore.buildDocsURI( "/deploying-services/service-ports/" )} target="_blank" > ports documentation </a>{" "} for more information. </Trans> ); if (networks != null && networks.length > 1) { networks = networks.map(({ mode, name }) => ({ name, mode: Networking.internalToJson[mode], })); return ( <div> <Trans render="h2" className="flush-top short-bottom"> Networking </Trans> <Trans render="p"> This service has advanced networking configuration, which we don't currently support in the UI. Please use the JSON editor to make changes. </Trans> <pre>{JSON.stringify(networks, null, 2)}</pre> </div> ); } return ( <div> <Trans render="h1" className="flush-top short-bottom"> Networking </Trans> <Trans render="p">Configure the networking for your service.</Trans> <FormRow> <FormGroup className="column-6" showError={Boolean(networkError)}> <FieldLabel> <FormGroupHeading> <FormGroupHeadingContent primary={true}> <Trans render="span">Network Type</Trans> </FormGroupHeadingContent> <FormGroupHeadingContent> <Tooltip content={tooltipContent} interactive={true} maxWidth={300} wrapText={true} > <InfoTooltipIcon /> </Tooltip> </FormGroupHeadingContent> </FormGroupHeading> </FieldLabel> {this.getTypeSelections()} <FieldError>{networkError}</FieldError> </FormGroup> </FormRow> {this.getServiceEndpointsSection()} </div> ); } } NetworkingFormSection.configReducers = { networks, portDefinitions: SingleContainerPortDefinitions, portMappings: SingleContainerPortMappings, portsAutoAssign(state, { type, path = [], value }) { const joinedPath = path.join("."); if (type === SET && joinedPath === "portsAutoAssign") { return value; } return state; }, }; export default NetworkingFormSection;
the_stack
import React, {Component} from 'react' import {Form, Input, Modal, Select, Row, Col} from 'antd' import {Plugin} from "../model/PluginModel"; import {ContainerModel} from "../../container/model/ContainerModel" import {FormComponentProps} from "antd/lib/form/Form"; import {kernel} from "../../../common/utils/IOC" import CommonUtils from "../../../common/utils/CommonUtils"; import {DynamicFormUtils} from "../../../common/utils/DynamicFormUtils"; import EnumUtils from "../../../common/utils/EnumUtils"; const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 20 } }; const modalWidth = 800; const FIELD_CONFIG_MAP = "fieldConfigMap"; const FIELD_CONFIG = "fieldConfig"; const CONFIG = "config"; const CONFIG_PREFIX = CONFIG + "."; const NAME = "name"; const LABEL = "label"; export interface ModalProps extends FormComponentProps{ plugin: Plugin; onOk: any; onCancel: any; } class PluginModal extends Component<ModalProps, {allContainers, selectedContainerId, selectedFieldNames}> { constructor(props){ super(props); this.state = { allContainers: [], selectedContainerId: null, selectedFieldNames: [] } } componentWillMount(){ const that = this; const containerModel = kernel.get(ContainerModel); containerModel.listAllContainers().then(data => { if (data && data.length > 1) { for(let container of data){ let containerFieldConfigs = container.fieldConfig; if(containerFieldConfigs){ let formFieldMap = {}; for(let containerField of containerFieldConfigs ){ const name = containerField[NAME]; containerField[NAME] = CONFIG_PREFIX + name; formFieldMap[name] = containerField; container[FIELD_CONFIG_MAP] = formFieldMap; } } } console.log(data); that.setState({ allContainers: data }) } }); const plugin = this.props.plugin; if(plugin){ const selectedNames = []; if(plugin.config){ for(let configKey in plugin.config){ selectedNames.push(CONFIG_PREFIX + configKey); } } const containerId = plugin.containerId; that.setState({ selectedFieldNames: selectedNames, selectedContainerId: containerId }); } } /** * 容器变更 * @returns {any} */ onContainerChange(value){ this.setState({ selectedContainerId: value, selectedFieldNames: [] }); } /** * 容器字段变更 * @returns {any} */ onContainerFieldsChange(value){ this.setState({ selectedFieldNames: value }); } render() { let isUpdate = false; if(this.props.plugin && this.props.plugin.id){ isUpdate = true; } let pluginObj = this.props.plugin ? this.props.plugin : new Plugin(); let handleOk = (e) => { e.preventDefault(); this.props.form.validateFields((errors) => { if (errors) { return } const data = { ...this.props.form.getFieldsValue(), id: pluginObj.id ? pluginObj.id : '' }; let config = data[CONFIG]; if(config){ data[CONFIG] = JSON.stringify(config); }else{ data[CONFIG] = ""; } this.props.onOk(data) }) }; const modalOpts = { title: isUpdate ? '编辑插件' : '添加插件', visible: true, maskClosable: false, width: modalWidth, onOk: handleOk, onCancel: this.props.onCancel }; /** * 初始化option */ const {selectedFieldNames, allContainers, selectedContainerId} = this.state; let containerOptions = []; if (allContainers) { for(let container of allContainers){ containerOptions.push(<option key={container.id + "" }>{container.name}</option>); } } /** * containerFieldOption */ let containerFieldOptions = []; let pluginAddedFieldConfig = []; if (allContainers) { for(let container of allContainers){ if(container.id == selectedContainerId){ const containerFieldConfigArray = container[FIELD_CONFIG]; if(containerFieldConfigArray && containerFieldConfigArray.length > 0){ for(let fcConfig of containerFieldConfigArray){ const name = fcConfig[NAME]; const label = fcConfig[LABEL]; let fieldExist = false; if(selectedFieldNames){ for(let fieldName of selectedFieldNames){ if(fieldName == name){ fieldExist = true; break; } } } if(fieldExist){ pluginAddedFieldConfig.push(fcConfig); } containerFieldOptions.push(<option key={name}>{label}</option>); } } break; } } } let fieldSelectedDoms = []; fieldSelectedDoms.push(<Form.Item label='容器参数' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator("containerFields-" + selectedContainerId, { initialValue: selectedFieldNames, rules: [ { required: false, message: '不能为空' } ] })(<Select allowClear={true} onChange={this.onContainerFieldsChange.bind(this)} mode="multiple"> {containerFieldOptions} </Select>)} </Form.Item>); let dynamicDoms = []; const isDomEdit = isUpdate && pluginObj["status"] == EnumUtils.statusOnline; if(pluginAddedFieldConfig){ for(let formField of pluginAddedFieldConfig){ let dom = DynamicFormUtils.getComponent({ property: formField, model: pluginObj, isEdit: isDomEdit, formParent: this, layout: { labelCol: { span: 4 }, wrapperCol: { span: 20 } } }); if(dom){ dynamicDoms.push(dom); } } } return (<Modal {...modalOpts}> <Form layout={'horizontal'} > <Row > <Col span={12}> <Form.Item label='名称:' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('name', { initialValue: CommonUtils.getStringValueFromModel("name", pluginObj, ""), rules: [ { required: true, message: '不能为空' } ] })(<Input/>)} </Form.Item> <Form.Item label='容器' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('containerId', { initialValue: CommonUtils.getStringValueFromModel("containerId", pluginObj, ""), rules: [ { required: true, message: '不能为空' } ] })(<Select onChange={this.onContainerChange.bind(this)}> {containerOptions} </Select>)} </Form.Item> {fieldSelectedDoms} {dynamicDoms} <Form.Item label='描述' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('description', { initialValue: CommonUtils.getStringValueFromModel("description", pluginObj, ""), rules: [ { required: false, message: '不能为空' } ] })(<Input.TextArea rows={6}/>)} </Form.Item> </Col> <Col span={12}> <Form.Item label='参数' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('fieldConfig', { initialValue: CommonUtils.getStringValueFromModel("fieldConfig", pluginObj, ""), rules: [ { required: false, message: '不能为空' } ] })(<Input.TextArea rows={20}/>)} </Form.Item> </Col> </Row> </Form> </Modal>); } } export default Form.create()(PluginModal);
the_stack
import Web3 from 'web3'; import {Currency, DeployErc20, TransferErc20} from '../model'; import { prepareXdcCustomErc20SignedTransaction, prepareXdcDeployErc20SignedTransaction, prepareXdcOrErc20SignedTransaction, sendXdcBurnErc721Transaction, sendXdcDeployErc721Transaction, sendXdcErc721Transaction, sendXdcMintErc721Transaction, sendXdcMintMultipleErc721Transaction, sendXdcSmartContractMethodInvocationTransaction, sendXdcSmartContractReadMethodInvocationTransaction, xdcGetGasPriceInWei } from './xdc'; describe('XDC transactions', () => { jest.setTimeout(19999) const providerAddr = 'https://rpc.apothem.network/' const broadcast = async (txData: string) => { const client = new Web3(providerAddr) const result: { txId: string } = await new Promise((resolve, reject) => { client.eth.sendSignedTransaction(txData) .once('transactionHash', txId => resolve({txId})) .on('error', e => reject(new Error(`Unable to broadcast transaction due to ${e.message}.`))) }) return result } it('should test valid transaction XDC data', async () => { const body = new TransferErc20() body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.amount = '0' body.to = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' const txData = await prepareXdcOrErc20SignedTransaction(body) expect(txData).toContain('0x') // console.log(await broadcast(txData)); }) it('should test valid transaction ERC20 data', async () => { const body = new TransferErc20() body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.amount = '0' body.to = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' const txData = await prepareXdcOrErc20SignedTransaction(body) expect(txData).toContain('0x') // console.log(await broadcast(txData)); }) it('should test valid custom transaction ERC20 data', async () => { const body = new TransferErc20(); body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.amount = '0' body.contractAddress = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' body.to = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' body.digits = 10 const txData = await prepareXdcCustomErc20SignedTransaction(body) expect(txData).toContain('0x') // console.log(await broadcast(txData)); }) it('should test valid custom deployment ERC20', async () => { const body = new DeployErc20() body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.symbol = 'SYMBOL' body.name = 'Test_ERC20' body.supply = '100' body.address = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' body.digits = 10 const txData = await prepareXdcDeployErc20SignedTransaction(body) expect(txData).toContain('0x') // console.log(await broadcast(txData)); }) it('should test invalid custom deployment ERC20, missing supply', async () => { const body = new DeployErc20() body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.symbol = 'SYMBOL' body.name = 'Test_ERC20' body.address = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' body.digits = 10 try { await prepareXdcDeployErc20SignedTransaction(body) fail('Validation did not pass.') } catch (e) { console.error(e) } }) it('should test invalid custom transaction ERC20 data, missing digits', async () => { const body = new TransferErc20(); body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.amount = '0' body.contractAddress = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' body.to = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' try { await prepareXdcCustomErc20SignedTransaction(body) fail('Validation did not pass.') } catch (e) { console.error(e) } }) it('should not test valid transaction data, missing currency', async () => { const body = new TransferErc20() body.fromPrivateKey = '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29' body.amount = '0' body.to = 'xdc811DfbFF13ADFBC3Cf653dCc373C03616D3471c9' try { await prepareXdcOrErc20SignedTransaction(body) fail('Validation did not pass.') } catch (e) { console.error(e) } }) it('should test ethGetGasPriceInWei', async () => { const gasPrice = await xdcGetGasPriceInWei() expect(gasPrice).not.toBeNull() }) it('should test read smart contract method invocation', async () => { const result = await sendXdcSmartContractReadMethodInvocationTransaction({ contractAddress: 'xdc595bad1621784e9b0161d909be0117f17a5d37ca', methodName: 'balanceOf', methodABI: { constant: true, inputs: [ { name: 'owner', type: 'address', }, ], name: 'balanceOf', outputs: [ { name: '', type: 'uint256', }, ], payable: false, stateMutability: 'view', type: 'function', }, params: ['xdc8c76887d2e738371bd750362fb55887343472346'], }) console.log(result) expect(result).not.toBeNull() }) it('should test write smart contract method invocation', async () => { const result = await sendXdcSmartContractMethodInvocationTransaction({ fromPrivateKey: '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29', contractAddress: 'xdcd7d3e5e2174b530fdfb6d680c07c8b34495e2195', fee: {gasLimit: '40000', gasPrice: '200'}, methodName: 'transferFrom', methodABI: { constant: false, inputs: [ { name: 'from', type: 'address', }, { name: 'to', type: 'address', }, { name: 'value', type: 'uint256', }, ], name: 'transferFrom', outputs: [ { name: '', type: 'bool', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, params: ['xdc811dfbff13adfbc3cf653dcc373c03616d3471c9', 'xdc8c76887d2e738371bd750362fb55887343472346', '1'], }) expect(result).not.toBeNull() }) it('should test ERC 721 mint transaction', async () => { try { const tokenId = new Date().getTime().toString() const mintedToken = await sendXdcMintErc721Transaction({ to: 'xdc811dfbff13adfbc3cf653dcc373c03616d3471c9', tokenId, url: 'https://www.seznam.cz', fromPrivateKey: '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29', chain: Currency.XDC, contractAddress: 'xdc687422eEA2cB73B5d3e242bA5456b782919AFc85', fee: { gasLimit: '50000', gasPrice: '110' } }) console.log(tokenId) expect(mintedToken).not.toBeNull() } catch (e) { console.log(e) } }) it('should test ERC 721 mint multiple transaction', async () => { const firstTokenId = new Date().getTime() const secondTokenId = firstTokenId + 1 const mintedTokens = await sendXdcMintMultipleErc721Transaction({ to: ['xdc811dfbff13adfbc3cf653dcc373c03616d3471c9', 'xdc811dfbff13adfbc3cf653dcc373c03616d3471c9'], tokenId: [firstTokenId.toString(), secondTokenId.toString()], url: ['https://www.seznam.cz', 'https://www.seznam.cz'], fromPrivateKey: '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29', chain: Currency.XDC, contractAddress: 'xdc687422eEA2cB73B5d3e242bA5456b782919AFc85', fee: { gasLimit: '50000', gasPrice: '100' } }) expect(mintedTokens).not.toBeNull() }) it('should test ERC 721 burn transaction', async () => { const burnErc721Token = await sendXdcBurnErc721Transaction({ tokenId: '1615552558810', fromPrivateKey: '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29', chain: Currency.XDC, contractAddress: 'xdc687422eEA2cB73B5d3e242bA5456b782919AFc85', fee: { gasLimit: '5000000', gasPrice: '110' }, }) expect(burnErc721Token).not.toBeNull() }) it('should test ERC 721 send transaction', async () => { const sendErc721Token = await sendXdcErc721Transaction({ to: 'xdc811dfbff13adfbc3cf653dcc373c03616d3471c9', tokenId: '1615546122766', fromPrivateKey: '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29', chain: Currency.XDC, contractAddress: 'xdc687422eEA2cB73B5d3e242bA5456b782919AFc85', fee: { gasLimit: '5000000', gasPrice: '100' } }) expect(sendErc721Token).not.toBeNull() }) it('should test ERC 721 deploy transaction', async () => { const deployErc721Token = await sendXdcDeployErc721Transaction({ symbol: '1oido3id3', fromPrivateKey: '0x1a4344e55c562db08700dd32e52e62e7c40b1ef5e27c6ddd969de9891a899b29', chain: Currency.XDC, name: '2123kd', }) expect(deployErc721Token).not.toBeNull() }) })
the_stack
jest.mock(require.resolve('prettier'), () => require('../__mocks__/prettier')); import {tmpdir} from 'os'; import * as path from 'path'; const prettier = require(require.resolve('prettier')); import * as fs from 'graceful-fs'; import {Frame} from 'jest-message-util'; import {saveInlineSnapshots} from '../InlineSnapshots'; let dir; beforeEach(() => { (prettier.resolveConfig.sync as jest.Mock).mockReset(); }); beforeEach(() => { dir = path.join(tmpdir(), `jest-inline-snapshot-test-${Date.now()}`); fs.mkdirSync(dir); }); test('saveInlineSnapshots() replaces empty function call with a template literal', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, `expect(1).toMatchInlineSnapshot();\n`); saveInlineSnapshots( [ { frame: {column: 11, file: filename, line: 1} as Frame, snapshot: `1`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( 'expect(1).toMatchInlineSnapshot(`1`);\n', ); }); test('saveInlineSnapshots() without prettier leaves formatting outside of snapshots alone', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, ` const a = [1, 2]; expect(a).toMatchInlineSnapshot(\`an out-of-date and also multi-line snapshot\`); expect(a).toMatchInlineSnapshot(); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); `.trim() + '\n', ); saveInlineSnapshots( [2, 4, 5].map(line => ({ frame: {column: 11, file: filename, line} as Frame, snapshot: `[1, 2]`, })), null, ); expect(fs.readFileSync(filename, 'utf8')).toBe( `const a = [1, 2]; expect(a).toMatchInlineSnapshot(\`[1, 2]\`); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); `, ); }); test('saveInlineSnapshots() with bad prettier path leaves formatting outside of snapshots alone', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, ` const a = [1, 2]; expect(a).toMatchInlineSnapshot(\`an out-of-date and also multi-line snapshot\`); expect(a).toMatchInlineSnapshot(); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); `.trim() + '\n', ); saveInlineSnapshots( [2, 4, 5].map(line => ({ frame: {column: 11, file: filename, line} as Frame, snapshot: `[1, 2]`, })), 'bad-prettier', ); expect(fs.readFileSync(filename, 'utf8')).toBe( `const a = [1, 2]; expect(a).toMatchInlineSnapshot(\`[1, 2]\`); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); `, ); }); test('saveInlineSnapshots() can handle typescript without prettier', () => { const filename = path.join(dir, 'my.test.ts'); fs.writeFileSync( filename, ` interface Foo { foo: string } const a: [Foo, Foo] = [{ foo: 'one' }, { foo: 'two' }]; expect(a).toMatchInlineSnapshot(); `.trim() + '\n', ); saveInlineSnapshots( [ { frame: {column: 11, file: filename, line: 5} as Frame, snapshot: `[{ foo: 'one' }, { foo: 'two' }]`, }, ], null, ); expect(fs.readFileSync(filename, 'utf8')).toBe( ` interface Foo { foo: string } const a: [Foo, Foo] = [{ foo: 'one' }, { foo: 'two' }]; expect(a).toMatchInlineSnapshot(\`[{ foo: 'one' }, { foo: 'two' }]\`); `.trim() + '\n', ); }); test('saveInlineSnapshots() can handle tsx without prettier', () => { const filename = path.join(dir, 'my.test.tsx'); fs.writeFileSync( filename, ` it('foos', async () => { const Foo = (props: { foo: string }) => <div>{props.foo}</div>; const a = await Foo({ foo: "hello" }); expect(a).toMatchInlineSnapshot(); }) `.trim() + '\n', ); saveInlineSnapshots( [ { frame: {column: 13, file: filename, line: 4} as Frame, snapshot: `<div>hello</div>`, }, ], null, ); expect(fs.readFileSync(filename, 'utf-8')).toBe( ` it('foos', async () => { const Foo = (props: { foo: string }) => <div>{props.foo}</div>; const a = await Foo({ foo: "hello" }); expect(a).toMatchInlineSnapshot(\`<div>hello</div>\`); }) `.trim() + '\n', ); }); test('saveInlineSnapshots() can handle flow and jsx without prettier', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, ` const Foo = (props: { foo: string }) => <div>{props.foo}</div>; const a = Foo({ foo: "hello" }); expect(a).toMatchInlineSnapshot(); `.trim() + '\n', ); fs.writeFileSync( path.join(dir, '.babelrc'), JSON.stringify({ presets: [ require.resolve('@babel/preset-flow'), require.resolve('@babel/preset-react'), ], }), ); saveInlineSnapshots( [ { frame: {column: 11, file: filename, line: 3} as Frame, snapshot: `<div>hello</div>`, }, ], null, ); expect(fs.readFileSync(filename, 'utf-8')).toBe( ` const Foo = (props: { foo: string }) => <div>{props.foo}</div>; const a = Foo({ foo: "hello" }); expect(a).toMatchInlineSnapshot(\`<div>hello</div>\`); `.trim() + '\n', ); }); test('saveInlineSnapshots() can use prettier to fix formatting for whole file', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, ` const a = [1, 2]; expect(a).toMatchInlineSnapshot(\`an out-of-date and also multi-line snapshot\`); expect(a).toMatchInlineSnapshot(); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); `.trim() + '\n', ); saveInlineSnapshots( [2, 4, 5].map(line => ({ frame: {column: 11, file: filename, line} as Frame, snapshot: `[1, 2]`, })), 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( `const a = [1, 2]; expect(a).toMatchInlineSnapshot(\`[1, 2]\`); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); expect(a).toMatchInlineSnapshot(\`[1, 2]\`); `, ); }); test.each([['babel'], ['flow'], ['typescript']])( 'saveInlineSnapshots() replaces existing template literal - %s parser', parser => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect(1).toMatchInlineSnapshot(`2`);\n'); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({parser}); saveInlineSnapshots( [ { frame: {column: 11, file: filename, line: 1} as Frame, snapshot: `1`, }, ], 'prettier', ); expect( (prettier.resolveConfig.sync as jest.Mock).mock.results[0].value, ).toEqual({parser}); expect(fs.readFileSync(filename, 'utf-8')).toBe( 'expect(1).toMatchInlineSnapshot(`1`);\n', ); }, ); test('saveInlineSnapshots() replaces existing template literal with property matchers', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect(1).toMatchInlineSnapshot({}, `2`);\n'); saveInlineSnapshots( [ { frame: {column: 11, file: filename, line: 1} as Frame, snapshot: `1`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( 'expect(1).toMatchInlineSnapshot({}, `1`);\n', ); }); test.each(['prettier', null])( 'saveInlineSnapshots() creates template literal with property matchers', prettierModule => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect(1).toMatchInlineSnapshot({});\n'); saveInlineSnapshots( [ { frame: {column: 11, file: filename, line: 1} as Frame, snapshot: `1`, }, ], prettierModule, ); expect(fs.readFileSync(filename, 'utf-8')).toBe( 'expect(1).toMatchInlineSnapshot({}, `1`);\n', ); }, ); test('saveInlineSnapshots() throws if frame does not match', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect(1).toMatchInlineSnapshot();\n'); const save = () => saveInlineSnapshots( [ { frame: { column: 2 /* incorrect */, file: filename, line: 1, } as Frame, snapshot: `1`, }, ], 'prettier', ); expect(save).toThrowError(/Couldn't locate all inline snapshots./); }); test('saveInlineSnapshots() throws if multiple calls to to the same location', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect(1).toMatchInlineSnapshot();\n'); const frame = {column: 11, file: filename, line: 1} as Frame; const save = () => saveInlineSnapshots( [ {frame, snapshot: `1`}, {frame, snapshot: `2`}, ], 'prettier', ); expect(save).toThrowError( /Multiple inline snapshots for the same call are not supported./, ); }); test('saveInlineSnapshots() uses escaped backticks', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, 'expect("`").toMatchInlineSnapshot();\n'); const frame = {column: 13, file: filename, line: 1} as Frame; saveInlineSnapshots([{frame, snapshot: '`'}], 'prettier'); expect(fs.readFileSync(filename, 'utf-8')).toBe( 'expect("`").toMatchInlineSnapshot(`\\``);\n', ); }); test('saveInlineSnapshots() works with non-literals in expect call', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync(filename, `expect({a: 'a'}).toMatchInlineSnapshot();\n`); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); saveInlineSnapshots( [ { frame: {column: 18, file: filename, line: 1} as Frame, snapshot: `{a: 'a'}`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "expect({a: 'a'}).toMatchInlineSnapshot(`{a: 'a'}`);\n", ); }); test('saveInlineSnapshots() indents multi-line snapshots with spaces', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, "it('is a test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n', ); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); saveInlineSnapshots( [ { frame: {column: 20, file: filename, line: 2} as Frame, snapshot: `\nObject {\n a: 'a'\n}\n`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "it('is a test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot(`\n" + ' Object {\n' + " a: 'a'\n" + ' }\n' + ' `);\n' + '});\n', ); }); test('saveInlineSnapshots() does not re-indent error snapshots', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, "it('is an error test', () => {\n" + ' expect(() => {\n' + " throw new Error(['a', 'b'].join('\\n'));\n" + ' }).toThrowErrorMatchingInlineSnapshot(`\n' + ' "a\n' + ' b"\n' + ' `);\n' + '});\n' + "it('is another test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n', ); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); saveInlineSnapshots( [ { frame: {column: 20, file: filename, line: 10} as Frame, snapshot: `\nObject {\n a: 'a'\n}\n`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "it('is an error test', () => {\n" + ' expect(() => {\n' + " throw new Error(['a', 'b'].join('\\n'));\n" + ' }).toThrowErrorMatchingInlineSnapshot(`\n' + ' "a\n' + ' b"\n' + ' `);\n' + '});\n' + "it('is another test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot(`\n" + ' Object {\n' + " a: 'a'\n" + ' }\n' + ' `);\n' + '});\n', ); }); test('saveInlineSnapshots() does not re-indent already indented snapshots', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, "it('is a test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n' + "it('is a another test', () => {\n" + " expect({b: 'b'}).toMatchInlineSnapshot(`\n" + ' Object {\n' + " b: 'b'\n" + ' }\n' + ' `);\n' + '});\n', ); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); saveInlineSnapshots( [ { frame: {column: 20, file: filename, line: 2} as Frame, snapshot: `\nObject {\n a: 'a'\n}\n`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "it('is a test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot(`\n" + ' Object {\n' + " a: 'a'\n" + ' }\n' + ' `);\n' + '});\n' + "it('is a another test', () => {\n" + " expect({b: 'b'}).toMatchInlineSnapshot(`\n" + ' Object {\n' + " b: 'b'\n" + ' }\n' + ' `);\n' + '});\n', ); }); test('saveInlineSnapshots() indents multi-line snapshots with tabs', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, "it('is a test', () => {\n" + " expect({a: 'a'}).toMatchInlineSnapshot();\n" + '});\n', ); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, useTabs: true, }); saveInlineSnapshots( [ { frame: {column: 20, file: filename, line: 2} as Frame, snapshot: `\nObject {\n a: 'a'\n}\n`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "it('is a test', () => {\n" + "\texpect({a: 'a'}).toMatchInlineSnapshot(`\n" + '\t\tObject {\n' + "\t\t a: 'a'\n" + '\t\t}\n' + '\t`);\n' + '});\n', ); }); test('saveInlineSnapshots() indents snapshots after prettier reformats', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, "it('is a test', () => expect({a: 'a'}).toMatchInlineSnapshot());\n", ); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); saveInlineSnapshots( [ { frame: {column: 40, file: filename, line: 1} as Frame, snapshot: `\nObject {\n a: 'a'\n}\n`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "it('is a test', () =>\n" + " expect({a: 'a'}).toMatchInlineSnapshot(`\n" + ' Object {\n' + " a: 'a'\n" + ' }\n' + ' `));\n', ); }); test('saveInlineSnapshots() does not indent empty lines', () => { const filename = path.join(dir, 'my.test.js'); fs.writeFileSync( filename, "it('is a test', () => expect(`hello\n\nworld`).toMatchInlineSnapshot());\n", ); (prettier.resolveConfig.sync as jest.Mock).mockReturnValue({ bracketSpacing: false, singleQuote: true, }); saveInlineSnapshots( [ { frame: {column: 9, file: filename, line: 3} as Frame, snapshot: `\nhello\n\nworld\n`, }, ], 'prettier', ); expect(fs.readFileSync(filename, 'utf-8')).toBe( "it('is a test', () =>\n" + ' expect(`hello\n\nworld`).toMatchInlineSnapshot(`\n' + ' hello\n' + '\n' + ' world\n' + ' `));\n', ); });
the_stack
import { inject, injectable } from 'inversify'; import { FindConditions, LessThan, LessThanOrEqual, MoreThanOrEqual, ObjectLiteral } from 'typeorm'; import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity'; import * as apid from '../../../api'; import * as mapid from '../../../node_modules/mirakurun/api'; import Program from '../../db/entities/Program'; import DateUtil from '../../util/DateUtil'; import StrUtil from '../../util/StrUtil'; import ILogger from '../ILogger'; import ILoggerModel from '../ILoggerModel'; import IPromiseRetry from '../IPromiseRetry'; import DBUtil from './DBUtil'; import IChannelTypeIndex from './IChannelTypeHash'; import IDBOperator from './IDBOperator'; import IProgramDB, { FindRuleOption, FindScheduleIdOption, FindScheduleOption, ProgramUpdateValues, ProgramWithOverlap, } from './IProgramDB'; interface FindQuery { strs: string[]; param: ObjectLiteral; } interface KeywordOption { cs: boolean; regexp: boolean; name: boolean; description: boolean; extended: boolean; } @injectable() export default class ProgramDB implements IProgramDB { private log: ILogger; private op: IDBOperator; private promieRetry: IPromiseRetry; constructor( @inject('ILoggerModel') logger: ILoggerModel, @inject('IDBOperator') op: IDBOperator, @inject('IPromiseRetry') promieRetry: IPromiseRetry, ) { this.log = logger.getLogger(); this.op = op; this.promieRetry = promieRetry; } /** * 全件削除 & 更新 * @param channelTypes: IChannelTypeHash * @param programs: mapid.Program[] */ public async insert(channelTypes: IChannelTypeIndex, programs: mapid.Program[]): Promise<void> { const updateTime = new Date().getTime(); const values: QueryDeepPartialEntity<Program>[] = []; for (const program of programs) { const value = this.createProgramValue(channelTypes, program, updateTime); if (value !== null) { values.push(value); } } // get queryRunner const connection = await this.op.getConnection(); const queryRunner = connection.createQueryRunner(); // start transaction await queryRunner.startTransaction(); let hasError = false; try { // 削除 await queryRunner.manager.delete(Program, {}); // 挿入処理 for (const value of values) { await queryRunner.manager.insert(Program, value); } await queryRunner.commitTransaction(); } catch (err) { console.error(err); hasError = true; await queryRunner.rollbackTransaction(); } finally { await queryRunner.release(); } if (hasError) { throw new Error('InsertError'); } } /** * mapid.Program から QueryDeepPartialEntity<Program> を生成する * @param channelTypes: IChannelTypeHash, * @param program: mapid.Program, * @param updateTime: number 更新時間 * @return QueryDeepPartialEntity<Program> | null データが作成出来ないときは null を返す */ private createProgramValue( channelTypes: IChannelTypeIndex, program: mapid.Program, updateTime: number, ): QueryDeepPartialEntity<Program> | null { if (typeof program.name === 'undefined') { return null; } // channelType, channel if ( typeof channelTypes[program.networkId] === 'undefined' || typeof channelTypes[program.networkId][program.serviceId] === 'undefined' ) { // サービスが存在しない return null; } const channelId = channelTypes[program.networkId][program.serviceId].id; const channelType = channelTypes[program.networkId][program.serviceId].type; const channel = channelTypes[program.networkId][program.serviceId].channel; // genre let genre1: number | null = null; let subGenre1: number | null = null; let genre2: number | null = null; let subGenre2: number | null = null; let genre3: number | null = null; let subGenre3: number | null = null; if (typeof program.genres !== 'undefined') { // 最大3つのジャンルを格納する if (program.genres[0].lv1 < 0xe) { genre1 = program.genres[0].lv1; subGenre1 = typeof program.genres[0].lv2 === 'undefined' ? null : program.genres[0].lv2; } if (program.genres.length > 1 && program.genres[1].lv1 < 0xe) { genre2 = program.genres[1].lv1; subGenre2 = typeof program.genres[1].lv2 === 'undefined' ? null : program.genres[1].lv2; } if (program.genres.length > 2 && program.genres[2].lv1 < 0xe) { genre3 = program.genres[2].lv1; subGenre3 = typeof program.genres[2].lv2 === 'undefined' ? null : program.genres[2].lv2; } } // 日本時間取得 const jaDate = DateUtil.getJaDate(new Date(program.startAt)); // 番組名 const name = StrUtil.toDBStr(program.name); const halfWidthName = StrUtil.toHalf(name); const value: QueryDeepPartialEntity<Program> = { id: program.id, updateTime: updateTime, channelId: channelId, eventId: program.eventId, serviceId: program.serviceId, networkId: program.networkId, startAt: program.startAt, endAt: program.startAt + program.duration, startHour: jaDate.getHours(), week: jaDate.getDay(), duration: program.duration, isFree: program.isFree, name: name, halfWidthName: halfWidthName, shortName: StrUtil.deleteBrackets(halfWidthName), genre1: genre1, subGenre1: subGenre1, genre2: genre2, subGenre2: subGenre2, genre3: genre3, subGenre3: subGenre3, channelType: channelType, channel: channel, }; // description if (typeof program.description === 'undefined' || program.description.length === 0) { value.description = null; value.halfWidthDescription = null; } else { const description = StrUtil.toDBStr(program.description); value.description = description; value.halfWidthDescription = StrUtil.toHalf(description); } // extended if (typeof program.extended === 'undefined') { value.extended = null; value.halfWidthExtended = null; value.rawExtended = null; value.rawHalfWidthExtended = null; } else { const extended = this.createExtendedStr(program.extended); value.extended = extended; value.halfWidthExtended = StrUtil.toHalf(extended); value.rawExtended = JSON.stringify(program.extended); const halfRawExtended: { [key: string]: string } = {}; for (const key in program.extended) { halfRawExtended[StrUtil.toHalf(key)] = StrUtil.toHalf(program.extended[key]); } value.rawHalfWidthExtended = JSON.stringify(halfRawExtended); } // video if (typeof program.video !== 'undefined') { value.videoType = program.video.type; value.videoResolution = program.video.resolution; value.videoStreamContent = program.video.streamContent; value.videoComponentType = program.video.componentType; } // audio if (typeof (program as any).audio !== 'undefined') { value.audioSamplingRate = (program as any).audio.samplingRate; value.audioComponentType = (program as any).audio.componentType; } // audios if (typeof (program as any).audios !== 'undefined') { for (const audio of (program as any).audios) { // TODO 複数音声データに対応する // 互換性維持のため main の音声情報だけを格納する if (audio.isMain === false) { continue; } value.audioSamplingRate = audio.samplingRate; value.audioComponentType = audio.componentType; } } return value; } /** * extended を結合 * @param extended extended * @return string */ private createExtendedStr(extended: { [description: string]: string }): string { let str = ''; for (const key in extended) { if (key.slice(0, 1) === '◇') { str += `\n${key}\n${extended[key]}`; } else { str += `\n◇${key}\n${extended[key]}`; } } const ret = StrUtil.toDBStr(str).trim(); return ret; } /** * event stream 用更新 * @param channelTypes: IChannelTypeHash * @param values ProgramUpdateValues * @return Promise<void> */ public async update(channelTypes: IChannelTypeIndex, values: ProgramUpdateValues): Promise<void> { const updateTime = new Date().getTime(); const insertValues: QueryDeepPartialEntity<Program>[] = []; for (const program of values.insert) { const value = this.createProgramValue(channelTypes, program, updateTime); if (value !== null) { insertValues.push(value); } } for (const program of values.update) { const value = this.createProgramValue(channelTypes, program, updateTime); if (value !== null) { insertValues.push(value); } } // get queryRunner const connection = await this.op.getConnection(); const queryRunner = connection.createQueryRunner(); // start transaction await queryRunner.startTransaction(); let hasError = false; try { // 削除処理 for (const id of values.delete) { await queryRunner.manager.delete(Program, id).catch(err => { this.log.system.error(`program delete error: ${id}`); this.log.system.error(err); }); } // 挿入処理 for (const value of insertValues) { await queryRunner.manager.insert(Program, value).catch(async err => { await queryRunner.manager.update(Program, value.id, value).catch(serr => { this.log.system.error('program update error'); this.log.system.error(err); this.log.system.error(serr); }); }); } await queryRunner.commitTransaction(); } catch (err) { console.error(err); hasError = true; await queryRunner.rollbackTransaction(); } finally { await queryRunner.release(); } if (hasError) { throw new Error('UpdateError'); } } /** * 指定した時刻より古い番組情報を削除する * @param time: apid.UnixtimeMS * @return Promise<void> */ public async deleteOld(time: apid.UnixtimeMS): Promise<void> { const connection = await this.op.getConnection(); const repository = connection.getRepository(Program); await this.promieRetry.run(() => { return repository.delete({ endAt: LessThan(time), }); }); } /** * program id を指定して検索 * @param programId: program id * @return Promise<Program | null> */ public async findId(programId: apid.ProgramId): Promise<Program | null> { const connection = await this.op.getConnection(); const repository = connection.getRepository(Program); const result = await this.promieRetry.run(() => { return repository.findOne({ where: [{ id: programId }], }); }); return typeof result === 'undefined' ? null : result; } /** * ルールにマッチする番組を検索 * @param searchOption: apid.RuleSearchOption * @param reserveOption?: apid.RuleReserveOption * @return Promise<Program[]> */ public async findRule(option: FindRuleOption): Promise<ProgramWithOverlap[]> { const connection = await this.op.getConnection(); const query: FindQuery = { strs: [], param: {}, }; // set query this.setKeywordQuery(option.searchOption, query); this.setChannelQuery(option.searchOption, query); this.setGenresQuery(option.searchOption, query); this.setTimesQuery(option.searchOption, query); this.setFreeQuery(option.searchOption, query); this.setDurationMinQuery(option.searchOption, query); this.setDurationMaxQuery(option.searchOption, query); this.setSearchPeriodsQuery(option.searchOption, query); // joint query str let str = ''; for (let i = 0; i < query.strs.length; i++) { if (query.strs[i].length === 0) { continue; } str += `(${query.strs[i]})`; if (i < query.strs.length - 1) { str += ' and '; } } // ルールのオプションが何もない場合 if (str.length === 0) { throw new Error('InvalidFindRuleOption'); } let select = await connection.createQueryBuilder().select('program'); if (typeof option.reserveOption !== 'undefined' && option.reserveOption.avoidDuplicate === true) { select = select.addSelect( this.createOverlapQueryStr(option.reserveOption.periodToAvoidDuplicate), 'overlap', ); } const queryBuilder = select .from(Program, 'program') .where(str, query.param) .andWhere(`${new Date().getTime()} <= program.endAt`) .orderBy('program.startAt', 'ASC') .limit(option.limit); const result = await this.promieRetry.run(() => { return queryBuilder.getRawAndEntities(); }); // overlap を追加 return result.entities.map((entity, i) => { // eslint-disable-next-line no-extra-boolean-cast (<any>entity).overlap = Boolean(!!result.raw[i].overlap); return <any>entity; }); } /** * キーワードの検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setKeywordQuery(searchOption: apid.RuleSearchOption, query: FindQuery): void { if (typeof searchOption.keyword !== 'undefined') { this.setKeywordOption( searchOption.keyword, this.createKeywordOption(searchOption, false), 'keyword', false, query, ); } if (typeof searchOption.ignoreKeyword !== 'undefined') { this.setKeywordOption( searchOption.ignoreKeyword, this.createKeywordOption(searchOption, true), 'ignoreKeyword', true, query, ); } } /** * keyword を指定してquery に キーワード検索のオプションをセットする * @param keyword: string keyword * @param option: KeywordOption * @param valueBaseName: string query.param に格納するときのベース名 * @param isIgnore: boolean 除外キーワードか * @param query: FindQuery */ private setKeywordOption( keyword: string, option: KeywordOption, valueBaseName: string, isIgnore: boolean, query: FindQuery, ): void { const or: string[] = []; if (option.regexp === true) { // 正規表現 const regexp = this.op.getRegexpStr(option.cs); const valueName = `${valueBaseName}Regexp`; query.param[valueName] = keyword; if (option.cs === true) { if (option.name === true) { or.push(`CAST(halfWidthName AS BINARY) ${regexp} :${valueName}`); } if (option.description === true) { or.push(`CAST(COALESCE(halfWidthDescription,'') AS BINARY) ${regexp} :${valueName}`); } if (option.extended === true) { or.push(`CAST(COALESCE(halfWidthExtended,'') AS BINARY) ${regexp} :${valueName}`); } } else { if (option.name === true) { or.push(`halfWidthName ${regexp} :${valueName}`); } if (option.description === true) { or.push(`COALESCE(halfWidthDescription,'') ${regexp} :${valueName}`); } if (option.extended === true) { or.push(`COALESCE(halfWidthExtended,'') ${regexp} :${valueName}`); } } } else { // あいまい検索 const keywords = StrUtil.toHalf(keyword).split(/ /); const like = this.op.getLikeStr(option.cs); const nameAnd: string[] = []; const descriptionAnd: string[] = []; const extendedAnd: string[] = []; keywords.forEach((str, i) => { str = `%${str}%`; if (option.name === true) { const valueName = `${valueBaseName}Name${i}`; nameAnd.push(`halfWidthName ${like} :${valueName}`); query.param[valueName] = str; } if (option.description === true) { const valueName = `${valueBaseName}Description${i}`; descriptionAnd.push(`COALESCE(halfWidthDescription,'') ${like} :${valueName}`); query.param[valueName] = str; } if (option.extended === true) { const valueName = `${valueBaseName}Extended${i}`; extendedAnd.push(`COALESCE(halfWidthExtended,'') ${like} :${valueName}`); query.param[valueName] = str; } }); if (nameAnd.length > 0) { or.push(`(${DBUtil.createAndQuery(nameAnd)})`); } if (descriptionAnd.length > 0) { or.push(`(${DBUtil.createAndQuery(descriptionAnd)})`); } if (extendedAnd.length > 0) { or.push(`(${DBUtil.createAndQuery(extendedAnd)})`); } } const orStr = DBUtil.createOrQuery(or); query.strs.push(isIgnore ? `(not (${orStr}))` : orStr); } /** * keyword 検査のオプションを生成する * @param option: apid.RuleSearchOption * @param isIgnore: boolean * @return KeywordOption */ private createKeywordOption(option: apid.RuleSearchOption, isIgnore: boolean): KeywordOption { const keyOption: KeywordOption = { cs: isIgnore ? !!option.ignoreKeyCS : !!option.keyCS, regexp: isIgnore ? !!option.ignoreKeyRegExp : !!option.keyRegExp, name: isIgnore ? !!option.ignoreName : !!option.name, description: isIgnore ? !!option.ignoreDescription : !!option.description, extended: isIgnore ? !!option.ignoreExtended : !!option.extended, }; if (this.op.isEnableCS() === false) { keyOption.cs = false; } if (this.op.isEnabledRegexp() === false) { keyOption.regexp = false; } return keyOption; } /** * 放送局の検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setChannelQuery(searchOption: apid.RuleSearchOption, query: FindQuery): void { if (typeof searchOption.channelIds !== 'undefined') { // in で channelId を列挙 this.createInQuery(query, 'channelId', searchOption.channelIds); } else { // in で channelType 列挙 const channelTypes: string[] = []; if (!!searchOption.GR === true) { channelTypes.push('GR'); } if (!!searchOption.BS === true) { channelTypes.push('BS'); } if (!!searchOption.CS === true) { channelTypes.push('CS'); } if (!!searchOption.SKY === true) { channelTypes.push('SKY'); } this.createInQuery(query, 'channelType', channelTypes); } } /** * ジャンルの検索オプションをセットする * @param option: apid.RuleSearchOption * @param query: FindQuery */ private setGenresQuery(option: apid.RuleSearchOption, query: FindQuery): void { if (typeof option.genres === 'undefined' || option.genres.length === 0) { return; } const strs: string[] = []; for (let i = 0; i < option.genres.length; i++) { const genreBaseName = `genre${i}`; const subGenreBaseName = `subgenre${i}`; query.param[genreBaseName] = option.genres[i].genre; if (typeof option.genres[i].subGenre === 'undefined') { strs.push( '(' + `genre1 = :${genreBaseName} or ` + `genre2 = :${genreBaseName} or ` + `genre3 = :${genreBaseName}` + ')', ); } else { strs.push( '(' + '(' + `genre1 = :${genreBaseName} and ` + `subGenre1 = :${subGenreBaseName}` + ') or ' + '(' + `genre2 = :${genreBaseName} and ` + `subGenre2 = :${subGenreBaseName}` + ') or ' + '(' + `genre3 = :${genreBaseName} and ` + `subGenre3 = :${subGenreBaseName}` + ')' + ')', ); query.param[subGenreBaseName] = option.genres[i].subGenre; } } query.strs.push(DBUtil.createOrQuery(strs)); } /** * 曜日と時刻レンジの検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setTimesQuery(option: apid.RuleSearchOption, query: FindQuery): void { if (typeof option.times === 'undefined' || option.times.length === 0) { return; } const strs: string[] = []; for (let i = 0; i < option.times.length; i++) { // 曜日 const weeks: number[] = []; if ((option.times[i].week & 0x01) !== 0) { weeks.push(0); // 日 } if ((option.times[i].week & 0x02) !== 0) { weeks.push(1); // 月 } if ((option.times[i].week & 0x04) !== 0) { weeks.push(2); // 火 } if ((option.times[i].week & 0x08) !== 0) { weeks.push(3); // 水 } if ((option.times[i].week & 0x10) !== 0) { weeks.push(4); // 木 } if ((option.times[i].week & 0x20) !== 0) { weeks.push(5); // 金 } if ((option.times[i].week & 0x40) !== 0) { weeks.push(6); // 土 } // 曜日情報がなければ無視 if (weeks.length === 0) { continue; } // 曜日情報を query に追加 const weekBaseColumnName = `week${i}`; let queryStr = `week in (:...${weekBaseColumnName})`; query.param[weekBaseColumnName] = weeks; // 時刻レンジを query に追加 const start = option.times[i].start; const range = option.times[i].range; if (typeof start !== 'undefined' && typeof range !== 'undefined') { const startHourBaseColumnName = `time${i}`; const endTime = start + range - 1; if (start === endTime) { queryStr += ` and startHour = :${startHourBaseColumnName}`; query.param[startHourBaseColumnName] = start; } else { const times: number[] = []; for (let j = start; j <= endTime; j++) { times.push(j % 24); } queryStr += `and startHour in (:...${startHourBaseColumnName})`; query.param[startHourBaseColumnName] = times; } } strs.push(`(${queryStr})`); } query.strs.push(DBUtil.createOrQuery(strs)); } /** * 無料放送の検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setFreeQuery(option: apid.RuleSearchOption, query: FindQuery): void { if (!!option.isFree === false) { return; } const column = 'isFree'; query.strs.push(`isFree = :${column}`); query.param[column] = this.op.convertBoolean(true); } /** * 動画最小長の検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setDurationMinQuery(option: apid.RuleSearchOption, query: FindQuery): void { if (typeof option.durationMin === 'undefined') { return; } const column = 'durationMin'; query.strs.push(`duration >= :${column}`); query.param[column] = option.durationMin * 1000; } /** * 動画大長の検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setDurationMaxQuery(option: apid.RuleSearchOption, query: FindQuery): void { if (typeof option.durationMax === 'undefined') { return; } const column = 'durationMax'; query.strs.push(`duration <= :${column}`); query.param[column] = option.durationMax * 1000; } /** * 検索対象期間の検索オプションをセットする * @param searchOption: apid.RuleSearchOption * @param query: FindQuery */ private setSearchPeriodsQuery(option: apid.RuleSearchOption, query: FindQuery): void { if (typeof option.searchPeriods === 'undefined' || option.searchPeriods.length === 0) { return; } const or: string[] = []; for (let i = 0; i < option.searchPeriods.length; i++) { const startAtColumn = `sarchPeriodsStartAt${i}`; const endAtColumn = `sarchPeriodsEndAt${i}`; query.param[startAtColumn] = option.searchPeriods[i].startAt; query.param[endAtColumn] = option.searchPeriods[i].endAt; or.push(`(startAt >= :${startAtColumn} and startAt <= :${endAtColumn})`); } query.strs.push(DBUtil.createOrQuery(or)); } /** * in query セット * @param query: FindQuery * @param column: 対象カラム名 * @param values: 列挙する値 */ private createInQuery(query: FindQuery, column: string, values: any[]): void { if (values.length === 0) { return; } query.strs.push(`${column} in (:...${column})`); query.param[column] = values; } /** * overlap 用 query 文字列を生成 * @param periodToAvoidDuplicate: 重複検索日数 */ private createOverlapQueryStr(periodToAvoidDuplicate: number | undefined): string { const period = typeof periodToAvoidDuplicate !== 'undefined' && periodToAvoidDuplicate > 0 ? periodToAvoidDuplicate * 24 * 60 * 60 * 1000 : 0; const now = new Date().getTime(); let str = 'case when id in ' + '(' + 'select P.id from program as P, recorded_history as R ' + 'where P.shortName = R.name ' + 'and P.channelId = R.channelId '; // 重複検索日数 if (period > 0) { str += `and R.endAt >= ${now - period} and R.endAt <= ${now} and P.endAt <= (R.endAt + ${period}) `; } else { str += `and R.endAt <= ${now} `; } str += ') then 1 else 0 end'; return str; } /** * channel Id と開始時刻を指定して番組情報を取得する * @param channelId: apid.ChannelId * @param startAt: apid.UnixtimeMS * @return Promise<Program | null> */ public async findChannelIdAndTime(channelId: apid.ChannelId, startAt: apid.UnixtimeMS): Promise<Program | null> { const connection = await this.op.getConnection(); const repository = connection.getRepository(Program); const result = await this.promieRetry.run(() => { return repository.find({ channelId: channelId, // startAt <= time && endAt >= time startAt: LessThanOrEqual(startAt), endAt: MoreThanOrEqual(startAt), }); }); return result.length === 0 ? null : result[0]; } /** * 全件取得 * @return Promise<Program[]> */ public async findAll(): Promise<Program[]> { const connection = await this.op.getConnection(); const repository = connection.getRepository(Program); return await this.promieRetry.run(() => { return repository.find({ order: { startAt: 'ASC', }, }); }); } /** * 番組表データ取得 * @param option: FindScheduleOption | FindScheduleIdOption * @return Promise<Program[]> */ public async findSchedule(option: FindScheduleOption | FindScheduleIdOption): Promise<Program[]> { const connection = await this.op.getConnection(); let queryOption: FindConditions<Program> | FindConditions<Program>[]; if (typeof (<FindScheduleIdOption>option).channelId !== 'undefined') { queryOption = { startAt: LessThanOrEqual(option.endAt), endAt: MoreThanOrEqual(option.startAt), channelId: (<FindScheduleIdOption>option).channelId, }; if (typeof option.isFree !== 'undefined') { queryOption.isFree = option.isFree; } } else if ( typeof (<FindScheduleOption>option).types !== 'undefined' && (<FindScheduleOption>option).types.length > 0 ) { queryOption = []; for (const type of (<FindScheduleOption>option).types) { const op: FindConditions<Program> = { startAt: LessThanOrEqual(option.endAt), endAt: MoreThanOrEqual(option.startAt), channelType: type, }; if (typeof option.isFree !== 'undefined') { op.isFree = option.isFree; } queryOption.push(op); } } else { throw new Error('FindScheduleOptionError'); } const repository = connection.getRepository(Program); return await this.promieRetry.run(() => { return repository.find({ where: queryOption, order: { startAt: 'ASC', }, }); }); } /** * 放映中の番組データを取得 * @param option: apid.BroadcastingScheduleOption 加算時間 (ms) * @return Promise<Program[]> */ public async findBroadcasting(option: apid.BroadcastingScheduleOption): Promise<Program[]> { let time = new Date().getTime(); if (typeof option.time !== 'undefined') { time += option.time; } const connection = await this.op.getConnection(); const repository = connection.getRepository(Program); return await this.promieRetry.run(() => { return repository.find({ where: { startAt: LessThanOrEqual(time), endAt: MoreThanOrEqual(time), }, order: { startAt: 'ASC', }, }); }); } }
the_stack
import * as path from "path"; import * as fs from "fs"; import { ECObjectsError, ECObjectsStatus, ECVersion, ISchemaLocater, Schema, SchemaContext, SchemaKey, SchemaMatchType } from "@itwin/ecschema-metadata"; import { FileSchemaKey, SchemaFileLocater, SchemaJsonFileLocater } from "@itwin/ecschema-locaters"; import { DOMParser } from "@xmldom/xmldom"; import { ECSchemaXmlContext, IModelHost } from "@itwin/core-backend"; import { ECSchemaToTs } from "./ecschema2ts"; const unitsSchemaKey = new SchemaKey("Units", 1, 0, 0); const formatsSchemaKey = new SchemaKey("Formats", 1, 0, 0); /** * The class is used to parse xml file by using native context. It converts the xml schema * to json schema and then, use Typescript side json deserialization to convert it to schema object. * @beta */ class SchemaBackendFileLocater extends SchemaFileLocater implements ISchemaLocater { private _nativeContext: ECSchemaXmlContext; public constructor(nativeContext: ECSchemaXmlContext) { super(); this._nativeContext = nativeContext; } /** * Async version of getSchemaSync() * @param key The schema key needed to locate the schema in the search path * @param matchType The SchemaMatchType * @param context The schema context used to parse schema */ public async getSchema<T extends Schema>(key: SchemaKey, matchType: SchemaMatchType, context: SchemaContext): Promise<T | undefined> { return this.getSchemaSync(key, matchType, context) as T; } /** * Attempt to retrieve a schema with the given schema key by using the configured search path. * @param key The schema key needed to locate the schema in the search path * @param matchType The SchemaMatchType * @param context The schema context used to parse schema */ public getSchemaSync<T extends Schema>(key: SchemaKey, matchType: SchemaMatchType, context: SchemaContext): T | undefined { const localPath: Set<string> = new Set<string>(); return this.getSchemaRecursively(key, matchType, context, localPath); } /** * Retrieve the schema key from schema Xml file. It looks very similar to `SchemaXmlFileLocater.getSchemaKey(string):SchemaKey` but not quite. * Because the schema version in 3.1 and below doesn't contain write version, we will have to manually add * 0 as a write version for it before converting to schema key * @param data content of the schema Xml file */ public getSchemaKey(data: string): SchemaKey { const matches = data.match(/<ECSchema ([^]+?)>/g); if (!matches || matches.length !== 1) throw new ECObjectsError(ECObjectsStatus.InvalidSchemaXML, `Could not find '<ECSchema>' tag in the given file`); // parse name and version const name = matches[0].match(/schemaName="(.+?)"/); const version = matches[0].match(/version="(.+?)"/); if (!name || name.length !== 2 || !version || version.length !== 2) throw new ECObjectsError(ECObjectsStatus.InvalidSchemaXML, `Could not find the ECSchema 'schemaName' or 'version' tag in the given file`); const versionStr: string = this.resolveECVersionString(version[1]); const key = new SchemaKey(name[1], ECVersion.fromString(versionStr)); return key; } /** * Attempt to retrieve a schema with the given schema key by using the configured search path. The locater will attempt to parse all the references first * before parsing the current schema. That way, both the native and ts side context will have all references needed to parse the current schema. * In case of cyclic dependency, it will throw error * @param key The schema key needed to locate the schema in the search path * @param matchType The SchemaMatchType * @param context The schema context used to parse schema * @param localPath The path of the recursion is following used to detect cyclic dependency */ private getSchemaRecursively<T extends Schema>(key: SchemaKey, matchType: SchemaMatchType, context: SchemaContext, localPath: Set<string>): T | undefined { // load the schema file const candidates: FileSchemaKey[] = this.findEligibleSchemaKeys(key, matchType, "xml"); if (0 === candidates.length) return undefined; const maxCandidate = candidates.sort(this.compareSchemaKeyByVersion)[candidates.length - 1]; const schemaPath = maxCandidate.fileName; if (undefined === this.fileExistsSync(schemaPath)) return undefined; // mark that schema is already visited const schemaKeyName = maxCandidate.toString(); localPath.add(schemaKeyName); // resolve all the references before beginning parsing the current schema const domParser: DOMParser = new DOMParser(); const schemaXmlDocument: Document = domParser.parseFromString(fs.readFileSync(schemaPath, "utf8")); const referenceKeys: SchemaKey[] = this.getReferenceSchemaKeys(schemaXmlDocument); for (const referenceKey of referenceKeys) { const referenceKeyName = referenceKey.toString(); // jump to the next reference if it is not visited. If it is, check if the current schema refers back to other visited schema node if (undefined === context.getSchemaSync(referenceKey, matchType)) { const referenceSchema = this.getSchemaRecursively(referenceKey, SchemaMatchType.LatestWriteCompatible, context, localPath); if (!referenceSchema) { throw new ECObjectsError(ECObjectsStatus.UnableToLocateSchema, `Could not locate reference schema, ${referenceKey.name}.${referenceKey.version.toString()} of schema ${key.name}.${key.version.toString()}`); } } else if (localPath.has(referenceKeyName)) { throw new ECObjectsError(ECObjectsStatus.InvalidSchemaXML, `Schema ${schemaKeyName} and ${referenceKeyName} form cyclic dependency`); } } localPath.delete(schemaKeyName); // it should be safe to parse the current schema because all the references are in the native context and the TS side schema context at this point const schemaJson = this._nativeContext.readSchemaFromXmlFile(schemaPath); return Schema.fromJsonSync(schemaJson, context) as T; } /** * Retrieve the reference schema keys by parsing the current Schema XML DOM * @param schemaXmlDocument Current schema XML DOM document */ private getReferenceSchemaKeys(schemaXmlDocument: Document): SchemaKey[] { const referenceDocuments = schemaXmlDocument.getElementsByTagName("ECSchemaReference"); const referenceSchemaKeys: SchemaKey[] = []; // unfortunately, for-of loop cannot work with HTMLCollectionOf<Element> type here // eslint-disable-next-line @typescript-eslint/prefer-for-of for (let i = 0; i < referenceDocuments.length; ++i) { const element = referenceDocuments[i]; const name = this.getRequiredXmlAttribute(element, "name", "The schema has an invalid ECSchemaReference attribute. One of the reference is missing the 'name' attribute"); let version = this.getRequiredXmlAttribute(element, "version", "The schema has an invalid ECSchemaReference attribute. One of the reference is missing the 'version' attribute"); version = this.resolveECVersionString(version); const key = new SchemaKey(name, ECVersion.fromString(version)); referenceSchemaKeys.push(key); } return referenceSchemaKeys; } /** * Retrieve the value of the attribute in the DOM Element * @param xmlElement The DOM Element * @param attribute The required attribute name of the DOM Element * @param errorMessage The error message if there is no attribute found in the DOM Element */ private getRequiredXmlAttribute(xmlElement: Element, attribute: string, errorMessage: string): string { const value = xmlElement.getAttribute(attribute); if (!value) throw new ECObjectsError(ECObjectsStatus.InvalidSchemaXML, errorMessage); return value; } /** * Attempt to check the ECVersion. If the ECVersion contains only read and minor version, it will add 00 to the write version. * Error will be thrown if the version format doesn't contain at least the read and minor version * @param version raw ECVersion string retrieved from the Schema XML DOM Element */ private resolveECVersionString(version: string): string { // check that version at leasts contain read and write number. If so, add 00 to the minor version if there is none existed in the version let versionNumbers: string[] = version.split("."); if (versionNumbers.length < 2) throw new ECObjectsError(ECObjectsStatus.InvalidSchemaXML, `'version' number does not at least have read and minor number in the given file`); else if (versionNumbers.length === 2) { versionNumbers.push("00"); const [readNumber, minorNumber, writeNumber] = versionNumbers; versionNumbers = [readNumber, writeNumber, minorNumber]; } return versionNumbers.join("."); } } /** * Deserializes ECXml and ECJson schema files. */ class SchemaDeserializer { /** * Deserializes the specified ECXml schema file in the given schema context. * @param schemaFilePath The path to a valid ECXml schema file. * @param schemaContext The schema context in which to deserialize the schema. * @param referencePaths Optional paths to search when locating schema references. */ public async deserializeXmlFile(schemaFilePath: string, schemaContext: SchemaContext, referencePaths?: string[]): Promise<Schema> { // If the schema file doesn't exist, throw an error if (!fs.existsSync(schemaFilePath)) throw new ECObjectsError(ECObjectsStatus.UnableToLocateSchema, `Unable to locate schema XML file at ${schemaFilePath}`); await IModelHost.startup(); // add reference paths to the native context if (undefined === referencePaths) referencePaths = []; referencePaths.push(path.dirname(schemaFilePath)); const nativeContext = new ECSchemaXmlContext(); const locater = new SchemaBackendFileLocater(nativeContext); for (const refPath of referencePaths) { locater.addSchemaSearchPath(refPath); nativeContext.addSchemaPath(refPath); } // parsing the current xml schema let schema: Schema | undefined; try { const schemaKey = locater.getSchemaKey(fs.readFileSync(schemaFilePath, "utf8")); // Units and Formats have to be added to the ts side context first because the native context will add them automatically to // the schema as references even if the schema does not use them if (!schemaKey.compareByName(unitsSchemaKey) && !schemaKey.compareByName(formatsSchemaKey)) { locater.getSchemaSync(unitsSchemaKey, SchemaMatchType.LatestWriteCompatible, schemaContext); locater.getSchemaSync(formatsSchemaKey, SchemaMatchType.LatestWriteCompatible, schemaContext); } schema = locater.getSchemaSync(schemaKey, SchemaMatchType.Exact, schemaContext); } finally { await IModelHost.shutdown(); } return schema!; } /** * Deserializes the specified ECJson schema file in the given schema context. * @param schemaFilePath The path to a valid ECJson schema file. * @param context The schema context in which to deserialize the schema. * @param referencePaths Optional paths to search when locating schema references. */ public deserializeJsonFile(schemaFilePath: string, context: SchemaContext, referencePaths?: string[]): Schema { // If the schema file doesn't exist, throw an error if (!fs.existsSync(schemaFilePath)) throw new ECObjectsError(ECObjectsStatus.UnableToLocateSchema, `Unable to locate schema JSON file at ${schemaFilePath}`); // add locater to the context if (!referencePaths) referencePaths = []; referencePaths.push(path.dirname(schemaFilePath)); const locater = new SchemaJsonFileLocater(); locater.addSchemaSearchPaths(referencePaths); context.addLocater(locater); // If the file cannot be parsed, throw an error. const schemaString = fs.readFileSync(schemaFilePath, "utf8"); let schemaJson: any; try { schemaJson = JSON.parse(schemaString); } catch (e: any) { throw new ECObjectsError(ECObjectsStatus.InvalidECJson, e.message); } return Schema.fromJsonSync(schemaJson, context); } } /** * Abstract interface to write the result of converting schema file to ts to different output (files, stdout, and so on). * Schema file path can be json or xml or both or an obscured file format depending how the concrete class interprets it. */ export interface ECSchemaToTsFileWriter { convertSchemaFile(context: SchemaContext, schemaPath: string, referencePaths?: string[]): Promise<string>; } /** * Concrete class to write ecschema2ts result to file */ export class ECSchemaToTsXmlWriter implements ECSchemaToTsFileWriter { private _ecschema2ts: ECSchemaToTs; private _deserializer: SchemaDeserializer; private _outdir: string; public constructor(outdir: string) { this._ecschema2ts = new ECSchemaToTs(); this._deserializer = new SchemaDeserializer(); this._outdir = outdir; } /** * Given a valid schema file path, the converted typescript files will be * created in the provided output directory. If the output directory does not exist the file will not be * created. * @param context Schema context used to find reference schema * @param schemaPath The full path to the ECSchema xml file * @param outdir The path to the directory to write the generated typescript file. */ public async convertSchemaFile(context: SchemaContext, schemaPath: string, referencePaths?: string[]): Promise<string> { // check if outdir is correct path if (!this._outdir) throw new Error(`The out directory ${this._outdir} is invalid.`); this._outdir = path.normalize(this._outdir) + path.sep; if (!fs.existsSync(this._outdir)) throw new Error(`The out directory ${this._outdir} does not exist.`); // convert schema to typescript String const schema = await this._deserializer.deserializeXmlFile(schemaPath, context, referencePaths); const tsString = this._ecschema2ts.convertSchemaToTs(schema); const schemaTsString = tsString.schemaTsString; const elemTsString = tsString.elemTsString; const propsTsString = tsString.propsTsString; // write to file let createdFilesLog: string = ""; const schemaFile = `${this._outdir}${schema.schemaKey.name}.ts`; fs.writeFileSync(schemaFile, schemaTsString); createdFilesLog += `Successfully created typescript file, "${schemaFile}".\r\n`; const elemFile = `${this._outdir}${schema.schemaKey.name}Elements.ts`; fs.writeFileSync(elemFile, elemTsString); createdFilesLog += `Successfully created typescript file, "${elemFile}".\r\n`; const propsElemFile = `${this._outdir}${schema.schemaKey.name}ElementProps.ts`; fs.writeFileSync(propsElemFile, propsTsString); createdFilesLog += `Successfully created typescript file, "propsElemFile".\r\n`; return createdFilesLog; } }
the_stack
const EventId = require('eventid'); import * as extend from 'extend'; import {google} from '../protos/protos'; import {objToStruct, structToObj, zuluToDateObj} from './utils/common'; import { makeHttpRequestData, CloudLoggingHttpRequest, RawHttpRequest, isRawHttpRequest, } from './utils/http-request'; import {CloudTraceContext, getOrInjectContext} from './utils/context'; const eventId = new EventId(); export const INSERT_ID_KEY = 'logging.googleapis.com/insertId'; export const LABELS_KEY = 'logging.googleapis.com/labels'; export const OPERATION_KEY = 'logging.googleapis.com/operation'; export const SOURCE_LOCATION_KEY = 'logging.googleapis.com/sourceLocation'; export const SPAN_ID_KEY = 'logging.googleapis.com/spanId'; export const TRACE_KEY = 'logging.googleapis.com/trace'; export const TRACE_SAMPLED_KEY = 'logging.googleapis.com/trace_sampled'; // Accepted field types from user supported by this client library. export type Timestamp = google.protobuf.ITimestamp | Date | string; export type LogSeverity = google.logging.type.LogSeverity | string; export type HttpRequest = | google.logging.type.IHttpRequest | CloudLoggingHttpRequest | RawHttpRequest; export type LogEntry = Omit< google.logging.v2.ILogEntry, 'timestamp' | 'severity' | 'httpRequest' > & { timestamp?: Timestamp | null; severity?: LogSeverity | null; httpRequest?: HttpRequest | null; }; // eslint-disable-next-line @typescript-eslint/no-explicit-any export type Data = any; // The expected format of a subset of Entry properties before submission to the // LoggingService API. export interface EntryJson { timestamp: Timestamp; insertId: number; jsonPayload?: google.protobuf.IStruct; textPayload?: string; httpRequest?: google.logging.type.IHttpRequest; trace?: string; spanId?: string; traceSampled?: boolean; } // The expected format of a subset of Entry properties before submission to a // custom transport, most likely to process.stdout. export interface StructuredJson { // Universally supported properties message?: string | object; httpRequest?: object; timestamp?: string; [INSERT_ID_KEY]?: string; [OPERATION_KEY]?: object; [SOURCE_LOCATION_KEY]?: object; [LABELS_KEY]?: object; [SPAN_ID_KEY]?: string; [TRACE_KEY]?: string; [TRACE_SAMPLED_KEY]?: boolean; // Properties not supported by all agents (e.g. Cloud Run, Functions) logName?: string; resource?: object; } export interface ToJsonOptions { removeCircular?: boolean; } /** * Create an entry object to define new data to insert into a meta. * * Note, {@link https://cloud.google.com/logging/quotas|Cloud Logging Quotas and limits} * dictates that the maximum log entry size, including all * {@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry|LogEntry Resource properties}, * cannot exceed approximately 256 KB. * * See {@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry|LogEntry JSON representation} * * @class * * @param {?object} [metadata] See a * [LogEntry * Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry). * @param {object|string} data The data to use as the value for this log * entry. * * If providing an object, these value types are supported: * - `String` * - `Number` * - `Boolean` * - `Buffer` * - `Object` * - `Array` * * Any other types are stringified with `String(value)`. * * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const syslog = logging.log('syslog'); * * const metadata = { * resource: { * type: 'gce_instance', * labels: { * zone: 'global', * instance_id: '3' * } * } * }; * * const entry = syslog.entry(metadata, { * delegate: 'my_username' * }); * * syslog.alert(entry, (err, apiResponse) => { * if (!err) { * // Log entry inserted successfully. * } * }); * * //- * // You will also receive `Entry` objects when using * // Logging#getEntries() and Log#getEntries(). * //- * logging.getEntries((err, entries) => { * if (!err) { * // entries[0].data = The data value from the log entry. * } * }); * ``` */ class Entry { metadata: LogEntry; data: Data; constructor(metadata?: LogEntry, data?: Data) { /** * @name Entry#metadata * @type {object} * @property {Date} timestamp * @property {number} insertId */ this.metadata = extend( { timestamp: new Date(), }, metadata ); // JavaScript date has a very coarse granularity (millisecond), which makes // it quite likely that multiple log entries would have the same timestamp. // The Logging API doesn't guarantee to preserve insertion order for entries // with the same timestamp. The service does use `insertId` as a secondary // ordering for entries with the same timestamp. `insertId` needs to be // globally unique (within the project) however. // // We use a globally unique monotonically increasing EventId as the // insertId. this.metadata.insertId = this.metadata.insertId || eventId.new(); /** * @name Entry#data * @type {object} */ this.data = data; } /** * Serialize an entry to the format the API expects. Read more: * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry * * @param {object} [options] Configuration object. * @param {boolean} [options.removeCircular] Replace circular references in an * object with a string value, `[Circular]`. * @param {string} [projectId] GCP Project ID. */ toJSON(options: ToJsonOptions = {}, projectId = '') { const entry: EntryJson = extend(true, {}, this.metadata) as {} as EntryJson; // Format log message if (Object.prototype.toString.call(this.data) === '[object Object]') { entry.jsonPayload = objToStruct(this.data, { removeCircular: !!options.removeCircular, stringify: true, }); } else if (typeof this.data === 'string') { entry.textPayload = this.data; } // Format log timestamp if (entry.timestamp instanceof Date) { const seconds = entry.timestamp.getTime() / 1000; const secondsRounded = Math.floor(seconds); entry.timestamp = { seconds: secondsRounded, nanos: Math.floor((seconds - secondsRounded) * 1e9), }; } else if (typeof entry.timestamp === 'string') { entry.timestamp = zuluToDateObj(entry.timestamp); } // Format httpRequest const req = this.metadata.httpRequest; if (isRawHttpRequest(req)) { entry.httpRequest = makeHttpRequestData(req); // Format trace and span const traceContext = this.extractTraceFromHeaders(projectId); if (traceContext) { if (!this.metadata.trace && traceContext.trace) entry.trace = traceContext.trace; if (!this.metadata.spanId && traceContext.spanId) entry.spanId = traceContext.spanId; if (this.metadata.traceSampled === undefined) entry.traceSampled = traceContext.traceSampled; } } return entry; } /** * Serialize an entry to a standard format for any transports, e.g. agents. * Read more: https://cloud.google.com/logging/docs/structured-logging */ toStructuredJSON(projectId = '') { const meta = this.metadata; // Mask out the keys that need to be renamed. /* eslint-disable @typescript-eslint/no-unused-vars */ const { textPayload, jsonPayload, insertId, trace, spanId, traceSampled, operation, sourceLocation, labels, ...validKeys } = meta; /* eslint-enable @typescript-eslint/no-unused-vars */ const entry: StructuredJson = extend(true, {}, validKeys) as {}; // Re-map keys names. entry[LABELS_KEY] = meta.labels ? Object.assign({}, meta.labels) : undefined; entry[INSERT_ID_KEY] = meta.insertId || undefined; entry[TRACE_KEY] = meta.trace || undefined; entry[SPAN_ID_KEY] = meta.spanId || undefined; entry[TRACE_SAMPLED_KEY] = 'traceSampled' in meta && meta.traceSampled !== null ? meta.traceSampled : undefined; // Format log payload. entry.message = meta.textPayload || meta.jsonPayload || meta.protoPayload || undefined; entry.message = this.data || entry.message; // Format timestamp if (meta.timestamp instanceof Date) { entry.timestamp = meta.timestamp.toISOString(); } // Format httprequest const req = meta.httpRequest; if (isRawHttpRequest(req)) { entry.httpRequest = makeHttpRequestData(req); // Detected trace context from headers if applicable. const traceContext = this.extractTraceFromHeaders(projectId); if (traceContext) { if (!entry[TRACE_KEY] && traceContext.trace) entry[TRACE_KEY] = traceContext.trace; if (!entry[SPAN_ID_KEY] && traceContext.spanId) entry[SPAN_ID_KEY] = traceContext.spanId; if (entry[TRACE_SAMPLED_KEY] === undefined) entry[TRACE_SAMPLED_KEY] = traceContext.traceSampled; } } return entry; } /** * extractTraceFromHeaders extracts trace and span information from raw HTTP * request headers only. * @private */ private extractTraceFromHeaders(projectId: string): CloudTraceContext | null { const rawReq = this.metadata.httpRequest; if (rawReq && 'headers' in rawReq) { return getOrInjectContext(rawReq, projectId, false); } return null; } /** * Create an Entry object from an API response, such as `entries:list`. * * @private * * @param {object} entry An API representation of an entry. See a * {@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry| LogEntry}. * @returns {Entry} */ static fromApiResponse_(entry: google.logging.v2.LogEntry) { let data = entry[entry.payload!]; if (entry.payload === 'jsonPayload') { data = structToObj(data); } const serializedEntry = new Entry(entry, data); if (entry.timestamp) { let ms = Number(entry.timestamp.seconds) * 1000; ms += Number(entry.timestamp.nanos) / 1e6; serializedEntry.metadata.timestamp = new Date(ms); } return serializedEntry; } } /** * Reference to the {@link Entry} class. * @name module:@google-cloud/logging.Entry * @see Entry */ export {Entry};
the_stack
* @module ViewDefinitions */ import { CompressedId64Set, Id64, Id64Array, Id64Set, Id64String, OrderedId64Iterable } from "@itwin/core-bentley"; import { BisCodeSpec, Code, CodeScopeProps, CodeSpec, ColorDef, DisplayStyle3dProps, DisplayStyle3dSettings, DisplayStyle3dSettingsProps, DisplayStyleProps, DisplayStyleSettings, PlanProjectionSettingsProps, RenderSchedule, SkyBoxImageProps, ViewFlags, } from "@itwin/core-common"; import { DefinitionElement, RenderTimeline } from "./Element"; import { IModelCloneContext } from "./IModelCloneContext"; import { IModelDb } from "./IModelDb"; /** A DisplayStyle defines the parameters for 'styling' the contents of a view. * Internally a DisplayStyle consists of a dictionary of several named 'styles' describing specific aspects of the display style as a whole. * Many ViewDefinitions may share the same DisplayStyle. * @public */ export abstract class DisplayStyle extends DefinitionElement { /** @internal */ public static override get className(): string { return "DisplayStyle"; } public abstract get settings(): DisplayStyleSettings; /** @internal */ protected constructor(props: DisplayStyleProps, iModel: IModelDb) { super(props, iModel); } /** Create a Code for a DisplayStyle given a name that is meant to be unique within the scope of the specified DefinitionModel. * @param iModel The IModelDb * @param scopeModelId The Id of the DefinitionModel that contains the DisplayStyle and provides the scope for its name. * @param codeValue The DisplayStyle name */ public static createCode(iModel: IModelDb, scopeModelId: CodeScopeProps, codeValue: string): Code { const codeSpec: CodeSpec = iModel.codeSpecs.getByName(BisCodeSpec.displayStyle); return new Code({ spec: codeSpec.id, scope: scopeModelId, value: codeValue }); } /** @alpha */ protected override collectPredecessorIds(predecessorIds: Id64Set): void { super.collectPredecessorIds(predecessorIds); for (const [id] of this.settings.subCategoryOverrides) { predecessorIds.add(id); } for (const excludedElementId of this.settings.excludedElementIds) predecessorIds.add(excludedElementId); if (this.settings.renderTimeline) { predecessorIds.add(this.settings.renderTimeline); } else { const script = this.loadScheduleScript(); if (script) script.script.discloseIds(predecessorIds); } } /** @alpha */ protected static override onCloned(context: IModelCloneContext, sourceElementProps: DisplayStyleProps, targetElementProps: DisplayStyleProps): void { super.onCloned(context, sourceElementProps, targetElementProps); if (!context.isBetweenIModels || !targetElementProps.jsonProperties?.styles) return; const settings = targetElementProps.jsonProperties.styles; if (settings.subCategoryOvr) { for (let i = 0; i < settings.subCategoryOvr.length; /* */) { const ovr = settings.subCategoryOvr[i]; ovr.subCategory = context.findTargetElementId(Id64.fromJSON(ovr.subCategory)); if (Id64.invalid === ovr.subCategory) settings.subCategoryOvr.splice(i, 1); else i++; } } if (settings.excludedElements) { const excluded: Id64Array = "string" === typeof settings.excludedElements ? CompressedId64Set.decompressArray(settings.excludedElements) : settings.excludedElements; for (let i = 0; i < excluded.length; /* */) { const remapped = context.findTargetElementId(excluded[i]); if (Id64.invalid === remapped) excluded.splice(i, 1); else excluded[i++] = remapped; } if (0 === excluded.length) delete settings.excludedElements; else settings.excludedElements = CompressedId64Set.compressIds(OrderedId64Iterable.sortArray(excluded)); } // eslint-disable-next-line deprecation/deprecation if (settings.renderTimeline) { const renderTimeline = context.findTargetElementId(settings.renderTimeline); if (Id64.isValid(renderTimeline)) settings.renderTimeline = renderTimeline; else delete settings.renderTimeline; } else if (settings.scheduleScript) { // eslint-disable-line deprecation/deprecation // eslint-disable-next-line deprecation/deprecation const scheduleScript = RenderTimeline.remapScript(context, settings.scheduleScript); if (scheduleScript.length > 0) settings.scheduleScript = scheduleScript; // eslint-disable-line deprecation/deprecation else delete settings.scheduleScript; // eslint-disable-line deprecation/deprecation } } public loadScheduleScript(): RenderSchedule.ScriptReference | undefined { let script; let sourceId; if (this.settings.renderTimeline) { const timeline = this.iModel.elements.tryGetElement<RenderTimeline>(this.settings.renderTimeline); if (timeline) { script = RenderSchedule.Script.fromJSON(timeline.scriptProps); sourceId = timeline.id; } } else if (this.settings.scheduleScriptProps) { // eslint-disable-line deprecation/deprecation // eslint-disable-next-line deprecation/deprecation script = RenderSchedule.Script.fromJSON(this.settings.scheduleScriptProps); sourceId = this.id; } return undefined !== sourceId && undefined !== script ? new RenderSchedule.ScriptReference(sourceId, script) : undefined; } } /** A DisplayStyle for 2d views. * @public */ export class DisplayStyle2d extends DisplayStyle { /** @internal */ public static override get className(): string { return "DisplayStyle2d"; } private readonly _settings: DisplayStyleSettings; public get settings(): DisplayStyleSettings { return this._settings; } /** @internal */ public constructor(props: DisplayStyleProps, iModel: IModelDb) { super(props, iModel); this._settings = new DisplayStyleSettings(this.jsonProperties); } /** Create a DisplayStyle2d for use by a ViewDefinition. * @param iModelDb The iModel * @param definitionModelId The [[DefinitionModel]] * @param name The name/CodeValue of the DisplayStyle2d * @returns The newly constructed DisplayStyle2d element. * @throws [[IModelError]] if unable to create the element. */ public static create(iModelDb: IModelDb, definitionModelId: Id64String, name: string): DisplayStyle2d { const displayStyleProps: DisplayStyleProps = { classFullName: this.classFullName, code: this.createCode(iModelDb, definitionModelId, name), model: definitionModelId, isPrivate: false, jsonProperties: { styles: { backgroundColor: 0, monochromeColor: ColorDef.white.toJSON(), viewflags: ViewFlags.defaults, }, }, }; return new DisplayStyle2d(displayStyleProps, iModelDb); } /** Insert a DisplayStyle2d for use by a ViewDefinition. * @param iModelDb Insert into this iModel * @param definitionModelId Insert the new DisplayStyle2d into this DefinitionModel * @param name The name of the DisplayStyle2d * @returns The Id of the newly inserted DisplayStyle2d element. * @throws [[IModelError]] if unable to insert the element. */ public static insert(iModelDb: IModelDb, definitionModelId: Id64String, name: string): Id64String { const displayStyle = this.create(iModelDb, definitionModelId, name); return iModelDb.elements.insertElement(displayStyle.toJSON()); } } /** Describes initial settings for a new [[DisplayStyle3d]]. * Most properties are inherited from [DisplayStyle3dSettingsProps]($common), but for backwards compatibility reasons, this interface is slightly awkward: * - It adds a `viewFlags` member that differs only in case and type from [DisplayStyleSettingsProps.viewflags]($common); and * - It extends the type of [DisplayStyleSettingsProps.backgroundColor]($common) to include [ColorDef]($common). * These idiosyncrasies will be addressed in a future version of core-backend. * @see [[DisplayStyle3d.create]]. * @public */ export interface DisplayStyleCreationOptions extends Omit<DisplayStyle3dSettingsProps, "backgroundColor" | "scheduleScript"> { /** If supplied, the [ViewFlags]($common) applied by the display style. * If undefined, [DisplayStyle3dSettingsProps.viewflags]($common) will be used if present (note the difference in case); otherwise, default-constructed [ViewFlags]($common) will be used. */ viewFlags?: ViewFlags; backgroundColor?: ColorDef | number; } /** A DisplayStyle for 3d views. * See [how to create a DisplayStyle3d]$(docs/learning/backend/CreateElements.md#DisplayStyle3d). * @public */ export class DisplayStyle3d extends DisplayStyle { /** @internal */ public static override get className(): string { return "DisplayStyle3d"; } private readonly _settings: DisplayStyle3dSettings; public get settings(): DisplayStyle3dSettings { return this._settings; } /** @internal */ public constructor(props: DisplayStyle3dProps, iModel: IModelDb) { super(props, iModel); this._settings = new DisplayStyle3dSettings(this.jsonProperties); } /** @alpha */ protected override collectPredecessorIds(predecessorIds: Id64Set): void { super.collectPredecessorIds(predecessorIds); for (const textureId of this.settings.environment.sky.textureIds) predecessorIds.add(textureId); if (this.settings.planProjectionSettings) for (const planProjectionSetting of this.settings.planProjectionSettings) predecessorIds.add(planProjectionSetting[0]); } /** @alpha */ protected static override onCloned(context: IModelCloneContext, sourceElementProps: DisplayStyle3dProps, targetElementProps: DisplayStyle3dProps): void { super.onCloned(context, sourceElementProps, targetElementProps); if (context.isBetweenIModels) { const convertTexture = (id: string) => Id64.isValidId64(id) ? context.findTargetElementId(id) : id; const skyBoxImageProps: SkyBoxImageProps | undefined = targetElementProps?.jsonProperties?.styles?.environment?.sky?.image; if (skyBoxImageProps?.texture && Id64.isValidId64(skyBoxImageProps.texture)) skyBoxImageProps.texture = convertTexture(skyBoxImageProps.texture); if (skyBoxImageProps?.textures) { skyBoxImageProps.textures.front = convertTexture(skyBoxImageProps.textures.front); skyBoxImageProps.textures.back = convertTexture(skyBoxImageProps.textures.back); skyBoxImageProps.textures.left = convertTexture(skyBoxImageProps.textures.left); skyBoxImageProps.textures.right = convertTexture(skyBoxImageProps.textures.right); skyBoxImageProps.textures.top = convertTexture(skyBoxImageProps.textures.top); skyBoxImageProps.textures.bottom = convertTexture(skyBoxImageProps.textures.bottom); } if (targetElementProps?.jsonProperties?.styles?.planProjections) { const remappedPlanProjections: { [modelId: string]: PlanProjectionSettingsProps } = {}; for (const entry of Object.entries(targetElementProps.jsonProperties.styles.planProjections)) { const remappedModelId: Id64String = context.findTargetElementId(entry[0]); if (Id64.isValidId64(remappedModelId)) { remappedPlanProjections[remappedModelId] = entry[1]; } } targetElementProps.jsonProperties.styles.planProjections = remappedPlanProjections; } } } /** Create a DisplayStyle3d for use by a ViewDefinition. * @param iModelDb The iModel * @param definitionModelId The [[DefinitionModel]] * @param name The name/CodeValue of the DisplayStyle3d * @returns The newly constructed DisplayStyle3d element. * @throws [[IModelError]] if unable to create the element. */ public static create(iModelDb: IModelDb, definitionModelId: Id64String, name: string, options?: DisplayStyleCreationOptions): DisplayStyle3d { options = options ?? {}; let viewflags = options.viewFlags?.toJSON(); if (!viewflags) viewflags = options.viewflags ?? new ViewFlags().toJSON(); const backgroundColor = options.backgroundColor instanceof ColorDef ? options.backgroundColor.toJSON() : options.backgroundColor; const settings: DisplayStyle3dSettingsProps = { ...options, viewflags, backgroundColor, }; const displayStyleProps: DisplayStyle3dProps = { classFullName: this.classFullName, code: this.createCode(iModelDb, definitionModelId, name), model: definitionModelId, jsonProperties: { styles: settings }, isPrivate: false, }; return new DisplayStyle3d(displayStyleProps, iModelDb); } /** * Insert a DisplayStyle3d for use by a ViewDefinition. * @param iModelDb Insert into this iModel * @param definitionModelId Insert the new DisplayStyle3d into this [[DefinitionModel]] * @param name The name of the DisplayStyle3d * @returns The Id of the newly inserted DisplayStyle3d element. * @throws [[IModelError]] if unable to insert the element. */ public static insert(iModelDb: IModelDb, definitionModelId: Id64String, name: string, options?: DisplayStyleCreationOptions): Id64String { const displayStyle = this.create(iModelDb, definitionModelId, name, options); return iModelDb.elements.insertElement(displayStyle.toJSON()); } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Trigger Schedule inside a Azure Data Factory. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleFactory = new azure.datafactory.Factory("exampleFactory", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * }); * const testPipeline = new azure.datafactory.Pipeline("testPipeline", { * resourceGroupName: azurerm_resource_group.test.name, * dataFactoryId: azurerm_data_factory.test.id, * }); * const testTriggerSchedule = new azure.datafactory.TriggerSchedule("testTriggerSchedule", { * dataFactoryId: azurerm_data_factory.test.id, * resourceGroupName: azurerm_resource_group.test.name, * pipelineName: testPipeline.name, * interval: 5, * frequency: "Day", * }); * ``` * * ## Import * * Data Factory Schedule Trigger can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:datafactory/triggerSchedule:TriggerSchedule example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/triggers/example * ``` */ export class TriggerSchedule extends pulumi.CustomResource { /** * Get an existing TriggerSchedule resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: TriggerScheduleState, opts?: pulumi.CustomResourceOptions): TriggerSchedule { return new TriggerSchedule(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:datafactory/triggerSchedule:TriggerSchedule'; /** * Returns true if the given object is an instance of TriggerSchedule. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is TriggerSchedule { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === TriggerSchedule.__pulumiType; } /** * Specifies if the Data Factory Schedule Trigger is activated. Defaults to `true`. */ public readonly activated!: pulumi.Output<boolean>; /** * List of tags that can be used for describing the Data Factory Schedule Trigger. */ public readonly annotations!: pulumi.Output<string[] | undefined>; /** * The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource. */ public readonly dataFactoryId!: pulumi.Output<string>; /** * The Data Factory name in which to associate the Linked Service with. Changing this forces a new resource. * * @deprecated `data_factory_name` is deprecated in favour of `data_factory_id` and will be removed in version 3.0 of the AzureRM provider */ public readonly dataFactoryName!: pulumi.Output<string>; /** * The Schedule Trigger's description. */ public readonly description!: pulumi.Output<string | undefined>; /** * The time the Schedule Trigger should end. The time will be represented in UTC. */ public readonly endTime!: pulumi.Output<string | undefined>; /** * The trigger frequency. Valid values include `Minute`, `Hour`, `Day`, `Week`, `Month`. Defaults to `Minute`. */ public readonly frequency!: pulumi.Output<string | undefined>; /** * The interval for how often the trigger occurs. This defaults to 1. */ public readonly interval!: pulumi.Output<number | undefined>; /** * Specifies the name of the Data Factory Schedule Trigger. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions. */ public readonly name!: pulumi.Output<string>; /** * The Data Factory Pipeline name that the trigger will act on. */ public readonly pipelineName!: pulumi.Output<string>; /** * The pipeline parameters that the trigger will act upon. */ public readonly pipelineParameters!: pulumi.Output<{[key: string]: string} | undefined>; /** * The name of the resource group in which to create the Data Factory Schedule Trigger. Changing this forces a new resource */ public readonly resourceGroupName!: pulumi.Output<string>; /** * A `schedule` block as defined below, which further specifies the recurrence schedule for the trigger. A schedule is capable of limiting or increasing the number of trigger executions specified by the `frequency` and `interval` properties. */ public readonly schedule!: pulumi.Output<outputs.datafactory.TriggerScheduleSchedule | undefined>; /** * The time the Schedule Trigger will start. This defaults to the current time. The time will be represented in UTC. */ public readonly startTime!: pulumi.Output<string>; /** * Create a TriggerSchedule resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: TriggerScheduleArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: TriggerScheduleArgs | TriggerScheduleState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as TriggerScheduleState | undefined; inputs["activated"] = state ? state.activated : undefined; inputs["annotations"] = state ? state.annotations : undefined; inputs["dataFactoryId"] = state ? state.dataFactoryId : undefined; inputs["dataFactoryName"] = state ? state.dataFactoryName : undefined; inputs["description"] = state ? state.description : undefined; inputs["endTime"] = state ? state.endTime : undefined; inputs["frequency"] = state ? state.frequency : undefined; inputs["interval"] = state ? state.interval : undefined; inputs["name"] = state ? state.name : undefined; inputs["pipelineName"] = state ? state.pipelineName : undefined; inputs["pipelineParameters"] = state ? state.pipelineParameters : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["schedule"] = state ? state.schedule : undefined; inputs["startTime"] = state ? state.startTime : undefined; } else { const args = argsOrState as TriggerScheduleArgs | undefined; if ((!args || args.pipelineName === undefined) && !opts.urn) { throw new Error("Missing required property 'pipelineName'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["activated"] = args ? args.activated : undefined; inputs["annotations"] = args ? args.annotations : undefined; inputs["dataFactoryId"] = args ? args.dataFactoryId : undefined; inputs["dataFactoryName"] = args ? args.dataFactoryName : undefined; inputs["description"] = args ? args.description : undefined; inputs["endTime"] = args ? args.endTime : undefined; inputs["frequency"] = args ? args.frequency : undefined; inputs["interval"] = args ? args.interval : undefined; inputs["name"] = args ? args.name : undefined; inputs["pipelineName"] = args ? args.pipelineName : undefined; inputs["pipelineParameters"] = args ? args.pipelineParameters : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["schedule"] = args ? args.schedule : undefined; inputs["startTime"] = args ? args.startTime : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(TriggerSchedule.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering TriggerSchedule resources. */ export interface TriggerScheduleState { /** * Specifies if the Data Factory Schedule Trigger is activated. Defaults to `true`. */ activated?: pulumi.Input<boolean>; /** * List of tags that can be used for describing the Data Factory Schedule Trigger. */ annotations?: pulumi.Input<pulumi.Input<string>[]>; /** * The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource. */ dataFactoryId?: pulumi.Input<string>; /** * The Data Factory name in which to associate the Linked Service with. Changing this forces a new resource. * * @deprecated `data_factory_name` is deprecated in favour of `data_factory_id` and will be removed in version 3.0 of the AzureRM provider */ dataFactoryName?: pulumi.Input<string>; /** * The Schedule Trigger's description. */ description?: pulumi.Input<string>; /** * The time the Schedule Trigger should end. The time will be represented in UTC. */ endTime?: pulumi.Input<string>; /** * The trigger frequency. Valid values include `Minute`, `Hour`, `Day`, `Week`, `Month`. Defaults to `Minute`. */ frequency?: pulumi.Input<string>; /** * The interval for how often the trigger occurs. This defaults to 1. */ interval?: pulumi.Input<number>; /** * Specifies the name of the Data Factory Schedule Trigger. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions. */ name?: pulumi.Input<string>; /** * The Data Factory Pipeline name that the trigger will act on. */ pipelineName?: pulumi.Input<string>; /** * The pipeline parameters that the trigger will act upon. */ pipelineParameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name of the resource group in which to create the Data Factory Schedule Trigger. Changing this forces a new resource */ resourceGroupName?: pulumi.Input<string>; /** * A `schedule` block as defined below, which further specifies the recurrence schedule for the trigger. A schedule is capable of limiting or increasing the number of trigger executions specified by the `frequency` and `interval` properties. */ schedule?: pulumi.Input<inputs.datafactory.TriggerScheduleSchedule>; /** * The time the Schedule Trigger will start. This defaults to the current time. The time will be represented in UTC. */ startTime?: pulumi.Input<string>; } /** * The set of arguments for constructing a TriggerSchedule resource. */ export interface TriggerScheduleArgs { /** * Specifies if the Data Factory Schedule Trigger is activated. Defaults to `true`. */ activated?: pulumi.Input<boolean>; /** * List of tags that can be used for describing the Data Factory Schedule Trigger. */ annotations?: pulumi.Input<pulumi.Input<string>[]>; /** * The Data Factory ID in which to associate the Linked Service with. Changing this forces a new resource. */ dataFactoryId?: pulumi.Input<string>; /** * The Data Factory name in which to associate the Linked Service with. Changing this forces a new resource. * * @deprecated `data_factory_name` is deprecated in favour of `data_factory_id` and will be removed in version 3.0 of the AzureRM provider */ dataFactoryName?: pulumi.Input<string>; /** * The Schedule Trigger's description. */ description?: pulumi.Input<string>; /** * The time the Schedule Trigger should end. The time will be represented in UTC. */ endTime?: pulumi.Input<string>; /** * The trigger frequency. Valid values include `Minute`, `Hour`, `Day`, `Week`, `Month`. Defaults to `Minute`. */ frequency?: pulumi.Input<string>; /** * The interval for how often the trigger occurs. This defaults to 1. */ interval?: pulumi.Input<number>; /** * Specifies the name of the Data Factory Schedule Trigger. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions. */ name?: pulumi.Input<string>; /** * The Data Factory Pipeline name that the trigger will act on. */ pipelineName: pulumi.Input<string>; /** * The pipeline parameters that the trigger will act upon. */ pipelineParameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The name of the resource group in which to create the Data Factory Schedule Trigger. Changing this forces a new resource */ resourceGroupName: pulumi.Input<string>; /** * A `schedule` block as defined below, which further specifies the recurrence schedule for the trigger. A schedule is capable of limiting or increasing the number of trigger executions specified by the `frequency` and `interval` properties. */ schedule?: pulumi.Input<inputs.datafactory.TriggerScheduleSchedule>; /** * The time the Schedule Trigger will start. This defaults to the current time. The time will be represented in UTC. */ startTime?: pulumi.Input<string>; }
the_stack
import { LearnerDashboardActivityIds, LearnerDashboardActivityIdsDict } from 'domain/learner_dashboard/learner-dashboard-activity-ids.model'; describe('Learner dashboard activity ids model', () => { let learnerDashboardActivityIdsDict: LearnerDashboardActivityIdsDict; beforeEach(() => { learnerDashboardActivityIdsDict = { incomplete_exploration_ids: ['0', '1'], incomplete_collection_ids: ['2', '3'], partially_learnt_topic_ids: ['4', '5'], completed_exploration_ids: ['6', '7'], completed_collection_ids: ['8', '9'], completed_story_ids: ['10', '11'], learnt_topic_ids: ['12', '13'], exploration_playlist_ids: ['14', '15'], collection_playlist_ids: ['16', '17'], topic_ids_to_learn: ['18', '19'], all_topic_ids: ['20', '21'], untracked_topic_ids: ['22', '23'] }; }); it('should check if activity id is present among learner dashboard ' + 'activity ids', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.includesActivity('0')).toEqual(true); expect(learnerDashboardActivityIds.includesActivity('1')).toEqual(true); expect(learnerDashboardActivityIds.includesActivity('8')).toEqual(true); expect(learnerDashboardActivityIds.includesActivity('24')).toEqual(false); expect(learnerDashboardActivityIds.includesActivity('25')).toEqual(false); expect(learnerDashboardActivityIds.includesActivity('26')).toEqual(false); }); it('should add exploration to learner playlist', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); learnerDashboardActivityIds.addToExplorationLearnerPlaylist('12'); expect(learnerDashboardActivityIds.explorationPlaylistIds).toEqual( ['14', '15', '12']); learnerDashboardActivityIds.addToExplorationLearnerPlaylist('13'); expect(learnerDashboardActivityIds.explorationPlaylistIds).toEqual( ['14', '15', '12', '13']); }); it('should add collection to learner playlist', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); learnerDashboardActivityIds.addToCollectionLearnerPlaylist('12'); expect(learnerDashboardActivityIds.collectionPlaylistIds).toEqual( ['16', '17', '12']); learnerDashboardActivityIds.addToCollectionLearnerPlaylist('13'); expect(learnerDashboardActivityIds.collectionPlaylistIds).toEqual( ['16', '17', '12', '13']); }); it('should remove exploration from learner playlist', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); learnerDashboardActivityIds.removeFromExplorationLearnerPlaylist('14'); expect(learnerDashboardActivityIds.explorationPlaylistIds).toEqual( ['15']); learnerDashboardActivityIds.removeFromExplorationLearnerPlaylist('15'); expect(learnerDashboardActivityIds.explorationPlaylistIds).toEqual([]); }); it('should remove collection from learner playlist', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); learnerDashboardActivityIds.removeFromCollectionLearnerPlaylist('16'); expect(learnerDashboardActivityIds.collectionPlaylistIds).toEqual( ['17']); learnerDashboardActivityIds.removeFromCollectionLearnerPlaylist('17'); expect(learnerDashboardActivityIds.collectionPlaylistIds).toEqual([]); }); it('should remove topic from learn', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); learnerDashboardActivityIds.removeTopicFromLearn('18'); expect(learnerDashboardActivityIds.topicIdsToLearn).toEqual( ['19']); learnerDashboardActivityIds.removeTopicFromLearn('19'); expect(learnerDashboardActivityIds.topicIdsToLearn).toEqual([]); }); it('should fetch the learner dashboard activity ids domain object from ' + 'the backend summary dict', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.incompleteExplorationIds).toEqual( ['0', '1']); expect(learnerDashboardActivityIds.incompleteCollectionIds).toEqual( ['2', '3']); expect(learnerDashboardActivityIds.partiallyLearntTopicIds).toEqual( ['4', '5']); expect(learnerDashboardActivityIds.completedExplorationIds).toEqual( ['6', '7']); expect(learnerDashboardActivityIds.completedCollectionIds).toEqual( ['8', '9']); expect(learnerDashboardActivityIds.completedStoryIds).toEqual( ['10', '11']); expect(learnerDashboardActivityIds.learntTopicIds).toEqual( ['12', '13']); expect(learnerDashboardActivityIds.explorationPlaylistIds).toEqual( ['14', '15']); expect(learnerDashboardActivityIds.collectionPlaylistIds).toEqual( ['16', '17']); }); it('should check if explorationId belongs to exploration playlist', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('14')) .toBe(true); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('15')) .toBe(true); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('6')) .toBe(false); expect(learnerDashboardActivityIds.belongsToExplorationPlaylist('10')) .toBe(false); }); it('should check if collectionId belongs to collection playlist', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('16')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('17')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('6')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCollectionPlaylist('8')) .toBe(false); }); it('should check if topicId belongs to learn', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('18')) .toBe(true); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('19')) .toBe(true); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('6')) .toBe(false); expect(learnerDashboardActivityIds.belongsToTopicsToLearn('10')) .toBe(false); }); it('should check if explorationId belongs to completed explorations', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('6')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('7')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('5')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('8')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedExplorations('10')) .toBe(false); }); it('should check if collectionId belongs to completed collections', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToCompletedCollections('8')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCompletedCollections('9')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCompletedCollections('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedCollections('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedCollections('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedCollections('7')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedCollections('12')) .toBe(false); }); it('should check if storyId belongs to completed stories', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToCompletedStories('10')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCompletedStories('11')) .toBe(true); expect(learnerDashboardActivityIds.belongsToCompletedStories('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedStories('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedStories('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedStories('8')) .toBe(false); expect(learnerDashboardActivityIds.belongsToCompletedStories('12')) .toBe(false); }); it('should check if topicId belongs to learnt topics', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToLearntTopics('12')) .toBe(true); expect(learnerDashboardActivityIds.belongsToLearntTopics('13')) .toBe(true); expect(learnerDashboardActivityIds.belongsToLearntTopics('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToLearntTopics('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToLearntTopics('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToLearntTopics('8')) .toBe(false); expect(learnerDashboardActivityIds.belongsToLearntTopics('11')) .toBe(false); }); it('should check if explorationId belongs to incomplete explorations', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('0')) .toBe(true); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('1')) .toBe(true); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('6')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('8')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteExplorations('10')) .toBe(false); }); it('should check if collectionId belongs to incomplete collections', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('2')) .toBe(true); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('3')) .toBe(true); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('4')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('6')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('8')) .toBe(false); expect(learnerDashboardActivityIds.belongsToIncompleteCollections('10')) .toBe(false); }); it('should check if topicsId belongs to partially learnt topics', () => { var learnerDashboardActivityIds = ( LearnerDashboardActivityIds.createFromBackendDict( learnerDashboardActivityIdsDict)); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('4')) .toBe(true); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('5')) .toBe(true); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('0')) .toBe(false); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('2')) .toBe(false); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('3')) .toBe(false); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('8')) .toBe(false); expect(learnerDashboardActivityIds.belongsToPartiallyLearntTopics('10')) .toBe(false); }); });
the_stack
import * as vscode from 'vscode'; import { CreateParams, CreatePullRequest, RemoteInfo } from '../../common/views'; import type { Branch } from '../api/api'; import Logger from '../common/logger'; import { Protocol } from '../common/protocol'; import { Remote } from '../common/remote'; import { ASSIGN_TO } from '../common/settingKeys'; import { getNonce, IRequestMessage, WebviewViewBase } from '../common/webview'; import { byRemoteName, DetachedHeadError, FolderRepositoryManager, PullRequestDefaults, SETTINGS_NAMESPACE, titleAndBodyFrom, } from './folderRepositoryManager'; import { RepoAccessAndMergeMethods } from './interface'; import { PullRequestModel } from './pullRequestModel'; import { getDefaultMergeMethod } from './pullRequestOverview'; import { variableSubstitution } from './utils'; export class CreatePullRequestViewProvider extends WebviewViewBase implements vscode.WebviewViewProvider { public readonly viewType = 'github:createPullRequest'; private _onDone = new vscode.EventEmitter<PullRequestModel | undefined>(); readonly onDone: vscode.Event<PullRequestModel | undefined> = this._onDone.event; private _onDidChangeBaseRemote = new vscode.EventEmitter<RemoteInfo>(); readonly onDidChangeBaseRemote: vscode.Event<RemoteInfo> = this._onDidChangeBaseRemote.event; private _onDidChangeBaseBranch = new vscode.EventEmitter<string>(); readonly onDidChangeBaseBranch: vscode.Event<string> = this._onDidChangeBaseBranch.event; private _onDidChangeCompareRemote = new vscode.EventEmitter<RemoteInfo>(); readonly onDidChangeCompareRemote: vscode.Event<RemoteInfo> = this._onDidChangeCompareRemote.event; private _onDidChangeCompareBranch = new vscode.EventEmitter<string>(); readonly onDidChangeCompareBranch: vscode.Event<string> = this._onDidChangeCompareBranch.event; private _compareBranch: string; private _baseBranch: string; private _firstLoad: boolean = true; constructor( extensionUri: vscode.Uri, private readonly _folderRepositoryManager: FolderRepositoryManager, private readonly _pullRequestDefaults: PullRequestDefaults, compareBranch: Branch, ) { super(extensionUri); this._defaultCompareBranch = compareBranch; } public resolveWebviewView( webviewView: vscode.WebviewView, _context: vscode.WebviewViewResolveContext, _token: vscode.CancellationToken, ) { super.resolveWebviewView(webviewView, _context, _token); webviewView.webview.html = this._getHtmlForWebview(); if (this._firstLoad) { this._firstLoad = false; // Reset any stored state. // TODO @RMacfarlane Clear stored state on extension deactivation instead. this.initializeParams(true); } else { this.initializeParams(); } } private _defaultCompareBranch: Branch; get defaultCompareBranch() { return this._defaultCompareBranch; } set defaultCompareBranch(compareBranch: Branch | undefined) { if ( compareBranch && (compareBranch?.name !== this._defaultCompareBranch.name || compareBranch?.upstream?.remote !== this._defaultCompareBranch.upstream?.remote) ) { this._defaultCompareBranch = compareBranch; void this.initializeParams(); this._onDidChangeCompareBranch.fire(this._defaultCompareBranch.name!); } } public show(compareBranch?: Branch): void { if (compareBranch) { this.defaultCompareBranch = compareBranch; } super.show(); } private async getTotalGitHubCommits(compareBranch: Branch, baseBranchName: string): Promise<number | undefined> { const origin = await this._folderRepositoryManager.getOrigin(compareBranch); if (compareBranch.upstream) { const headRepo = this._folderRepositoryManager.findRepo(byRemoteName(compareBranch.upstream.remote)); if (headRepo) { const headBranch = `${headRepo.remote.owner}:${compareBranch.name ?? ''}`; const baseBranch = `${this._pullRequestDefaults.owner}:${baseBranchName}`; const compareResult = await origin.compareCommits(baseBranch, headBranch); return compareResult?.total_commits; } } return undefined; } private async getTitleAndDescription(compareBranch: Branch, baseBranch: string): Promise<{ title: string, description: string }> { let title: string = ''; let description: string = ''; // Use same default as GitHub, if there is only one commit, use the commit, otherwise use the branch name, as long as it is not the default branch. // By default, the base branch we use for comparison is the base branch of origin. Compare this to the // compare branch if it has a GitHub remote. const origin = await this._folderRepositoryManager.getOrigin(compareBranch); let useBranchName = this._pullRequestDefaults.base === compareBranch.name; Logger.debug(`Compare branch name: ${compareBranch.name}, Base branch name: ${this._pullRequestDefaults.base}`, 'CreatePullRequestViewProvider'); try { const name = compareBranch.name; const [totalCommits, lastCommit, pullRequestTemplate] = await Promise.all([ this.getTotalGitHubCommits(compareBranch, baseBranch), name ? titleAndBodyFrom(await this._folderRepositoryManager.getTipCommitMessage(name)) : undefined, await this.getPullRequestTemplate() ]); Logger.debug(`Total commits: ${totalCommits}`, 'CreatePullRequestViewProvider'); if (totalCommits === undefined) { // There is no upstream branch. Use the last commit as the title and description. useBranchName = false; } else if (totalCommits > 1) { const defaultBranch = await origin.getDefaultBranch(); useBranchName = defaultBranch !== compareBranch.name; } // Set title if (useBranchName && name) { title = `${name.charAt(0).toUpperCase()}${name.slice(1)}`; } else if (name && lastCommit) { title = lastCommit.title; } // Set description if (pullRequestTemplate && lastCommit?.body) { description = `${lastCommit.body}\n\n${pullRequestTemplate}`; } else if (pullRequestTemplate) { description = pullRequestTemplate; } else if (lastCommit?.body && (this._pullRequestDefaults.base !== compareBranch.name)) { description = lastCommit.body; } } catch (e) { // Ignore and fall back to commit message Logger.debug(`Error while getting total commits: ${e}`, 'CreatePullRequestViewProvider'); } return { title, description }; } private async getPullRequestTemplate(): Promise<string | undefined> { const templateUris = await this._folderRepositoryManager.getPullRequestTemplates(); if (templateUris[0]) { try { const templateContent = await vscode.workspace.fs.readFile(templateUris[0]); return new TextDecoder('utf-8').decode(templateContent); } catch (e) { Logger.appendLine(`Reading pull request template failed: ${e}`); return undefined; } } return undefined; } private async getMergeConfiguration(owner: string, name: string): Promise<RepoAccessAndMergeMethods> { const repo = this._folderRepositoryManager.createGitHubRepositoryFromOwnerName(owner, name); return repo.getRepoAccessAndMergeMethods(); } public async initializeParams(reset: boolean = false): Promise<void> { // Do the fast initialization first, then update with the slower initialization. const params = await this.initializeParamsFast(reset); this.initializeParamsSlow(params); } private async initializeParamsSlow(params: CreateParams): Promise<void> { if (!this.defaultCompareBranch) { throw new DetachedHeadError(this._folderRepositoryManager.repository); } if (!params.defaultBaseRemote || !params.defaultCompareRemote) { throw new Error('Create Pull Request view unable to initialize without default remotes.'); } const defaultOrigin = await this._folderRepositoryManager.getOrigin(this.defaultCompareBranch); const branchesForRemote = await defaultOrigin.listBranches(this._pullRequestDefaults.owner, this._pullRequestDefaults.repo); // Ensure default into branch is in the remotes list if (!branchesForRemote.includes(this._pullRequestDefaults.base)) { branchesForRemote.push(this._pullRequestDefaults.base); branchesForRemote.sort(); } let branchesForCompare = branchesForRemote; if (params.defaultCompareRemote.owner !== params.defaultBaseRemote.owner) { branchesForCompare = await defaultOrigin.listBranches( params.defaultCompareRemote.owner, params.defaultCompareRemote.repositoryName, ); } // Ensure default from branch is in the remotes list if (this.defaultCompareBranch.name && !branchesForCompare.includes(this.defaultCompareBranch.name)) { branchesForCompare.push(this.defaultCompareBranch.name); branchesForCompare.sort(); } params.branchesForRemote = branchesForRemote; params.branchesForCompare = branchesForCompare; this._postMessage({ command: 'pr.initialize', params, }); } private async initializeParamsFast(reset: boolean = false): Promise<CreateParams> { if (!this.defaultCompareBranch) { throw new DetachedHeadError(this._folderRepositoryManager.repository); } const defaultBaseRemote: RemoteInfo = { owner: this._pullRequestDefaults.owner, repositoryName: this._pullRequestDefaults.repo, }; const defaultOrigin = await this._folderRepositoryManager.getOrigin(this.defaultCompareBranch); const defaultCompareRemote: RemoteInfo = { owner: defaultOrigin.remote.owner, repositoryName: defaultOrigin.remote.repositoryName, }; const defaultBaseBranch = this._pullRequestDefaults.base; const [configuredGitHubRemotes, allGitHubRemotes, defaultTitleAndDescription, mergeConfiguration] = await Promise.all([ this._folderRepositoryManager.getGitHubRemotes(), this._folderRepositoryManager.getAllGitHubRemotes(), this.getTitleAndDescription(this.defaultCompareBranch, defaultBaseBranch), this.getMergeConfiguration(defaultBaseRemote.owner, defaultBaseRemote.repositoryName) ]); const configuredRemotes: RemoteInfo[] = configuredGitHubRemotes.map(remote => { return { owner: remote.owner, repositoryName: remote.repositoryName, }; }); const allRemotes: RemoteInfo[] = allGitHubRemotes.map(remote => { return { owner: remote.owner, repositoryName: remote.repositoryName, }; }); const defaultCompareBranch = this.defaultCompareBranch.name ?? ''; const params: CreateParams = { availableBaseRemotes: configuredRemotes, availableCompareRemotes: allRemotes, defaultBaseRemote, defaultBaseBranch, defaultCompareRemote, defaultCompareBranch, branchesForRemote: [defaultBaseBranch], // We'll populate the branches in the slow phase as they are less likely to be needed. branchesForCompare: [defaultCompareBranch], defaultTitle: defaultTitleAndDescription.title, defaultDescription: defaultTitleAndDescription.description, isDraft: false, defaultMergeMethod: getDefaultMergeMethod(mergeConfiguration.mergeMethodsAvailability), allowAutoMerge: mergeConfiguration.viewerCanAutoMerge, mergeMethodsAvailability: mergeConfiguration.mergeMethodsAvailability, createError: '' }; this._compareBranch = this.defaultCompareBranch.name ?? ''; this._baseBranch = defaultBaseBranch; this._postMessage({ command: reset ? 'reset' : 'pr.initialize', params, }); return params; } private async changeRemote( message: IRequestMessage<{ owner: string; repositoryName: string }>, isBase: boolean, ): Promise<void> { const { owner, repositoryName } = message.args; let githubRepository = this._folderRepositoryManager.findRepo( repo => owner === repo.remote.owner && repositoryName === repo.remote.repositoryName, ); if (!githubRepository) { githubRepository = this._folderRepositoryManager.createGitHubRepositoryFromOwnerName(owner, repositoryName); } if (!githubRepository) { throw new Error('No matching GitHub repository found.'); } const defaultBranch = await githubRepository.getDefaultBranch(); const newBranches = await githubRepository.listBranches(owner, repositoryName); if (!isBase && this.defaultCompareBranch?.name && !newBranches.includes(this.defaultCompareBranch.name)) { newBranches.push(this.defaultCompareBranch.name); newBranches.sort(); } let newBranch: string | undefined; if (isBase) { newBranch = defaultBranch; this._baseBranch = defaultBranch; this._onDidChangeBaseRemote.fire({ owner, repositoryName }); this._onDidChangeBaseBranch.fire(defaultBranch); } else { if (this.defaultCompareBranch?.name) { newBranch = this.defaultCompareBranch?.name; this._compareBranch = this.defaultCompareBranch?.name; } this._onDidChangeCompareRemote.fire({ owner, repositoryName }); } // TODO: if base is change need to update auto merge return this._replyMessage(message, { branches: newBranches, defaultBranch: newBranch }); } private async autoAssign(pr: PullRequestModel): Promise<void> { const configuration = vscode.workspace.getConfiguration(SETTINGS_NAMESPACE).get<string | undefined>(ASSIGN_TO); if (!configuration) { return; } const resolved = await variableSubstitution(configuration, pr, undefined, this._folderRepositoryManager.getCurrentUser(pr.githubRepository)?.login); if (!resolved) { return; } try { await pr.updateAssignees([resolved]); } catch (e) { vscode.window.showErrorMessage(`Unable to assign pull request to user ${resolved}.`); } } private async create(message: IRequestMessage<CreatePullRequest>): Promise<void> { try { const compareOwner = message.args.compareOwner; const compareRepositoryName = message.args.compareRepo; const compareBranchName = message.args.compareBranch; const compareGithubRemoteName = `${compareOwner}/${compareRepositoryName}`; const compareBranch = await this._folderRepositoryManager.repository.getBranch(compareBranchName); let headRepo = compareBranch.upstream ? this._folderRepositoryManager.findRepo((githubRepo) => { return (githubRepo.remote.owner === compareOwner) && (githubRepo.remote.repositoryName === compareRepositoryName); }) : undefined; let existingCompareUpstream = headRepo?.remote; if (!existingCompareUpstream || (existingCompareUpstream.owner !== compareOwner) || (existingCompareUpstream.repositoryName !== compareRepositoryName)) { // We assume this happens only when the compare branch is based on the current branch. const shouldPushUpstream = await vscode.window.showInformationMessage( `There is no upstream branch for '${compareBranchName}'.\n\nDo you want to publish it and then create the pull request?`, { modal: true }, 'Publish Branch', ); if (shouldPushUpstream === 'Publish Branch') { let createdPushRemote: Remote | undefined; const pushRemote = this._folderRepositoryManager.repository.state.remotes.find(localRemote => { if (!localRemote.pushUrl) { return false; } const testRemote = new Remote(localRemote.name, localRemote.pushUrl, new Protocol(localRemote.pushUrl)); if ((testRemote.owner.toLowerCase() === compareOwner.toLowerCase()) && (testRemote.repositoryName.toLowerCase() === compareRepositoryName.toLowerCase())) { createdPushRemote = testRemote; return true; } return false; }); if (pushRemote && createdPushRemote) { Logger.appendLine(`Found push remote ${pushRemote.name} for ${compareOwner}/${compareRepositoryName} and branch ${compareBranchName}`, 'CreatePullRequestViewProvider'); await this._folderRepositoryManager.repository.push(pushRemote.name, compareBranchName, true); existingCompareUpstream = createdPushRemote; headRepo = this._folderRepositoryManager.findRepo(byRemoteName(existingCompareUpstream.remoteName)); } else { this._throwError(message, `The current repository does not have a push remote for ${compareGithubRemoteName}`); } } } if (!existingCompareUpstream) { this._throwError(message, 'No upstream for the compare branch.'); return; } if (!headRepo) { throw new Error(`Unable to find GitHub repository matching '${existingCompareUpstream.remoteName}'. You can add '${existingCompareUpstream.remoteName}' to the setting "githubPullRequests.remotes" to ensure '${existingCompareUpstream.remoteName}' is found.`); } const head = `${headRepo.remote.owner}:${compareBranchName}`; const createdPR = await this._folderRepositoryManager.createPullRequest({ ...message.args, head }); // Create was cancelled if (!createdPR) { this._throwError(message, 'There must be a difference in commits to create a pull request.'); } else { if (message.args.autoMerge) { await createdPR.enableAutoMerge(message.args.mergeMethod); } await this.autoAssign(createdPR); await this._replyMessage(message, {}); this._onDone.fire(createdPR); } } catch (e) { this._throwError(message, e.message); } } private async changeBranch(message: IRequestMessage<string | { name: string }>, isBase: boolean): Promise<void> { const newBranch = (typeof message.args === 'string') ? message.args : message.args.name; let compareBranch: Branch | undefined; if (isBase) { this._baseBranch = newBranch; this._onDidChangeBaseBranch.fire(newBranch); } else { try { compareBranch = await this._folderRepositoryManager.repository.getBranch(newBranch); this._onDidChangeCompareBranch.fire(compareBranch.name!); } catch (e) { vscode.window.showErrorMessage('Branch does not exist locally.'); } } compareBranch = compareBranch ?? await this._folderRepositoryManager.repository.getBranch(this._compareBranch); const titleAndDescription = await this.getTitleAndDescription(compareBranch, this._baseBranch); return this._replyMessage(message, { title: titleAndDescription.title, description: titleAndDescription.description }); } protected async _onDidReceiveMessage(message: IRequestMessage<any>) { const result = await super._onDidReceiveMessage(message); if (result !== this.MESSAGE_UNHANDLED) { return; } switch (message.command) { case 'pr.cancelCreate': vscode.commands.executeCommand('setContext', 'github:createPullRequest', false); this._onDone.fire(undefined); return this._replyMessage(message, undefined); case 'pr.create': return this.create(message); case 'pr.changeBaseRemote': return this.changeRemote(message, true); case 'pr.changeBaseBranch': return this.changeBranch(message, true); case 'pr.changeCompareRemote': return this.changeRemote(message, false); case 'pr.changeCompareBranch': return this.changeBranch(message, false); default: // Log error vscode.window.showErrorMessage('Unsupported webview message'); } } private _getHtmlForWebview() { const nonce = getNonce(); const uri = vscode.Uri.joinPath(this._extensionUri, 'dist', 'webview-create-pr-view.js'); return `<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src vscode-resource: https:; script-src 'nonce-${nonce}'; style-src vscode-resource: 'unsafe-inline' http: https: data:;"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create Pull Request</title> </head> <body> <div id="app"></div> <script nonce="${nonce}" src="${this._webview!.asWebviewUri(uri).toString()}"></script> </body> </html>`; } }
the_stack
declare module "fela" { import * as CSS from 'csstype'; import { TRuleType, TKeyframeType, TFontType, TStaticType, TClearType } from 'fela-utils'; export type TRuleProps = {}; export type TRule<T = TRuleProps> = (props: T, renderer: IRenderer) => IStyle export type TKeyFrame<T = TRuleProps> = (props: T, renderer: IRenderer) => { from?: IStyle, to?: IStyle, [persent: string]: IStyle | undefined; }; type TRendererCreator = (config?: IConfig) => IRenderer; type TRenderType = 'RULE' | 'KEYFRAME' | 'FONT' | 'STATIC'; type TPlugin<T = Record<string, unknown>> = { ( style: IStyle, type: TRenderType, renderer: IRenderer, props: T, ): IStyle; }; type TEnhancer = (renderer: IRenderer) => IRenderer; //http://fela.js.org/docs/advanced/Enhancers.html type TSubscribeMessageType = TRuleType | TKeyframeType | TFontType | TStaticType | TClearType interface ISubscribeMessage { type: TSubscribeMessageType; } interface ISubscribeRuleOrStaticObjectMessage extends ISubscribeMessage { static?: boolean; declaration: string; selector: string; media: string; } interface ISubscribeKeyframesMessage extends ISubscribeMessage { name: string; keyframe: string; } interface ISubscribeFontFaceMessage extends ISubscribeMessage { fontFamily: string; fontFace: string; } interface ISubscribeStaticStringMessage extends ISubscribeMessage { css: string; } interface ISubscribeClearMessage extends ISubscribeMessage { } interface IRenderer { renderRule<T = TRuleProps>(rule: TRule<T>, props: T): string renderKeyframe<T = TRuleProps>(keyFrame: TKeyFrame<T>, props: T): string; renderFont<T = TRuleProps>(family: string, files: Array<string>, props: T): void; renderStatic(style: string, selector?: string): void; renderStatic(style: IStyle, selector: string): void; renderToString(): string; subscribe(event: (msg: ISubscribeRuleOrStaticObjectMessage | ISubscribeKeyframesMessage | ISubscribeFontFaceMessage | ISubscribeStaticStringMessage | ISubscribeClearMessage) => void): { unsubscribe: () => void; } clear(): void; } //http://fela.js.org/docs/advanced/RendererConfiguration.html interface IConfig { plugins?: Array<TPlugin>; keyframePrefixes?: Array<string>; enhancers?: Array<TEnhancer>; mediaQueryOrder?: Array<string>; selectorPrefix?: string; specificityPrefix?: string; filterClassName?: (className: string) => boolean; devMode?: boolean; } type CSSObject = CSSProperties & CSSPseudos; type CSSCustom = { [prop: string]: CSSCustomPrimitive | IStyle }; type CSSCustomPrimitive = IStylePrimitiveExtension[keyof IStylePrimitiveExtension]; type CSSProperties = CSS.Properties<number | string>; type CSSPropertiesFallback = CSS.PropertiesFallback<number | string>; type CSSPseudos = { [K in CSS.Pseudos]?: CSSObject; }; interface IStyleExtension { __brand?: never } interface IStylePrimitiveExtension { _string: string; _number: number; } export type IStyle = | CSSObject | CSSCustom | IStyleExtension; function createRenderer(config?: IConfig): IRenderer; function combineRules<A, B>(a: TRule<A>, b: TRule<B>): TRule<A & B> function combineRules<A, B, C>( a: TRule<A>, b: TRule<B>, c: TRule<C>, ): TRule<A & B & C> function combineRules(...rules: Array<TRule>): TRule function enhance(...enhancers: Array<TEnhancer>): (rendererCreator: TRendererCreator) => TRendererCreator; } declare module "fela-dom" { import { IRenderer, TRenderType } from 'fela'; function render(renderer: IRenderer): void; function rehydrate(renderer: IRenderer): void; function renderToMarkup(renderer: IRenderer): string; function renderToSheetList(renderer: IRenderer): { css: string, type: TRenderType, media?: string, support?: boolean, }[]; } declare module "fela-tools" { import { TRule, TRuleProps, IStyle, IRenderer } from "fela"; export type TMultiRuleObject<Props = TRuleProps, Styles = {}> = {[key in keyof Styles]: TRule<Props> | IStyle} export type TMultiRuleFunction<Props = TRuleProps, Styles = {}> = (props: Props, renderer: IRenderer) => TMultiRuleObject<Props, Styles> export type TMultiRule<Props = TRuleProps, Styles = {}> = TMultiRuleObject<Props, Styles> | TMultiRuleFunction<Props, Styles> export type TPartialMultiRuleObject<Props = TRuleProps, Styles = {}> = Partial<TMultiRuleObject<Props, Styles>> export type TPartialMultiRuleFunction<Props = TRuleProps, Styles = {}> = (props: Props, renderer: IRenderer) => TPartialMultiRuleObject<Props, Styles> export type TPartialMultiRule<Props = TRuleProps, Styles = {}> = TPartialMultiRuleObject<Props, Styles> | TPartialMultiRuleFunction<Props, Styles> export type TNormalizedMultiRule<Props = TRuleProps, Styles = {}> = (props: Props, renderer: IRenderer) => {[key in keyof Styles]: TRule<Props>} function combineMultiRules<A, SA, B, SB>( a: TMultiRule<A, SA>, b: TMultiRule<B, SB> ): TNormalizedMultiRule<A & B, SA & SB> function combineMultiRules<A, SA, B, SB, C, SC>( a: TMultiRule<A, SA>, b: TMultiRule<B, SB>, c: TMultiRule<C, SC>, ): TNormalizedMultiRule<A & B & C, SA & SB & SC> function combineMultiRules(...rules: Array<TMultiRule>): TNormalizedMultiRule function mapValueToMediaQuery( queryValueMap: { [key: string]: string }, mapper: ((value: string) => object) | string ): object; function renderToElement( renderer: IRenderer, mountNode: { textContent: string }, ): (() => void); function renderToString( renderer: IRenderer, ): string; } /** * ENHANCERS */ declare module "fela-beautifier" { import { TEnhancer } from "fela"; export default function(options?: object): TEnhancer; } declare module "fela-identifier" { import { TRule, TEnhancer } from "fela"; interface Configs { prefix?: string; generator?: (name?: string, index?: number) => string; } type Identifier = (name?: string) => TRule & { className: string; toString(): string; }; export default function(configs?: Configs): TEnhancer & Identifier; } declare module "fela-layout-debugger" { import { TEnhancer } from "fela"; interface DebuggerOptions { mode?: "outline" | "backgroundColor"; thickness?: number; } export default function(options?: DebuggerOptions): TEnhancer; } declare module "fela-logger" { import { TEnhancer } from "fela"; interface LoggerOptions { logCSS?: boolean; formatCSS?: boolean; } export default function(options?: LoggerOptions): TEnhancer; } declare module "fela-monolithic" { import { TEnhancer } from "fela"; interface MonolithicOptions { prettySelectors?: boolean; } export default function(options?: MonolithicOptions): TEnhancer; } declare module "fela-perf" { import { TEnhancer } from "fela"; export default function(): TEnhancer; } declare module "fela-statistics" { import { TEnhancer } from "fela"; export default function(): TEnhancer; } declare module "fela-utils" { export type TRuleType = "RULE" export type TKeyframeType = "KEYFRAME" export type TFontType = "FONT" export type TStaticType = "STATIC" export type TClearType = "CLEAR" export const RULE_TYPE: TRuleType export const KEYFRAME_TYPE: TKeyframeType export const FONT_TYPE: TFontType export const STATIC_TYPE: TStaticType export const CLEAR_TYPE: TClearType } declare module "fela-sort-media-query-mobile-first" { import { TEnhancer } from "fela"; export default function(): TEnhancer; } /** * PLUGINS */ declare module "fela-plugin-bidi" { import { TPlugin } from "fela"; export default function(flowDirection: 'ltr' | 'rtl'): TPlugin; } declare module "fela-plugin-custom-property" { import { TPlugin } from "fela"; interface CustomProperties { [property: string]: (value: any) => any, } export default function(properties: CustomProperties): TPlugin; } declare module "fela-plugin-embedded" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-extend" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-friendly-pseudo-class" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-important" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-isolation" { import { TPlugin } from "fela"; interface IsolationOptions { exclude?: string[]; } export default function(options?: IsolationOptions): TPlugin; } declare module "fela-plugin-logger" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-named-keys" { import { TPlugin } from "fela"; interface MediaQueryMap { [key: string]: string; } export default function(mediaQueryMap: MediaQueryMap): TPlugin; } declare module "fela-plugin-native-media-query" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-placeholder-prefixer" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-fullscreen-prefixer" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-pseudo-prefixer" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-theme-value" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-prefixer" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-rtl" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-simulate" { import { TPlugin } from "fela"; export default function(): TPlugin; } declare module "fela-plugin-unit" { import { TPlugin } from "fela"; export type Unit = "ch" | "em" | "ex" | "rem" | "vh" | "vw" | "vmin" | "vmax" | "px" | "cm" | "mm" | "in" | "pc" | "pt" | "mozmm"; export interface UnitPerProperty { [key: string]: string; } export default function( unit?: Unit, unitPerProperty?: UnitPerProperty, isUnitlessProperty?: (property: string) => boolean, ): TPlugin; } declare module "fela-plugin-validator" { import { TPlugin } from "fela"; interface Configs { logInvalid?: boolean; deleteInvalid?: boolean; useCSSLint?: boolean | object; } export default function(configs?: Configs): TPlugin; } /** * PRESETS */ declare module "fela-preset-web" { import { TPlugin } from "fela"; import { Unit, UnitPerProperty } from "fela-plugin-unit"; type UnitConfig1 = [Unit] type UnitConfig2 = [Unit, UnitPerProperty] type UnitConfig3 = [Unit, UnitPerProperty, (property: string) => boolean] type UnitConfig = UnitConfig1 | UnitConfig2 | UnitConfig3 export function createWebPreset({ unit }: { unit?: UnitConfig }): TPlugin[]; const presets: TPlugin[]; export default presets; } declare module "fela-preset-dev" { import { TPlugin } from "fela"; const presets: TPlugin[]; export default presets; }
the_stack
import { AppChallenge, ChallengeEvents, ChallengeStatus } from "@connext/types"; import { ChannelSigner, computeAppChallengeHash, computeCancelDisputeHash, getRandomAddress, getRandomBytes32, toBN, } from "@connext/utils"; import { BigNumberish, Contract, ContractFactory, Wallet, constants, utils } from "ethers"; import { AppWithAction, ChallengeRegistry } from "../artifacts"; import { ActionType, AppWithCounterAction, AppWithCounterClass, AppWithCounterState, encodeAction, encodeOutcome, encodeState, emptyChallenge, expect, provider, sortSignaturesBySignerAddress, } from "./utils"; const { Zero, One, HashZero } = constants; const { keccak256 } = utils; export const setupContext = async (givenAppDefinition?: Contract) => { // 0xaeF082d339D227646DB914f0cA9fF02c8544F30b const alice = new Wallet("0x3570f77380e22f8dc2274d8fd33e7830cc2d29cf76804e8c21f4f7a6cc571d27"); // 0xb37e49bFC97A948617bF3B63BC6942BB15285715 const bob = new Wallet("0x4ccac8b1e81fb18a98bbaf29b9bfe307885561f71b76bd4680d7aec9d0ddfcfd"); // NOTE: sometimes using the [0] indexed wallet will fail to deploy the // contracts in the first test suite (almost like a promised tx isnt // completed). Hacky fix: use a different wallet const deployer = (await provider.getWallets())[2]; // app helpers const ONCHAIN_CHALLENGE_TIMEOUT = 30; const DEFAULT_TIMEOUT = 10; const CHANNEL_NONCE = 42; // We don't compute or verify the multisig address const multisigAddress = getRandomAddress(); //////////////////////////////////////// // Internal Helpers const appRegistry = await new ContractFactory( ChallengeRegistry.abi, ChallengeRegistry.bytecode, deployer, ).deploy(); await appRegistry.deployed(); const appDefinition = givenAppDefinition || (await new ContractFactory(AppWithAction.abi, AppWithAction.bytecode, deployer).deploy()); await appDefinition.deployed(); const appInstance = new AppWithCounterClass( [alice.address, bob.address], multisigAddress, appDefinition.address, DEFAULT_TIMEOUT, CHANNEL_NONCE, ); const getSignatures = async (digest: string): Promise<string[]> => await sortSignaturesBySignerAddress(digest, [ await new ChannelSigner(bob.privateKey).signMessage(digest), await new ChannelSigner(alice.privateKey).signMessage(digest), ]); //////////////////////////////////////// // Exported Methods const getChallenge = async (): Promise<AppChallenge> => { const [status, appStateHash, versionNumber, finalizesAt] = await appRegistry.getAppChallenge( appInstance.identityHash, ); return { status, appStateHash, versionNumber, finalizesAt }; }; const getOutcome = async (): Promise<string> => appRegistry.getOutcome(appInstance.identityHash); const verifyChallenge = async (expected: Partial<AppChallenge>) => { expect(await getChallenge()).to.containSubset(expected); }; const isProgressable = async () => appRegistry.isProgressable(await getChallenge(), appInstance.defaultTimeout); const isDisputable = async (challenge?: AppChallenge) => appRegistry.isDisputable(challenge || (await getChallenge())); const isFinalized = async () => appRegistry.isFinalized(await getChallenge(), appInstance.defaultTimeout); const isCancellable = async (challenge?: AppChallenge) => appRegistry.isCancellable(challenge || (await getChallenge()), appInstance.defaultTimeout); const hasPassed = (timeout: BigNumberish) => appRegistry.hasPassed(toBN(timeout)); const verifySignatures = async ( digest: string = getRandomBytes32(), signatures?: string[], signers?: string[], ) => appRegistry.verifySignatures( signatures || (await getSignatures(digest)), digest, signers || [alice.address, bob.address], ); const wrapInEventVerification = async ( contractCall: any, expected: Partial<AppChallenge> = {}, ) => { const { status, appStateHash, finalizesAt, versionNumber } = await getChallenge(); await expect(contractCall) .to.emit(appRegistry, ChallengeEvents.ChallengeUpdated) .withArgs( appInstance.identityHash, // identityHash expected.status || status, // status expected.appStateHash || appStateHash, // appStateHash expected.versionNumber || versionNumber, // versionNumber expected.finalizesAt || finalizesAt, // finalizesAt ); }; // State Progression methods const setOutcome = async (encodedFinalState?: string): Promise<void> => wrapInEventVerification( appRegistry.setOutcome(appInstance.appIdentity, encodedFinalState || HashZero), { status: ChallengeStatus.OUTCOME_SET }, ); const setOutcomeAndVerify = async (encodedFinalState?: string): Promise<void> => { await setOutcome(encodedFinalState); expect(await getOutcome()).to.eq(encodeOutcome()); await verifyChallenge({ status: ChallengeStatus.OUTCOME_SET }); }; const setState = async ( versionNumber: number, appState?: string, timeout: number = ONCHAIN_CHALLENGE_TIMEOUT, ) => { const stateHash = keccak256(appState || HashZero); const digest = computeAppChallengeHash( appInstance.identityHash, stateHash, versionNumber, timeout, ); const call = appRegistry.setState(appInstance.appIdentity, { versionNumber, appStateHash: stateHash, timeout, signatures: await getSignatures(digest), }); const blockNumber = await provider.getBlockNumber(); // FIXME: why is this off by one? const finalizesAt = toBN(blockNumber).add(timeout).add(1); await wrapInEventVerification(call, { status: ChallengeStatus.IN_DISPUTE, appStateHash: stateHash, versionNumber: toBN(versionNumber), finalizesAt, }); }; const setStateAndVerify = async ( versionNumber: number, appState?: string, timeout: number = ONCHAIN_CHALLENGE_TIMEOUT, ) => { await setState(versionNumber, appState, timeout); await verifyChallenge({ versionNumber: toBN(versionNumber), appStateHash: keccak256(appState || HashZero), status: ChallengeStatus.IN_DISPUTE, }); }; const progressState = async ( state: AppWithCounterState, action: AppWithCounterAction, signer: Wallet, resultingState?: AppWithCounterState, resultingStateVersionNumber?: BigNumberish, resultingStateTimeout?: number, ) => { resultingState = resultingState ?? { counter: action.actionType === ActionType.ACCEPT_INCREMENT ? state.counter : state.counter.add(action.increment), }; const resultingStateHash = keccak256(encodeState(resultingState)); resultingStateVersionNumber = resultingStateVersionNumber ?? (await getChallenge()).versionNumber.add(One); resultingStateTimeout = resultingStateTimeout ?? 0; const digest = computeAppChallengeHash( appInstance.identityHash, resultingStateHash, resultingStateVersionNumber, resultingStateTimeout, ); const req = { appStateHash: resultingStateHash, versionNumber: resultingStateVersionNumber, timeout: resultingStateTimeout, signatures: [await new ChannelSigner(signer.privateKey).signMessage(digest)], }; const blockNumber = await provider.getBlockNumber(); const timeout = appInstance.defaultTimeout; // FIXME: why is this off by one? const finalizesAt = toBN(blockNumber).add(timeout).add(1); await wrapInEventVerification( appRegistry.progressState( appInstance.appIdentity, req, encodeState(state), encodeAction(action), ), { status: resultingState.counter.gt(5) ? ChallengeStatus.EXPLICITLY_FINALIZED : ChallengeStatus.IN_ONCHAIN_PROGRESSION, appStateHash: resultingStateHash, versionNumber: toBN(resultingStateVersionNumber), finalizesAt, }, ); }; const progressStateAndVerify = async ( state: AppWithCounterState, action: AppWithCounterAction, signer: Wallet = bob, ) => { const existingChallenge = await getChallenge(); expect(await isProgressable()).to.be.true; const resultingState: AppWithCounterState = { counter: action.actionType === ActionType.ACCEPT_INCREMENT ? state.counter : state.counter.add(action.increment), }; const resultingStateHash = keccak256(encodeState(resultingState)); const explicitlyFinalized = resultingState.counter.gt(5); const status = explicitlyFinalized ? ChallengeStatus.EXPLICITLY_FINALIZED : ChallengeStatus.IN_ONCHAIN_PROGRESSION; const expected = { appStateHash: resultingStateHash, versionNumber: existingChallenge.versionNumber.add(One), status, }; await progressState(state, action, signer); await verifyChallenge(expected); expect(await isProgressable()).to.be.equal(!explicitlyFinalized); }; const setAndProgressStateAndVerify = async ( versionNumber: number, state: AppWithCounterState, action: AppWithCounterAction, timeout: number = 0, turnTaker: Wallet = bob, ) => { await setAndProgressState(versionNumber, state, action, timeout, turnTaker); const resultingState: AppWithCounterState = { counter: action.actionType === ActionType.ACCEPT_INCREMENT ? state.counter : state.counter.add(action.increment), }; const resultingStateHash = keccak256(encodeState(resultingState)); const status = resultingState.counter.gt(5) ? ChallengeStatus.EXPLICITLY_FINALIZED : ChallengeStatus.IN_ONCHAIN_PROGRESSION; await verifyChallenge({ appStateHash: resultingStateHash, versionNumber: One.add(versionNumber), status, }); expect(await isProgressable()).to.be.equal(status === ChallengeStatus.IN_ONCHAIN_PROGRESSION); }; // No need to verify events here because `setAndProgress` simply emits // the events from other contracts const setAndProgressState = async ( versionNumber: number, state: AppWithCounterState, action: AppWithCounterAction, timeout: number = 0, turnTaker: Wallet = bob, ) => { const stateHash = keccak256(encodeState(state)); const stateDigest = computeAppChallengeHash( appInstance.identityHash, stateHash, versionNumber, timeout, ); const resultingState: AppWithCounterState = { counter: action.actionType === ActionType.ACCEPT_INCREMENT ? state.counter : state.counter.add(action.increment), }; const timeout2 = 0; const resultingStateHash = keccak256(encodeState(resultingState)); const resultingStateDigest = computeAppChallengeHash( appInstance.identityHash, resultingStateHash, One.add(versionNumber), timeout2, ); const req1 = { versionNumber, appStateHash: stateHash, timeout, signatures: await getSignatures(stateDigest), }; const req2 = { versionNumber: One.add(versionNumber), appStateHash: resultingStateHash, timeout: timeout2, signatures: [await new ChannelSigner(turnTaker.privateKey).signMessage(resultingStateDigest)], }; await appRegistry.setAndProgressState( appInstance.appIdentity, req1, req2, encodeState(state), encodeAction(action), ); }; // TODO: why does event verification fail? // await wrapInEventVerification( const cancelDispute = async (versionNumber: number, signatures?: string[]): Promise<void> => { const digest = computeCancelDisputeHash(appInstance.identityHash, toBN(versionNumber)); await appRegistry.cancelDispute(appInstance.appIdentity, { versionNumber: toBN(versionNumber), signatures: signatures || (await getSignatures(digest)), }); }; const cancelDisputeAndVerify = async ( versionNumber: number, signatures?: string[], ): Promise<void> => { await cancelDispute(versionNumber, signatures); await verifyChallenge(emptyChallenge); }; return { // app defaults alice, appRegistry, bob, state0: { counter: Zero }, state1: { counter: toBN(2) }, action: { actionType: ActionType.SUBMIT_COUNTER_INCREMENT, increment: toBN(2) }, explicitlyFinalizingAction: { actionType: ActionType.SUBMIT_COUNTER_INCREMENT, increment: toBN(6), }, ONCHAIN_CHALLENGE_TIMEOUT, DEFAULT_TIMEOUT, appInstance, // helper fns getChallenge, verifyChallenge, verifyEmptyChallenge: () => verifyChallenge(emptyChallenge), isProgressable, isFinalized, isCancellable, hasPassed, isDisputable, verifySignatures, // state progression setOutcome, setOutcomeAndVerify, setState, setStateAndVerify, progressState, progressStateAndVerify, setAndProgressState, setAndProgressStateAndVerify, cancelDispute, cancelDisputeAndVerify, }; };
the_stack
// Generated by: https://github.com/david-driscoll/atom-typescript-generator // Generation tool by david-driscoll <https://github.com/david-driscoll/> /// <reference path="../event-kit/event-kit.d.ts" /> declare module FirstMate { /** * Registry containing one or more grammars. */ class GrammarRegistry { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(options? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ clear() : void; /** * Invoke the given callback when a grammar is added to the registry. * @param callback - {Function} to call when a grammar is added. */ onDidAddGrammar(callback : Function /* needs to be defined */) : EventKit.Disposable; /** * Invoke the given callback when a grammar is updated due to a grammar * it depends on being added or removed from the registry. * @param callback - {Function} to call when a grammar is updated. */ onDidUpdateGrammar(callback : Function /* needs to be defined */) : EventKit.Disposable; /** * Get all the grammars in this registry. */ getGrammars() : Grammar[]; /** * Get a grammar with the given scope name. * @param scopeName? - A {String} such as `"source.js"`. */ grammarForScopeName(scopeName? : string) : string; /** * Add a grammar to this registry. * * A 'grammar-added' event is emitted after the grammar is added. * @param grammar? - The {Grammar} to add. This should be a value previously returned from {::readGrammar} or {::readGrammarSync}. */ addGrammar(grammar? : Grammar) : Grammar; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ removeGrammar(grammar? : Grammar) : Grammar; /** * Remove the grammar with the given scope name. * @param scopeName? - A {String} such as `"source.js"`. */ removeGrammarForScopeName(scopeName? : string) : string; /** * Read a grammar synchronously but don't add it to the registry. * @param grammarPath? - A {String} absolute file path to a grammar file. * Returns a {Grammar}. */ readGrammarSync(grammarPath? : string) : Grammar; /** * Read a grammar asynchronously but don't add it to the registry. * @param grammarPath? - A {String} absolute file path to a grammar file. * @param callback? - A {Function} to call when read with the following arguments: */ readGrammar(grammarPath? : string, callback? : Function) : Grammar; /** * Read a grammar synchronously and add it to this registry. * @param grammarPath? - A {String} absolute file path to a grammar file. * Returns a {Grammar}. */ loadGrammarSync(grammarPath? : string) : Grammar; /** * Read a grammar asynchronously and add it to the registry. * @param grammarPath? - A {String} absolute file path to a grammar file. * @param callback? - A {Function} to call when loaded with the following arguments: */ loadGrammar(grammarPath? : string, callback? : Function) : Grammar; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ startIdForScope(scope? : any) : void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ endIdForScope(scope? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ scopeForId(id? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ grammarUpdated(scopeName? : string) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ createGrammar(grammarPath? : string, object? : any) : Grammar; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ decodeTokens(lineText? : string, tags? : any, scopeTags? : any, fn? : any) : Atom.Token[]; } /** * Grammar that tokenizes lines of text. */ class Grammar { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ registry: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ registration: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(registry? : any, options? : any); /** * Invoke the given callback when this grammar is updated due to a * grammar it depends on being added or removed from the registry. * @param callback - {Function} to call when this grammar is updated. */ onDidUpdate(callback : Function /* needs to be defined */) : EventKit.Disposable; /** * Tokenize all lines in the given text. * @param text? - A {String} containing one or more lines. */ tokenizeLines(text? : string) : string[]; /** * Tokenize the line of text. * @param line? - A {String} of text to tokenize. * @param ruleStack? - An optional {Array} of rules previously returned from this method. This should be null when tokenizing the first line in the file. * @param firstLine? - A optional {Boolean} denoting whether this is the first line in the file which defaults to `false`. This should be `true` when tokenizing the first line in the file. */ tokenizeLine(line? : string, ruleStack? : any[], firstLine? : boolean, compatibilityMode? : any) : number; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ activate() : void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ deactivate() : void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ clearRules() : Rule[]; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getInitialRule() : Rule; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getRepository() : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ addIncludedGrammarScope(scope? : any) : void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ grammarUpdated(scopeName? : string) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ startIdForScope(scope? : any) : void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ endIdForScope(scope? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ scopeForId(id? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ createRule(options? : any) : Rule; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ createPattern(options? : any) : Pattern; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getMaxTokensPerLine() : number; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ scopesFromStack(stack? : any, rule? : Rule, endPatternMatch? : any) : any; name: string; } /** * TokenizeLineResult * This class was not documented by atomdoc, assume it is private. Use with caution. */ class TokenizeLineResult { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ line: number; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ openScopeTags: void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ tags: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ ruleStack: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ registry: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(line? : number, openScopeTags? : any, tags? : any, ruleStack? : any, registry? : any); } /** * Injections * This class was not documented by atomdoc, assume it is private. Use with caution. */ class Injections { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ grammar: Grammar; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(grammar? : Grammar, injections? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getScanner(injection? : any) : Scanner; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getScanners(ruleStack? : any) : Scanner[]; } /** * A grammar with no patterns that is always available from a {GrammarRegistry} * even when it is completely empty. */ class NullGrammar extends Grammar { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(registry? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getScore() : any; } /** * Pattern * This class was not documented by atomdoc, assume it is private. Use with caution. */ class Pattern { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ grammar: Grammar; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ registry: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(grammar? : Grammar, registry? : any, options? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getRegex(firstLine? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], anchorPosition? : TextBuffer.Point | { row: number; column: number } | [number, number]) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ hasAnchor() : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ replaceAnchor(firstLine? : number, offset? : any, anchor? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ resolveBackReferences(line? : number, beginCaptureIndices? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ ruleForInclude(baseGrammar? : Grammar, name? : string) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getIncludedPatterns(baseGrammar? : Grammar, included? : any) : Pattern[]; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ resolveScopeName(scopeName? : string, line? : number, captureIndices? : any) : string; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ handleMatch(stack? : any, line? : number, captureIndices? : any, rule? : Rule, endPatternMatch? : any) : void; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ tagsForCaptureRule(rule? : Rule, line? : number, captureStart? : any, captureEnd? : any, stack? : any) : Rule; /** * Get the tokens for the capture indices. * * line - The string being tokenized. * currentCaptureIndices - The current array of capture indices being * processed into tokens. This method is called * recursively and this array will be modified inside * this method. * allCaptureIndices - The array of all capture indices, this array will not * be modified. * stack - An array of rules. * This field or method was marked private by atomdoc. Use with caution. * Returns a non-null but possibly empty array of tokens */ tagsForCaptureIndices(line? : number, currentCaptureIndices? : any, allCaptureIndices? : any, stack? : any) : any; } /** * Rule * This class was not documented by atomdoc, assume it is private. Use with caution. */ class Rule { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ grammar: Grammar; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ registry: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ scopeName: string; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ contentScopeName: string; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ endPattern: Pattern; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ applyEndPatternLast: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(grammar? : Grammar, registry? : any, options? : (scopeName? : string,contentScopeName? : string,patterns? : Pattern[],endPattern? : Pattern,applyEndPatternLast? : any) => any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getIncludedPatterns(baseGrammar? : Grammar, included? : any) : Pattern[]; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ clearAnchorPosition() : TextBuffer.Point; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getScanner(baseGrammar? : Grammar) : Scanner; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ scanInjections(ruleStack? : any, line? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], firstLine? : number) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ normalizeCaptureIndices(line? : number, captureIndices? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ findNextMatch(ruleStack? : any, line? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], firstLine? : number) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getNextTags(ruleStack? : any, line? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], firstLine? : number) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ getRuleToPush(line? : number, beginPatternCaptureIndices? : any) : any; } /** * Wrapper class for {OnigScanner} that caches them based on the presence of any * anchor characters that change based on the current position being scanned. */ class Scanner { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ patterns: Pattern[]; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(patterns? : Pattern[]); /** * Create a new {OnigScanner} with the given options. * This field or method was marked private by atomdoc. Use with caution. */ createScanner(firstLine? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], anchorPosition? : TextBuffer.Point | { row: number; column: number } | [number, number]) : Scanner; /** * Get the {OnigScanner} for the given position and options. * This field or method was marked private by atomdoc. Use with caution. */ getScanner(firstLine? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], anchorPosition? : TextBuffer.Point | { row: number; column: number } | [number, number]) : Scanner; /** * Find the next match on the line start at the given position * * line - the string being scanned. * firstLine - true if the first line is being scanned. * position - numeric position to start scanning at. * anchorPosition - numeric position of the last anchored match. * Returns an Object with details about the match or null if no match found. */ findNextMatch(line? : number, firstLine? : number, position? : TextBuffer.Point | { row: number; column: number } | [number, number], anchorPosition? : TextBuffer.Point | { row: number; column: number } | [number, number]) : any; /** * Handle the given match by calling `handleMatch` on the * matched {Pattern}. * * match - An object returned from a previous call to `findNextMatch`. * stack - An array of {Rule} objects. * line - The string being scanned. * rule - The rule that matched. * endPatternMatch - true if the rule's end pattern matched. */ handleMatch(match? : any, stack? : any, line? : number, rule? : Rule, endPatternMatch? : any) : void; } /** * SegmentMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class SegmentMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(segments? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scope? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * TrueMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class TrueMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches() : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * ScopeMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class ScopeMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(first? : any, others? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scope? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * PathMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class PathMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(first? : any, others? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scopes? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * OrMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class OrMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ left: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ right: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(left? : any, right? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scopes? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * AndMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class AndMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ left: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ right: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(left? : any, right? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scopes? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * NegateMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class NegateMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matcher: any /* default */; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(matcher? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scopes? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * CompositeMatcher * This class was not documented by atomdoc, assume it is private. Use with caution. */ class CompositeMatcher { /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ constructor(left? : any, operator? : any, right? : any); /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ matches(scopes? : any) : any; /** * This field or method was not documented by atomdoc, assume it is private. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } /** * ScopeSelector * This class was not documented by atomdoc, assume it is private. Use with caution. */ class ScopeSelector { /** * Create a new scope selector. * * source - A {String} to parse as a scope selector. * This field or method was marked private by atomdoc. Use with caution. */ constructor(source? : any); /** * Check if this scope selector matches the scopes. * * scopes - An {Array} of {String}s or a single {String}. * This field or method was marked private by atomdoc. Use with caution. * Returns a {Boolean}. */ matches(scopes? : any) : boolean; /** * Convert this TextMate scope selector to a CSS selector. * This field or method was marked private by atomdoc. Use with caution. */ toCssSelector() : ScopedPropertyStore.Selector; } } declare module "first-mate" { class ScopeSelector extends FirstMate.ScopeSelector {} class GrammarRegistry extends FirstMate.GrammarRegistry {} class Grammar extends FirstMate.Grammar {} }
the_stack
declare const monaco; const languages = monaco.languages; const CompletionItemKind = languages.CompletionItemKind; const CompletionItemInsertTextRule = languages.CompletionItemInsertTextRule; type CompletionItem = typeof languages.CompletionItem; type IModel = any; type IPosition = any; type IRichLanguageConfiguration = any; let completionItems: CompletionItem[] = null; export function getWatCompletionItems() { const keyword = CompletionItemKind.Keyword; if (completionItems) { return completionItems; } return (completionItems = [ { label: 'module', documentation: '', kind: keyword, insertText: 'module' }, { label: 'func', documentation: 'function declaration', kind: keyword, insertText: 'func' }, { label: 'param', documentation: 'parameter', kind: keyword, insertText: { value: 'param ${1:identifier} ${2:type}' } as any }, { label: 'i32', documentation: '32-bit integer', kind: keyword, insertText: 'i32' }, { label: 'i64', documentation: '64-bit integer', kind: keyword, insertText: 'i64' }, { label: 'f32', documentation: '32-bit floating point', kind: keyword, insertText: 'f32' }, { label: 'f64', documentation: '64-bit floating point', kind: keyword, insertText: 'f64' }, { label: 'anyfunc', documentation: 'function reference', kind: keyword, insertText: 'anyfunc' }, { label: 'i32.load8_s', documentation: 'load 1 byte and sign-extend i8 to i32', kind: keyword, insertText: 'i32.load8_s' }, { label: 'i32.load8_u', documentation: 'load 1 byte and zero-extend i8 to i32', kind: keyword, insertText: 'i32.load8_u' }, { label: 'i32.load16_s', documentation: 'load 2 bytes and sign-extend i16 to i32', kind: keyword, insertText: 'i32.load16_s' }, { label: 'i32.load16_u', documentation: 'load 2 bytes and zero-extend i16 to i32', kind: keyword, insertText: 'i32.load16_u' }, { label: 'i32.load', documentation: 'load 4 bytes as i32', kind: keyword, insertText: 'i32.load' }, { label: 'i64.load8_s', documentation: 'load 1 byte and sign-extend i8 to i64', kind: keyword, insertText: 'i64.load8_s' }, { label: 'i64.load8_u', documentation: 'load 1 byte and zero-extend i8 to i64', kind: keyword, insertText: 'i64.load8_u' }, { label: 'i64.load16_s', documentation: 'load 2 bytes and sign-extend i16 to i64', kind: keyword, insertText: 'i64.load16_s' }, { label: 'i64.load16_u', documentation: 'load 2 bytes and zero-extend i16 to i64', kind: keyword, insertText: 'i64.load16_u' }, { label: 'i64.load32_s', documentation: 'load 4 bytes and sign-extend i32 to i64', kind: keyword, insertText: 'i64.load32_s' }, { label: 'i64.load32_u', documentation: 'load 4 bytes and zero-extend i32 to i64', kind: keyword, insertText: 'i64.load32_u' }, { label: 'i64.load', documentation: 'load 8 bytes as i64', kind: keyword, insertText: 'i64.load' }, { label: 'f32.load', documentation: 'load 4 bytes as f32', kind: keyword, insertText: 'f32.load' }, { label: 'f64.load', documentation: 'load 8 bytes as f64', kind: keyword, insertText: 'f64.load' }, { label: 'i32.store8', documentation: 'wrap i32 to i8 and store 1 byte', kind: keyword, insertText: 'i32.store8' }, { label: 'i32.store16', documentation: 'wrap i32 to i16 and store 2 bytes', kind: keyword, insertText: 'i32.store16' }, { label: 'i32.store', documentation: '(no conversion) store 4 bytes', kind: keyword, insertText: 'i32.store' }, { label: 'i64.store8', documentation: 'wrap i64 to i8 and store 1 byte', kind: keyword, insertText: 'i64.store8' }, { label: 'i64.store16', documentation: 'wrap i64 to i16 and store 2 bytes', kind: keyword, insertText: 'i64.store16' }, { label: 'i64.store32', documentation: 'wrap i64 to i32 and store 4 bytes', kind: keyword, insertText: 'i64.store32' }, { label: 'i64.store', documentation: '(no conversion) store 8 bytes', kind: keyword, insertText: 'i64.store' }, { label: 'f32.store', documentation: '(no conversion) store 4 bytes', kind: keyword, insertText: 'f32.store' }, { label: 'f64.store', documentation: '(no conversion) store 8 bytes', kind: keyword, insertText: 'f64.store' }, { label: 'get_local', documentation: 'read the current value of a local variable', kind: keyword, insertText: 'get_local' }, { label: 'set_local', documentation: 'set the current value of a local variable', kind: keyword, insertText: 'set_local' }, { label: 'tee_local', documentation: 'like `set_local`, but also returns the set value', kind: keyword, insertText: 'tee_local' }, { label: 'get_global', documentation: 'get the current value of a global variable', kind: keyword, insertText: 'get_global' }, { label: 'set_global', documentation: 'set the current value of a global variable', kind: keyword, insertText: 'set_global' }, { label: 'nop', documentation: 'no operation, no effect', kind: keyword, insertText: 'nop' }, { label: 'block', documentation: 'the beginning of a block construct, a sequence of instructions with a label at the end', kind: keyword, insertText: 'block' }, { label: 'loop', documentation: 'a block with a label at the beginning which may be used to form loops', kind: keyword, insertText: 'loop' }, { label: 'if', documentation: 'the beginning of an if construct with an implicit *then* block', kind: keyword, insertText: 'if' }, { label: 'else', documentation: 'marks the else block of an if', kind: keyword, insertText: 'else' }, { label: 'br', documentation: 'branch to a given label in an enclosing construct', kind: keyword, insertText: 'br' }, { label: 'br_if', documentation: 'conditionally branch to a given label in an enclosing construct', kind: keyword, insertText: 'br_if' }, { label: 'br_table', documentation: 'a jump table which jumps to a label in an enclosing construct', kind: keyword, insertText: 'br_table' }, { label: 'return', documentation: 'return zero or more values from this function', kind: keyword, insertText: 'return' }, { label: 'end', documentation: 'an instruction that marks the end of a block, loop, if, or function', kind: keyword, insertText: 'end' }, { label: 'call', documentation: 'call function directly', kind: keyword, insertText: 'call' }, { label: 'call_indirect', documentation: 'call function indirectly', kind: keyword, insertText: 'call_indirect' }, { label: 'i64.const', documentation: 'produce the value of an i64 immediate', kind: keyword, insertText: { value: 'i64.const ${1:constant}' } }, { label: 'i32.const', documentation: 'produce the value of an i32 immediate', kind: keyword, insertText: { value: 'i32.const ${1:constant}' } }, { label: 'f32.const', documentation: 'produce the value of an f32 immediate', kind: keyword, insertText: { value: 'f32.const ${1:constant}' } }, { label: 'f64.const', documentation: 'produce the value of an f64 immediate', kind: keyword, insertText: { value: 'f64.const ${1:constant}' } }, { label: 'i32.add', documentation: 'sign-agnostic addition', kind: keyword, insertText: 'i32.add' }, { label: 'i32.sub', documentation: 'sign-agnostic subtraction', kind: keyword, insertText: 'i32.sub' }, { label: 'i32.mul', documentation: 'sign-agnostic multiplication (lower 32-bits)', kind: keyword, insertText: 'i32.mul' }, { label: 'i32.div_s', documentation: 'signed division (result is truncated toward zero)', kind: keyword, insertText: 'i32.div_s' }, { label: 'i32.div_u', documentation: 'unsigned division (result is [floored](https://en.wikipedia.org/wiki/Floor_and_ceiling_functions))', kind: keyword, insertText: 'i32.div_u' }, { label: 'i32.rem_s', documentation: 'signed remainder (result has the sign of the dividend)', kind: keyword, insertText: 'i32.rem_s' }, { label: 'i32.rem_u', documentation: 'unsigned remainder', kind: keyword, insertText: 'i32.rem_u' }, { label: 'i32.and', documentation: 'sign-agnostic bitwise and', kind: keyword, insertText: 'i32.and' }, { label: 'i32.or', documentation: 'sign-agnostic bitwise inclusive or', kind: keyword, insertText: 'i32.or' }, { label: 'i32.xor', documentation: 'sign-agnostic bitwise exclusive or', kind: keyword, insertText: 'i32.xor' }, { label: 'i32.shl', documentation: 'sign-agnostic shift left', kind: keyword, insertText: 'i32.shl' }, { label: 'i32.shr_u', documentation: 'zero-replicating (logical) shift right', kind: keyword, insertText: 'i32.shr_u' }, { label: 'i32.shr_s', documentation: 'sign-replicating (arithmetic) shift right', kind: keyword, insertText: 'i32.shr_s' }, { label: 'i32.rotl', documentation: 'sign-agnostic rotate left', kind: keyword, insertText: 'i32.rotl' }, { label: 'i32.rotr', documentation: 'sign-agnostic rotate right', kind: keyword, insertText: 'i32.rotr' }, { label: 'i32.eq', documentation: 'sign-agnostic compare equal', kind: keyword, insertText: 'i32.eq' }, { label: 'i32.ne', documentation: 'sign-agnostic compare unequal', kind: keyword, insertText: 'i32.ne' }, { label: 'i32.lt_s', documentation: 'signed less than', kind: keyword, insertText: 'i32.lt_s' }, { label: 'i32.le_s', documentation: 'signed less than or equal', kind: keyword, insertText: 'i32.le_s' }, { label: 'i32.lt_u', documentation: 'unsigned less than', kind: keyword, insertText: 'i32.lt_u' }, { label: 'i32.le_u', documentation: 'unsigned less than or equal', kind: keyword, insertText: 'i32.le_u' }, { label: 'i32.gt_s', documentation: 'signed greater than', kind: keyword, insertText: 'i32.gt_s' }, { label: 'i32.ge_s', documentation: 'signed greater than or equal', kind: keyword, insertText: 'i32.ge_s' }, { label: 'i32.gt_u', documentation: 'unsigned greater than', kind: keyword, insertText: 'i32.gt_u' }, { label: 'i32.ge_u', documentation: 'unsigned greater than or equal', kind: keyword, insertText: 'i32.ge_u' }, { label: 'i32.clz', documentation: 'sign-agnostic count leading zero bits (All zero bits are considered leading if the value is zero)', kind: keyword, insertText: 'i32.clz' }, { label: 'i32.ctz', documentation: 'sign-agnostic count trailing zero bits (All zero bits are considered trailing if the value is zero)', kind: keyword, insertText: 'i32.ctz' }, { label: 'i32.popcnt', documentation: 'sign-agnostic count number of one bits', kind: keyword, insertText: 'i32.popcnt' }, { label: 'i32.eqz', documentation: 'compare equal to zero (return 1 if operand is zero, 0 otherwise)', kind: keyword, insertText: 'i32.eqz' }, { label: 'f32.add', documentation: 'addition', kind: keyword, insertText: 'f32.add' }, { label: 'f32.sub', documentation: 'subtraction', kind: keyword, insertText: 'f32.sub' }, { label: 'f32.mul', documentation: 'multiplication', kind: keyword, insertText: 'f32.mul' }, { label: 'f32.div', documentation: 'division', kind: keyword, insertText: 'f32.div' }, { label: 'f32.abs', documentation: 'absolute value', kind: keyword, insertText: 'f32.abs' }, { label: 'f32.neg', documentation: 'negation', kind: keyword, insertText: 'f32.neg' }, { label: 'f32.copysign', documentation: 'copysign', kind: keyword, insertText: 'f32.copysign' }, { label: 'f32.ceil', documentation: 'ceiling operator', kind: keyword, insertText: 'f32.ceil' }, { label: 'f32.floor', documentation: 'floor operator', kind: keyword, insertText: 'f32.floor' }, { label: 'f32.trunc', documentation: 'round to nearest integer towards zero', kind: keyword, insertText: 'f32.trunc' }, { label: 'f32.nearest', documentation: 'round to nearest integer, ties to even', kind: keyword, insertText: 'f32.nearest' }, { label: 'f32.eq', documentation: 'compare ordered and equal', kind: keyword, insertText: 'f32.eq' }, { label: 'f32.ne', documentation: 'compare unordered or unequal', kind: keyword, insertText: 'f32.ne' }, { label: 'f32.lt', documentation: 'compare ordered and less than', kind: keyword, insertText: 'f32.lt' }, { label: 'f32.le', documentation: 'compare ordered and less than or equal', kind: keyword, insertText: 'f32.le' }, { label: 'f32.gt', documentation: 'compare ordered and greater than', kind: keyword, insertText: 'f32.gt' }, { label: 'f32.ge', documentation: 'compare ordered and greater than or equal', kind: keyword, insertText: 'f32.ge' }, { label: 'f32.sqrt', documentation: 'square root', kind: keyword, insertText: 'f32.sqrt' }, { label: 'f32.min', documentation: 'minimum (binary operator); if either operand is NaN, returns NaN', kind: keyword, insertText: 'f32.min' }, { label: 'f32.max', documentation: 'maximum (binary operator); if either operand is NaN, returns NaN', kind: keyword, insertText: 'f32.max' }, { label: 'f64.add', documentation: 'addition', kind: keyword, insertText: 'f64.add' }, { label: 'f64.sub', documentation: 'subtraction', kind: keyword, insertText: 'f64.sub' }, { label: 'f64.mul', documentation: 'multiplication', kind: keyword, insertText: 'f64.mul' }, { label: 'f64.div', documentation: 'division', kind: keyword, insertText: 'f64.div' }, { label: 'f64.abs', documentation: 'absolute value', kind: keyword, insertText: 'f64.abs' }, { label: 'f64.neg', documentation: 'negation', kind: keyword, insertText: 'f64.neg' }, { label: 'f64.copysign', documentation: 'copysign', kind: keyword, insertText: 'f64.copysign' }, { label: 'f64.ceil', documentation: 'ceiling operator', kind: keyword, insertText: 'f64.ceil' }, { label: 'f64.floor', documentation: 'floor operator', kind: keyword, insertText: 'f64.floor' }, { label: 'f64.trunc', documentation: 'round to nearest integer towards zero', kind: keyword, insertText: 'f64.trunc' }, { label: 'f64.nearest', documentation: 'round to nearest integer, ties to even', kind: keyword, insertText: 'f64.nearest' }, { label: 'f64.eq', documentation: 'compare ordered and equal', kind: keyword, insertText: 'f64.eq' }, { label: 'f64.ne', documentation: 'compare unordered or unequal', kind: keyword, insertText: 'f64.ne' }, { label: 'f64.lt', documentation: 'compare ordered and less than', kind: keyword, insertText: 'f64.lt' }, { label: 'f64.le', documentation: 'compare ordered and less than or equal', kind: keyword, insertText: 'f64.le' }, { label: 'f64.gt', documentation: 'compare ordered and greater than', kind: keyword, insertText: 'f64.gt' }, { label: 'f64.ge', documentation: 'compare ordered and greater than or equal', kind: keyword, insertText: 'f64.ge' }, { label: 'f64.sqrt', documentation: 'square root', kind: keyword, insertText: 'f64.sqrt' }, { label: 'f64.min', documentation: 'minimum (binary operator); if either operand is NaN, returns NaN', kind: keyword, insertText: 'f64.min' }, { label: 'f64.max', documentation: 'maximum (binary operator); if either operand is NaN, returns NaN', kind: keyword, insertText: 'f64.max' }, { label: 'i32.wrap/i64', documentation: 'wrap a 64-bit integer to a 32-bit integer', kind: keyword, insertText: 'i32.wrap/i64' }, { label: 'i32.trunc_s/f32', documentation: 'truncate a 32-bit float to a signed 32-bit integer', kind: keyword, insertText: 'i32.trunc_s/f32' }, { label: 'i32.trunc_s/f64', documentation: 'truncate a 64-bit float to a signed 32-bit integer', kind: keyword, insertText: 'i32.trunc_s/f64' }, { label: 'i32.trunc_u/f32', documentation: 'truncate a 32-bit float to an unsigned 32-bit integer', kind: keyword, insertText: 'i32.trunc_u/f32' }, { label: 'i32.trunc_u/f64', documentation: 'truncate a 64-bit float to an unsigned 32-bit integer', kind: keyword, insertText: 'i32.trunc_u/f64' }, { label: 'i32.reinterpret/f32', documentation: 'reinterpret the bits of a 32-bit float as a 32-bit integer', kind: keyword, insertText: 'i32.reinterpret/f32' }, { label: 'i64.extend_s/i32', documentation: 'extend a signed 32-bit integer to a 64-bit integer', kind: keyword, insertText: 'i64.extend_s/i32' }, { label: 'i64.extend_u/i32', documentation: 'extend an unsigned 32-bit integer to a 64-bit integer', kind: keyword, insertText: 'i64.extend_u/i32' }, { label: 'i64.trunc_s/f32', documentation: 'truncate a 32-bit float to a signed 64-bit integer', kind: keyword, insertText: 'i64.trunc_s/f32' }, { label: 'i64.trunc_s/f64', documentation: 'truncate a 64-bit float to a signed 64-bit integer', kind: keyword, insertText: 'i64.trunc_s/f64' }, { label: 'i64.trunc_u/f32', documentation: 'truncate a 32-bit float to an unsigned 64-bit integer', kind: keyword, insertText: 'i64.trunc_u/f32' }, { label: 'i64.trunc_u/f64', documentation: 'truncate a 64-bit float to an unsigned 64-bit integer', kind: keyword, insertText: 'i64.trunc_u/f64' }, { label: 'i64.reinterpret/f64', documentation: 'reinterpret the bits of a 64-bit float as a 64-bit integer', kind: keyword, insertText: 'i64.reinterpret/f64' }, { label: 'f32.demote/f64', documentation: 'demote a 64-bit float to a 32-bit float', kind: keyword, insertText: 'f32.demote/f64' }, { label: 'f32.convert_s/i32', documentation: 'convert a signed 32-bit integer to a 32-bit float', kind: keyword, insertText: 'f32.convert_s/i32' }, { label: 'f32.convert_s/i64', documentation: 'convert a signed 64-bit integer to a 32-bit float', kind: keyword, insertText: 'f32.convert_s/i64' }, { label: 'f32.convert_u/i32', documentation: 'convert an unsigned 32-bit integer to a 32-bit float', kind: keyword, insertText: 'f32.convert_u/i32' }, { label: 'f32.convert_u/i64', documentation: 'convert an unsigned 64-bit integer to a 32-bit float', kind: keyword, insertText: 'f32.convert_u/i64' }, { label: 'f32.reinterpret/i32', documentation: 'reinterpret the bits of a 32-bit integer as a 32-bit float', kind: keyword, insertText: 'f32.reinterpret/i32' }, { label: 'f64.promote/f32', documentation: 'promote a 32-bit float to a 64-bit float', kind: keyword, insertText: 'f64.promote/f32' }, { label: 'f64.convert_s/i32', documentation: 'convert a signed 32-bit integer to a 64-bit float', kind: keyword, insertText: 'f64.convert_s/i32' }, { label: 'f64.convert_s/i64', documentation: 'convert a signed 64-bit integer to a 64-bit float', kind: keyword, insertText: 'f64.convert_s/i64' }, { label: 'f64.convert_u/i32', documentation: 'convert an unsigned 32-bit integer to a 64-bit float', kind: keyword, insertText: 'f64.convert_u/i32' }, { label: 'f64.convert_u/i64', documentation: 'convert an unsigned 64-bit integer to a 64-bit float', kind: keyword, insertText: 'f64.convert_u/i64' }, { label: 'f64.reinterpret/i64', documentation: 'reinterpret the bits of a 64-bit integer as a 64-bit float', kind: keyword, insertText: 'f64.reinterpret/i64' }, { label: 'current_memory', documentation: 'current memory size in 64k pages', kind: keyword, insertText: 'current_memory' }, { label: 'grow_memory', documentation: 'grow memory size by the specified amount of 64k pages', kind: keyword, insertText: 'grow_memory' } ]); } const LanguageConfiguration: IRichLanguageConfiguration = { // the default separators except `@$` wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\'\,\.\<\>\/\?\s]+)/g, comments: { lineComment: ';;' }, brackets: [ ['{', '}'], ['[', ']'], ['(', ')'] ], autoClosingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: "'", close: "'" }, { open: "'", close: "'" } ], surroundingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: "'", close: "'" }, { open: "'", close: "'" }, { open: '<', close: '>' } ] }; const MonarchDefinitions = { // Set defaultToken to invalid to see what you do not tokenize yet // defaultToken: 'invalid', keywords: [ 'module', 'table', 'memory', 'export', 'import', 'func', 'result', 'offset', 'anyfunc', 'type', 'data', 'start', 'element', 'global', 'local', 'mut', 'param', 'result', 'i32.load8_s', 'i32.load8_u', 'i32.load16_s', 'i32.load16_u', 'i32.load', 'i64.load8_s', 'i64.load8_u', 'i64.load16_s', 'i64.load16_u', 'i64.load32_s', 'i64.load32_u', 'i64.load', 'f32.load', 'f64.load', 'i32.store8', 'i32.store16', 'i32.store', 'i64.store8', 'i64.store16', 'i64.store32', 'i64.store', 'f32.store', 'f64.store', 'i32.const', 'i64.const', 'f32.const', 'f64.const', 'i32.add', 'i32.sub', 'i32.mul', 'i32.div_s', 'i32.div_u', 'i32.rem_s', 'i32.rem_u', 'i32.and', 'i32.or', 'i32.xor', 'i32.shl', 'i32.shr_u', 'i32.shr_s', 'i32.rotl', 'i32.rotr', 'i32.eq', 'i32.ne', 'i32.lt_s', 'i32.le_s', 'i32.lt_u', 'i32.le_u', 'i32.gt_s', 'i32.ge_s', 'i32.gt_u', 'i32.ge_u', 'i32.clz', 'i32.ctz', 'i32.popcnt', 'i32.eqz', 'f32.add', 'f32.sub', 'f32.mul', 'f32.div', 'f32.abs', 'f32.neg', 'f32.copysign', 'f32.ceil', 'f32.floor', 'f32.trunc', 'f32.nearest', 'f32.eq', 'f32.ne', 'f32.lt', 'f32.le', 'f32.gt', 'f32.ge', 'f32.sqrt', 'f32.min', 'f32.max', 'f64.add', 'f64.sub', 'f64.mul', 'f64.div', 'f64.abs', 'f64.neg', 'f64.copysign', 'f64.ceil', 'f64.floor', 'f64.trunc', 'f64.nearest', 'f64.eq', 'f64.ne', 'f64.lt', 'f64.le', 'f64.gt', 'f64.ge', 'f64.sqrt', 'f64.min', 'f64.max', 'i32.wrap/i64', 'i32.trunc_s/f32', 'i32.trunc_s/f64', 'i32.trunc_u/f32', 'i32.trunc_u/f64', 'i32.reinterpret/f32', 'i64.extend_s/i32', 'i64.extend_u/i32', 'i64.trunc_s/f32', 'i64.trunc_s/f64', 'i64.trunc_u/f32', 'i64.trunc_u/f64', 'i64.reinterpret/f64', 'f32.demote/f64', 'f32.convert_s/i32', 'f32.convert_s/i64', 'f32.convert_u/i32', 'f32.convert_u/i64', 'f32.reinterpret/i32', 'f64.promote/f32', 'f64.convert_s/i32', 'f64.convert_s/i64', 'f64.convert_u/i32', 'f64.convert_u/i64', 'f64.reinterpret/i64', 'local.get', 'local.set', 'local.tee', 'global.get', 'global.set', 'global.tee', 'get_local', 'set_local', 'tee_local', 'get_global', 'set_global', 'current_memory', 'grow_memory' ], typeKeywords: ['i32', 'i64', 'f32', 'f64', 'anyfunc'], operators: [] as any, brackets: [ ['(', ')', 'bracket.parenthesis'], ['{', '}', 'bracket.curly'], ['[', ']', 'bracket.square'] ], // we include these common regular expressions symbols: /[=><!~?:&|+\-*\/\^%]+/, // C# style strings escapes: /\\(?:[abfnrtv\\'']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, // The main tokenizer for our languages tokenizer: { root: [ // identifiers and keywords [ /[a-z_$][\w$\.]*/, { cases: { '@keywords': 'keyword', '@typeKeywords': 'type', '@default': 'type.identifier' } } ], // numbers [/\d+/, 'number'], // strings [/'/, { token: 'string.quote', bracket: '@open', next: '@string' }], [/[{}()\[\]]/, '@brackets'] ] as any, comment: [ [/[^\/*]+/, 'comment'], [/\/\*/, 'comment', '@push'], // nested comment ['\\*/', 'comment', '@pop'], [/[\/*]/, 'comment'], [/;;/, 'comment'] ], string: [ [/[^\\']+/, 'string'], [/@escapes/, 'string.escape'], [/\\./, 'string.escape.invalid'], [/'/, { token: 'string.quote', bracket: '@close', next: '@pop' }] ], whitespace: [ [/[ \t\r\n]+/, 'white'], [/\/\*/, 'comment', '@comment'], [/\/\/.*$/, 'comment'], [/;;/, 'comment'] ] } }; export function watWordAt(s: string, i: number) { const l = s.slice(0, i + 1).search(/[A-Za-z0-9_\.\/]+$/); const r = s.slice(i).search(/[^A-Za-z0-9_\.\/]/); if (r < 0) { return { index: l, word: s.slice(l) }; } return { index: l, word: s.slice(l, r + i) }; } export const Wat = { MonarchDefinitions, LanguageConfiguration, CompletionItemProvider: { provideCompletionItems: function(model: IModel, position: IPosition) { return getWatCompletionItems(); } }, HoverProvider: { provideHover: function(model: IModel, position: IPosition) { const lineContent = model.getLineContent(position.lineNumber); const { index, word } = watWordAt(lineContent, position.column - 1); if (!word) { return; } const watCompletionItems = getWatCompletionItems() as any; const predicate = x => x.label === word; const item = watCompletionItems.find(predicate); if (!item) { return; } return { range: new monaco.Range( position.lineNumber, index + 1, position.lineNumber, index + 1 + word.length ), contents: [ '**DETAILS**', { language: 'html', value: item.documentation } ] }; } } }; monaco.languages.onLanguage('wat', () => { monaco.languages.setMonarchTokensProvider( 'wat', Wat.MonarchDefinitions as any ); monaco.languages.setLanguageConfiguration('wat', Wat.LanguageConfiguration); monaco.languages.registerCompletionItemProvider( 'wat', Wat.CompletionItemProvider ); monaco.languages.registerHoverProvider('wat', Wat.HoverProvider as any); }); monaco.languages.register({ id: 'wat' }); monaco.languages.registerCompletionItemProvider( 'wat', { provideCompletionItems: function() { return { suggestions: [ { label: 'const', kind: monaco.languages.CompletionItemKind.Function, documentation: 'i32', insertText: 'i32.const ${1:value}', insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet }, { label: 'function', kind: monaco.languages.CompletionItemKind.Keyword, documentation: 'i32', insertText: '(func $${1:name} ${2:params} (result i32)\n ${3}\n)', insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet }, { label: 'add', kind: monaco.languages.CompletionItemKind.Keyword, documentation: 'i32', insertText: 'i32.add', insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet }, { label: 'param', kind: monaco.languages.CompletionItemKind.Keyword, documentation: 'i32', insertText: '(param $${1:name} i32) ', insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet }, { label: 'local.get', kind: monaco.languages.CompletionItemKind.Keyword, documentation: 'i32', insertText: 'local.get $${1:name}', insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet }, { label: 'global.get', kind: monaco.languages.CompletionItemKind.Keyword, documentation: 'i32', insertText: 'global.get $${1:name}', insertTextRules: CompletionItemInsertTextRule.InsertAsSnippet } ] }; } }, '(' );
the_stack
import { createCompilerHost, createFSHost, getSmartContractPath, normalizePath, PouchDBFileSystem, } from '@neo-one/local-browser'; import { getSemanticDiagnostics } from '@neo-one/smart-contract-compiler'; import { comlink } from '@neo-one/worker'; import { map } from 'rxjs/operators'; import ts from 'typescript'; import { createFileSystem } from '../engine/create'; interface Options { readonly compilerOptions: ts.CompilerOptions; readonly isSmartContract: boolean; readonly id: string; readonly endpoint: comlink.Endpoint; readonly fileNames: readonly string[]; } interface ParsedBase { readonly tags?: string; readonly documentation?: string; readonly contents: string; } interface ParsedInfo extends ParsedBase { readonly textSpan: ts.TextSpan; } interface ParsedDetails extends ParsedBase { readonly name: string; readonly kind: ts.ScriptElementKind; // tslint:disable-next-line:readonly-array readonly codeActions?: ts.CodeAction[]; } export interface FlattenedDiagnostic extends ts.Diagnostic { readonly message: string; } // tslint:disable-next-line no-let let versionNumber = 0; const getVersion = () => { const current = versionNumber; versionNumber += 1; return `${current}`; }; const createLanguageService = ( fs: PouchDBFileSystem, fileNamesIn: readonly string[], compilerOptions: ts.CompilerOptions, isSmartContract: boolean, tmpFS: Map<string, string>, ): ts.LanguageService => { const versions = new Map<string, string>(); fs.changes$ .pipe( map((change) => { versions.set(change.id, `${change.seq}`); }), ) .subscribe(); const fileNames = isSmartContract ? fileNamesIn.concat([getSmartContractPath('global.d.ts'), getSmartContractPath('index.d.ts')]) : fileNamesIn; const host: ts.LanguageServiceHost = { ...createFSHost(fs), getNewLine: () => '\n', useCaseSensitiveFileNames: () => true, getScriptFileNames: () => [...fileNames], getCurrentDirectory: () => '/', getDefaultLibFileName: (opts: ts.CompilerOptions) => { const result = ts.getDefaultLibFilePath(opts); return `/node_modules/typescript/lib/${result.slice(2)}`; }, getCompilationSettings: (): ts.CompilerOptions => compilerOptions, getScriptVersion: (fileNameIn: string): string => { const fileName = normalizePath(fileNameIn); if (tmpFS.has(fileName)) { return getVersion(); } const version = versions.get(fileName); return version === undefined ? '-1' : version; }, getScriptSnapshot: (fileNameIn: string): ts.IScriptSnapshot | undefined => { try { const fileName = normalizePath(fileNameIn); let textIn = tmpFS.get(fileName); if (textIn === undefined) { textIn = fs.readFileSync(fileName); } const text = textIn; return { getText: (start, end) => text.substring(start, end), getLength: () => text.length, getChangeRange: () => undefined, }; } catch { return undefined; } }, getScriptKind: (fileName: string): ts.ScriptKind => { const suffix = fileName.substr(fileName.lastIndexOf('.') + 1); switch (suffix) { case 'ts': return ts.ScriptKind.TS; case 'tsx': return ts.ScriptKind.TSX; case 'js': return ts.ScriptKind.JS; case 'jsx': return ts.ScriptKind.JSX; default: return compilerOptions.allowJs ? ts.ScriptKind.JS : ts.ScriptKind.TS; } }, }; return ts.createLanguageService(host); }; const clearFiles = (diagnostics: readonly ts.Diagnostic[]) => { // Clear the `file` field, which cannot be JSON'yfied because it // contains cyclic data structures. diagnostics.forEach((diag) => { // tslint:disable-next-line no-object-mutation diag.file = undefined; const related = diag.relatedInformation as ts.Diagnostic[] | undefined; if (related !== undefined) { related.forEach((diag2) => { // tslint:disable-next-line no-object-mutation diag2.file = undefined; }); } }); }; const convertFormattingOptions = (options: monaco.languages.FormattingOptions): ts.FormatCodeOptions => ({ ConvertTabsToSpaces: options.insertSpaces, TabSize: options.tabSize, IndentSize: options.tabSize, IndentStyle: ts.IndentStyle.Smart, NewLineCharacter: '\n', InsertSpaceAfterCommaDelimiter: true, InsertSpaceAfterSemicolonInForStatements: true, InsertSpaceBeforeAndAfterBinaryOperators: true, InsertSpaceAfterKeywordsInControlFlowStatements: true, InsertSpaceAfterFunctionKeywordForAnonymousFunctions: true, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, PlaceOpenBraceOnNewLineForControlBlocks: false, PlaceOpenBraceOnNewLineForFunctions: false, }); const convertTags = (tags: readonly ts.JSDocTagInfo[] | undefined) => tags ? // tslint:disable-next-line:prefer-template '\n\n' + tags .map((tag) => { if (tag.name === 'example' && tag.text) { return `*@${tag.name}*\n` + '```typescript-internal\n' + tag.text + '\n```\n'; } const label = `*@${tag.name}*`; if (!tag.text) { return label; } return label + (tag.text.match(/\r\n|\n/g) ? ' \n' + tag.text : ` - ${tag.text}`); }) .join(' \n\n') : ''; const preferences = { includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: true }; const defaultFormatOptions: ts.FormatCodeSettings = { convertTabsToSpaces: true, tabSize: 2, indentSize: 2, indentStyle: ts.IndentStyle.Smart, newLineCharacter: '\n', insertSpaceAfterCommaDelimiter: true, insertSpaceAfterSemicolonInForStatements: true, insertSpaceBeforeAndAfterBinaryOperators: true, insertSpaceAfterKeywordsInControlFlowStatements: true, insertSpaceAfterFunctionKeywordForAnonymousFunctions: true, insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, placeOpenBraceOnNewLineForControlBlocks: false, placeOpenBraceOnNewLineForFunctions: false, }; const TRIGGER_CHARACTERS = new Set(['.', '"', "'", '`', '/', '@', '<']); export class AsyncLanguageService { private readonly fs: Promise<PouchDBFileSystem>; private readonly tmpFS: Map<string, string>; private readonly languageService: Promise<ts.LanguageService>; private readonly isSmartContract: boolean; public constructor({ id, endpoint, isSmartContract, compilerOptions, fileNames }: Options) { this.fs = createFileSystem(id, endpoint); this.tmpFS = new Map(); this.languageService = this.fs.then((fs) => createLanguageService(fs, fileNames, compilerOptions, isSmartContract, this.tmpFS), ); this.isSmartContract = isSmartContract; } public readonly getSyntacticDiagnostics = ( fileName: string, files: { readonly [key: string]: string }, ): Promise<readonly FlattenedDiagnostic[]> => this.languageService.then((languageService) => this.withTmpFS(files, () => { const diagnostics = languageService.getSyntacticDiagnostics(fileName); clearFiles(diagnostics); return diagnostics.map((diagnostic) => ({ ...diagnostic, message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), })); }), ); public readonly getSemanticDiagnostics = ( fileName: string, files: { readonly [key: string]: string }, ): Promise<readonly FlattenedDiagnostic[]> => // tslint:disable-next-line: no-useless-cast Promise.all([this.fs, this.languageService] as const).then(([fs, languageService]) => this.withTmpFS(files, () => { const diagnostics = this.isSmartContract ? getSemanticDiagnostics(fileName, languageService, createCompilerHost({ fs })) : languageService.getSemanticDiagnostics(fileName); clearFiles(diagnostics); return diagnostics.map((diagnostic) => ({ ...diagnostic, message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), })); }), ); public readonly getCompilerOptionsDiagnostics = (_fileName: string): Promise<readonly ts.Diagnostic[]> => this.languageService.then((languageService) => { const diagnostics = languageService.getCompilerOptionsDiagnostics(); clearFiles(diagnostics); return diagnostics; }); public readonly getCompletionsAtPosition = ( fileName: string, position: number, triggerCharacterIn: string | undefined, files: { readonly [key: string]: string }, ): Promise<ts.CompletionInfo | undefined> => this.languageService.then((languageService) => this.withTmpFS(files, () => { let triggerCharacter: ts.CompletionsTriggerCharacter | undefined; if (triggerCharacterIn !== undefined && TRIGGER_CHARACTERS.has(triggerCharacterIn)) { triggerCharacter = triggerCharacterIn as ts.CompletionsTriggerCharacter; } return languageService.getCompletionsAtPosition(fileName, position, { ...preferences, triggerCharacter }); }), ); public readonly getCompletionEntryDetails = ( fileName: string, position: number, entry: string, formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings = defaultFormatOptions, source?: string, ): Promise<ts.CompletionEntryDetails | undefined> => this.languageService.then((languageService) => languageService.getCompletionEntryDetails(fileName, position, entry, formatOptions, source, preferences), ); public readonly parseCompletionEntryDetails = async ( fileName: string, position: number, entry: string, formatOptions: ts.FormatCodeOptions | ts.FormatCodeSettings = defaultFormatOptions, source?: string, ): Promise<ParsedDetails | undefined> => { const details = await this.getCompletionEntryDetails(fileName, position, entry, formatOptions, source); if (!details) { return undefined; } return { contents: ts.displayPartsToString(details.displayParts), documentation: ts.displayPartsToString(details.documentation), tags: convertTags(details.tags), name: details.name, kind: details.kind, codeActions: details.codeActions, }; }; public readonly getCodeFixesAtPosition = ( fileName: string, start: number, end: number, errorCodes: readonly number[], files: { readonly [key: string]: string }, ): Promise<readonly ts.CodeFixAction[]> => this.languageService.then((languageService) => this.withTmpFS(files, () => languageService.getCodeFixesAtPosition(fileName, start, end, errorCodes, defaultFormatOptions, preferences), ), ); public readonly getSignatureHelpItems = ( fileName: string, position: number, files: { readonly [key: string]: string }, ): Promise<ts.SignatureHelpItems | undefined> => this.languageService.then((languageService) => this.withTmpFS(files, () => languageService.getSignatureHelpItems(fileName, position, undefined)), ); public readonly createSignatures = async ( fileName: string, position: number, files: { readonly [key: string]: string }, ): Promise< | { readonly activeSignature: number; readonly activeParameter: number; readonly signatures: readonly monaco.languages.SignatureInformation[]; } | undefined > => { const info = await this.getSignatureHelpItems(fileName, position, files); if (!info) { return undefined; } const signatures: monaco.languages.SignatureInformation[] = []; info.items.forEach((item) => { const signature: monaco.languages.SignatureInformation = { label: '', documentation: undefined, parameters: [], }; // tslint:disable-next-line:no-object-mutation signature.label += ts.displayPartsToString(item.prefixDisplayParts); item.parameters.forEach((p, i, a) => { const label = ts.displayPartsToString(p.displayParts); const parameter: monaco.languages.ParameterInformation = { label, documentation: { value: ts.displayPartsToString(p.documentation), }, }; // tslint:disable-next-line:no-object-mutation signature.label += label; // tslint:disable-next-line:no-array-mutation signature.parameters.push(parameter); if (i < a.length - 1) { // tslint:disable-next-line:no-object-mutation signature.label += ts.displayPartsToString(item.separatorDisplayParts); } }); // tslint:disable-next-line:no-object-mutation signature.label += ts.displayPartsToString(item.suffixDisplayParts); // tslint:disable-next-line:no-array-mutation signatures.push(signature); }); return { activeSignature: info.selectedItemIndex, activeParameter: info.argumentIndex, signatures, }; }; public readonly getQuickInfoAtPosition = (fileName: string, position: number): Promise<ts.QuickInfo | undefined> => this.languageService.then((languageService) => languageService.getQuickInfoAtPosition(fileName, position)); public readonly parseInfoAtPosition = async (fileName: string, position: number): Promise<ParsedInfo | undefined> => { const info = await this.getQuickInfoAtPosition(fileName, position); if (!info) { return undefined; } return { textSpan: info.textSpan, tags: convertTags(info.tags), documentation: ts.displayPartsToString(info.documentation), contents: ts.displayPartsToString(info.displayParts), }; }; public readonly getOccurrencesAtPosition = ( fileName: string, position: number, ): Promise<readonly ts.ReferenceEntry[] | undefined> => // tslint:disable-next-line deprecation this.languageService.then((languageService) => languageService.getOccurrencesAtPosition(fileName, position)); public readonly getDefinitionAtPosition = ( fileName: string, position: number, ): Promise<readonly ts.DefinitionInfo[] | undefined> => this.languageService.then((languageService) => languageService.getDefinitionAtPosition(fileName, position)); public readonly getReferencesAtPosition = ( fileName: string, position: number, ): Promise<readonly ts.ReferenceEntry[] | undefined> => this.languageService.then((languageService) => languageService.getReferencesAtPosition(fileName, position)); public readonly getNavigationBarItems = (fileName: string): Promise<readonly ts.NavigationBarItem[]> => this.languageService.then((languageService) => languageService.getNavigationBarItems(fileName)); public readonly getFormattingEditsForDocument = ( fileName: string, options: ts.FormatCodeOptions, ): Promise<readonly ts.TextChange[]> => this.languageService.then((languageService) => languageService.getFormattingEditsForDocument(fileName, options)); public readonly getFormattingEditsForRange = ( fileName: string, start: number, end: number, optionsIn: monaco.languages.FormattingOptions, ): Promise<readonly ts.TextChange[]> => { const options = convertFormattingOptions(optionsIn); return this.languageService.then((languageService) => languageService.getFormattingEditsForRange(fileName, start, end, options), ); }; public readonly getFormattingEditsAfterKeystroke = ( fileName: string, postion: number, ch: string, optionsIn: monaco.languages.FormattingOptions, ): Promise<readonly ts.TextChange[]> => { const options = convertFormattingOptions(optionsIn); return this.languageService.then((languageService) => languageService.getFormattingEditsAfterKeystroke(fileName, postion, ch, options), ); }; public readonly getEmitOutput = (fileName: string): Promise<ts.EmitOutput> => this.languageService.then((languageService) => languageService.getEmitOutput(fileName)); private withTmpFS<T>(files: { readonly [key: string]: string }, func: () => T): T { this.tmpFS.clear(); Object.entries(files).forEach(([path, content]) => { this.tmpFS.set(path, content); }); try { return func(); } finally { this.tmpFS.clear(); } } } export interface ICreateData { readonly compilerOptions: ts.CompilerOptions; readonly isSmartContract: boolean; readonly fileSystemID: string; }
the_stack
module Display { class DirtyArea { private _xBegin:number = null; private _yBegin:number = null; private _xEnd:number = null; private _yEnd:number = null; public expand(x:number, y:number) { this._xBegin = this._xBegin === null ? x : Math.min(this._xBegin, x); this._xEnd = this._xEnd === null ? x : Math.max(this._xEnd, x); this._yBegin = this._yBegin === null ? y :Math.min(this._yBegin, y); this._yEnd = this._xEnd === null ? y :Math.max(this._yEnd, y); } public asRect():Rectangle { if (this.isEmpty()) { return new Rectangle(0, 0, 0, 0); } return new Rectangle(this._xBegin, this._yBegin, this._xEnd - this._xBegin, this._yEnd - this._yBegin); } public isEmpty():boolean { return this._xBegin === null || this._yBegin === null || this._xEnd === null || this._yEnd === null; } public reset():void { this._xBegin = null; this._xEnd = null; this._yBegin = null; this._yEnd = null; } } /** * Bitmap AS3 Polyfill class * Note: This is NOT equivalent to the Bitmap library class of the same name! * @author Jim Chen */ export class Bitmap extends DisplayObject { private _bitmapData:BitmapData | null = null; constructor(bitmapData:BitmapData | null = null) { super(Runtime.generateId('obj-bmp')); this._bitmapData = bitmapData; } get width():number { console.log(this._bitmapData); return this._bitmapData !== null ? this._bitmapData.width * this.scaleX : 0; } get height():number { return this._bitmapData !== null ? this._bitmapData.height * this.scaleY : 0; } set width(w:number) { if (this._bitmapData !== null && this._bitmapData.width > 0) { this.scaleX = w / this._bitmapData.width; } } set height(h:number) { if (this._bitmapData !== null && this._bitmapData.height > 0) { this.scaleY = h / this._bitmapData.height; } } public getBitmapData():BitmapData { return this._bitmapData; } public setBitmapData(bitmapData:BitmapData):void { if (typeof bitmapData !== 'undefined') { this._bitmapData = bitmapData; // Propagate up this.methodCall('setBitmapData', bitmapData.getId()); } } public serialize():Object { var serialized:Object = super.serialize(); serialized["class"] = 'Bitmap'; if (this._bitmapData !== null) { serialized["bitmapData"] = this._bitmapData.getId(); } return serialized; } } /** * BitmapData Polyfill class * @author Jim Chen */ export class BitmapData implements Runtime.RegisterableObject { private _id:string; private _rect:Rectangle; private _locked:boolean = false; private _dirtyArea:DirtyArea; private _transparent:boolean; private _fillColor:number; private _byteArray:Array<number>; constructor(width:number, height:number, transparent:boolean = true, fillColor:number = 0xffffffff, id:string = Runtime.generateId('obj-bmp-data')) { this._id = id; this._rect = new Rectangle(0, 0, width, height); this._transparent = transparent; this._fillColor = fillColor; this._dirtyArea = new DirtyArea(); this._fill(); // Register this Runtime.registerObject(this); } private _fill():void { this._byteArray = []; for (var i = 0; i < this._rect.width * this._rect.height; i++) { this._byteArray.push(this._fillColor); } } private _updateBox(changeRect:Rectangle = null):void { if (this._dirtyArea.isEmpty()) { // Don't update anything if nothing was changed return; } if (this._locked) { // Don't send updates if this is locked return; } var change:Rectangle = changeRect === null ? this._dirtyArea.asRect() : changeRect; // Make sure we're not out-of-bounds if (!this._rect.containsRect(change)) { __trace('BitmapData._updateBox box ' + change.toString() + ' out of bonunds ' + this._rect.toString(), 'err'); throw new Error('Rectangle provided was not within image bounds.'); } // Extract the values var region:Array<number> = []; for (var i = 0; i < change.height; i++) { for (var j = 0; j < change.width; j++) { region.push(this._byteArray[(change.y + i) * this._rect.width + change.x + j]); } } this._methodCall('updateBox', { 'box': change.serialize(), 'values': region }); this._dirtyArea.reset(); } private _methodCall(methodName:string, params:any):void { __pchannel("Runtime:CallMethod", { "id": this._id, "method": methodName, "params": params }); } get height():number { return this._rect.height; } get width():number { return this._rect.width; } get rect():Rectangle { return this._rect; } set height(_height:number) { __trace('BitmapData.height is read-only', 'warn'); } set width(_width:number) { __trace('BitmapData.height is read-only', 'warn'); } set rect(_rect:Rectangle) { __trace('BitmapData.rect is read-only', 'warn'); } public draw(source:DisplayObject|BitmapData, matrix:Matrix = null, colorTransform:ColorTransform = null, blendMode:string = null, clipRect:Rectangle = null, smoothing:boolean = false):void { if (!(source instanceof BitmapData)) { __trace('Drawing non BitmapData is not supported!', 'err'); return; } if (matrix !== null) { __trace('Matrix transforms not supported yet.', 'warn'); } if (colorTransform !== null) { __trace('Color transforms not supported yet.', 'warn'); } if (blendMode !== null && blendMode !== 'normal') { __trace('Blend mode [' + blendMode + '] not supported yet.', 'warn'); } if (smoothing !== false) { __trace('Smoothign not supported!', 'warn'); } this.lock(); if (clipRect === null) { clipRect = new Rectangle(0, 0, source.width, source.height); } this.setPixels(clipRect, source.getPixels(clipRect)); this.unlock(); } public getPixel(x:number, y:number):number { return this.getPixel32(x, y) & 0x00ffffff; } public getPixel32(x:number, y:number):number { if (x >= this._rect.width || y >= this._rect.height || x < 0 || y < 0) { throw new Error('Coordinates out of bounds'); } try { return this._transparent ? this._byteArray[y * this._rect.width + x] : (this._byteArray[y * this._rect.width + x] & 0x00ffffff) + 0xff000000; } catch (e) { return this._fillColor; } } public getPixels(rect:Rectangle):ByteArray { if (typeof rect === 'undefined' || rect === null) { throw new Error('Expected a region to acquire pixels.'); } if (rect.width === 0 || rect.height === 0) { return new ByteArray(); } var region:ByteArray = new ByteArray(); for (var i = 0; i < rect.height; i++) { this._byteArray.slice((rect.y + i) * this._rect.width + rect.x, (rect.y + i) * this._rect.width + rect.x + rect.width).forEach(function (v) { region.push(v) }); } return region; } public setPixel(x:number, y:number, color:number):void { // Force alpha channel to be full this.setPixel32(x, y, (color & 0x00ffffff) + 0xff000000); } public setPixel32(x:number, y:number, color:number):void { if (!this._transparent) { // Force alpha channel color = (color & 0x00ffffff) + 0xff000000; } this._byteArray[y * this._rect.width + x] = color; this._dirtyArea.expand(x, y); this._updateBox(); } public setPixels(rect:Rectangle, input:Array<number>):void { if (rect.width === 0 || rect.height === 0) { return; } // Test if the input is correct length if (input.length !== rect.width * rect.height) { throw new Error('setPixels expected ' + (rect.width * rect.height) + ' pixels, but actually got ' + input.length); } if (!this._transparent) { input = input.map(function (color) { return (color & 0x00ffffff) + 0xff000000; }); } for (var i = 0; i < rect.width; i++) { for (var j = 0; j < rect.height; j++) { this._byteArray[(rect.y + j) * this.width + (rect.x + i)] = input[j * rect.width + i]; this._dirtyArea.expand(i, j); } } this._updateBox(); } public getVector(rect:Rectangle):Array<number> { if (this._rect.equals(rect)) { return this._byteArray; } var vector:Array<number> = []; for (var j = rect.y; j < rect.y + rect.height; j++) { for (var i = rect.x; i < rect.x + rect.width; i++) { vector.push(rect[j * this._rect.width + i]); } } return vector; } public lock():void { this._locked = true; } public unlock(changeRect:Rectangle = null):void { this._locked = false; if (changeRect == null) { this._updateBox(); } else { this._updateBox(changeRect); } } public dispatchEvent(_event:string, _data?:any):void { } public getId():string { return this._id; } public serialize():Object { return { 'class':'BitmapData', 'width': this._rect.width, 'height': this._rect.height, 'fill': this._fillColor }; } public unload():void { this._methodCall('unload', null); } public clone():BitmapData { var data = new BitmapData(this.width, this.height, this._transparent, this._fillColor); data._byteArray = this._byteArray.slice(0); data._updateBox(data._rect); return data; } } }
the_stack
import { Vector } from '../vector'; import { StructVector } from './struct'; import { valueToString } from '../util/pretty'; import { DataType, Struct, RowLike } from '../type'; /** @ignore */ const kParent = Symbol.for('parent'); /** @ignore */ const kRowIndex = Symbol.for('rowIndex'); /** @ignore */ const kKeyToIdx = Symbol.for('keyToIdx'); /** @ignore */ const kIdxToVal = Symbol.for('idxToVal'); /** @ignore */ const kCustomInspect = Symbol.for('nodejs.util.inspect.custom'); abstract class Row<K extends PropertyKey = any, V = any> implements Map<K, V> { public readonly size: number; public readonly [Symbol.toStringTag]: string; protected [kRowIndex]: number; protected [kParent]: Vector<Struct>; protected [kKeyToIdx]: Map<K, number>; protected [kIdxToVal]: V[]; constructor(parent: Vector<Struct>, numKeys: number) { this[kParent] = parent; this.size = numKeys; } public abstract keys(): IterableIterator<K>; public abstract values(): IterableIterator<V>; public abstract getKey(idx: number): K; public abstract getIndex(key: K): number; public abstract getValue(idx: number): V; public abstract setValue(idx: number, val: V): void; public entries() { return this[Symbol.iterator](); } public has(key: K) { return this.get(key) !== undefined; } public get(key: K) { let val = undefined; if (key != null) { const ktoi = this[kKeyToIdx] || (this[kKeyToIdx] = new Map()); let idx = ktoi.get(key); if (idx !== undefined) { const itov = this[kIdxToVal] || (this[kIdxToVal] = new Array(this.size)); ((val = itov[idx]) !== undefined) || (itov[idx] = val = this.getValue(idx)); } else if ((idx = this.getIndex(key)) > -1) { ktoi.set(key, idx); const itov = this[kIdxToVal] || (this[kIdxToVal] = new Array(this.size)); ((val = itov[idx]) !== undefined) || (itov[idx] = val = this.getValue(idx)); } } return val; } public set(key: K, val: V) { if (key != null) { const ktoi = this[kKeyToIdx] || (this[kKeyToIdx] = new Map()); let idx = ktoi.get(key); if (idx === undefined) { ktoi.set(key, idx = this.getIndex(key)); } if (idx > -1) { const itov = this[kIdxToVal] || (this[kIdxToVal] = new Array(this.size)); itov[idx] = <any> this.setValue(idx, val); } } return this; } public clear(): void { throw new Error(`Clearing ${this[Symbol.toStringTag]} not supported.`); } public delete(_: K): boolean { throw new Error(`Deleting ${this[Symbol.toStringTag]} values not supported.`); } public *[Symbol.iterator](): IterableIterator<[K, V]> { const ki = this.keys(); const vi = this.values(); const ktoi = this[kKeyToIdx] || (this[kKeyToIdx] = new Map()); const itov = this[kIdxToVal] || (this[kIdxToVal] = new Array(this.size)); for (let k: K, v: V, i = 0, kr: IteratorResult<K>, vr: IteratorResult<V>; !((kr = ki.next()).done || (vr = vi.next()).done); ++i ) { k = kr.value; v = vr.value; itov[i] = v; ktoi.has(k) || ktoi.set(k, i); yield [k, v]; } } public forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void { const ki = this.keys(); const vi = this.values(); const callback = thisArg === undefined ? callbackfn : (v: V, k: K, m: Map<K, V>) => callbackfn.call(thisArg, v, k, m); const ktoi = this[kKeyToIdx] || (this[kKeyToIdx] = new Map()); const itov = this[kIdxToVal] || (this[kIdxToVal] = new Array(this.size)); for (let k: K, v: V, i = 0, kr: IteratorResult<K>, vr: IteratorResult<V>; !((kr = ki.next()).done || (vr = vi.next()).done); ++i ) { k = kr.value; v = vr.value; itov[i] = v; ktoi.has(k) || ktoi.set(k, i); callback(v, k, this); } } public toArray() { return [...this.values()]; } public toJSON() { const obj = {} as any; this.forEach((val, key) => obj[key] = val); return obj; } public inspect() { return this.toString(); } public [kCustomInspect]() { return this.toString(); } public toString() { const str: string[] = []; this.forEach((val, key) => { key = valueToString(key); val = valueToString(val); str.push(`${key}: ${val}`); }); return `{ ${str.join(', ')} }`; } protected static [Symbol.toStringTag] = ((proto: Row) => { Object.defineProperties(proto, { 'size': { writable: true, enumerable: false, configurable: false, value: 0 }, [kParent]: { writable: true, enumerable: false, configurable: false, value: null }, [kRowIndex]: { writable: true, enumerable: false, configurable: false, value: -1 }, }); return (proto as any)[Symbol.toStringTag] = 'Row'; })(Row.prototype); } export class MapRow<K extends DataType = any, V extends DataType = any> extends Row<K['TValue'], V['TValue'] | null> { constructor(slice: Vector<Struct<{ key: K; value: V }>>) { super(slice, slice.length); return createRowProxy(this); } public keys() { return this[kParent].getChildAt(0)![Symbol.iterator](); } public values() { return this[kParent].getChildAt(1)![Symbol.iterator](); } public getKey(idx: number): K['TValue'] { return this[kParent].getChildAt(0)!.get(idx); } public getIndex(key: K['TValue']): number { return this[kParent].getChildAt(0)!.indexOf(key); } public getValue(index: number): V['TValue'] | null { return this[kParent].getChildAt(1)!.get(index); } public setValue(index: number, value: V['TValue'] | null): void { this[kParent].getChildAt(1)!.set(index, value); } } export class StructRow<T extends { [key: string]: DataType } = any> extends Row<keyof T, T[keyof T]['TValue'] | null> { constructor(parent: StructVector<T>) { super(parent, parent.type.children.length); return defineRowProxyProperties(this); } public *keys() { for (const field of this[kParent].type.children) { yield field.name as keyof T; } } public *values() { for (const field of this[kParent].type.children) { yield (this as RowLike<T>)[field.name]; } } public getKey(idx: number): keyof T { return this[kParent].type.children[idx].name as keyof T; } public getIndex(key: keyof T): number { return this[kParent].type.children.findIndex((f) => f.name === key); } public getValue(index: number): T[keyof T]['TValue'] | null { return this[kParent].getChildAt(index)!.get(this[kRowIndex]); } public setValue(index: number, value: T[keyof T]['TValue'] | null): void { return this[kParent].getChildAt(index)!.set(this[kRowIndex], value); } } Object.setPrototypeOf(Row.prototype, Map.prototype); /** @ignore */ const defineRowProxyProperties = (() => { const desc = { enumerable: true, configurable: false, get: null as any, set: null as any }; return <T extends Row>(row: T) => { let idx = -1; const ktoi = row[kKeyToIdx] || (row[kKeyToIdx] = new Map()); const getter = (key: any) => function(this: T) { return this.get(key); }; const setter = (key: any) => function(this: T, val: any) { return this.set(key, val); }; for (const key of row.keys()) { ktoi.set(key, ++idx); desc.get = getter(key); desc.set = setter(key); Object.prototype.hasOwnProperty.call(row, key) || (desc.enumerable = true, Object.defineProperty(row, key, desc)); Object.prototype.hasOwnProperty.call(row, idx) || (desc.enumerable = false, Object.defineProperty(row, idx, desc)); } desc.get = desc.set = null; return row; }; })(); /** @ignore */ const createRowProxy = (() => { if (typeof Proxy === 'undefined') { return defineRowProxyProperties; } const has = Row.prototype.has; const get = Row.prototype.get; const set = Row.prototype.set; const getKey = Row.prototype.getKey; const RowProxyHandler: ProxyHandler<Row> = { isExtensible() { return false; }, deleteProperty() { return false; }, preventExtensions() { return true; }, ownKeys(row: Row) { return [...row.keys()].map((x) => `${x}`); }, has(row: Row, key: PropertyKey) { switch (key) { case 'getKey': case 'getIndex': case 'getValue': case 'setValue': case 'toArray': case 'toJSON': case 'inspect': case 'constructor': case 'isPrototypeOf': case 'propertyIsEnumerable': case 'toString': case 'toLocaleString': case 'valueOf': case 'size': case 'has': case 'get': case 'set': case 'clear': case 'delete': case 'keys': case 'values': case 'entries': case 'forEach': case '__proto__': case '__defineGetter__': case '__defineSetter__': case 'hasOwnProperty': case '__lookupGetter__': case '__lookupSetter__': case Symbol.iterator: case Symbol.toStringTag: case kParent: case kRowIndex: case kIdxToVal: case kKeyToIdx: case kCustomInspect: return true; } if (typeof key === 'number' && !row.has(key)) { key = row.getKey(key); } return row.has(key); }, get(row: Row, key: PropertyKey, receiver: any) { switch (key) { case 'getKey': case 'getIndex': case 'getValue': case 'setValue': case 'toArray': case 'toJSON': case 'inspect': case 'constructor': case 'isPrototypeOf': case 'propertyIsEnumerable': case 'toString': case 'toLocaleString': case 'valueOf': case 'size': case 'has': case 'get': case 'set': case 'clear': case 'delete': case 'keys': case 'values': case 'entries': case 'forEach': case '__proto__': case '__defineGetter__': case '__defineSetter__': case 'hasOwnProperty': case '__lookupGetter__': case '__lookupSetter__': case Symbol.iterator: case Symbol.toStringTag: case kParent: case kRowIndex: case kIdxToVal: case kKeyToIdx: case kCustomInspect: return Reflect.get(row, key, receiver); } if (typeof key === 'number' && !has.call(receiver, key)) { key = getKey.call(receiver, key); } return get.call(receiver, key); }, set(row: Row, key: PropertyKey, val: any, receiver: any) { switch (key) { case kParent: case kRowIndex: case kIdxToVal: case kKeyToIdx: return Reflect.set(row, key, val, receiver); case 'getKey': case 'getIndex': case 'getValue': case 'setValue': case 'toArray': case 'toJSON': case 'inspect': case 'constructor': case 'isPrototypeOf': case 'propertyIsEnumerable': case 'toString': case 'toLocaleString': case 'valueOf': case 'size': case 'has': case 'get': case 'set': case 'clear': case 'delete': case 'keys': case 'values': case 'entries': case 'forEach': case '__proto__': case '__defineGetter__': case '__defineSetter__': case 'hasOwnProperty': case '__lookupGetter__': case '__lookupSetter__': case Symbol.iterator: case Symbol.toStringTag: return false; } if (typeof key === 'number' && !has.call(receiver, key)) { key = getKey.call(receiver, key); } return has.call(receiver, key) ? !!set.call(receiver, key, val) : false; }, }; return <T extends Row>(row: T) => new Proxy(row, RowProxyHandler) as T; })();
the_stack
import { captureException } from '@sentry/core'; import { DebouncerEvents } from '../lib/collections/debouncerEvents/collection'; import { forumTypeSetting, testServerSetting } from '../lib/instanceSettings'; import moment from '../lib/moment-timezone'; import { addCronJob } from './cronUtil'; import { Vulcan } from '../lib/vulcan-lib/config'; let eventDebouncersByName: Partial<Record<string,EventDebouncer<any,any>>> = {}; export type DebouncerTiming = { type: "none" } | { type: "delayed", delayMinutes: number, maxDelayMinutes?: number } | { type: "daily", timeOfDayGMT: number } | { type: "weekly", timeOfDayGMT: number, dayOfWeekGMT: string } // Defines a debouncable event type; that is, an event which, some time after // it happens, causes a function call, with events grouped together into a // single call. We store these events in the database, rather than use a simple // callback function, because this happens over long time scales, the server // might restart before the handler fires, and the handler might run on a // different server than the event(s) was/were generated. // // Each debounced event has a name, which is used in the database to identify // its type and the callback that will handle it. Event types are independent. // Each debounced event also has a key (a JSON object); events with different // keys are also independent. For example, when debouncing notifications to // users, the key would contain a userId. Finally, each debounced event has // eventData (a JSON object); events with different eventData are *not* // independent, and the callback will receive an array containing the eventData // for all of the grouped events. // // Within events that are grouped (ie, that share a name and a key), the way // timing works is: // * When a debounced event happens, it goes into a "pending" state // * When the callback fires, it handles all pending events that share a name // and key, and moves them out of the pending the state // * A callback fires when either delayTime or upperBoundTime is passed // // There are several different possible timing rules. In some cases, these // correspond to user configuration, so different (name,key) pairs can have // different timing rules. A timing rule is an object with a string field "type" // plus other fields depending on the type. The possible timing rules are: // // none: // Events fire on the next cron-tick after they're added (up to 1min). // delayed: // * delayMinutes: number // * maxDelayMinutes: number // Events fire when either it has // been delayMinutes since any event was added to the group, or // maxDelayMinutes since the first event was added to the group // daily: // * timeOfDayGMT: number // There is a day-boundary once per day, at timeOfDayGMT. Events fire // when the current time and the oldest event in the group are on opposite // sides of a day-boundary. // weekly: // * timeOfDayGMT: number // * dayOfWeekGMT: string // As daily, except that in addition to timeOfDayGMT there is also a // dayOfWeekGMT, which is a string like "Saturday". // // The timing rule is specified when each event is being added. If an event // would be added to a group with a different timing rule, that group fires // according to whichever timing rule would make it fire soonest. // // Constructor parameters: // * name: (String) - Used to identify this event type in the database. Must // be unique across EventDebouncers. // * defaultTiming: (Object, optional) - If an event is added with no timing // rule specified, this timing rule is used. If this argument is omitted, // then a timing rule is required when adding an event. // * callback: (key:JSON, events: Array[JSONObject])=>None export class EventDebouncer<KeyType,ValueType> { name: string defaultTiming?: DebouncerTiming callback: (key: KeyType, events: Array<ValueType>)=>void constructor({ name, defaultTiming, callback }: { name: string, defaultTiming: DebouncerTiming, callback: (key: KeyType, events: Array<ValueType>)=>void, }) { if (!name || !callback) throw new Error("EventDebouncer constructor: missing required argument"); if (name in eventDebouncersByName) throw new Error(`Duplicate name for EventDebouncer: ${name}`); this.name = name; this.defaultTiming = defaultTiming; this.callback = callback; eventDebouncersByName[name] = this; } // Add a debounced event. // // Parameters: // * key: (JSON) // * data: (JSON) // * timing: (Object) // * af: (bool) recordEvent = async ({key, data, timing=null, af=false}: { key: KeyType, data: ValueType, timing?: DebouncerTiming|null, af?: boolean, }) => { const timingRule = timing || this.defaultTiming; if (!timingRule) { throw new Error("EventDebouncer.recordEvent: missing timing argument and no defaultTiming set."); } const { newDelayTime, newUpperBoundTime } = this.parseTiming(timingRule); // On rawCollection because minimongo doesn't support $max/$min on Dates await DebouncerEvents.rawCollection().updateOne({ name: this.name, af: af, key: JSON.stringify(key), dispatched: false, }, { $max: { delayTime: newDelayTime.getTime() }, $min: { upperBoundTime: newUpperBoundTime.getTime() }, $push: { pendingEvents: data, } }, { upsert: true }); } parseTiming = (timing: DebouncerTiming) => { const now = new Date(); const msPerMin = 60*1000; switch(timing.type) { default: case "none": return { newDelayTime: now, newUpperBoundTime: now } case "delayed": return { newDelayTime: new Date(now.getTime() + (timing.delayMinutes * msPerMin)), newUpperBoundTime: new Date(now.getTime() + ((timing.maxDelayMinutes||timing.delayMinutes) * msPerMin)), }; case "daily": const nextDailyBatchTime = getDailyBatchTimeAfter(now, timing.timeOfDayGMT); return { newDelayTime: nextDailyBatchTime, newUpperBoundTime: nextDailyBatchTime, } case "weekly": const nextWeeklyBatchTime = getWeeklyBatchTimeAfter(now, timing.timeOfDayGMT, timing.dayOfWeekGMT); return { newDelayTime: nextWeeklyBatchTime, newUpperBoundTime: nextWeeklyBatchTime, } } } _dispatchEvent = async (key: KeyType, events: Array<ValueType>) => { try { //eslint-disable-next-line no-console console.log(`Handling ${events.length} grouped ${this.name} events`); await this.callback(key, events); } catch(e) { //eslint-disable-next-line no-console console.error(e); } }; } // Get the earliest time after now which matches the given time of day. Limited // to one-minute precision. export const getDailyBatchTimeAfter = (now: Date, timeOfDayGMT: number) => { let todaysBatch = moment(now).tz("GMT"); todaysBatch.set('hour', Math.floor(timeOfDayGMT)); todaysBatch.set('minute', 60*(timeOfDayGMT%1)); todaysBatch.set('second', 0); todaysBatch.set('millisecond', 0); if (todaysBatch.isBefore(now)) { return moment(todaysBatch).add(1, 'days').toDate(); } else { return todaysBatch.toDate(); } } // Get the earliest time after now which matches the given time of day and day // of the week. One-minute precision. export const getWeeklyBatchTimeAfter = (now: Date, timeOfDayGMT: number, dayOfWeekGMT: string) => { const nextDailyBatch = moment(getDailyBatchTimeAfter(now, timeOfDayGMT)).tz("GMT"); // Target day of the week, as an integer 0-6 const nextDailyBatchDayOfWeekNum = nextDailyBatch.day(); const targetDayOfWeekNum = moment().day(dayOfWeekGMT).day(); const daysOfWeekDifference = ((targetDayOfWeekNum - nextDailyBatchDayOfWeekNum ) + 7) % 7; const nextWeeklyBatch = nextDailyBatch.add(daysOfWeekDifference, 'days'); return nextWeeklyBatch.toDate(); } const dispatchEvent = async (event: DbDebouncerEvents) => { const eventDebouncer = eventDebouncersByName[event.name]; if (!eventDebouncer) { // eslint-disable-next-line no-console throw new Error(`Unrecognized event type: ${event.name}`); } await eventDebouncer._dispatchEvent(JSON.parse(event.key), event.pendingEvents); } export const dispatchPendingEvents = async () => { const now = new Date().getTime(); const af = forumTypeSetting.get() === 'AlignmentForum' let eventToHandle: any = null; do { // Finds one grouped event that is ready to go, and marks it as handled in // the same operation (to prevent race conditions between multiple servers // checking for events at the same time). // // On rawCollection so that this doesn't get routed through Minimongo, which // doesn't support findOneAndUpdate. const queryResult: any = await DebouncerEvents.rawCollection().findOneAndUpdate( { dispatched: false, af: af, $or: [ { delayTime: {$lt: now} }, { upperBoundTime: {$lt: now} } ] }, { $set: { dispatched: true } } ); eventToHandle = queryResult.value; if (eventToHandle) { try { await dispatchEvent(eventToHandle); } catch (e) { await DebouncerEvents.rawUpdateOne({ _id: eventToHandle._id }, { $set: { failed: true } }); captureException(new Error(`Exception thrown while handling debouncer event ${eventToHandle._id}: ${e}`)); captureException(e); } } // Keep checking for more events to handle so long as one was handled. } while (eventToHandle); }; // Given a Date, dispatch any pending debounced events that would fire on or // before then. If no date is given, dispatch any pending events, regardless of // their timer. You would do this interactively if you're testing and don't // want to wait. export const forcePendingEvents = async (upToDate=null) => { let eventToHandle = null; const af = forumTypeSetting.get() === 'AlignmentForum' let countHandled = 0; do { const queryResult = await DebouncerEvents.rawCollection().findOneAndUpdate( { dispatched: false, af: af, }, { $set: { dispatched: true } }, ); eventToHandle = queryResult.value; if (eventToHandle) { await dispatchEvent(eventToHandle); countHandled++; } // Keep checking for more events to handle so long as one was handled. } while (eventToHandle); // eslint-disable-next-line no-console console.log(`Forced ${countHandled} pending event${countHandled === 1 ? "" : "s"}`); } Vulcan.forcePendingEvents = forcePendingEvents; if (!testServerSetting.get()) { addCronJob({ name: "Debounced event handler", // Once per minute, on the minute cronStyleSchedule: '* * * * *', job() { void dispatchPendingEvents(); } }); }
the_stack
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core'; import { IonRefresher } from '@ionic/angular'; import { CoreApp } from '@services/app'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreCoursesHelper } from '@features/courses/services/courses-helper'; import { AddonCalendar, AddonCalendarProvider } from '../../services/calendar'; import { AddonCalendarOffline } from '../../services/calendar-offline'; import { AddonCalendarSync, AddonCalendarSyncProvider } from '../../services/calendar-sync'; import { AddonCalendarFilter, AddonCalendarHelper } from '../../services/calendar-helper'; import { Network, NgZone } from '@singletons'; import { Subscription } from 'rxjs'; import { CoreEnrolledCourseData } from '@features/courses/services/courses'; import { ActivatedRoute, Params } from '@angular/router'; import { AddonCalendarCalendarComponent } from '../../components/calendar/calendar'; import { AddonCalendarUpcomingEventsComponent } from '../../components/upcoming-events/upcoming-events'; import { AddonCalendarFilterComponent } from '../../components/filter/filter'; import { CoreNavigator } from '@services/navigator'; import { CoreLocalNotifications } from '@services/local-notifications'; import { CoreConstants } from '@/core/constants'; import { CoreMainMenuDeepLinkManager } from '@features/mainmenu/classes/deep-link-manager'; /** * Page that displays the calendar events. */ @Component({ selector: 'page-addon-calendar-index', templateUrl: 'index.html', }) export class AddonCalendarIndexPage implements OnInit, OnDestroy { @ViewChild(AddonCalendarCalendarComponent) calendarComponent?: AddonCalendarCalendarComponent; @ViewChild(AddonCalendarUpcomingEventsComponent) upcomingEventsComponent?: AddonCalendarUpcomingEventsComponent; protected currentSiteId: string; // Observers. protected newEventObserver?: CoreEventObserver; protected discardedObserver?: CoreEventObserver; protected editEventObserver?: CoreEventObserver; protected deleteEventObserver?: CoreEventObserver; protected undeleteEventObserver?: CoreEventObserver; protected syncObserver?: CoreEventObserver; protected manualSyncObserver?: CoreEventObserver; protected onlineObserver?: Subscription; protected filterChangedObserver?: CoreEventObserver; year?: number; month?: number; canCreate = false; courses: Partial<CoreEnrolledCourseData>[] = []; notificationsEnabled = false; loaded = false; hasOffline = false; isOnline = false; syncIcon = CoreConstants.ICON_LOADING; showCalendar = true; loadUpcoming = false; filter: AddonCalendarFilter = { filtered: false, courseId: undefined, categoryId: undefined, course: true, group: true, site: true, user: true, category: true, }; constructor( protected route: ActivatedRoute, ) { this.currentSiteId = CoreSites.getCurrentSiteId(); // Listen for events added. When an event is added, reload the data. this.newEventObserver = CoreEvents.on( AddonCalendarProvider.NEW_EVENT_EVENT, (data) => { if (data && data.eventId) { this.loaded = false; this.refreshData(true, false, true); } }, this.currentSiteId, ); // Listen for new event discarded event. When it does, reload the data. this.discardedObserver = CoreEvents.on(AddonCalendarProvider.NEW_EVENT_DISCARDED_EVENT, () => { this.loaded = false; this.refreshData(true, false, true); }, this.currentSiteId); // Listen for events edited. When an event is edited, reload the data. this.editEventObserver = CoreEvents.on( AddonCalendarProvider.EDIT_EVENT_EVENT, (data) => { if (data && data.eventId) { this.loaded = false; this.refreshData(true, false, true); } }, this.currentSiteId, ); // Refresh data if calendar events are synchronized automatically. this.syncObserver = CoreEvents.on(AddonCalendarSyncProvider.AUTO_SYNCED, () => { this.loaded = false; this.refreshData(false, false, true); }, this.currentSiteId); // Refresh data if calendar events are synchronized manually but not by this page. this.manualSyncObserver = CoreEvents.on(AddonCalendarSyncProvider.MANUAL_SYNCED, (data) => { if (data && data.source != 'index') { this.loaded = false; this.refreshData(false, false, true); } }, this.currentSiteId); // Update the events when an event is deleted. this.deleteEventObserver = CoreEvents.on(AddonCalendarProvider.DELETED_EVENT_EVENT, () => { this.loaded = false; this.refreshData(false, false, true); }, this.currentSiteId); // Update the "hasOffline" property if an event deleted in offline is restored. this.undeleteEventObserver = CoreEvents.on(AddonCalendarProvider.UNDELETED_EVENT_EVENT, async () => { this.hasOffline = await AddonCalendarOffline.hasOfflineData(); }, this.currentSiteId); this.filterChangedObserver = CoreEvents.on( AddonCalendarProvider.FILTER_CHANGED_EVENT, async (filterData) => { this.filter = filterData; // Course viewed has changed, check if the user can create events for this course calendar. this.canCreate = await AddonCalendarHelper.canEditEvents(this.filter.courseId); }, ); // Refresh online status when changes. this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. NgZone.run(() => { this.isOnline = CoreApp.isOnline(); }); }); } /** * View loaded. */ ngOnInit(): void { this.notificationsEnabled = CoreLocalNotifications.isAvailable(); this.loadUpcoming = !!CoreNavigator.getRouteBooleanParam('upcoming'); this.showCalendar = !this.loadUpcoming; this.route.queryParams.subscribe(async () => { this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId'); this.year = CoreNavigator.getRouteNumberParam('year'); this.month = CoreNavigator.getRouteNumberParam('month'); this.filter.filtered = !!this.filter.courseId; this.fetchData(true, false); }); const deepLinkManager = new CoreMainMenuDeepLinkManager(); deepLinkManager.treatLink(); } /** * Fetch all the data required for the view. * * @param sync Whether it should try to synchronize offline events. * @param showErrors Whether to show sync errors to the user. * @return Promise resolved when done. */ async fetchData(sync?: boolean, showErrors?: boolean): Promise<void> { this.syncIcon = CoreConstants.ICON_LOADING; this.isOnline = CoreApp.isOnline(); if (sync) { // Try to synchronize offline events. try { const result = await AddonCalendarSync.syncEvents(); if (result.warnings && result.warnings.length) { CoreDomUtils.showErrorModal(result.warnings[0]); } if (result.updated) { // Trigger a manual sync event. result.source = 'index'; CoreEvents.trigger( AddonCalendarSyncProvider.MANUAL_SYNCED, result, this.currentSiteId, ); } } catch (error) { if (showErrors) { CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } } } try { const promises: Promise<void>[] = []; this.hasOffline = false; // Load courses for the popover. promises.push(CoreCoursesHelper.getCoursesForPopover(this.filter.courseId).then((data) => { this.courses = data.courses; return; })); // Check if user can create events. promises.push(AddonCalendarHelper.canEditEvents(this.filter.courseId).then((canEdit) => { this.canCreate = canEdit; return; })); // Check if there is offline data. promises.push(AddonCalendarOffline.hasOfflineData().then((hasOffline) => { this.hasOffline = hasOffline; return; })); await Promise.all(promises); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.loaded = true; this.syncIcon = CoreConstants.ICON_SYNC; } /** * Refresh the data. * * @param refresher Refresher. * @param done Function to call when done. * @param showErrors Whether to show sync errors to the user. * @return Promise resolved when done. */ async doRefresh(refresher?: IonRefresher, done?: () => void, showErrors?: boolean): Promise<void> { if (!this.loaded) { return; } await this.refreshData(true, showErrors).finally(() => { refresher?.complete(); done && done(); }); } /** * Refresh the data. * * @param sync Whether it should try to synchronize offline events. * @param showErrors Whether to show sync errors to the user. * @param afterChange Whether the refresh is done after an event has changed or has been synced. * @return Promise resolved when done. */ async refreshData(sync = false, showErrors = false, afterChange = false): Promise<void> { this.syncIcon = CoreConstants.ICON_LOADING; const promises: Promise<void>[] = []; promises.push(AddonCalendar.invalidateAllowedEventTypes()); // Refresh the sub-component. if (this.showCalendar && this.calendarComponent) { promises.push(this.calendarComponent.refreshData(afterChange)); } else if (!this.showCalendar && this.upcomingEventsComponent) { promises.push(this.upcomingEventsComponent.refreshData()); } await Promise.all(promises).finally(() => this.fetchData(sync, showErrors)); } /** * Navigate to a particular event. * * @param eventId Event to load. */ gotoEvent(eventId: number): void { CoreNavigator.navigateToSitePath(`/calendar/event/${eventId}`); } /** * View a certain day. * * @param data Data with the year, month and day. */ gotoDay(data: {day: number; month: number; year: number}): void { const params: Params = { day: data.day, month: data.month, year: data.year, }; Object.keys(this.filter).forEach((key) => { params[key] = this.filter[key]; }); CoreNavigator.navigateToSitePath('/calendar/day', { params }); } /** * Show the filter menu. */ async openFilter(): Promise<void> { await CoreDomUtils.openSideModal({ component: AddonCalendarFilterComponent, componentProps: { courses: this.courses, filter: this.filter, }, }); } /** * Open page to create/edit an event. * * @param eventId Event ID to edit. */ openEdit(eventId?: number): void { const params: Params = {}; eventId = eventId || 0; if (this.filter.courseId) { params.courseId = this.filter.courseId; } CoreNavigator.navigateToSitePath(`/calendar/edit/${eventId}`, { params }); } /** * Open calendar events settings. */ openSettings(): void { CoreNavigator.navigateToSitePath('/calendar/calendar-settings'); } /** * Toogle display: monthly view or upcoming events. */ toggleDisplay(): void { this.showCalendar = !this.showCalendar; if (!this.showCalendar) { this.loadUpcoming = true; } } /** * Page destroyed. */ ngOnDestroy(): void { this.newEventObserver?.off(); this.discardedObserver?.off(); this.editEventObserver?.off(); this.deleteEventObserver?.off(); this.undeleteEventObserver?.off(); this.syncObserver?.off(); this.manualSyncObserver?.off(); this.filterChangedObserver?.off(); this.onlineObserver?.unsubscribe(); } }
the_stack
import { Currencies, OffersData, TradesData, Depth, Currency, Interval, HighLowOpenClose, Markets, Offers, Offer, BisqTrade, MarketVolume, Tickers, Ticker, SummarizedIntervals, SummarizedInterval } from './interfaces'; const strtotime = require('./strtotime'); class BisqMarketsApi { private cryptoCurrencyData: Currency[] = []; private fiatCurrencyData: Currency[] = []; private activeCryptoCurrencyData: Currency[] = []; private activeFiatCurrencyData: Currency[] = []; private offersData: OffersData[] = []; private tradesData: TradesData[] = []; private fiatCurrenciesIndexed: { [code: string]: true } = {}; private allCurrenciesIndexed: { [code: string]: Currency } = {}; private tradeDataByMarket: { [market: string]: TradesData[] } = {}; private tickersCache: Ticker | Tickers | null = null; constructor() { } setOffersData(offers: OffersData[]) { this.offersData = offers; } setTradesData(trades: TradesData[]) { this.tradesData = trades; this.tradeDataByMarket = {}; this.tradesData.forEach((trade) => { trade._market = trade.currencyPair.toLowerCase().replace('/', '_'); if (!this.tradeDataByMarket[trade._market]) { this.tradeDataByMarket[trade._market] = []; } this.tradeDataByMarket[trade._market].push(trade); }); } setCurrencyData(cryptoCurrency: Currency[], fiatCurrency: Currency[], activeCryptoCurrency: Currency[], activeFiatCurrency: Currency[]) { this.cryptoCurrencyData = cryptoCurrency, this.fiatCurrencyData = fiatCurrency, this.activeCryptoCurrencyData = activeCryptoCurrency, this.activeFiatCurrencyData = activeFiatCurrency; this.fiatCurrenciesIndexed = {}; this.allCurrenciesIndexed = {}; this.fiatCurrencyData.forEach((currency) => { currency._type = 'fiat'; this.fiatCurrenciesIndexed[currency.code] = true; this.allCurrenciesIndexed[currency.code] = currency; }); this.cryptoCurrencyData.forEach((currency) => { currency._type = 'crypto'; this.allCurrenciesIndexed[currency.code] = currency; }); } updateCache() { this.tickersCache = null; this.tickersCache = this.getTicker(); } getCurrencies( type: 'crypto' | 'fiat' | 'active' | 'all' = 'all', ): Currencies { let currencies: Currency[]; switch (type) { case 'fiat': currencies = this.fiatCurrencyData; break; case 'crypto': currencies = this.cryptoCurrencyData; break; case 'active': currencies = this.activeCryptoCurrencyData.concat(this.activeFiatCurrencyData); break; case 'all': default: currencies = this.cryptoCurrencyData.concat(this.fiatCurrencyData); } const result = {}; currencies.forEach((currency) => { result[currency.code] = currency; }); return result; } getDepth( market: string, ): Depth { const currencyPair = market.replace('_', '/').toUpperCase(); const buys = this.offersData .filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'BUY') .map((offer) => offer.price) .sort((a, b) => b - a) .map((price) => this.intToBtc(price)); const sells = this.offersData .filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'SELL') .map((offer) => offer.price) .sort((a, b) => a - b) .map((price) => this.intToBtc(price)); const result = {}; result[market] = { 'buys': buys, 'sells': sells, }; return result; } getOffers( market: string, direction?: 'buy' | 'sell', ): Offers { const currencyPair = market.replace('_', '/').toUpperCase(); let buys: Offer[] | null = null; let sells: Offer[] | null = null; if (!direction || direction === 'buy') { buys = this.offersData .filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'BUY') .sort((a, b) => b.price - a.price) .map((offer) => this.offerDataToOffer(offer, market)); } if (!direction || direction === 'sell') { sells = this.offersData .filter((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'SELL') .sort((a, b) => a.price - b.price) .map((offer) => this.offerDataToOffer(offer, market)); } const result: Offers = {}; result[market] = { 'buys': buys, 'sells': sells, }; return result; } getMarkets(): Markets { const allCurrencies = this.getCurrencies(); const activeCurrencies = this.getCurrencies('active'); const markets = {}; for (const currency of Object.keys(activeCurrencies)) { if (allCurrencies[currency].code === 'BTC') { continue; } const isFiat = allCurrencies[currency]._type === 'fiat'; const pmarketname = allCurrencies['BTC']['name']; const lsymbol = isFiat ? 'BTC' : currency; const rsymbol = isFiat ? currency : 'BTC'; const lname = isFiat ? pmarketname : allCurrencies[currency].name; const rname = isFiat ? allCurrencies[currency].name : pmarketname; const ltype = isFiat ? 'crypto' : allCurrencies[currency]._type; const rtype = isFiat ? 'fiat' : 'crypto'; const lprecision = 8; const rprecision = isFiat ? 2 : 8; const pair = lsymbol.toLowerCase() + '_' + rsymbol.toLowerCase(); markets[pair] = { 'pair': pair, 'lname': lname, 'rname': rname, 'lsymbol': lsymbol, 'rsymbol': rsymbol, 'lprecision': lprecision, 'rprecision': rprecision, 'ltype': ltype, 'rtype': rtype, 'name': lname + '/' + rname, }; } return markets; } getTrades( market: string, timestamp_from?: number, timestamp_to?: number, trade_id_from?: string, trade_id_to?: string, direction?: 'buy' | 'sell', limit: number = 100, sort: 'asc' | 'desc' = 'desc', ): BisqTrade[] { limit = Math.min(limit, 2000); const _market = market === 'all' ? undefined : market; if (!timestamp_from) { timestamp_from = new Date('2016-01-01').getTime() / 1000; } if (!timestamp_to) { timestamp_to = new Date().getTime() / 1000; } const matches = this.getTradesByCriteria(_market, timestamp_to, timestamp_from, trade_id_to, trade_id_from, direction, sort, limit, false); if (sort === 'asc') { matches.sort((a, b) => a.tradeDate - b.tradeDate); } else { matches.sort((a, b) => b.tradeDate - a.tradeDate); } return matches.map((trade) => { const bsqTrade: BisqTrade = { direction: trade.primaryMarketDirection, price: trade._tradePriceStr, amount: trade._tradeAmountStr, volume: trade._tradeVolumeStr, payment_method: trade.paymentMethod, trade_id: trade.offerId, trade_date: trade.tradeDate, }; if (market === 'all') { bsqTrade.market = trade._market; } return bsqTrade; }); } getVolumes( market?: string, timestamp_from?: number, timestamp_to?: number, interval: Interval = 'auto', milliseconds?: boolean, timestamp: 'no' | 'yes' = 'yes', ): MarketVolume[] { if (milliseconds) { timestamp_from = timestamp_from ? timestamp_from / 1000 : timestamp_from; timestamp_to = timestamp_to ? timestamp_to / 1000 : timestamp_to; } if (!timestamp_from) { timestamp_from = new Date('2016-01-01').getTime() / 1000; } if (!timestamp_to) { timestamp_to = new Date().getTime() / 1000; } const trades = this.getTradesByCriteria(market, timestamp_to, timestamp_from, undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER); if (interval === 'auto') { const range = timestamp_to - timestamp_from; interval = this.getIntervalFromRange(range); } const intervals: any = {}; const marketVolumes: MarketVolume[] = []; for (const trade of trades) { const traded_at = trade['tradeDate'] / 1000; const interval_start = this.intervalStart(traded_at, interval); if (!intervals[interval_start]) { intervals[interval_start] = { 'volume': 0, 'num_trades': 0, }; } const period = intervals[interval_start]; period['period_start'] = interval_start; period['volume'] += this.fiatCurrenciesIndexed[trade.currency] ? trade._tradeAmount : trade._tradeVolume; period['num_trades']++; } for (const p in intervals) { if (intervals.hasOwnProperty(p)) { const period = intervals[p]; marketVolumes.push({ period_start: timestamp === 'no' ? new Date(period['period_start'] * 1000).toISOString() : period['period_start'], num_trades: period['num_trades'], volume: this.intToBtc(period['volume']), }); } } return marketVolumes; } getTicker( market?: string, ): Tickers | Ticker | null { if (market) { return this.getTickerFromMarket(market); } if (this.tickersCache) { return this.tickersCache; } const allMarkets = this.getMarkets(); const tickers = {}; for (const m in allMarkets) { if (allMarkets.hasOwnProperty(m)) { tickers[allMarkets[m].pair] = this.getTickerFromMarket(allMarkets[m].pair); } } return tickers; } getTickerFromMarket(market: string): Ticker | null { let ticker: Ticker; const timestamp_from = strtotime('-24 hour'); const timestamp_to = new Date().getTime() / 1000; const trades = this.getTradesByCriteria(market, timestamp_to, timestamp_from, undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER); const periods: SummarizedInterval[] = Object.values(this.getTradesSummarized(trades, timestamp_from)); const allCurrencies = this.getCurrencies(); const currencyRight = allCurrencies[market.split('_')[1].toUpperCase()]; if (periods[0]) { ticker = { 'last': this.intToBtc(periods[0].close), 'high': this.intToBtc(periods[0].high), 'low': this.intToBtc(periods[0].low), 'volume_left': this.intToBtc(periods[0].volume_left), 'volume_right': this.intToBtc(periods[0].volume_right), 'buy': null, 'sell': null, }; } else { const lastTrade = this.tradeDataByMarket[market]; if (!lastTrade) { return null; } const tradePrice = lastTrade[0].primaryMarketTradePrice * Math.pow(10, 8 - currencyRight.precision); const lastTradePrice = this.intToBtc(tradePrice); ticker = { 'last': lastTradePrice, 'high': lastTradePrice, 'low': lastTradePrice, 'volume_left': '0', 'volume_right': '0', 'buy': null, 'sell': null, }; } const timestampFromMilli = timestamp_from * 1000; const timestampToMilli = timestamp_to * 1000; const currencyPair = market.replace('_', '/').toUpperCase(); const offersData = this.offersData.slice().sort((a, b) => a.price - b.price); const buy = offersData.find((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'BUY' && offer.date >= timestampFromMilli && offer.date <= timestampToMilli ); const sell = offersData.find((offer) => offer.currencyPair === currencyPair && offer.primaryMarketDirection === 'SELL' && offer.date >= timestampFromMilli && offer.date <= timestampToMilli ); if (buy) { ticker.buy = this.intToBtc(buy.primaryMarketPrice * Math.pow(10, 8 - currencyRight.precision)); } if (sell) { ticker.sell = this.intToBtc(sell.primaryMarketPrice * Math.pow(10, 8 - currencyRight.precision)); } return ticker; } getHloc( market: string, interval: Interval = 'auto', timestamp_from?: number, timestamp_to?: number, milliseconds?: boolean, timestamp: 'no' | 'yes' = 'yes', ): HighLowOpenClose[] { if (milliseconds) { timestamp_from = timestamp_from ? timestamp_from / 1000 : timestamp_from; timestamp_to = timestamp_to ? timestamp_to / 1000 : timestamp_to; } if (!timestamp_from) { timestamp_from = new Date('2016-01-01').getTime() / 1000; } if (!timestamp_to) { timestamp_to = new Date().getTime() / 1000; } const trades = this.getTradesByCriteria(market, timestamp_to, timestamp_from, undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER); if (interval === 'auto') { const range = timestamp_to - timestamp_from; interval = this.getIntervalFromRange(range); } const intervals = this.getTradesSummarized(trades, timestamp_from, interval); const hloc: HighLowOpenClose[] = []; for (const p in intervals) { if (intervals.hasOwnProperty(p)) { const period = intervals[p]; hloc.push({ period_start: timestamp === 'no' ? new Date(period['period_start'] * 1000).toISOString() : period['period_start'], open: this.intToBtc(period['open']), close: this.intToBtc(period['close']), high: this.intToBtc(period['high']), low: this.intToBtc(period['low']), avg: this.intToBtc(period['avg']), volume_right: this.intToBtc(period['volume_right']), volume_left: this.intToBtc(period['volume_left']), }); } } return hloc; } private getIntervalFromRange(range: number): Interval { // two days range loads minute data if (range <= 3600) { // up to one hour range loads minutely data return 'minute'; } else if (range <= 1 * 24 * 3600) { // up to one day range loads half-hourly data return 'half_hour'; } else if (range <= 3 * 24 * 3600) { // up to 3 day range loads hourly data return 'hour'; } else if (range <= 7 * 24 * 3600) { // up to 7 day range loads half-daily data return 'half_day'; } else if (range <= 60 * 24 * 3600) { // up to 2 month range loads daily data return 'day'; } else if (range <= 12 * 31 * 24 * 3600) { // up to one year range loads weekly data return 'week'; } else if (range <= 12 * 31 * 24 * 3600) { // up to 5 year range loads monthly data return 'month'; } else { // greater range loads yearly data return 'year'; } } getVolumesByTime(time: number): MarketVolume[] { const timestamp_from = new Date().getTime() / 1000 - time; const timestamp_to = new Date().getTime() / 1000; const trades = this.getTradesByCriteria(undefined, timestamp_to, timestamp_from, undefined, undefined, undefined, 'asc', Number.MAX_SAFE_INTEGER); const markets: any = {}; for (const trade of trades) { if (!markets[trade._market]) { markets[trade._market] = { 'volume': 0, 'num_trades': 0, }; } markets[trade._market]['volume'] += this.fiatCurrenciesIndexed[trade.currency] ? trade._tradeAmount : trade._tradeVolume; markets[trade._market]['num_trades']++; } return markets; } private getTradesSummarized(trades: TradesData[], timestamp_from: number, interval?: string): SummarizedIntervals { const intervals: any = {}; const intervals_prices: any = {}; for (const trade of trades) { const traded_at = trade.tradeDate / 1000; const interval_start = !interval ? timestamp_from : this.intervalStart(traded_at, interval); if (!intervals[interval_start]) { intervals[interval_start] = { 'open': 0, 'close': 0, 'high': 0, 'low': 0, 'avg': 0, 'volume_right': 0, 'volume_left': 0, }; intervals_prices[interval_start] = []; } const period = intervals[interval_start]; const price = trade._tradePrice; if (!intervals_prices[interval_start]['leftvol']) { intervals_prices[interval_start]['leftvol'] = []; } if (!intervals_prices[interval_start]['rightvol']) { intervals_prices[interval_start]['rightvol'] = []; } intervals_prices[interval_start]['leftvol'].push(trade._tradeAmount); intervals_prices[interval_start]['rightvol'].push(trade._tradeVolume); if (price) { const plow = period['low']; period['period_start'] = interval_start; period['open'] = period['open'] || price; period['close'] = price; period['high'] = price > period['high'] ? price : period['high']; period['low'] = (plow && price > plow) ? period['low'] : price; period['avg'] = intervals_prices[interval_start]['rightvol'].reduce((p: number, c: number) => c + p, 0) / intervals_prices[interval_start]['leftvol'].reduce((c: number, p: number) => c + p, 0) * 100000000; period['volume_left'] += trade._tradeAmount; period['volume_right'] += trade._tradeVolume; } } return intervals; } private getTradesByCriteria( market: string | undefined, timestamp_to: number, timestamp_from: number, trade_id_to: string | undefined, trade_id_from: string | undefined, direction: 'buy' | 'sell' | undefined, sort: string, limit: number, integerAmounts: boolean = true, ): TradesData[] { let trade_id_from_ts: number | null = null; let trade_id_to_ts: number | null = null; const allCurrencies = this.getCurrencies(); const timestampFromMilli = timestamp_from * 1000; const timestampToMilli = timestamp_to * 1000; // note: the offer_id_from/to depends on iterating over trades in // descending chronological order. const tradesDataSorted = this.tradesData.slice(); if (sort === 'asc') { tradesDataSorted.reverse(); } let matches: TradesData[] = []; for (const trade of tradesDataSorted) { if (trade_id_from === trade.offerId) { trade_id_from_ts = trade.tradeDate; } if (trade_id_to === trade.offerId) { trade_id_to_ts = trade.tradeDate; } if (trade_id_to && trade_id_to_ts === null) { continue; } if (trade_id_from && trade_id_from_ts != null && trade_id_from_ts !== trade.tradeDate) { continue; } if (market && market !== trade._market) { continue; } if (timestampFromMilli && timestampFromMilli > trade.tradeDate) { continue; } if (timestampToMilli && timestampToMilli < trade.tradeDate) { continue; } if (direction && direction !== trade.direction.toLowerCase()) { continue; } // Filter out bogus trades with BTC/BTC or XXX/XXX market. // See github issue: https://github.com/bitsquare/bitsquare/issues/883 const currencyPairs = trade.currencyPair.split('/'); if (currencyPairs[0] === currencyPairs[1]) { continue; } const currencyLeft = allCurrencies[currencyPairs[0]]; const currencyRight = allCurrencies[currencyPairs[1]]; if (!currencyLeft || !currencyRight) { continue; } const tradePrice = trade.primaryMarketTradePrice * Math.pow(10, 8 - currencyRight.precision); const tradeAmount = trade.primaryMarketTradeAmount * Math.pow(10, 8 - currencyLeft.precision); const tradeVolume = trade.primaryMarketTradeVolume * Math.pow(10, 8 - currencyRight.precision); if (integerAmounts) { trade._tradePrice = tradePrice; trade._tradeAmount = tradeAmount; trade._tradeVolume = tradeVolume; trade._offerAmount = trade.offerAmount; } else { trade._tradePriceStr = this.intToBtc(tradePrice); trade._tradeAmountStr = this.intToBtc(tradeAmount); trade._tradeVolumeStr = this.intToBtc(tradeVolume); trade._offerAmountStr = this.intToBtc(trade.offerAmount); } matches.push(trade); if (matches.length >= limit) { break; } } if ((trade_id_from && !trade_id_from_ts) || (trade_id_to && !trade_id_to_ts)) { matches = []; } return matches; } private intervalStart(ts: number, interval: string): number { switch (interval) { case 'minute': return (ts - (ts % 60)); case '10_minute': return (ts - (ts % 600)); case 'half_hour': return (ts - (ts % 1800)); case 'hour': return (ts - (ts % 3600)); case 'half_day': return (ts - (ts % (3600 * 12))); case 'day': return strtotime('midnight today', ts); case 'week': return strtotime('midnight sunday last week', ts); case 'month': return strtotime('midnight first day of this month', ts); case 'year': return strtotime('midnight first day of january', ts); default: throw new Error('Unsupported interval: ' + interval); } } private offerDataToOffer(offer: OffersData, market: string): Offer { const currencyPairs = market.split('_'); const currencyRight = this.allCurrenciesIndexed[currencyPairs[1].toUpperCase()]; const currencyLeft = this.allCurrenciesIndexed[currencyPairs[0].toUpperCase()]; const price = offer['primaryMarketPrice'] * Math.pow( 10, 8 - currencyRight['precision']); const amount = offer['primaryMarketAmount'] * Math.pow( 10, 8 - currencyLeft['precision']); const volume = offer['primaryMarketVolume'] * Math.pow( 10, 8 - currencyRight['precision']); return { offer_id: offer.id, offer_date: offer.date, direction: offer.primaryMarketDirection, min_amount: this.intToBtc(offer.minAmount), amount: this.intToBtc(amount), price: this.intToBtc(price), volume: this.intToBtc(volume), payment_method: offer.paymentMethod, offer_fee_txid: null, }; } private intToBtc(val: number): string { return (val / 100000000).toFixed(8); } } export default new BisqMarketsApi();
the_stack
import i18next from "i18next"; import { action, runInAction } from "mobx"; import retry from "retry"; import formatError from "terriajs-cesium/Source/Core/formatError"; import Rectangle from "terriajs-cesium/Source/Core/Rectangle"; import Resource from "terriajs-cesium/Source/Core/Resource"; import TileProviderError from "terriajs-cesium/Source/Core/TileProviderError"; import ImageryProvider from "terriajs-cesium/Source/Scene/ImageryProvider"; import when from "terriajs-cesium/Source/ThirdParty/when"; import Constructor from "../Core/Constructor"; import TerriaError from "../Core/TerriaError"; import getUrlForImageryTile from "../Map/getUrlForImageryTile"; import CommonStrata from "../Models/Definition/CommonStrata"; import CompositeCatalogItem from "../Models/Catalog/CatalogItems/CompositeCatalogItem"; import Model from "../Models/Definition/Model"; import CatalogMemberTraits from "../Traits/TraitsClasses/CatalogMemberTraits"; import MappableTraits from "../Traits/TraitsClasses/MappableTraits"; import RasterLayerTraits from "../Traits/TraitsClasses/RasterLayerTraits"; import DiscretelyTimeVaryingMixin from "./DiscretelyTimeVaryingMixin"; import MappableMixin from "./MappableMixin"; type ModelType = Model< MappableTraits & RasterLayerTraits & CatalogMemberTraits > & MappableMixin.Instance; /** * A mixin for handling tile errors in raster layers * */ function TileErrorHandlerMixin<T extends Constructor<ModelType>>(Base: T) { abstract class Klass extends Base { tileFailures = 0; private readonly tileRetriesByMap: Map<string, number> = new Map(); tileRetryOptions: retry.OperationOptions = { retries: 8, minTimeout: 200, randomize: true }; /** * A hook that may be implemented by catalog items for custom handling of tile errors. * * @param maybeError A tile request promise that that fails with the tile error * @param tile The tile to be fetched * @returns A modified promise * * The item can then decide to retry the tile request after adding custom parameters * like an authentication token. */ handleTileError?: ( request: Promise<void>, tile: { x: number; y: number; level: number } ) => Promise<void>; get hasTileErrorHandlerMixin() { return true; } /* * Handling tile errors is really complicated because: * * 1) things go wrong for a variety of weird reasons including server * misconfiguration, servers that are flakey but not totally broken, * etc. * * 2) we want to fail as gracefully as possible, and give flakey servers * every chance chance to shine * * 3) we don't generally have enough information the first time something fails. * * There are several mechanisms in play here: * - Cesium's Resource automatically keeps trying to load any resource * that fails until told to stop, but tells us each time. * - The "retry" library knows how to pace the retries, and when to actually stop. */ onTileLoadError(tileProviderError: TileProviderError): void { const operation = retry.operation(this.tileRetryOptions); // Ideally this should be a `Promise` but we use a less ideal `when` for now // because our cesium fork expects a when object here: // https://github.com/TerriaJS/cesium/blob/terriajs/Source/Core/TileProviderError.js#L161 // // result.reject = stop trying to load this tile // result.resolve = retry loading this tile const result = when.defer(); const imageryProvider = tileProviderError.provider as ImageryProvider; const tile = { x: tileProviderError.x, y: tileProviderError.y, level: tileProviderError.level }; // We're only concerned about failures for tiles that actually overlap this item's extent. if ( isTileOutsideExtent( tile, runInAction(() => this.cesiumRectangle), imageryProvider ) ) { tileProviderError.retry = false; return; } /** Helper methods **/ // Give up loading this (definitively, unexpectedly bad) tile and // possibly give up on this layer entirely. const failTile = action((e: Error) => { this.tileFailures += 1; const opts = this.tileErrorHandlingOptions; const thresholdBeforeDisablingItem = opts.thresholdBeforeDisablingItem === undefined ? 5 : opts.thresholdBeforeDisablingItem; if (this.tileFailures > thresholdBeforeDisablingItem && this.show) { if (isThisItemABaseMap()) { this.terria.raiseErrorToUser( new TerriaError({ sender: this, title: i18next.t( "models.imageryLayer.accessingBaseMapErrorTitle" ), message: i18next.t( "models.imageryLayer.accessingBaseMapErrorMessage", { name: this.name } ) + "<pre>" + formatError(e) + "</pre>" }) ); } else { this.terria.raiseErrorToUser( new TerriaError({ sender: this, title: i18next.t( "models.imageryLayer.accessingCatalogItemErrorTitle" ), message: i18next.t( "models.imageryLayer.accessingCatalogItemErrorMessage", { name: this.name } ) + "<pre>" + formatError(e) + "</pre>" }) ); } this.setTrait(CommonStrata.user, "show", false); } operation.stop(); result.reject(); }); const tellMapToSilentlyGiveUp = () => { operation.stop(); result.reject(); }; const retryWithBackoff = (e: Error) => { operation.retry(e) || failTile(e); }; const tellMapToRetry = () => { operation.stop(); result.resolve(); }; const getTileKey = (tile: { x: number; y: number; level: number }) => { const time = DiscretelyTimeVaryingMixin.isMixedInto(this) ? this.currentTime : ""; const key = `L${tile.level}X${tile.x}Y${tile.y}${time}`; return key; }; const isThisItemABaseMap = () => { const baseMap = this.terria.mainViewer.baseMap; return this === (baseMap as any) ? true : baseMap instanceof CompositeCatalogItem ? baseMap.memberModels.includes(this) : false; }; /** End helper methods **/ // By setting retry to a promise, we tell cesium/leaflet to // reload the tile if the promise resolves successfully // https://github.com/TerriaJS/cesium/blob/terriajs/Source/Core/TileProviderError.js#L161 tileProviderError.retry = result; if (tileProviderError.timesRetried === 0) { // There was an intervening success, so restart our count of the tile failures. this.tileFailures = 0; this.tileRetriesByMap.clear(); } operation.attempt( action(async attemptNumber => { if (this.show === false) { // If the layer is no longer shown, ignore errors and don't retry. tellMapToSilentlyGiveUp(); return; } const { ignoreUnknownTileErrors, treat403AsError, treat404AsError } = this.tileErrorHandlingOptions; // Browsers don't tell us much about a failed image load, so we do an // XHR to get more error information if needed. const maybeXhr = attemptNumber === 1 ? Promise.reject(tileProviderError.error) : fetchTileImage(tile, imageryProvider); if (this.handleTileError && maybeXhr) { // Give the catalog item a chance to handle this error. this.handleTileError(maybeXhr as any, tile); } try { await maybeXhr; const key = getTileKey(tile); const retriesByMap = this.tileRetriesByMap .set(key, (this.tileRetriesByMap.get(key) || 0) + 1) .get(key) || 0; if (retriesByMap > 5) { // Be careful: it's conceivable that a request here will always // succeed while a request made by the map will always fail, // e.g. as a result of different request headers. We must not get // stuck repeating the request forever in that scenario. Instead, // we should give up after a few attempts. failTile({ name: i18next.t("models.imageryLayer.tileErrorTitle"), message: i18next.t("models.imageryLayer.tileErrorMessage", { url: getUrlForImageryTile( imageryProvider, tileProviderError.x, tileProviderError.y, tileProviderError.level ) }) }); } else { // Either: // - the XHR request for more information surprisingly worked // this time, let's hope the good luck continues when Cesium/Leaflet retries. // - the ImageryCatalogItem looked at the error and said we should try again. tellMapToRetry(); } } catch (error) { // This attempt failed. We'll either retry (for 500s) or give up // depending on the status code. const e: Error & { statusCode?: number } = error || {}; if (e.statusCode === undefined) { if (runInAction(() => ignoreUnknownTileErrors)) { tellMapToSilentlyGiveUp(); } else if ((e as any).target !== undefined) { // This is a failed image element, which means we got a 200 response but // could not load it as an image. failTile({ name: i18next.t("models.imageryLayer.tileErrorTitle"), message: i18next.t("models.imageryLayer.tileErrorMessageII", { url: getUrlForImageryTile( imageryProvider, tile.x, tile.y, tile.level ) }) }); } else { // Unknown error failTile({ name: i18next.t("models.imageryLayer.unknownTileErrorTitle"), message: i18next.t( "models.imageryLayer.unknownTileErrorMessage", { url: getUrlForImageryTile( imageryProvider, tile.x, tile.y, tile.level ) } ) }); } } else if (e.statusCode >= 400 && e.statusCode < 500) { if (e.statusCode === 403 && treat403AsError === false) { tellMapToSilentlyGiveUp(); } else if (e.statusCode === 404 && treat404AsError === false) { tellMapToSilentlyGiveUp(); } else { failTile(e); } } else if (e.statusCode >= 500 && e.statusCode < 600) { retryWithBackoff(e); } else { failTile(e); } } }) ); } } /** * Trying fetching image using an XHR request */ function fetchTileImage( tile: { x: number; y: number; level: number }, imageryProvider: ImageryProvider ) { const tileUrl = getUrlForImageryTile( imageryProvider, tile.x, tile.y, tile.level ); if (tileUrl) { return Resource.fetchImage({ url: tileUrl, preferBlob: true }); } return Promise.reject(); } function isTileOutsideExtent( tile: { x: number; y: number; level: number }, rectangle: Rectangle | undefined, imageryProvider: ImageryProvider ): boolean { if (rectangle === undefined) { // If the rectangle is not defined, assume the tile is inside. return false; } const tilingScheme = imageryProvider.tilingScheme; const tileExtent = tilingScheme.tileXYToRectangle( tile.x, tile.y, tile.level ); const intersection = Rectangle.intersection(tileExtent, rectangle); return intersection === undefined; } return Klass; } namespace TileErrorHandlerMixin { export interface Instance extends InstanceType<ReturnType<typeof TileErrorHandlerMixin>> {} export function isMixedInto(model: any): model is Instance { return model?.hasTileErrorHandlerMixin; } } export default TileErrorHandlerMixin;
the_stack
import { sep as osPathSeparator } from 'path'; import * as vscode from 'vscode'; import { TestLoadFinishedEvent, TestLoadStartedEvent, RetireEvent } from 'vscode-test-adapter-api'; import * as api from 'vscode-test-adapter-api'; import * as Sentry from '@sentry/node'; import { LoggerWrapper } from './LoggerWrapper'; import { RootSuite } from './RootSuite'; import { generateId } from './Util'; import { TaskQueue } from './util/TaskQueue'; import { SharedVariables, TestRunEvent } from './SharedVariables'; import { Catch2Section, Catch2Test } from './framework/Catch2Test'; import { AbstractRunnable } from './AbstractRunnable'; import { Configurations, Config } from './Configurations'; import { readJSONSync } from 'fs-extra'; import { join } from 'path'; import { AbstractTest, AbstractTestEvent } from './AbstractTest'; import { createPythonIndexerForPathVariable, ResolveRuleAsync, resolveVariablesAsync } from './util/ResolveRule'; import { inspect } from 'util'; export class TestAdapter implements api.TestAdapter, vscode.Disposable { private readonly _testsEmitter = new vscode.EventEmitter<TestLoadStartedEvent | TestLoadFinishedEvent>(); private readonly _testStatesEmitter = new vscode.EventEmitter<TestRunEvent>(); private readonly _retireEmitter = new vscode.EventEmitter<RetireEvent>(); private readonly _disposables: vscode.Disposable[] = []; private readonly _shared: SharedVariables; private _rootSuite: RootSuite; private readonly _isDebugExtension: boolean = process.env['C2_DEBUG'] === 'true'; public constructor(public readonly workspaceFolder: vscode.WorkspaceFolder, log: LoggerWrapper) { const configuration = this._getConfiguration(log); log.info( 'Extension constructor', this.workspaceFolder.name, this.workspaceFolder.index, this.workspaceFolder.uri.fsPath, process.platform, process.version, process.versions, vscode.version, ); if (!this._isDebugExtension) configuration.askSentryConsent(); try { let extensionInfo: { version: string; publisher: string; name: string; }; try { const pjson = readJSONSync(join(__dirname, '../../package.json')); extensionInfo = { version: pjson.version, publisher: pjson.publisher, name: pjson.name }; } catch (e) { log.exceptionS(e, __dirname); extensionInfo = { version: '<unknown-version>', publisher: '<unknown-publisher>', name: '<unknown-name>' }; } const enabled = !this._isDebugExtension && configuration.isSentryEnabled(); log.info('sentry.io is', enabled); const release = extensionInfo.publisher + '-' + extensionInfo.name + '@' + extensionInfo.version; Sentry.init({ dsn: 'https://0cfbeca1e97e4478a5d7e9c77925d92f@sentry.io/1554599', enabled, release, defaultIntegrations: false, normalizeDepth: 10, }); Sentry.setTags({ platform: process.platform, vscodeVersion: vscode.version, version: extensionInfo.version, publisher: extensionInfo.publisher, }); try { const opt = Intl.DateTimeFormat().resolvedOptions(); Sentry.setTags({ timeZone: opt.timeZone, locale: opt.locale }); } catch (e) { log.exceptionS(e); } Sentry.setUser({ id: configuration.getOrCreateUserId() }); //Sentry.setTag('workspaceFolder', hashString(this.workspaceFolder.uri.fsPath)); //'Framework' message includes this old message too: Sentry.captureMessage('Extension was activated', Sentry.Severity.Log); log.setContext('config', configuration.getValues()); const extensionsChanged = (): void => { try { const activeExtensions = vscode.extensions.all.filter(ex => ex.isActive).map(ex => ex.id); const vscodeRemote = activeExtensions.find(ex => ex.startsWith('ms-vscode-remote.')); log.debug('Active extensions', `activeVSCodeRemote(${vscodeRemote})`, activeExtensions); Sentry.setTag('activeVSCodeRemote', vscodeRemote ? vscodeRemote : 'undefined'); } catch (e) { log.exceptionS(e); } }; extensionsChanged(); this._disposables.push(vscode.extensions.onDidChange(extensionsChanged)); } catch (e) { log.exceptionS(e); } this._disposables.push(this._testsEmitter); this._disposables.push(this._testStatesEmitter); const loadWithTask = async (task: () => Promise<void | unknown[]>): Promise<void> => { this._sendLoadingEventIfNeeded(); try { const errors = await task(); this._sendLoadingFinishedEventIfNeeded(errors); } catch (reason) { log.warnS('loadTask exception', reason); this._sendLoadingFinishedEventIfNeeded([reason]); } }; const sendRetireEvent = (runnables: Iterable<AbstractRunnable>): void => { const ids: string[] = []; for (const r of runnables) for (const test of r.tests) if (!test.skipped) ids.push(test.id); this._retireEmitter.fire({ tests: ids }); }; const sendTestRunEvent = (event: TestRunEvent): void => { const label = event.type === 'suite' ? typeof event.suite === 'string' ? event.suite : event.suite.label : event.type === 'test' ? typeof event.test === 'string' ? event.test : event.test.label : event.type; this._shared.log.setNextInspectOptions({ depth: 0 }); this._shared.log.debug('Event fired', label, event); this._testStatesEmitter.fire(event); }; const sendTestEventsWithStartAndFin = (testEvents: AbstractTestEvent[]): void => { if (testEvents.length > 0) { const testRunId = generateId(); this._rootSuite.sendStartEventIfNeeded( testRunId, testEvents.map(v => v.test), ); for (let i = 0; i < testEvents.length; ++i) { const test = this._rootSuite.findTestById(testEvents[i].test); if (test) { // we dont need to send events about ancestors: https://github.com/hbenl/vscode-test-explorer/issues/141 this._testStatesEmitter.fire(testEvents[i]); } else { log.error('sendTestEventEmitter.event', testEvents[i], this._rootSuite); } } this._rootSuite.sendFinishedEventIfNeeded(testRunId); } }; const executeTaskQueue = new TaskQueue(); const executeTask = ( taskName: string, varToValue: readonly ResolveRuleAsync[], cancellationToken: vscode.CancellationToken, ): Promise<number | undefined> => { return executeTaskQueue.then(async () => { const tasks = await vscode.tasks.fetchTasks(); const found = tasks.find(t => t.name === taskName); if (found === undefined) { const msg = `Could not find task with name "${taskName}".`; log.warn(msg); throw Error(msg); } const resolvedTask = await resolveVariablesAsync(found, varToValue); // Task.name setter needs to be triggered in order for the task to clear its __id field // (https://github.com/microsoft/vscode/blob/ba33738bb3db01e37e3addcdf776c5a68d64671c/src/vs/workbench/api/common/extHostTypes.ts#L1976), // otherwise task execution fails with "Task not found". resolvedTask.name += ''; if (cancellationToken.isCancellationRequested) return; const result = new Promise<number | undefined>(resolve => { const disp1 = vscode.tasks.onDidEndTask((e: vscode.TaskEndEvent) => { if (e.execution.task.name === resolvedTask.name) { log.info('Task execution has finished', resolvedTask.name); disp1.dispose(); resolve(undefined); } }); const disp2 = vscode.tasks.onDidEndTaskProcess((e: vscode.TaskProcessEndEvent) => { if (e.execution.task.name === resolvedTask.name) { log.info('Task execution has finished', resolvedTask.name, e.exitCode); disp2.dispose(); resolve(e.exitCode); } }); }); log.info('Task execution has started', resolvedTask); const execution = await vscode.tasks.executeTask(resolvedTask); cancellationToken.onCancellationRequested(() => { log.info('Task execution was terminated', execution.task.name); execution.terminate(); }); return result; }); }; const workspaceNameRes: ResolveRuleAsync = { resolve: '${workspaceName}', rule: this.workspaceFolder.name }; this._disposables.push( vscode.workspace.onDidChangeWorkspaceFolders(() => { workspaceNameRes.rule = this.workspaceFolder.name; }), ); const variableToValue: ResolveRuleAsync[] = [ { resolve: /\$\{assert(?::([^}]+))?\}/, rule: async (m: RegExpMatchArray): Promise<never> => { const msg = m[1] ? ': ' + m[1] : ''; throw Error('Assertion while resolving variable' + msg); }, }, { resolve: '${osPathSep}', rule: osPathSeparator }, createPythonIndexerForPathVariable('workspaceFolder', this.workspaceFolder.uri.fsPath), { resolve: '${workspaceDirectory}', rule: this.workspaceFolder.uri.fsPath }, { resolve: '${osPathEnvSep}', rule: process.platform === 'win32' ? ';' : ':' }, { resolve: /\$\{command:([^}]+)\}/, rule: async (m: RegExpMatchArray): Promise<string> => { try { const ruleV = await vscode.commands.executeCommand<string>(m[1]); if (ruleV !== undefined) return ruleV; } catch (reason) { log.warnS("couldn't resolve command", m[0]); } return m[0]; }, }, workspaceNameRes, ]; this._shared = new SharedVariables( log, this.workspaceFolder, loadWithTask, sendRetireEvent, sendTestRunEvent, sendTestEventsWithStartAndFin, executeTask, variableToValue, configuration.getRandomGeneratorSeed(), configuration.getExecWatchTimeout(), configuration.getExecRunningTimeout(), configuration.getExecParsingTimeout(), configuration.getDefaultNoThrow(), configuration.getParallelExecutionLimit(), configuration.getEnableTestListCaching(), configuration.getEnableStrictPattern(), configuration.getGoogleTestTreatGMockWarningAs(), configuration.getGoogleTestGMockVerbose(), ); this._disposables.push( Configurations.onDidChange(changeEvent => { try { const config = this._getConfiguration(log); try { Sentry.setContext('config', config.getValues()); } catch (e) { log.exceptionS(e); } const affectsAny = (...config: Config[]): boolean => config.some(c => changeEvent.affectsConfiguration(c, this.workspaceFolder.uri)); if (affectsAny('test.randomGeneratorSeed')) { this._shared.rngSeed = config.getRandomGeneratorSeed(); } if (affectsAny('discovery.gracePeriodForMissing')) { this._shared.execWatchTimeout = config.getExecWatchTimeout(); } if (affectsAny('test.runtimeLimit')) { this._shared.setExecRunningTimeout(config.getExecRunningTimeout()); } if (affectsAny('discovery.runtimeLimit')) { this._shared.setExecRunningTimeout(config.getExecParsingTimeout()); } if (affectsAny('debug.noThrow')) { this._shared.isNoThrow = config.getDefaultNoThrow(); } if (affectsAny('test.parallelExecutionLimit')) { this._shared.taskPool.maxTaskCount = config.getParallelExecutionLimit(); } if (affectsAny('discovery.testListCaching')) { this._shared.enabledTestListCaching = config.getEnableTestListCaching(); } if (affectsAny('discovery.strictPattern')) { this._shared.enabledStrictPattern = config.getEnableStrictPattern(); } if (affectsAny('gtest.treatGmockWarningAs')) { this._shared.googleTestTreatGMockWarningAs = config.getGoogleTestTreatGMockWarningAs(); } if (affectsAny('gtest.gmockVerbose')) { this._shared.googleTestGMockVerbose = config.getGoogleTestGMockVerbose(); } if (affectsAny('test.randomGeneratorSeed', 'gtest.treatGmockWarningAs', 'gtest.gmockVerbose')) { this._retireEmitter.fire({}); } if ( affectsAny( 'test.workingDirectory', 'test.advancedExecutables', 'test.executables', 'test.parallelExecutionOfExecutableLimit', 'discovery.strictPattern', ) ) { this.load(); } } catch (e) { this._shared.log.exceptionS(e); } }), ); this._rootSuite = new RootSuite(undefined, this._shared); } public dispose(): void { this._shared.log.info('dispose', this.workspaceFolder); this._disposables.forEach(d => { try { d.dispose(); } catch (e) { this._shared.log.error('dispose', e, d); } }); try { this._shared.dispose(); } catch (e) { this._shared.log.error('dispose', e, this._shared); } try { this._rootSuite.dispose(); } catch (e) { this._shared.log.error('dispose', e, this._rootSuite); } } public get testStates(): vscode.Event<TestRunEvent> { return this._testStatesEmitter.event; } public get tests(): vscode.Event<TestLoadStartedEvent | TestLoadFinishedEvent> { return this._testsEmitter.event; } public get retire(): vscode.Event<RetireEvent> { return this._retireEmitter.event; } private _testLoadingCounter = 0; private _testLoadingErrors: unknown[] = []; private _sendLoadingEventIfNeeded(): void { if (this._testLoadingCounter++ === 0) { this._shared.log.info('load started'); this._testsEmitter.fire({ type: 'started' }); this._testLoadingErrors = []; } } private _sendLoadingFinishedEventIfNeeded(errors: void | unknown[]): void { if (errors && errors.length) { try { this._testLoadingErrors.push(...errors); } catch (reason) { this._shared.log.exceptionS(reason); } } if (this._testLoadingCounter < 1) { this._shared.log.error('loading counter is too low'); this._testLoadingCounter = 0; this._testLoadingErrors = []; debugger; return; } if (this._testLoadingCounter-- === 1) { this._shared.log.info('load finished', this._rootSuite.children.length); if (this._testLoadingErrors.length > 0) { this._testsEmitter.fire({ type: 'finished', errorMessage: this._testLoadingErrors .map(err => (err instanceof Error ? `${err.name}: ${err.message}` : inspect(err))) .join('\n'), }); } else if (this._rootSuite.children.length === 0) { this._testsEmitter.fire({ type: 'finished', suite: undefined, }); } else { this._testsEmitter.fire({ type: 'finished', suite: this._rootSuite.getInterfaceObj(), }); } } } public async load(): Promise<void> { this._shared.log.info('load called'); try { this.cancel(); this._rootSuite.dispose(); const configuration = this._getConfiguration(this._shared.log); this._rootSuite = new RootSuite(this._rootSuite.id, this._shared); const exec = configuration.getExecutables(this._shared); return await this._shared.loadWithTask(() => { return this._rootSuite.load(exec); }); } catch (reason) { vscode.window.showErrorMessage('Unable to load tests: ' + reason); } } public cancel(): void { this._shared.log.debug('canceled'); this._rootSuite.cancel(); } private readonly _busyMsg = 'The adapter is busy. Please wait before you start another task. (If you are not running tests or debugging currently then this is a bug.)'; public run(tests: string[]): Promise<void> { if (this._isDebugging) { this._shared.log.warn(this._busyMsg); throw Error(this._busyMsg); } return this._rootSuite.run(tests); } private static _debugMetricSent = false; private _isDebugging = false; public async debug(tests: string[]): Promise<void> { if (this._rootSuite.isRunning || this._isDebugging) { this._shared.log.warn(this._busyMsg); throw Error(this._busyMsg); } this._isDebugging = true; try { this._shared.log.info('Using debug'); if (this._rootSuite.findChildSuite(s => tests.indexOf(s.id) != -1)) { this._shared.log.info('unsupported suite debug', tests); throw Error('Suites cannot be debugged.'); } const runnableToTestMap = tests .map(t => this._rootSuite.findTestById(t)) .reduce((runnableToTestMap, test) => { if (test === undefined) return runnableToTestMap; const tests = runnableToTestMap.get(test.runnable); if (tests) tests.push(test!); else runnableToTestMap.set(test.runnable, [test]); return runnableToTestMap; }, new Map<AbstractRunnable, Readonly<AbstractTest>[]>()); if (runnableToTestMap.size !== 1) { this._shared.log.error('unsupported executable count', tests); throw Error('Unsupported input. It seems you would like to debug more tests from different executables.'); } const [runnable, runnableTests] = [...runnableToTestMap][0]; this._shared.log.setNextInspectOptions({ depth: 5 }); this._shared.log.info('test', runnable, runnableTests); const configuration = this._getConfiguration(this._shared.log); const label = runnableTests.length > 1 ? `(${runnableTests.length} tests)` : runnableTests[0].label; const suiteLabels = runnableTests.length > 1 ? '' : [...runnableTests[0].route()] .filter((v, i, a) => i < a.length - 1) .map(s => s.label) .join(' ← '); const argsArray = runnable.getDebugParams(runnableTests, configuration.getDebugBreakOnFailure()); if (runnableTests.length === 1 && runnableTests[0] instanceof Catch2Test) { const sections = (runnableTests[0] as Catch2Test).sections; if (sections && sections.length > 0) { interface QuickPickItem extends vscode.QuickPickItem { sectionStack: Catch2Section[]; } const items: QuickPickItem[] = [ { label: label, sectionStack: [], description: 'Select the section combo you wish to debug or choose this to debug all of it.', }, ]; const traverse = ( stack: Catch2Section[], section: Catch2Section, hasNextStack: boolean[], hasNext: boolean, ): void => { const currStack = stack.concat(section); const space = '\u3000'; let label = hasNextStack.map(h => (h ? '┃' : space)).join(''); label += hasNext ? '┣' : '┗'; label += section.name; items.push({ label: label, description: section.failed ? '❌' : '✅', sectionStack: currStack, }); for (let i = 0; i < section.children.length; ++i) traverse(currStack, section.children[i], hasNextStack.concat(hasNext), i < section.children.length - 1); }; for (let i = 0; i < sections.length; ++i) traverse([], sections[i], [], i < sections.length - 1); const pick = await vscode.window.showQuickPick(items); if (pick === undefined) return Promise.resolve(); pick.sectionStack.forEach(s => { argsArray.push('-c'); argsArray.push(s.escapedName); }); } } const argsArrayFunc = async (): Promise<string[]> => argsArray; const [debugConfigTemplate, debugConfigTemplateSource] = configuration.getDebugConfigurationTemplate(); this._shared.log.debug('debugConfigTemplate', { debugConfigTemplateSource, debugConfigTemplate }); if (!TestAdapter._debugMetricSent) { this._shared.log.infoSWithTags('Using debug', { debugConfigTemplateSource }); TestAdapter._debugMetricSent = true; } const envVars = Object.assign({}, process.env, runnable.properties.options.env); { const setEnvKey = 'testMate.cpp.debug.setEnv'; if (typeof debugConfigTemplate[setEnvKey] === 'object') { for (const envName in debugConfigTemplate[setEnvKey]) { const envValue = debugConfigTemplate[setEnvKey][envName]; if (typeof envValue !== 'string') this._shared.log.warn( 'Wrong value. testMate.cpp.debug.setEnv should contains only string values', envName, setEnvKey, ); else if (envValue === null) delete envVars[envName]; else envVars[envName] = envValue; } } } const varToResolve: ResolveRuleAsync[] = [ ...runnable.properties.varToValue, { resolve: '${suiteLabel}', rule: suiteLabels }, { resolve: '${label}', rule: label }, { resolve: '${exec}', rule: runnable.properties.path }, { resolve: '${args}', rule: argsArrayFunc }, // deprecated { resolve: '${argsArray}', rule: argsArrayFunc }, { resolve: '${argsArrayFlat}', rule: argsArrayFunc, isFlat: true }, { resolve: '${argsStr}', rule: async (): Promise<string> => '"' + argsArray.map(a => a.replace('"', '\\"')).join('" "') + '"', }, { resolve: '${cwd}', rule: runnable.properties.options.cwd!.toString() }, { resolve: '${envObj}', rule: async (): Promise<NodeJS.ProcessEnv> => envVars, }, { resolve: '${envObjArray}', rule: async (): Promise<{ name: string; value: string }[]> => Object.keys(envVars).map(name => { return { name, value: envVars[name] || '' }; }), }, { resolve: '${sourceFileMapObj}', rule: async (): Promise<Record<string, string>> => runnable.properties.sourceFileMap, }, ]; const debugConfig = await resolveVariablesAsync(debugConfigTemplate, varToResolve); // we dont know better: https://github.com/Microsoft/vscode/issues/70125 const magicValueKey = 'magic variable 🤦🏼‍'; const magicValue = generateId(); debugConfig[magicValueKey] = magicValue; this._shared.log.info('Debug: resolved debugConfig:', debugConfig); const cancellationTokenSource = new vscode.CancellationTokenSource(); await this._rootSuite.runTasks('before', runnableToTestMap, cancellationTokenSource.token); await runnable.runTasks('beforeEach', this._shared.taskPool, cancellationTokenSource.token); let terminateConn: vscode.Disposable | undefined; const terminated = new Promise<void>(resolve => { terminateConn = vscode.debug.onDidTerminateDebugSession((session: vscode.DebugSession) => { const session2 = session as unknown as { configuration: { [prop: string]: string } }; if (session2.configuration && session2.configuration[magicValueKey] === magicValue) { cancellationTokenSource.cancel(); resolve(); terminateConn && terminateConn.dispose(); } }); }).finally(() => { this._shared.log.info('debugSessionTerminated'); }); this._shared.log.info('startDebugging'); const debugSessionStarted = await vscode.debug.startDebugging(this.workspaceFolder, debugConfig); if (debugSessionStarted) { this._shared.log.info('debugSessionStarted'); await terminated; } else { terminateConn && terminateConn.dispose(); throw Error( 'Failed starting the debug session. Maybe something wrong with "testMate.cpp.debug.configTemplate".', ); } await runnable.runTasks('afterEach', this._shared.taskPool, cancellationTokenSource.token); await this._rootSuite.runTasks('after', runnableToTestMap, cancellationTokenSource.token); } catch (err) { this._shared.log.warn(err); throw err; } finally { this._isDebugging = false; } } private _getConfiguration(log: LoggerWrapper): Configurations { return new Configurations(log, this.workspaceFolder.uri); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/groupsMappers"; import * as Parameters from "../models/parameters"; import { AzureMigrateContext } from "../azureMigrateContext"; /** Class representing a Groups. */ export class Groups { private readonly client: AzureMigrateContext; /** * Create a Groups. * @param {AzureMigrateContext} client Reference to the service client. */ constructor(client: AzureMigrateContext) { this.client = client; } /** * Get all groups created in the project. Returns a json array of objects of type 'group' as * specified in the Models section. * @summary Get all groups * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param [options] The optional parameters * @returns Promise<Models.GroupsListByProjectResponse> */ listByProject(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<Models.GroupsListByProjectResponse>; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param callback The callback */ listByProject(resourceGroupName: string, projectName: string, callback: msRest.ServiceCallback<Models.GroupResultList>): void; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param options The optional parameters * @param callback The callback */ listByProject(resourceGroupName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.GroupResultList>): void; listByProject(resourceGroupName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.GroupResultList>, callback?: msRest.ServiceCallback<Models.GroupResultList>): Promise<Models.GroupsListByProjectResponse> { return this.client.sendOperationRequest( { resourceGroupName, projectName, options }, listByProjectOperationSpec, callback) as Promise<Models.GroupsListByProjectResponse>; } /** * Get information related to a specific group in the project. Returns a json object of type * 'group' as specified in the models section. * @summary Get a specific group. * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param [options] The optional parameters * @returns Promise<Models.GroupsGetResponse> */ get(resourceGroupName: string, projectName: string, groupName: string, options?: msRest.RequestOptionsBase): Promise<Models.GroupsGetResponse>; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param callback The callback */ get(resourceGroupName: string, projectName: string, groupName: string, callback: msRest.ServiceCallback<Models.Group>): void; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, projectName: string, groupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Group>): void; get(resourceGroupName: string, projectName: string, groupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Group>, callback?: msRest.ServiceCallback<Models.Group>): Promise<Models.GroupsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, projectName, groupName, options }, getOperationSpec, callback) as Promise<Models.GroupsGetResponse>; } /** * Create a new group by sending a json object of type 'group' as given in Models section as part * of the Request Body. The group name in a project is unique. Labels can be applied on a group as * part of creation. * * If a group with the groupName specified in the URL already exists, then this call acts as an * update. * * This operation is Idempotent. * @summary Create a new group with specified settings. If group with the name provided already * exists, then the existing group is updated. * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param [options] The optional parameters * @returns Promise<Models.GroupsCreateResponse> */ create(resourceGroupName: string, projectName: string, groupName: string, options?: Models.GroupsCreateOptionalParams): Promise<Models.GroupsCreateResponse>; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param callback The callback */ create(resourceGroupName: string, projectName: string, groupName: string, callback: msRest.ServiceCallback<Models.Group>): void; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, projectName: string, groupName: string, options: Models.GroupsCreateOptionalParams, callback: msRest.ServiceCallback<Models.Group>): void; create(resourceGroupName: string, projectName: string, groupName: string, options?: Models.GroupsCreateOptionalParams | msRest.ServiceCallback<Models.Group>, callback?: msRest.ServiceCallback<Models.Group>): Promise<Models.GroupsCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, projectName, groupName, options }, createOperationSpec, callback) as Promise<Models.GroupsCreateResponse>; } /** * Delete the group from the project. The machines remain in the project. Deleting a non-existent * group results in a no-operation. * * A group is an aggregation mechanism for machines in a project. Therefore, deleting group does * not delete machines in it. * @summary Delete the group * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param [options] The optional parameters * @returns Promise<Models.GroupsDeleteResponse> */ deleteMethod(resourceGroupName: string, projectName: string, groupName: string, options?: msRest.RequestOptionsBase): Promise<Models.GroupsDeleteResponse>; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param callback The callback */ deleteMethod(resourceGroupName: string, projectName: string, groupName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName Name of the Azure Resource Group that project is part of. * @param projectName Name of the Azure Migrate project. * @param groupName Unique name of a group within a project. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, projectName: string, groupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, projectName: string, groupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.GroupsDeleteResponse> { return this.client.sendOperationRequest( { resourceGroupName, projectName, groupName, options }, deleteMethodOperationSpec, callback) as Promise<Models.GroupsDeleteResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByProjectOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.projectName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.GroupResultList, headersMapper: Mappers.GroupsListByProjectHeaders }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups/{groupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.projectName, Parameters.groupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.Group, headersMapper: Mappers.GroupsGetHeaders }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups/{groupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.projectName, Parameters.groupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: [ "options", "group" ], mapper: Mappers.Group }, responses: { 200: { bodyMapper: Mappers.Group, headersMapper: Mappers.GroupsCreateHeaders }, 201: { bodyMapper: Mappers.Group, headersMapper: Mappers.GroupsCreateHeaders }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/projects/{projectName}/groups/{groupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.projectName, Parameters.groupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { headersMapper: Mappers.GroupsDeleteHeaders }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import { bufferToHex, ecsign, keccak, publicToAddress, toBuffer, } from 'ethereumjs-util'; import { rawEncode, soliditySHA3 } from 'ethereumjs-abi'; import { concatSig, isNullish, legacyToBuffer, recoverPublicKey, } from './utils'; /** * This is the message format used for `V1` of `signTypedData`. */ export type TypedDataV1 = TypedDataV1Field[]; /** * This represents a single field in a `V1` `signTypedData` message. * * @property name - The name of the field. * @property type - The type of a field (must be a supported Solidity type). * @property value - The value of the field. */ export interface TypedDataV1Field { name: string; type: string; value: any; } /** * Represents the version of `signTypedData` being used. * * V1 is based upon [an early version of EIP-712](https://github.com/ethereum/EIPs/pull/712/commits/21abe254fe0452d8583d5b132b1d7be87c0439ca) * that lacked some later security improvements, and should generally be neglected in favor of * later versions. * * V3 is based on EIP-712, except that arrays and recursive data structures are not supported. * * V4 is based on EIP-712, and includes full support of arrays and recursive data structures. */ export enum SignTypedDataVersion { V1 = 'V1', V3 = 'V3', V4 = 'V4', } export interface MessageTypeProperty { name: string; type: string; } export interface MessageTypes { EIP712Domain: MessageTypeProperty[]; [additionalProperties: string]: MessageTypeProperty[]; } /** * This is the message format used for `signTypeData`, for all versions * except `V1`. * * @template T - The custom types used by this message. * @property types - The custom types used by this message. * @property primaryType - The type of the message. * @property domain - Signing domain metadata. The signing domain is the intended context for the * signature (e.g. the dapp, protocol, etc. that it's intended for). This data is used to * construct the domain seperator of the message. * @property domain.name - The name of the signing domain. * @property domain.version - The current major version of the signing domain. * @property domain.chainId - The chain ID of the signing domain. * @property domain.verifyingContract - The address of the contract that can verify the signature. * @property domain.salt - A disambiguating salt for the protocol. * @property message - The message to be signed. */ export interface TypedMessage<T extends MessageTypes> { types: T; primaryType: keyof T; domain: { name?: string; version?: string; chainId?: number; verifyingContract?: string; salt?: ArrayBuffer; }; message: Record<string, unknown>; } export const TYPED_MESSAGE_SCHEMA = { type: 'object', properties: { types: { type: 'object', additionalProperties: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, type: { type: 'string', enum: getSolidityTypes() }, }, required: ['name', 'type'], }, }, }, primaryType: { type: 'string' }, domain: { type: 'object' }, message: { type: 'object' }, }, required: ['types', 'primaryType', 'domain', 'message'], }; /** * Get a list of all Solidity types. * * @returns A list of all Solidity types. */ function getSolidityTypes() { const types = ['bool', 'address', 'string', 'bytes']; const ints = Array.from(new Array(32)).map( (_, index) => `int${(index + 1) * 8}`, ); const uints = Array.from(new Array(32)).map( (_, index) => `uint${(index + 1) * 8}`, ); const bytes = Array.from(new Array(32)).map( (_, index) => `bytes${index + 1}`, ); return [...types, ...ints, ...uints, ...bytes]; } /** * Validate that the given value is a valid version string. * * @param version - The version value to validate. * @param allowedVersions - A list of allowed versions. If omitted, all versions are assumed to be * allowed. */ function validateVersion( version: SignTypedDataVersion, allowedVersions?: SignTypedDataVersion[], ) { if (!Object.keys(SignTypedDataVersion).includes(version)) { throw new Error(`Invalid version: '${version}'`); } else if (allowedVersions && !allowedVersions.includes(version)) { throw new Error( `SignTypedDataVersion not allowed: '${version}'. Allowed versions are: ${allowedVersions.join( ', ', )}`, ); } } /** * Encode a single field. * * @param types - All type definitions. * @param name - The name of the field to encode. * @param type - The type of the field being encoded. * @param value - The value to encode. * @param version - The EIP-712 version the encoding should comply with. * @returns Encoded representation of the field. */ function encodeField( types: Record<string, MessageTypeProperty[]>, name: string, type: string, value: any, version: SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ): [type: string, value: any] { validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); if (types[type] !== undefined) { return [ 'bytes32', version === SignTypedDataVersion.V4 && value == null // eslint-disable-line no-eq-null ? '0x0000000000000000000000000000000000000000000000000000000000000000' : keccak(encodeData(type, value, types, version)), ]; } if (value === undefined) { throw new Error(`missing value for field ${name} of type ${type}`); } if (type === 'bytes') { return ['bytes32', keccak(value)]; } if (type === 'string') { // convert string to buffer - prevents ethUtil from interpreting strings like '0xabcd' as hex if (typeof value === 'string') { value = Buffer.from(value, 'utf8'); } return ['bytes32', keccak(value)]; } if (type.lastIndexOf(']') === type.length - 1) { if (version === SignTypedDataVersion.V3) { throw new Error( 'Arrays are unimplemented in encodeData; use V4 extension', ); } const parsedType = type.slice(0, type.lastIndexOf('[')); const typeValuePairs = value.map((item) => encodeField(types, name, parsedType, item, version), ); return [ 'bytes32', keccak( rawEncode( typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v), ), ), ]; } return [type, value]; } /** * Encodes an object by encoding and concatenating each of its members. * * @param primaryType - The root type. * @param data - The object to encode. * @param types - Type definitions for all types included in the message. * @param version - The EIP-712 version the encoding should comply with. * @returns An encoded representation of an object. */ function encodeData( primaryType: string, data: Record<string, unknown>, types: Record<string, MessageTypeProperty[]>, version: SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ): Buffer { validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); const encodedTypes = ['bytes32']; const encodedValues: unknown[] = [hashType(primaryType, types)]; for (const field of types[primaryType]) { if (version === SignTypedDataVersion.V3 && data[field.name] === undefined) { continue; } const [type, value] = encodeField( types, field.name, field.type, data[field.name], version, ); encodedTypes.push(type); encodedValues.push(value); } return rawEncode(encodedTypes, encodedValues); } /** * Encodes the type of an object by encoding a comma delimited list of its members. * * @param primaryType - The root type to encode. * @param types - Type definitions for all types included in the message. * @returns An encoded representation of the primary type. */ function encodeType( primaryType: string, types: Record<string, MessageTypeProperty[]>, ): string { let result = ''; const unsortedDeps = findTypeDependencies(primaryType, types); unsortedDeps.delete(primaryType); const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; for (const type of deps) { const children = types[type]; if (!children) { throw new Error(`No type definition specified: ${type}`); } result += `${type}(${types[type] .map(({ name, type: t }) => `${t} ${name}`) .join(',')})`; } return result; } /** * Finds all types within a type definition object. * * @param primaryType - The root type. * @param types - Type definitions for all types included in the message. * @param results - The current set of accumulated types. * @returns The set of all types found in the type definition. */ function findTypeDependencies( primaryType: string, types: Record<string, MessageTypeProperty[]>, results: Set<string> = new Set(), ): Set<string> { [primaryType] = primaryType.match(/^\w*/u); if (results.has(primaryType) || types[primaryType] === undefined) { return results; } results.add(primaryType); for (const field of types[primaryType]) { findTypeDependencies(field.type, types, results); } return results; } /** * Hashes an object. * * @param primaryType - The root type. * @param data - The object to hash. * @param types - Type definitions for all types included in the message. * @param version - The EIP-712 version the encoding should comply with. * @returns The hash of the object. */ function hashStruct( primaryType: string, data: Record<string, unknown>, types: Record<string, MessageTypeProperty[]>, version: SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ): Buffer { validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); return keccak(encodeData(primaryType, data, types, version)); } /** * Hashes the type of an object. * * @param primaryType - The root type to hash. * @param types - Type definitions for all types included in the message. * @returns The hash of the object type. */ function hashType( primaryType: string, types: Record<string, MessageTypeProperty[]>, ): Buffer { return keccak(encodeType(primaryType, types)); } /** * Removes properties from a message object that are not defined per EIP-712. * * @param data - The typed message object. * @returns The typed message object with only allowed fields. */ function sanitizeData<T extends MessageTypes>( data: TypedMessage<T>, ): TypedMessage<T> { const sanitizedData: Partial<TypedMessage<T>> = {}; for (const key in TYPED_MESSAGE_SCHEMA.properties) { if (data[key]) { sanitizedData[key] = data[key]; } } if ('types' in sanitizedData) { sanitizedData.types = { EIP712Domain: [], ...sanitizedData.types }; } return sanitizedData as Required<TypedMessage<T>>; } /** * Hash a typed message according to EIP-712. The returned message starts with the EIP-712 prefix, * which is "1901", followed by the hash of the domain separator, then the data (if any). * The result is hashed again and returned. * * This function does not sign the message. The resulting hash must still be signed to create an * EIP-712 signature. * * @param typedData - The typed message to hash. * @param version - The EIP-712 version the encoding should comply with. * @returns The hash of the typed message. */ function eip712Hash<T extends MessageTypes>( typedData: TypedMessage<T>, version: SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ): Buffer { validateVersion(version, [SignTypedDataVersion.V3, SignTypedDataVersion.V4]); const sanitizedData = sanitizeData(typedData); const parts = [Buffer.from('1901', 'hex')]; parts.push( hashStruct( 'EIP712Domain', sanitizedData.domain, sanitizedData.types, version, ), ); if (sanitizedData.primaryType !== 'EIP712Domain') { parts.push( hashStruct( // TODO: Validate that this is a string, so this type cast can be removed. sanitizedData.primaryType as string, sanitizedData.message, sanitizedData.types, version, ), ); } return keccak(Buffer.concat(parts)); } /** * A collection of utility functions used for signing typed data. */ export const TypedDataUtils = { encodeData, encodeType, findTypeDependencies, hashStruct, hashType, sanitizeData, eip712Hash, }; /** * Generate the "V1" hash for the provided typed message. * * The hash will be generated in accordance with an earlier version of the EIP-712 * specification. This hash is used in `signTypedData_v1`. * * @param typedData - The typed message. * @returns The '0x'-prefixed hex encoded hash representing the type of the provided message. */ export function typedSignatureHash(typedData: TypedDataV1Field[]): string { const hashBuffer = _typedSignatureHash(typedData); return bufferToHex(hashBuffer); } /** * Generate the "V1" hash for the provided typed message. * * The hash will be generated in accordance with an earlier version of the EIP-712 * specification. This hash is used in `signTypedData_v1`. * * @param typedData - The typed message. * @returns The hash representing the type of the provided message. */ function _typedSignatureHash(typedData: TypedDataV1): Buffer { const error = new Error('Expect argument to be non-empty array'); if ( typeof typedData !== 'object' || !('length' in typedData) || !typedData.length ) { throw error; } const data = typedData.map(function (e) { if (e.type !== 'bytes') { return e.value; } return legacyToBuffer(e.value); }); const types = typedData.map(function (e) { return e.type; }); const schema = typedData.map(function (e) { if (!e.name) { throw error; } return `${e.type} ${e.name}`; }); return soliditySHA3( ['bytes32', 'bytes32'], [ soliditySHA3(new Array(typedData.length).fill('string'), schema), soliditySHA3(types, data), ], ); } /** * Sign typed data according to EIP-712. The signing differs based upon the `version`. * * V1 is based upon [an early version of EIP-712](https://github.com/ethereum/EIPs/pull/712/commits/21abe254fe0452d8583d5b132b1d7be87c0439ca) * that lacked some later security improvements, and should generally be neglected in favor of * later versions. * * V3 is based on [EIP-712](https://eips.ethereum.org/EIPS/eip-712), except that arrays and * recursive data structures are not supported. * * V4 is based on [EIP-712](https://eips.ethereum.org/EIPS/eip-712), and includes full support of * arrays and recursive data structures. * * @param options - The signing options. * @param options.privateKey - The private key to sign with. * @param options.data - The typed data to sign. * @param options.version - The signing version to use. * @returns The '0x'-prefixed hex encoded signature. */ export function signTypedData< V extends SignTypedDataVersion, T extends MessageTypes, >({ privateKey, data, version, }: { privateKey: Buffer; data: V extends 'V1' ? TypedDataV1 : TypedMessage<T>; version: V; }): string { validateVersion(version); if (isNullish(data)) { throw new Error('Missing data parameter'); } else if (isNullish(privateKey)) { throw new Error('Missing private key parameter'); } const messageHash = version === SignTypedDataVersion.V1 ? _typedSignatureHash(data as TypedDataV1) : TypedDataUtils.eip712Hash( data as TypedMessage<T>, version as SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ); const sig = ecsign(messageHash, privateKey); return concatSig(toBuffer(sig.v), sig.r, sig.s); } /** * Recover the address of the account that created the given EIP-712 * signature. The version provided must match the version used to * create the signature. * * @param options - The signature recovery options. * @param options.data - The typed data that was signed. * @param options.signature - The '0x-prefixed hex encoded message signature. * @param options.version - The signing version to use. * @returns The '0x'-prefixed hex address of the signer. */ export function recoverTypedSignature< V extends SignTypedDataVersion, T extends MessageTypes, >({ data, signature, version, }: { data: V extends 'V1' ? TypedDataV1 : TypedMessage<T>; signature: string; version: V; }): string { validateVersion(version); if (isNullish(data)) { throw new Error('Missing data parameter'); } else if (isNullish(signature)) { throw new Error('Missing signature parameter'); } const messageHash = version === SignTypedDataVersion.V1 ? _typedSignatureHash(data as TypedDataV1) : TypedDataUtils.eip712Hash( data as TypedMessage<T>, version as SignTypedDataVersion.V3 | SignTypedDataVersion.V4, ); const publicKey = recoverPublicKey(messageHash, signature); const sender = publicToAddress(publicKey); return bufferToHex(sender); }
the_stack
import { HeaderMenu } from './grid.header.menu'; declare const Slick: any; /** * slick grid header builder class */ export class SlickGridHeader { /* tslint:disable:variable-name function-name */ private _asyncPostRender: string = null; private _behavior: string = null; private _cannotTriggerInsert: boolean = null; private _cssClass: string = ''; private _defaultSortAsc: boolean = true; private _editor: GRID_EDIT_TYPE = null; private _field: string = ''; private _focusable: boolean = true; private _formatter: any = null; private _headerCssClass: string = null; private _id: string = ''; private _maxWidth: string = null; private _minWidth: number = 30; private _name: string = ''; private _rerenderOnResize: boolean = false; private _resizable: boolean = true; private _selectable: boolean = true; private _sortable: boolean = false; private _toolTip: string = ''; private _width: number; private _columnType:string; private _header : HeaderMenu; /////////////////////////////////////////////////////////// // // _validator // _unselectable // // - 원본 라이브러리에 없는 옵션 // /////////////////////////////////////////////////////////// private _validator: any; private _unselectable: boolean; constructor() { } get columnType(): string { return this._columnType; } //noinspection JSUnusedGlobalSymbols ColumnType(value: string): SlickGridHeader { this._columnType = value; return this; } get asyncPostRender(): string { return this._asyncPostRender; } //noinspection JSUnusedGlobalSymbols AsyncPostRender(value: string): SlickGridHeader { this._asyncPostRender = value; return this; } get behavior(): string { return this._behavior; } //noinspection JSUnusedGlobalSymbols Behavior(value: string): SlickGridHeader { this._behavior = value; return this; } get cannotTriggerInsert(): boolean { return this._cannotTriggerInsert; } //noinspection JSUnusedGlobalSymbols CannotTriggerInsert(value: boolean): SlickGridHeader { this._cannotTriggerInsert = value; return this; } get cssClass(): string { return this._cssClass; } //noinspection JSUnusedGlobalSymbols CssClass(value: string): SlickGridHeader { this._cssClass = value; return this; } get defaultSortAsc(): boolean { return this._defaultSortAsc; } //noinspection JSUnusedGlobalSymbols DefaultSortAsc(value: boolean): SlickGridHeader { this._defaultSortAsc = value; return this; } get editor(): GRID_EDIT_TYPE { return this._editor; } //noinspection JSUnusedGlobalSymbols Editor(value: GRID_EDIT_TYPE): SlickGridHeader { switch ( value ) { case GRID_EDIT_TYPE.PERCENT : this._editor = Slick.Editors.PercentComplete; break; case GRID_EDIT_TYPE.CHECK : this._editor = Slick.Editors.Checkbox; break; case GRID_EDIT_TYPE.TEXT : default: this._editor = Slick.Editors.Text; break; } return this; } get field(): string { return this._field; } //noinspection JSUnusedGlobalSymbols Field(value: string): SlickGridHeader { this._field = value; return this; } get focusable(): boolean { return this._focusable; } //noinspection JSUnusedGlobalSymbols Focusable(value: boolean): SlickGridHeader { this._focusable = value; return this; } get formatter(): any { return this._formatter; } //noinspection JSUnusedGlobalSymbols Formatter(value: any): SlickGridHeader { this._formatter = value; return this; } get headerCssClass(): string { return this._headerCssClass; } //noinspection JSUnusedGlobalSymbols HeaderCssClass(value: string): SlickGridHeader { this._headerCssClass = value; return this; } get id(): string { return this._id; } //noinspection JSUnusedGlobalSymbols Id(value: string): SlickGridHeader { this._id = value; return this; } get maxWidth(): string { return this._maxWidth; } //noinspection JSUnusedGlobalSymbols MaxWidth(value: string): SlickGridHeader { this._maxWidth = value; return this; } get minWidth(): number { return this._minWidth; } //noinspection JSUnusedGlobalSymbols MinWidth(value: number): SlickGridHeader { this._minWidth = value; return this; } get name(): string { return this._name; } //noinspection JSUnusedGlobalSymbols Name(value: string): SlickGridHeader { this._name = value; return this; } get rerenderOnResize(): boolean { return this._rerenderOnResize; } //noinspection JSUnusedGlobalSymbols RerenderOnResize(value: boolean): SlickGridHeader { this._rerenderOnResize = value; return this; } get resizable(): boolean { return this._resizable; } //noinspection JSUnusedGlobalSymbols Resizable(value: boolean): SlickGridHeader { this._resizable = value; return this; } get selectable(): boolean { return this._selectable; } //noinspection JSUnusedGlobalSymbols Selectable(value: boolean): SlickGridHeader { this._selectable = value; return this; } get sortable(): boolean { return this._sortable; } //noinspection JSUnusedGlobalSymbols Sortable(value: boolean): SlickGridHeader { this._sortable = value; return this; } get toolTip(): string { return this._toolTip; } //noinspection JSUnusedGlobalSymbols ToolTip(value: string): SlickGridHeader { this._toolTip = value; return this; } get width(): number { return this._width; } //noinspection JSUnusedGlobalSymbols Width(value: number): SlickGridHeader { this._width = value; return this; } get validator(): any { return this._validator; } //noinspection JSUnusedGlobalSymbols Validator(value: any): SlickGridHeader { this._validator = value; return this; } get unselectable(): boolean { return this._unselectable; } //noinspection JSUnusedGlobalSymbols Unselectable(value: boolean): SlickGridHeader { this._unselectable = value; return this; } get header(): HeaderMenu { return this._header; } //noinspection JSUnusedGlobalSymbols Header(value: HeaderMenu): SlickGridHeader { this._header = value; return this; } build(): Header { return new Header(this); } } export enum GRID_EDIT_TYPE { TEXT = 'REJECTED', PERCENT = 'EXPIRED', CHECK = 'LOCKED' } export class Header { public asyncPostRender: string; public behavior: string; public cannotTriggerInsert: boolean; public cssClass: string; public defaultSortAsc: boolean; public editor: any; public field: string; public focusable: boolean; public formatter: any; public headerCssClass: string; public id: string; public maxWidth: string; public minWidth: number; public name: string; public rerenderOnResize: boolean; public resizable: boolean; public selectable: boolean; public sortable: boolean; public toolTip: string; public width: number; public validator: any; public unselectable: boolean; public header : HeaderMenu; public columnType : string; public setFormatter( formatter:any ) { this.formatter = formatter; } constructor(builder: SlickGridHeader) { if (typeof builder.asyncPostRender !== 'undefined') { this.asyncPostRender = builder.asyncPostRender; } if (typeof builder.behavior !== 'undefined') { this.behavior = builder.behavior; } if (typeof builder.cannotTriggerInsert !== 'undefined') { this.cannotTriggerInsert = builder.cannotTriggerInsert; } if (typeof builder.cssClass !== 'undefined') { this.cssClass = builder.cssClass; } if (typeof builder.defaultSortAsc !== 'undefined') { this.defaultSortAsc = builder.defaultSortAsc; } if (typeof builder.editor !== 'undefined') { switch ( builder.editor ) { case GRID_EDIT_TYPE.PERCENT : this.editor = Slick.Editors.PercentComplete; break; case GRID_EDIT_TYPE.CHECK : this.editor = Slick.Editors.Checkbox; break; case GRID_EDIT_TYPE.TEXT : default: this.editor = Slick.Editors.Text; break; } } if (typeof builder.field !== 'undefined') { this.field = builder.field; } if (typeof builder.focusable !== 'undefined') { this.focusable = builder.focusable; } if (typeof builder.formatter !== 'undefined') { this.formatter = builder.formatter; } if (typeof builder.headerCssClass !== 'undefined') { this.headerCssClass = builder.headerCssClass; } if (typeof builder.id !== 'undefined') { this.id = builder.id; } if (typeof builder.maxWidth !== 'undefined') { this.maxWidth = builder.maxWidth; } if (typeof builder.minWidth !== 'undefined') { this.minWidth = builder.minWidth; } if (typeof builder.name !== 'undefined') { this.name = builder.name; } if (typeof builder.rerenderOnResize !== 'undefined') { this.rerenderOnResize = builder.rerenderOnResize; } if (typeof builder.resizable !== 'undefined') { this.resizable = builder.resizable; } if (typeof builder.selectable !== 'undefined') { this.selectable = builder.selectable; } if (typeof builder.sortable !== 'undefined') { this.sortable = builder.sortable; } if (typeof builder.toolTip !== 'undefined') { this.toolTip = builder.toolTip; } if (typeof builder.width !== 'undefined') { this.width = builder.width; } if (typeof builder.validator !== 'undefined') { this.validator = builder.validator; } if (typeof builder.unselectable !== 'undefined') { this.unselectable = builder.unselectable; } if (typeof builder.header !== 'undefined') { this.header = builder.header; } if (typeof builder.columnType !== 'undefined') { this.columnType = builder.columnType; } } /* tslint:enable:variable-name function-name */ }
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { HarnessLoader, TestKey } from '@angular/cdk/testing'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { MatInputHarness } from '@angular/material/input/testing'; import { MatFormFieldHarness } from '@angular/material/form-field/testing'; import { MatButtonHarness } from '@angular/material/button/testing'; import { MatChipListHarness } from '@angular/material/chips/testing'; import { MatSelectHarness } from '@angular/material/select/testing'; import { MatAutocompleteHarness } from '@angular/material/autocomplete/testing'; import { MatDialogHarness } from '@angular/material/dialog/testing'; import { HttpTestingController } from '@angular/common/http/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { InteractivityChecker } from '@angular/cdk/a11y'; import { MatSlideToggleHarness } from '@angular/material/slide-toggle/testing'; import { GioSaveBarHarness } from '@gravitee/ui-particles-angular'; import { OrgSettingsGeneralComponent } from './org-settings-general.component'; import { CONSTANTS_TESTING, GioHttpTestingModule } from '../../../shared/testing'; import { OrganizationSettingsModule } from '../organization-settings.module'; import { ConsoleSettings } from '../../../entities/consoleSettings'; import { GioFormTagsInputHarness } from '../../../shared/components/gio-form-tags-input/gio-form-tags-input.harness'; describe('ConsoleSettingsComponent', () => { let fixture: ComponentFixture<OrgSettingsGeneralComponent>; let loader: HarnessLoader; let rootLoader: HarnessLoader; let httpTestingController: HttpTestingController; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [NoopAnimationsModule, GioHttpTestingModule, OrganizationSettingsModule], }) .overrideProvider(InteractivityChecker, { useValue: { isFocusable: () => true, // This checks focus trap, set it to true to avoid the warning }, }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OrgSettingsGeneralComponent); loader = TestbedHarnessEnvironment.loader(fixture); rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture); httpTestingController = TestBed.inject(HttpTestingController); fixture.detectChanges(); }); it('should loading when no setting is provided', async () => { httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/settings`); expect(fixture.componentInstance.isLoading).toBeTruthy(); }); describe('management', () => { it('should disable field when setting is readonly', async () => { expectConsoleSettingsGetRequest({ management: { title: 'Title', userCreation: { enabled: false, }, }, metadata: { readonly: ['management.title'], }, }); const titleFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Title' })); expect(await titleFormField.isDisabled()).toEqual(true); const activateSupportSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'support' })); expect(await activateSupportSlideToggle.isDisabled()).toEqual(false); }); it('should save management settings', async () => { expectConsoleSettingsGetRequest({ management: { title: 'Title', support: { enabled: false, }, pathBasedApiCreation: { enabled: true, }, userCreation: { enabled: false, }, }, }); const titleFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Title' })); const titleInput = await titleFormField.getControl(MatInputHarness); await titleInput?.setValue('New Title'); const activateSupportSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'support' })); await activateSupportSlideToggle.check(); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ management: { title: 'New Title', support: { enabled: true, }, pathBasedApiCreation: { enabled: true, }, userCreation: { enabled: false, }, }, }); }); it('should disable automaticValidation when userCreation is not checked', async () => { expectConsoleSettingsGetRequest({ management: { userCreation: { enabled: true, }, automaticValidation: { enabled: true, }, }, }); const titleFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Title' })); const titleInput = await titleFormField.getControl(MatInputHarness); await titleInput?.setValue('New Title'); const userCreationSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'userCreation' })); const automaticValidationSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'automaticValidation' })); expect(await automaticValidationSlideToggle.isDisabled()).toEqual(false); await userCreationSlideToggle.toggle(); // expect automaticValidation SlideToggle not to be visible expect(await loader.getAllHarnesses(MatSlideToggleHarness.with({ name: 'automaticValidation' }))).toEqual([]); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ management: { userCreation: { enabled: false, }, automaticValidation: { enabled: true, }, }, }); }); }); describe('theme', () => { it('should disable field when setting is readonly', async () => { expectConsoleSettingsGetRequest({ theme: { name: undefined, logo: 'The logo', loader: '', }, metadata: { readonly: ['theme.name', 'theme.logo', 'theme.loader'], }, }); const nameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Name' })); expect(await nameFormField.isDisabled()).toEqual(true); const logoFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Logo' })); expect(await logoFormField.isDisabled()).toEqual(true); const loaderFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Loader' })); expect(await loaderFormField.isDisabled()).toEqual(true); }); it('should save theme settings', async () => { expectConsoleSettingsGetRequest({ theme: { name: undefined, logo: 'The logo', loader: '', css: 'red style', }, }); const nameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Name' })); await (await nameFormField.getControl(MatInputHarness)).setValue('New name'); const logoFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Logo' })); await (await logoFormField.getControl(MatInputHarness)).setValue(''); const loaderFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Loader' })); await (await loaderFormField.getControl(MatInputHarness)).setValue('New loader'); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ theme: { name: 'New name', logo: '', loader: 'New loader', css: 'red style', }, }); }); }); describe('scheduler', () => { it('should disable field when setting is readonly', async () => { expectConsoleSettingsGetRequest({ scheduler: { tasks: undefined, notifications: 0, }, metadata: { readonly: ['scheduler.tasks', 'scheduler.notifications'], }, }); const taskFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Tasks/ })); expect(await taskFormField.isDisabled()).toEqual(true); const notificationFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Notifications/ })); expect(await notificationFormField.isDisabled()).toEqual(true); }); it('should save scheduler settings', async () => { expectConsoleSettingsGetRequest({ scheduler: { tasks: undefined, notifications: 0, }, }); const taskFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Tasks/ })); await (await taskFormField.getControl(MatInputHarness)).setValue('666'); const notificationFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Notifications/ })); await (await notificationFormField.getControl(MatInputHarness)).setValue(''); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ scheduler: { tasks: 666, notifications: null, }, }); }); }); describe('alert', () => { it('should disable field when setting is readonly', async () => { expectConsoleSettingsGetRequest({ alert: { enabled: false, }, metadata: { readonly: ['alert.enabled'], }, }); const enableAlertingSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'alert' })); expect(await enableAlertingSlideToggle.isDisabled()).toEqual(true); }); it('should save alert settings', async () => { expectConsoleSettingsGetRequest({ alert: { enabled: false, }, }); const enableAlertingSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'alert' })); await enableAlertingSlideToggle.check(); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ alert: { enabled: true, }, }); }); }); describe('cors', () => { it('should disable field when setting is readonly', async () => { expectConsoleSettingsGetRequest({ cors: { allowOrigin: undefined, allowMethods: ['GET', 'POST'], allowHeaders: ['a', 'b'], exposedHeaders: [], maxAge: 42, }, metadata: { readonly: ['cors.allowOrigin', 'cors.allowMethods', 'cors.allowHeaders', 'cors.exposedHeaders', 'cors.maxAge'], }, }); const allowOriginFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Allow-Origin' })); expect(await allowOriginFormField.isDisabled()).toEqual(true); const allowMethodsFormField = await loader.getHarness( MatFormFieldHarness.with({ floatingLabelText: 'Access-Control-Allow-Methods' }), ); expect(await allowMethodsFormField.isDisabled()).toEqual(true); const allowHeadersFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Allow-Headers' })); expect(await allowHeadersFormField.isDisabled()).toEqual(true); const exposedHeadersFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Exposed-Headers' })); expect(await exposedHeadersFormField.isDisabled()).toEqual(true); const maxAgeFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Max age/ })); expect(await maxAgeFormField.isDisabled()).toEqual(true); }); it('should save cors settings', async () => { expectConsoleSettingsGetRequest({ cors: { allowOrigin: undefined, allowMethods: ['GET', 'POST'], allowHeaders: ['x-foo', 'x-bar'], exposedHeaders: [], maxAge: 42, }, }); // # Allow-Origin const allowOriginFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Allow-Origin' })); expect(await (await allowOriginFormField.getControl(GioFormTagsInputHarness)).getTags()).toEqual([]); // Add valid RegExp const allowOriginTagsInput = await allowOriginFormField.getControl(GioFormTagsInputHarness); await allowOriginTagsInput.addTag('(Valid|RegExp)', 'blur'); // # Access-Control-Allow-Methods const allowMethodsFormField = await loader.getHarness( MatFormFieldHarness.with({ floatingLabelText: 'Access-Control-Allow-Methods' }), ); // Open select and select DELETE option const allowMethodsSelect = await allowMethodsFormField.getControl(MatSelectHarness); await allowMethodsSelect.open(); await (await allowMethodsSelect.getOptions({ text: 'DELETE' }))[0].click(); await allowMethodsSelect.close(); // Check selected options expect(await allowMethodsSelect.getValueText()).toEqual('GET, DELETE, POST'); // # Allow-Headers const allowHeadersFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Allow-Headers' })); const allowHeadersChipList = await allowHeadersFormField.getControl(MatChipListHarness); const allowHeadersChipListInput = await allowHeadersChipList.getInput(); // Add new custom header await allowHeadersChipListInput.setValue('x-ray'); await allowHeadersChipListInput.sendSeparatorKey(TestKey.ENTER); // Remove x-foo header await (await allowHeadersChipList.getChips({ text: 'x-foo' }))[0].remove(); // Check headers const allowHeadersChips = await Promise.all(await (await allowHeadersChipList.getChips()).map((c) => c.getText())); expect(allowHeadersChips).toEqual(['x-bar', 'x-ray']); // # Exposed-Headers const exposedHeadersFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Exposed-Headers' })); const exposedHeadersChipList = await exposedHeadersFormField.getControl(MatChipListHarness); const exposedHeadersAutocomplete = await exposedHeadersFormField.getControl(MatAutocompleteHarness); // Select `Cache-Control` with autocomplete await exposedHeadersAutocomplete.focus(); await exposedHeadersAutocomplete.selectOption({ text: 'Cache-Control' }); // Check headers const exposedHeadersChips = await Promise.all(await (await exposedHeadersChipList.getChips()).map((c) => c.getText())); expect(exposedHeadersChips).toEqual(['Cache-Control']); // # Max age const maxAgeFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Max age/ })); await (await maxAgeFormField.getControl(MatInputHarness)).setValue('666'); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ cors: { allowOrigin: ['(Valid|RegExp)'], allowMethods: ['GET', 'DELETE', 'POST'], allowHeaders: ['x-bar', 'x-ray'], exposedHeaders: ['Cache-Control'], maxAge: 666, }, }); }); it('should open confirm dialog for the addition of a Allow-Origin with `*`', async () => { expectConsoleSettingsGetRequest({ cors: { allowOrigin: undefined, }, }); // # Allow-Origin const allowOriginFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: 'Allow-Origin' })); expect(await (await allowOriginFormField.getControl(GioFormTagsInputHarness)).getTags()).toEqual([]); // Add `*` and confirm dialog const allowOriginChipListInput = await allowOriginFormField.getControl(GioFormTagsInputHarness); await allowOriginChipListInput.addTag('*'); const dialogOne = await rootLoader.getHarness(MatDialogHarness); expect(await dialogOne.getId()).toEqual('allowAllOriginsConfirmDialog'); await dialogOne.close(); await allowOriginChipListInput.addTag('*'); const dialogTwo = await rootLoader.getHarness(MatDialogHarness); await (await dialogTwo.getHarness(MatButtonHarness.with({ text: /^Yes,/ }))).click(); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ cors: { allowOrigin: ['*'], }, }); }); }); describe('email', () => { it('should disable field when setting is readonly', async () => { expectConsoleSettingsGetRequest({ email: { enabled: true, }, metadata: { readonly: [ 'email.enabled', 'email.host', 'email.port', 'email.username', 'email.password', 'email.protocol', 'email.subject', 'email.from', 'email.properties.auth', 'email.properties.startTlsEnable', 'email.properties.sslTrust', ], }, }); const emailEnabledEnableSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'emailEnabled' })); expect(await emailEnabledEnableSlideToggle.isDisabled()).toEqual(true); await Promise.all( ['Host', 'Port', 'Username', 'Password', 'Protocol', 'Subject', 'From', 'SSL Trust'].map(async (floatingLabelText) => { const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText })); expect(await emailFormField.isDisabled()).toEqual(true); }), ); const propertiesAuthSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'emailPropertiesAuth' })); expect(await propertiesAuthSlideToggle.isDisabled()).toEqual(true); const propertiesStartTlsEnableSlideToggle = await loader.getHarness( MatSlideToggleHarness.with({ name: 'emailPropertiesStartTlsEnable' }), ); expect(await propertiesStartTlsEnableSlideToggle.isDisabled()).toEqual(true); }); it('should save email settings', async () => { expectConsoleSettingsGetRequest({ email: { enabled: true, host: 'Host', port: 42, username: 'Username', password: 'Password', protocol: 'Protocol', subject: 'Subject', from: 'From', properties: { auth: true, startTlsEnable: false, sslTrust: undefined }, }, }); await Promise.all( ['Host', 'Username', 'Password', 'Protocol', 'Subject', 'From', 'SSL Trust'].map(async (floatingLabelText) => { const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText })); await (await emailFormField.getControl(MatInputHarness)).setValue(`New ${floatingLabelText}`); }), ); const propertiesAuthSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'emailPropertiesAuth' })); await propertiesAuthSlideToggle.uncheck(); const propertiesStartTlsEnableSlideToggle = await loader.getHarness( MatSlideToggleHarness.with({ name: 'emailPropertiesStartTlsEnable' }), ); await propertiesStartTlsEnableSlideToggle.check(); const saveButton = await loader.getHarness(GioSaveBarHarness); await saveButton.clickSubmit(); expectConsoleSettingsSendRequest({ email: { enabled: true, host: 'New Host', port: 42, username: 'New Username', password: 'New Password', protocol: 'New Protocol', subject: 'New Subject', from: 'NewFrom', properties: { auth: false, startTlsEnable: true, sslTrust: 'New SSL Trust' }, }, }); }); it('should disable all email settings when email.enabled is not checked', async () => { expectConsoleSettingsGetRequest({ email: { enabled: true, }, metadata: { readonly: ['email.host', 'email.port', 'email.properties.auth'], }, }); const emailEnabledEnableSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'emailEnabled' })); await emailEnabledEnableSlideToggle.uncheck(); // expect all email settings to be not visible await Promise.all( ['Host', 'Port', 'Username', 'Password', 'Protocol', 'Subject', 'From', 'SSL Trust'].map(async (floatingLabelText) => { const isEmailFormFieldVisible = await loader .getHarness(MatFormFieldHarness.with({ floatingLabelText })) .then(() => true) .catch(() => false); expect(isEmailFormFieldVisible).toEqual(false); }), ); const isPropertiesAuthSlideToggleVisible = await loader .getHarness(MatSlideToggleHarness.with({ name: 'emailPropertiesAuth' })) .then(() => true) .catch(() => false); expect(await isPropertiesAuthSlideToggleVisible).toEqual(false); const isPropertiesStartTlsEnableSlideToggleVisible = await loader .getHarness(MatSlideToggleHarness.with({ name: 'emailPropertiesStartTlsEnable' })) .then(() => true) .catch(() => false); expect(await isPropertiesStartTlsEnableSlideToggleVisible).toEqual(false); await emailEnabledEnableSlideToggle.check(); // Expect all email settings to be enabled except for read-only settings await Promise.all( ['Username', 'Password', 'Protocol', 'Subject', 'From', 'SSL Trust'].map(async (floatingLabelText) => { const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText })); expect(await emailFormField.isDisabled()).toEqual(false); }), ); await Promise.all( ['Host', 'Port'].map(async (floatingLabelText) => { const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText })); expect(await emailFormField.isDisabled()).toEqual(true); }), ); const propertiesAuthSlideToggle = await loader.getHarness(MatSlideToggleHarness.with({ name: 'emailPropertiesAuth' })); expect(await propertiesAuthSlideToggle.isDisabled()).toEqual(true); const propertiesStartTlsEnableSlideToggle = await loader.getHarness( MatSlideToggleHarness.with({ name: 'emailPropertiesStartTlsEnable' }), ); expect(await propertiesStartTlsEnableSlideToggle.isDisabled()).toEqual(false); }); }); afterEach(() => { httpTestingController.verify(); }); function expectConsoleSettingsSendRequest(consoleSettingsPayload: ConsoleSettings) { const req = httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/settings`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toMatchObject(consoleSettingsPayload); } function expectConsoleSettingsGetRequest(consoleSettingsResponse: ConsoleSettings) { const req = httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/settings`); expect(req.request.method).toEqual('GET'); req.flush(consoleSettingsResponse); } });
the_stack
import * as util from './util'; import Queue from './Queue'; // Internal interface for BST interface BSTreeNode<T> { element: T; leftCh: BSTreeNode<T> | null; rightCh: BSTreeNode<T> | null; parent: BSTreeNode<T> | null; } /** * General binary search tree implementation. * * This interface allows one to search elements using a subset of their attributes (thus the * tree can be used as an index for complex objects). * The attributes required to define an ordering in the tree must be defined in the type K. * Any additional attribute must be defined in the type V. * * @see BSTree */ export default class BSTreeKV<K, V extends K> { private root: BSTreeNode<V> | null; private compare: util.ICompareFunction<K>; private nElements: number; /** * Creates an empty binary search tree. * @class <p>A binary search tree is a binary tree in which each * internal node stores an element such that the elements stored in the * left subtree are less than it and the elements * stored in the right subtree are greater.</p> * <p>Formally, a binary search tree is a node-based binary tree data structure which * has the following properties:</p> * <ul> * <li>The left subtree of a node contains only nodes with elements less * than the node's element</li> * <li>The right subtree of a node contains only nodes with elements greater * than the node's element</li> * <li>Both the left and right subtrees must also be binary search trees.</li> * </ul> * <p>If the inserted elements are custom objects a compare function must * be provided at construction time, otherwise the <=, === and >= operators are * used to compare elements. Example:</p> * <pre> * function compare(a, b) { * if (a is less than b by some ordering criterion) { * return -1; * } if (a is greater than b by the ordering criterion) { * return 1; * } * // a must be equal to b * return 0; * } * </pre> * @constructor * @param {function(Object,Object):number=} compareFunction optional * function used to compare two elements. Must return a negative integer, * zero, or a positive integer as the first argument is less than, equal to, * or greater than the second. */ constructor(compareFunction?: util.ICompareFunction<K>) { this.root = null; this.compare = compareFunction || util.defaultCompare; this.nElements = 0; } /** * Adds the specified element to this tree if it is not already present. * @param {Object} element the element to insert. * @return {boolean} true if this tree did not already contain the specified element. */ add(element: V): boolean { if (util.isUndefined(element)) { return false; } if (this.insertNode(this.createNode(element)) !== null) { this.nElements++; return true; } return false; } /** * Removes all of the elements from this tree. */ clear(): void { this.root = null; this.nElements = 0; } /** * Returns true if this tree contains no elements. * @return {boolean} true if this tree contains no elements. */ isEmpty(): boolean { return this.nElements === 0; } /** * Returns the number of elements in this tree. * @return {number} the number of elements in this tree. */ size(): number { return this.nElements; } /** * Returns true if this tree contains the specified element. * @param {Object} element element to search for. * @return {boolean} true if this tree contains the specified element, * false otherwise. */ contains(element: K): boolean { if (util.isUndefined(element)) { return false; } return this.searchNode(this.root, element) !== null; } /** * Looks for the value with the provided search key. * @param {Object} element The key to look for * @return {Object} The value found or undefined if it was not found. */ search(element: K): V | undefined { const ret = this.searchNode(this.root, element); if (ret === null) { return undefined; } return ret.element; } /** * Removes the specified element from this tree if it is present. * @return {boolean} true if this tree contained the specified element. */ remove(element: K): boolean { const node = this.searchNode(this.root, element); if (node === null) { return false; } this.removeNode(node); this.nElements--; return true; } /** * Executes the provided function once for each element present in this tree in * in-order. * @param {function(Object):*} callback function to execute, it is invoked with one * argument: the element value, to break the iteration you can optionally return false. */ inorderTraversal(callback: util.ILoopFunction<V>): void { this.inorderTraversalAux(this.root, callback, { stop: false }); } /** * Executes the provided function once for each element present in this tree in pre-order. * @param {function(Object):*} callback function to execute, it is invoked with one * argument: the element value, to break the iteration you can optionally return false. */ preorderTraversal(callback: util.ILoopFunction<V>): void { this.preorderTraversalAux(this.root, callback, { stop: false }); } /** * Executes the provided function once for each element present in this tree in post-order. * @param {function(Object):*} callback function to execute, it is invoked with one * argument: the element value, to break the iteration you can optionally return false. */ postorderTraversal(callback: util.ILoopFunction<V>): void { this.postorderTraversalAux(this.root, callback, { stop: false }); } /** * Executes the provided function once for each element present in this tree in * level-order. * @param {function(Object):*} callback function to execute, it is invoked with one * argument: the element value, to break the iteration you can optionally return false. */ levelTraversal(callback: util.ILoopFunction<V>): void { this.levelTraversalAux(this.root, callback); } /** * Returns the minimum element of this tree. * @return {*} the minimum element of this tree or undefined if this tree is * is empty. */ minimum(): V | undefined { if (this.isEmpty() || this.root === null) { return undefined; } return this.minimumAux(this.root).element; } /** * Returns the maximum element of this tree. * @return {*} the maximum element of this tree or undefined if this tree is * is empty. */ maximum(): V | undefined { if (this.isEmpty() || this.root === null) { return undefined; } return this.maximumAux(this.root).element; } /** * Executes the provided function once for each element present in this tree in inorder. * Equivalent to inorderTraversal. * @param {function(Object):*} callback function to execute, it is * invoked with one argument: the element value, to break the iteration you can * optionally return false. */ forEach(callback: util.ILoopFunction<V>): void { this.inorderTraversal(callback); } /** * Returns an array containing all of the elements in this tree in in-order. * @return {Array} an array containing all of the elements in this tree in in-order. */ toArray(): V[] { const array: Array<V> = []; this.inorderTraversal(function(element: V): boolean { array.push(element); return true; }); return array; } /** * Returns the height of this tree. * @return {number} the height of this tree or -1 if is empty. */ height(): number { return this.heightAux(this.root); } /** * @private */ private searchNode(node: BSTreeNode<V> | null, element: K): BSTreeNode<V> | null { let cmp: number = 1; while (node !== null && cmp !== 0) { cmp = this.compare(element, node.element); if (cmp < 0) { node = node.leftCh; } else if (cmp > 0) { node = node.rightCh; } } return node; } /** * @private */ private transplant(n1: BSTreeNode<V>, n2: BSTreeNode<V> | null): void { if (n1.parent === null) { this.root = n2; } else if (n1 === n1.parent.leftCh) { n1.parent.leftCh = n2; } else { n1.parent.rightCh = n2; } if (n2 !== null) { n2.parent = n1.parent; } } /** * @private */ private removeNode(node: BSTreeNode<V>): void { if (node.leftCh === null) { this.transplant(node, node.rightCh); } else if (node.rightCh === null) { this.transplant(node, node.leftCh); } else { const y = this.minimumAux(node.rightCh); if (y.parent !== node) { this.transplant(y, y.rightCh); y.rightCh = node.rightCh; y.rightCh.parent = y; } this.transplant(node, y); y.leftCh = node.leftCh; y.leftCh.parent = y; } } /** * @private */ private inorderTraversalAux(node: BSTreeNode<V> | null, callback: util.ILoopFunction<V>, signal: { stop: boolean; }): void { if (node === null || signal.stop) { return; } this.inorderTraversalAux(node.leftCh, callback, signal); if (signal.stop) { return; } signal.stop = callback(node.element) === false; if (signal.stop) { return; } this.inorderTraversalAux(node.rightCh, callback, signal); } /** * @private */ private levelTraversalAux(node: BSTreeNode<V> | null, callback: util.ILoopFunction<V>) { const queue = new Queue<BSTreeNode<V>>(); if (node !== null) { queue.enqueue(node); } node = queue.dequeue() || null; while (node != null) { if (callback(node.element) === false) { return; } if (node.leftCh !== null) { queue.enqueue(node.leftCh); } if (node.rightCh !== null) { queue.enqueue(node.rightCh); } node = queue.dequeue() || null; } } /** * @private */ private preorderTraversalAux(node: BSTreeNode<V> | null, callback: util.ILoopFunction<V>, signal: { stop: boolean; }) { if (node === null || signal.stop) { return; } signal.stop = callback(node.element) === false; if (signal.stop) { return; } this.preorderTraversalAux(node.leftCh, callback, signal); if (signal.stop) { return; } this.preorderTraversalAux(node.rightCh, callback, signal); } /** * @private */ private postorderTraversalAux(node: BSTreeNode<V> | null, callback: util.ILoopFunction<V>, signal: { stop: boolean; }) { if (node === null || signal.stop) { return; } this.postorderTraversalAux(node.leftCh, callback, signal); if (signal.stop) { return; } this.postorderTraversalAux(node.rightCh, callback, signal); if (signal.stop) { return; } signal.stop = callback(node.element) === false; } /** * @private */ private minimumAux(node: BSTreeNode<V>): BSTreeNode<V>; private minimumAux(node: BSTreeNode<V> | null): BSTreeNode<V> | null; private minimumAux(node: BSTreeNode<V> | null): BSTreeNode<V> | null { while (node != null && node.leftCh !== null) { node = node.leftCh; } return node; } /** * @private */ private maximumAux(node: BSTreeNode<V>): BSTreeNode<V>; private maximumAux(node: BSTreeNode<V> | null): BSTreeNode<V> | null; private maximumAux(node: BSTreeNode<V> | null): BSTreeNode<V> | null { while (node != null && node.rightCh !== null) { node = node.rightCh; } return node; } /** * @private */ private heightAux(node: BSTreeNode<V> | null): number { if (node === null) { return -1; } return Math.max(this.heightAux(node.leftCh), this.heightAux(node.rightCh)) + 1; } /* * @private */ private insertNode(node: BSTreeNode<V>): BSTreeNode<V> | null { let parent: any = null; let position = this.root; while (position !== null) { const cmp = this.compare(node.element, position.element); if (cmp === 0) { return null; } else if (cmp < 0) { parent = position; position = position.leftCh; } else { parent = position; position = position.rightCh; } } node.parent = parent; if (parent === null) { // tree is empty this.root = node; } else if (this.compare(node.element, parent.element) < 0) { parent.leftCh = node; } else { parent.rightCh = node; } return node; } /** * @private */ private createNode(element: V): BSTreeNode<V> { return { element: element, leftCh: null, rightCh: null, parent: null }; } }
the_stack
import * as assert from 'assert'; import * as path from 'path'; import * as fs from 'fs'; import { DiagnosticSeverity } from 'vscode'; import { before } from 'mocha'; import { PassThrough } from 'stream'; import { ModelCheckResult, CheckState, CheckStatus, ModelCheckResultSource, Value, SpecFiles } from '../../../src/model/check'; import { TlcModelCheckerStdoutParser } from '../../../src/parsers/tlc'; import { CheckResultBuilder, pos, range, struct, v, set, message, sourceLink, traceItem } from '../shortcuts'; const TEST_SPEC_FILES = new SpecFiles('/Users/alice/TLA/foo.tla', '/Users/alice/TLA/foo.cfg'); const FIXTURES_PATH = path.resolve(__dirname, '../../../../tests/fixtures/parsers/tlc'); suite('TLC Output Parser Test Suite', () => { before(() => { Value.switchIdsOff(); }); test('Parses minimal PlusCal output', () => { return assertOutput('empty-calplus.out', TEST_SPEC_FILES, new CheckResultBuilder('empty-calplus.out', CheckState.Success, CheckStatus.Finished) .addDColFilePath('/Users/bob/example.tla') .addDColFilePath('/private/var/folders/tla/T/TLC.tla') .addDColFilePath('/private/var/folders/tla/T/Naturals.tla') .addDColFilePath('/private/var/folders/tla/T/Sequences.tla') .addDColFilePath('/private/var/folders/tla/T/FiniteSets.tla') .setStartDateTime('2019-08-17 00:11:08') .setEndDateTime('2019-08-17 00:11:09') .setDuration(886) .setProcessInfo( 'Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571' + ' with 1 worker on 4 cores with 1820MB heap and 64MB offheap memory [pid: 91333]' + ' (Mac OS X 10.14.5 x86_64, Amazon.com Inc. 11.0.3 x86_64, MSBDiskFPSet, DiskStateQueue).') .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 2, 3, 2, 0) .addCoverage('example', 'Init', '/Users/bob/example.tla', range(13, 0, 13, 4), 1, 1) .addCoverage('example', 'Lbl_1', '/Users/bob/example.tla', range(15, 0, 15, 5), 1, 1) .addCoverage('example', 'Terminating', '/Users/bob/example.tla', range(20, 0, 20, 11), 1, 0) .build() ); }); test('Captures Print/PrintT output', () => { return assertOutput('print-output.out', TEST_SPEC_FILES, new CheckResultBuilder('foo', CheckState.Success, CheckStatus.Finished) .setStartDateTime('2019-01-01 01:02:03') .setEndDateTime('2019-01-01 01:02:05') .setDuration(2345) .addInitState('00:00:00', 0, 5184, 5184, 5184) .addOutLine('Foo') .addOutLine('Bar', 2) .addOutLine('Baz') .build() ); }); test('Captures output from external modules that override stdout', () => { return assertOutput('override-stdout.out', TEST_SPEC_FILES, new CheckResultBuilder('foo', CheckState.Success, CheckStatus.Finished) .setStartDateTime('2019-01-01 01:02:03') .setEndDateTime('2019-01-01 01:02:05') .setDuration(2345) .addInitState('00:00:00', 0, 5184, 5184, 5184) .addOutLine('Line 1 from external module') .addOutLine('Line 2') .build() ); }); test('Respects severity levels', () => { return assertOutput('severity-levels.out', TEST_SPEC_FILES, new CheckResultBuilder('foo', CheckState.Error, CheckStatus.Finished) .setStartDateTime('2019-01-01 01:02:03') .setEndDateTime('2019-01-01 01:02:05') .setDuration(2345) .addInitState('00:00:00', 0, 5184, 5184, 5184) .addOutLine('Info message.') .addWarning([message('Warning message.')]) .addError([message('Error message.')]) .addError([message('TLC bug info.')]) .build() ); }); test('Captures warnings', () => { return assertOutput('warning.out', TEST_SPEC_FILES, new CheckResultBuilder('warning.out', CheckState.Success, CheckStatus.Finished) .addDColFilePath('/Users/bob/example.tla') .setStartDateTime('2019-08-17 00:11:08') .setEndDateTime('2019-08-17 00:11:09') .setDuration(886) .addWarning([ message('Please run the Java VM which executes TLC with a throughput optimized garbage collector' + ' by passing the "-XX:+UseParallelGC" property.') ]) .setProcessInfo( 'Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571' + ' with 1 worker on 4 cores with 1820MB heap and 64MB offheap memory [pid: 91333]' + ' (Mac OS X 10.14.5 x86_64, Amazon.com Inc. 11.0.3 x86_64, MSBDiskFPSet, DiskStateQueue).') .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 2, 3, 2, 0) .addCoverage('example', 'Init', '/Users/bob/example.tla', range(13, 0, 13, 4), 1, 1) .build() ); }); test('Reports failure when errors are present', () => { // The check state is Error despite the 2193 (TLC_SUCCESS) message. // It happens when the -continue option is used. return assertOutput('error-continue.out', TEST_SPEC_FILES, new CheckResultBuilder('error-continue.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/example.tla') .setStartDateTime('2019-08-17 00:11:08') .setEndDateTime('2019-08-17 00:11:09') .setDuration(886) .setProcessInfo( 'Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571' + ' with 1 worker on 4 cores with 1820MB heap and 64MB offheap memory [pid: 91333]' + ' (Mac OS X 10.14.5 x86_64, Amazon.com Inc. 11.0.3 x86_64, MSBDiskFPSet, DiskStateQueue).') .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 2, 3, 2, 0) .addCoverage('example', 'Init', '/Users/bob/example.tla', range(13, 0, 13, 4), 1, 1) .addError( [message('Invariant FooInvariant is violated.')], [ traceItem(1, 'Initial predicate', '', '', undefined, range(0, 0, 0, 0), struct('', v('FooVar', '1..2'), v('BarVar', '-1')) ) ] ) .build() ); }); test('Captures SANY errors', () => { return assertOutput('sany-error.out', TEST_SPEC_FILES, new CheckResultBuilder('sany-error.out', CheckState.Error, CheckStatus.Finished) .setProcessInfo('Running breadth-first search Model-Checking with fp 86 and seed -5126315020031287108.') .addDColFilePath(TEST_SPEC_FILES.tlaFilePath) .setStartDateTime('2019-08-17 02:04:44') .setEndDateTime('2019-08-17 02:04:44') .setDuration(380) .addDColMessage( TEST_SPEC_FILES.tlaFilePath, range(4, 7, 4, 8), "Unknown operator: `a'.", DiagnosticSeverity.Error ) .addError([message("Unknown operator: `a'.")]) .addError([message('Parsing or semantic analysis failed.')]) .build() ); }); test('Captures SANY warnings', () => { return assertOutput('sany-warning.out', TEST_SPEC_FILES, new CheckResultBuilder('sany-warning.out', CheckState.Error, CheckStatus.Finished) .setProcessInfo('Running breadth-first search Model-Checking with fp 86 and seed -5126315020031287108.') .addDColFilePath(TEST_SPEC_FILES.tlaFilePath) .setStartDateTime('2019-08-17 02:04:44') .setEndDateTime('2019-08-17 02:04:44') .setDuration(380) .addDColMessage( TEST_SPEC_FILES.tlaFilePath, range(4, 7, 4, 8), "Multiple declarations of operator `a'.", DiagnosticSeverity.Warning ) .addWarning([message("Multiple declarations of operator `a'.")]) .build() ); }); test('Parses error trace', () => { const specFiles = new SpecFiles('/Users/bob/error_trace.tla', '/Users/bob/error_trace.cfg'); return assertOutput('error-trace.out', specFiles, new CheckResultBuilder('error-trace.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/error_trace.tla') .addDColFilePath('/private/var/folders/tla/Integers.tla') .addDColFilePath('/private/var/folders/tla/Naturals.tla') .setProcessInfo('Running breadth-first search Model-Checking with fp 6 and seed -9020681683977717109.') .setStartDateTime('2019-08-17 02:37:50') .setEndDateTime('2019-08-17 02:37:51') .setDuration(1041) .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 3, 4, 4, 1) .addCoverage('error_trace', 'Init', '/Users/bob/error_trace.tla', range(7, 0, 7, 4), 2, 2) .addCoverage('error_trace', 'SomeFunc', '/Users/bob/error_trace.tla', range(11, 0, 11, 11), 5, 3) .addError( [message('Invariant FooInvariant is violated.')], [ traceItem(1, 'Initial predicate', '', '', undefined, range(0, 0, 0, 0), struct('', v('FooVar', '1..2'), v('BarVar', '-1')) ), traceItem(2, 'SomeFunc in error_trace', 'error_trace', 'SomeFunc', '/Users/bob/error_trace.tla', range(12, 8, 14, 24), struct('', set('FooVar', v(1, '1')).setModified(), v('BarVar', '1').setModified() ).setModified() ), traceItem(3, 'SomeFunc in error_trace', 'error_trace', 'SomeFunc', '/Users/bob/error_trace.tla', range(12, 8, 14, 24), struct('', set('FooVar', v(1, '4').setModified(), v(2, 'TRUE').setAdded()).setModified(), v('BarVar', '40').setModified() ).setModified() ) ] ) .build() ); }); test('Parses error trace with stuttering state', () => { const specFiles = new SpecFiles('/Users/bob/stuttering.tla', '/Users/bob/stuttering.cfg'); return assertOutput('error-trace-stuttering.out', specFiles, new CheckResultBuilder('stuttering.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/stuttering.tla') .setProcessInfo('Running breadth-first search Model-Checking with fp 6 and seed -9020681683977717109.') .setStartDateTime('2019-08-17 02:37:50') .setEndDateTime('2019-08-17 02:37:51') .setDuration(1041) .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 3, 4, 4, 1) .addError( [ message('Temporal properties were violated.')], [ traceItem(1, 'Initial predicate', '', '', undefined, range(0, 0, 0, 0), struct('', v('Foo', '1')) ), traceItem(2, 'Stuttering', '', '', undefined, range(0, 0, 0, 0), struct('') ) ] ) .build() ); }); test('Parses error trace with back-to-previous-state', () => { const specFiles = new SpecFiles('/Users/bob/back_to_state.tla', '/Users/bob/back_to_state.cfg'); return assertOutput('error-trace-back-to-state.out', specFiles, new CheckResultBuilder('back_to_state.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/back_to_state.tla') .setProcessInfo('Running breadth-first search Model-Checking with fp 6 and seed -9020681683977717109.') .setStartDateTime('2019-08-17 02:37:50') .setEndDateTime('2019-08-17 02:37:51') .setDuration(1041) .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 3, 4, 4, 1) .addError( [ message('Temporal properties were violated.')], [ traceItem(1, 'Initial predicate', '', '', undefined, range(0, 0, 0, 0), struct('', v('Foo', '1')) ), traceItem(2, 'Cycle in back_to_state', 'back_to_state', 'Cycle', '/Users/bob/back_to_state.tla', range(41, 9, 47, 30), struct('', v('Foo', '2').setModified()).setModified() ), traceItem(2, 'Back to state', 'back_to_state', 'Cycle', '/Users/bob/back_to_state.tla', range(41, 9, 47, 30), struct('') ) ] ) .build() ); }); test('Parses error trace with back-to-previous-state-ext', () => { const specFiles = new SpecFiles('/Users/bob/back_to_state.tla', '/Users/bob/back_to_state.cfg'); return assertOutput('error-trace-back-to-state-ext.out', specFiles, new CheckResultBuilder('back_to_state.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/back_to_state.tla') .setProcessInfo('Running breadth-first search Model-Checking with fp 6 and seed -9020681683977717109.') .setStartDateTime('2019-08-17 02:37:50') .setEndDateTime('2019-08-17 02:37:51') .setDuration(1041) .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 3, 4, 4, 1) .addError( [ message('Temporal properties were violated.')], [ traceItem(1, 'Initial predicate', '', '', undefined, range(0, 0, 0, 0), struct('', v('Foo', '1')) ), traceItem(2, 'Cycle in back_to_state', 'back_to_state', 'Cycle', '/Users/bob/back_to_state.tla', range(41, 9, 47, 30), struct('', v('Foo', '2').setModified()).setModified() ), traceItem(1, 'Cycle in back_to_state (Back to state)', 'back_to_state', 'Cycle', '/Users/bob/back_to_state.tla', range(41, 9, 47, 30), struct('') ) ] ) .build() ); }); test('Parses error trace with a single variable', () => { // Such variables has no `/\` at the beginning const specFiles = new SpecFiles('/Users/bob/error_trace.tla', '/Users/bob/error_trace.cfg'); return assertOutput('error-trace-single.out', specFiles, new CheckResultBuilder('error-trace-single.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/error_trace.tla') .setProcessInfo('Running breadth-first search Model-Checking with fp 6 and seed -9020681683977717109.') .setStartDateTime('2019-08-17 02:37:50') .setEndDateTime('2019-08-17 02:37:51') .setDuration(1041) .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 3, 4, 4, 1) .addError( [ message('Invariant FooInvariant is violated.')], [ traceItem(1, 'Initial predicate', '', '', undefined, range(0, 0, 0, 0), struct('', struct('Var', v('foo', '1'), v('bar', '2'))) ) ] ) .build() ); }); test('Handles nested exception messages', () => { // Messages 1000 `TLC threw an unexpected exception...` // contains a nested message with details that must be combined with the outer one. return assertOutput('nested-exception-message.out', TEST_SPEC_FILES, new CheckResultBuilder('nested-exception-message.out', CheckState.Error, CheckStatus.Finished) .setProcessInfo('Running breadth-first search Model-Checking with fp 95 and seed -5827499341661814189.') .setEndDateTime('2019-08-18 21:16:19') .setDuration(262) .addError([ message('TLC threw an unexpected exception.'), message('This was probably caused by an error in the spec or model.'), message('See the User Output or TLC Console for clues to what happened.'), message('The exception was a tlc2.tool.ConfigFileException'), message(': '), message('TLC found an error in the configuration file at line 6'), message('It was expecting = or <-, but did not find it.') ]) .build() ); }); test('Extracts links from error messages', () => { return assertOutput('error-message-links.out', TEST_SPEC_FILES, new CheckResultBuilder('error-message-links.out', CheckState.Error, CheckStatus.Finished) .addDColFilePath('/Users/bob/error_message_links.tla') .setProcessInfo('Running breadth-first search Model-Checking with fp 6 and seed -9020681683977717109.') .setStartDateTime('2019-08-17 02:37:50') .setEndDateTime('2019-08-17 02:37:51') .setDuration(1041) .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 3, 4, 4, 1) .addError([ message('The error occurred when TLC was evaluating the nested'), message('expressions at the following positions:'), message( '0. ', sourceLink( 'Line 38, column 10 to line 50, column 44 in error_message_links', '/Users/bob/error_message_links.tla', pos(37, 9) ) ), message( '1. ', sourceLink( 'Line 40, column 13 to line 42, column 24 in error_message_links', '/Users/bob/error_message_links.tla', pos(39, 12) ), '. It\'s a pity.' ) ]) .build() ); }); test('Handles no-line-break message end', () => { // bla-bla-bla@!@!@ENDMSG 2193 @!@!@ return assertOutput('no-line-break-end.out', TEST_SPEC_FILES, new CheckResultBuilder('no-line-break-end.out', CheckState.Success, CheckStatus.Finished) .addDColFilePath('/Users/bob/example.tla') .setStartDateTime('2019-08-17 00:12:01') .setEndDateTime('2019-08-17 00:12:02') .setDuration(400) .setProcessInfo( 'Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571' + ' with 1 worker on 4 cores with 1820MB heap and 64MB offheap memory [pid: 91333]' + ' (Mac OS X 10.14.5 x86_64, Amazon.com Inc. 11.0.3 x86_64, MSBDiskFPSet, DiskStateQueue).') .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 2, 3, 2, 0) .addCoverage('example', 'Init', '/Users/bob/example.tla', range(13, 0, 13, 4), 1, 1) .build() ); }); test('Handles no-line-break message switch', () => { // https://github.com/alygin/vscode-tlaplus/issues/47 return assertOutput('no-line-break-switch.out', TEST_SPEC_FILES, new CheckResultBuilder('no-line-break-switch.out', CheckState.Success, CheckStatus.Finished) .addDColFilePath('/Users/bob/example.tla') .setStartDateTime('2019-08-17 00:12:01') .setEndDateTime('2019-08-17 00:12:02') .setDuration(400) .setProcessInfo( 'Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571' + ' with 1 worker on 4 cores with 1820MB heap and 64MB offheap memory [pid: 91333]' + ' (Mac OS X 10.14.5 x86_64, Amazon.com Inc. 11.0.3 x86_64, MSBDiskFPSet, DiskStateQueue).') .addInitState('00:00:00', 0, 1, 1, 1) .addInitState('00:00:01', 2, 3, 2, 0) .addCoverage('example', 'Init', '/Users/bob/example.tla', range(13, 0, 13, 4), 1, 1) .build() ); }); test('Rewrites initial state item with the same timestamp', () => { return assertOutput('state-timestamp-duplication.out', TEST_SPEC_FILES, new CheckResultBuilder('state-timestamp-duplication.out', CheckState.Success, CheckStatus.Finished) .addDColFilePath('/Users/bob/example.tla') .addDColFilePath('/private/var/folders/tla/T/TLC.tla') .setStartDateTime('2019-08-17 00:11:08') .setEndDateTime('2019-08-17 00:11:09') .setDuration(886) .setProcessInfo('Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571.') .addInitState('00:00:00', 0, 1, 1, 1) // .addInitState('00:00:01', 2, 3, 2, 0) <-- This one must be substituted for the following .addInitState('00:00:01', 2, 13, 12, 0) .addCoverage('example', 'Init', '/Users/bob/example.tla', range(13, 0, 13, 4), 1, 1) .addCoverage('example', 'Lbl_1', '/Users/bob/example.tla', range(15, 0, 15, 5), 1, 1) .addCoverage('example', 'Terminating', '/Users/bob/example.tla', range(20, 0, 20, 11), 1, 0) .build() ); }); test('Handles coverage info that contains location', () => { return assertOutput('coverage-with-location.out', TEST_SPEC_FILES, new CheckResultBuilder('coverage-with-location.out', CheckState.Success, CheckStatus.Finished) .addDColFilePath('/Users/alice/issue_209.tla') .addDColFilePath('/private/var/folders/tla/T/TLC.tla') .setStartDateTime('2021-07-10 11:49:12') .setEndDateTime('2021-07-10 11:49:13') .setDuration(1166) .setProcessInfo('Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571.') .addInitState('00:00:00', 2, 7, 3, 0) .addCoverage('issue_209', 'Init', '/Users/alice/issue_209.tla', range(4, 0, 4, 4), 1, 1) .addCoverage('issue_209', 'Next', '/Users/alice/issue_209.tla', range(5, 0, 5, 4), 6, 2) .build() ); }); test('Parses localized integers', () => { return assertOutput('localized-ints.out', TEST_SPEC_FILES, new CheckResultBuilder('localized-ints.out', CheckState.Stopped, CheckStatus.CheckingLiveness) .addDColFilePath('/Users/charlie/issue_229.tla') .setStartDateTime('2021-07-06 16:22:05') .setProcessInfo('Running breadth-first search Model-Checking with fp 22 and seed -5755320172003082571.') .addInitState('00:00:00', 0, 16, 16, 16) .addInitState('00:00:03', 6, 65577, 11342, 6463) .addInitState('00:01:11', 14, 3191033, 346966, 92794) .addInitState('00:02:31', 16, 6349139, 683798, 186242) .addCoverage('issue_229', 'Init', '/Users/charlie/issue_229.tla', range(36, 0, 36, 4), 16, 16) .addCoverage('issue_229', 'Next', '/Users/charlie/issue_229.tla', range(117, 0, 117, 4), 951429, 101618) .build() ); }); }); class CheckResultHolder { checkResult: ModelCheckResult = ModelCheckResult.createEmpty(ModelCheckResultSource.OutFile); } function assertEquals(actual: ModelCheckResult, expected: ModelCheckResult) { assert.equal(actual.state, expected.state, "State doesn't match"); assert.equal(actual.status, expected.status, "Status doesn't match"); assert.equal(actual.processInfo, expected.processInfo, "Process info doesn't match"); assert.equal(actual.startDateTimeStr, expected.startDateTimeStr, "Start date/time doesn't match"); assert.equal(actual.endDateTimeStr, expected.endDateTimeStr, "End date/time doesn't match"); assert.equal(actual.duration, expected.duration, "Duration doesn't match"); assert.deepEqual(actual.outputLines, expected.outputLines, "Output lines don't match"); assert.deepEqual(actual.initialStatesStat, expected.initialStatesStat, "Initial states statistics doesn't match"); assert.deepEqual(actual.coverageStat, expected.coverageStat, "Coverage statistics doesn't match"); assert.deepEqual(actual.sanyMessages, expected.sanyMessages, "SANY messages don't match"); assert.deepEqual(actual.warnings, expected.warnings, "Warnings don't match"); assert.deepEqual(actual.errors, expected.errors, "Erros don't match"); } async function assertOutput(fileName: string, specFiles: SpecFiles, expected: ModelCheckResult): Promise<void> { const filePath = path.join(FIXTURES_PATH, fileName); const buffer = fs.readFileSync(filePath); const stream = new PassThrough(); stream.end(buffer); const crh = new CheckResultHolder(); const parser = new TlcModelCheckerStdoutParser( ModelCheckResultSource.OutFile, stream, specFiles, false, cr => { crh.checkResult = cr; } ); return parser.readAll().then(() => assertEquals(crh.checkResult, expected)); }
the_stack
import React, { Component, Key } from 'react'; import classNames from 'classnames'; import { action, toJS } from 'mobx'; import noop from 'lodash/noop'; import KeyCode from 'choerodon-ui/lib/_util/KeyCode'; import ConfigContext from 'choerodon-ui/lib/config-provider/ConfigContext'; import DataSet from '../data-set/DataSet'; import Record from '../data-set/Record'; import Table, { onColumnResizeProps, TableProps } from '../table/Table'; import TableProfessionalBar from '../table/query-bar/TableProfessionalBar'; import { SelectionMode, TableMode, TableQueryBarType } from '../table/enum'; import { DataSetEvents, DataSetSelection } from '../data-set/enum'; import { ColumnProps } from '../table/Column'; import { modalChildrenProps } from '../modal/interface'; import autobind from '../_util/autobind'; import { getColumnKey } from '../table/utils'; import SelectionList, { TIMESTAMP, SelectionsPosition } from './SelectionList'; import { LovConfig, ViewRenderer, SelectionProps } from './Lov'; import { FormContextValue } from '../form/FormContext'; export interface LovViewProps { dataSet: DataSet; config: LovConfig; context: FormContextValue; tableProps?: Partial<TableProps>; multiple: boolean; values: any[]; viewMode?: string; onSelect: (records: Record | Record[]) => void; onBeforeSelect?: (records: Record | Record[]) => boolean | undefined; modal?: modalChildrenProps; popupHidden?: boolean; valueField?: string; textField?: string; viewRenderer?: ViewRenderer; showSelectedInView?: boolean; selectionProps?: SelectionProps, } export default class LovView extends Component<LovViewProps> { static get contextType() { return ConfigContext; } selection: DataSetSelection | false; selectionMode: SelectionMode | undefined; resizedColumns: Map<Key, number> = new Map<Key, number>(); @action componentWillMount() { const { dataSet, dataSet: { selection }, multiple, viewMode, } = this.props; this.selection = selection; dataSet.selection = multiple ? DataSetSelection.multiple : DataSetSelection.single; if ((viewMode === 'popup' || viewMode === 'drawer' || viewMode === 'modal') && multiple) { dataSet.addEventListener(DataSetEvents.batchSelect, this.handleSelect); dataSet.addEventListener(DataSetEvents.batchUnSelect, this.handleSelect); } } @action componentWillUnmount() { const { dataSet, multiple, viewMode } = this.props; dataSet.selection = this.selection; if ((viewMode === 'popup' || viewMode === 'drawer' || viewMode === 'modal') && multiple) { dataSet.removeEventListener(DataSetEvents.batchSelect, this.handleSelect); dataSet.removeEventListener(DataSetEvents.batchUnSelect, this.handleSelect); } } shouldComponentUpdate(nextProps: Readonly<LovViewProps>): boolean { const { viewMode } = this.props; if (viewMode === 'popup' && nextProps.popupHidden) { return false; } return true; } /* istanbul ignore next */ getColumns(): ColumnProps[] | undefined { const { config: { lovItems }, tableProps, viewMode, } = this.props; return lovItems ? lovItems .filter(({ gridField }) => gridField === 'Y') .sort(({ gridFieldSequence: seq1 }, { gridFieldSequence: seq2 }) => seq1 - seq2) .map<ColumnProps>(({ display, gridFieldName, gridFieldWidth, gridFieldAlign }) => { let column: ColumnProps | undefined = {}; if (tableProps && tableProps.columns) { column = tableProps.columns.find(c => c.name === gridFieldName); } return { ...column, key: gridFieldName, header: display, name: gridFieldName, width: viewMode === 'popup' ? gridFieldName ? this.resizedColumns.get(gridFieldName) : undefined : gridFieldWidth, align: gridFieldAlign, editor: false, }; }) : undefined; } @autobind handleSelect(event?: React.MouseEvent | any) { const { selectionMode } = this; const { onSelect, onBeforeSelect = noop, modal, multiple, dataSet, tableProps, viewMode, showSelectedInView, } = this.props; // 为了drawer模式下右侧勾选项的顺序 if (showSelectedInView && (viewMode === 'drawer' || viewMode === 'modal') && multiple) { if (event && event.records) { event.records.forEach(item => { if (item.isSelected) { item.setState(TIMESTAMP, new Date().getTime()); } else { item.setState(TIMESTAMP, 0); } }); } } let records: Record[] = selectionMode === SelectionMode.treebox ? dataSet.treeSelected : (selectionMode === SelectionMode.rowbox || multiple) ? dataSet.selected : dataSet.current ? [dataSet.current] : []; // 满足单选模式下,双击和勾选框选中均支持 if (tableProps && tableProps.alwaysShowRowBox && !event) { records = dataSet.selected; } const record: Record | Record[] | undefined = multiple ? records : records[0]; if (record && onBeforeSelect(record) !== false) { if (modal && (!event || !multiple)) { modal.close(); } if (!event || !multiple || viewMode === 'popup') { onSelect(record); } } return false; } /* istanbul ignore next */ @autobind handleKeyDown(e) { if (e.keyCode === KeyCode.ENTER) { this.handleSelect(); } } /** * 单选 onRow 处理 * @param props */ @autobind handleRow(props) { const { tableProps } = this.props; if (tableProps) { const { onRow } = tableProps; if (onRow) { return { onDoubleClick: this.handleSelect, ...onRow(props), }; } } return { onDoubleClick: this.handleSelect, }; } @autobind handleSingleRow() { return { onClick: this.handleSelect, }; } @autobind handleColumnResize(props: onColumnResizeProps) { const { width, column } = props; this.resizedColumns.set(getColumnKey(column), width); } renderTable() { const { dataSet, config: { queryBar, height, treeFlag, queryColumns, tableProps: configTableProps = {} }, multiple, tableProps, viewMode, context, showSelectedInView, } = this.props; const { getConfig } = context; const columns = this.getColumns(); const popup = viewMode === 'popup'; const modal = viewMode === 'modal'; const drawer = viewMode === 'drawer'; const lovTableProps: TableProps = { autoFocus: true, mode: treeFlag === 'Y' ? TableMode.tree : TableMode.list, onKeyDown: this.handleKeyDown, dataSet, columns, queryFieldsLimit: queryColumns, queryBar: queryBar || getConfig('lovQueryBar') || getConfig('queryBar'), selectionMode: SelectionMode.none, ...configTableProps, ...tableProps, className: classNames(configTableProps && configTableProps.className, tableProps && tableProps.className), style: { ...(configTableProps && configTableProps.style), height, ...(tableProps && tableProps.style), }, queryBarProps: { ...(tableProps && tableProps.queryBarProps), ...getConfig('lovQueryBarProps'), }, }; if (multiple) { if (popup || !tableProps || !tableProps.selectionMode) { if (lovTableProps.mode === TableMode.tree) { lovTableProps.selectionMode = SelectionMode.treebox; } else { lovTableProps.selectionMode = SelectionMode.rowbox; } } if (lovTableProps.selectionMode !== SelectionMode.rowbox && lovTableProps.selectionMode !== SelectionMode.treebox) { lovTableProps.highLightRow = false; lovTableProps.selectedHighLightRow = true; } } else if (popup) { lovTableProps.onRow = this.handleSingleRow; } else if (lovTableProps.selectionMode !== SelectionMode.rowbox) { lovTableProps.onRow = this.handleRow; } else { lovTableProps.highLightRow = false; lovTableProps.selectedHighLightRow = true; } if (popup) { if (lovTableProps.showSelectionCachedButton === undefined) { lovTableProps.showSelectionCachedButton = false; lovTableProps.showCachedSelection = true; } lovTableProps.autoWidth = true; lovTableProps.onColumnResize = this.handleColumnResize; } const isProfessionalBar = lovTableProps.queryBar === TableQueryBarType.professionalBar; if (!popup && !lovTableProps.queryBar && isProfessionalBar) { lovTableProps.queryBar = (props) => <TableProfessionalBar {...props} />; } if ((modal || drawer) && showSelectedInView) { lovTableProps.showSelectionTips = false; } this.selectionMode = lovTableProps.selectionMode; return ( <> <Table {...lovTableProps} /> {modal && this.renderSelectionList()} </> ); } renderSelectionList() { const { dataSet, valueField = '', textField = '', config: { treeFlag, tableProps: configTableProps = {} }, tableProps, multiple, viewMode, showSelectedInView, selectionProps, } = this.props; if (!showSelectedInView || !multiple) { return null; } if (!this.selectionMode) { const selectionMode = tableProps?.selectionMode || configTableProps?.selectionMode; if (!selectionMode) { this.selectionMode = treeFlag === 'Y' ? SelectionMode.treebox : SelectionMode.rowbox; } else { this.selectionMode = selectionMode; } } const selectionsPosition = viewMode === 'drawer' ? SelectionsPosition.side : (viewMode === 'modal' ? SelectionsPosition.below : undefined); return ( <SelectionList dataSet={dataSet} treeFlag={treeFlag} valueField={valueField} textField={textField} selectionsPosition={selectionsPosition} selectionProps={selectionProps} /> ); } render() { const { modal, viewRenderer, dataSet, viewMode, config: lovConfig, textField, valueField, multiple, } = this.props; if (modal) { modal.handleOk(this.handleSelect); } return ( <> {viewMode === 'drawer' && this.renderSelectionList()} <div> {viewRenderer ? toJS( viewRenderer({ dataSet, lovConfig, textField, valueField, multiple, modal, }), ) : this.renderTable()} </div> </> ); } }
the_stack
export module InteractiveDataDisplay { //Chart Viewer export interface ViewState { [name: string]: any; } export interface Titles { [seriesName: string]: string; } export interface PlotInfo { kind: string; displayName: string; titles?: Titles; [propertyName: string]: any; } export interface ChartInfo { [id: string]: PlotInfo; } export interface PropertyTitles { [prop: string]: string; } export interface ViewerControl { update(plots: ChartInfo): any; viewState: ViewState; dispose(): void; } /**ChartViewer.show() gets a map of pairs (plot identifier, plot definition) as a second argument. Plot definition is a collection of key- value pairs specifying properties of a plot, such as line stroke or marker shape. Each plot definition has at least one property which is type; it determines a rendering method and must be known to the ChartViewer.*/ function show(domElement: HTMLElement, plots: ChartInfo, viewState?: ViewState): InteractiveDataDisplay.ViewerControl; //==================Interactive Data Display===================== //settings /**minimum size in pixels of the element to be rendered*/ export var MinSizeToShow: any; /**extra padding in pixels which is added to padding computed by the plots*/ export var Padding: any; /**max number of iterations in loop of ticks creating*/ export var maxTickArrangeIterations: any; /**length of ordinary tick*/ export var tickLength: any; /**minimum space (in px) between 2 labels on axis*/ export var minLabelSpace: any; /**minimum space (in px) between 2 ticks on axis*/ export var minTickSpace: any; /**minimum order when labels on logarithmic scale are written with supscript*/ export var minLogOrder: any; /**minimum order when labels on numeric scale are written with supscript*/ export var minNumOrder: any; /**delay(seconds) between mouse stops over an element and the tooltip appears*/ export var TooltipDelay: any; /**duration(seconds) when tooltip is shown*/ export var TooltipDuration: any; /**browser - dependent prefix for the set of css styles*/ export var CssPrefix: any; export var ZIndexNavigationLayer: any; export var ZIndexDOMMarkers: any; export var ZIndexTooltipLayer: any; //readers export function readTable(jqPlotDiv: any): any; export function readCsv(jqPlotDiv: any): any; export function readCsv2d(jqDiv: any): any; //palettes /**Represents a mapping from a number to a value (e.g. a color) The function color has an domain [min,max]. If type is absolute, min and max are arbitrary numbers such that max>min. If type is relative, min=0,max=1, and a user of the palette should normalize the values to that range. Argument of the color is normalized to the domain of the function palettePoints is an array of hslaColor.*/ export class ColorPalette { isNormalized: boolean; range: MinMax; points: any; constructor(isNormalized: boolean, range: MinMax, palettePoints: any); getRgba(value: any): any; getHsla(value: any): any; absolute(min: any, max: any): any; relative(): any; banded(bands: any): ColorPalette; /**Discretizes the palette Returns an Uint8Array array of numbers with length (4 x number of colors), contains 4 numbers (r,g,b,a) for each color, where 0 <= r,g,b,a <= 255*/ static toArray(palette: any, n: any): any; static create(): ColorPalette; static parse(paletteString?: any): ColorPalette; static colorFromString(hexColor: any): any; static RGBtoHSL(rgbaColor: any): any; static HSLtoRGB(hslaColor: any): any; } export class Lexer { position: any; paletteString: any; currentSeparator: any; currentLexeme: any; currentNumber: any; currentColor: any; constructor(paletteString: string); readNext(): any; } export class ColorPaletteViewer { axisVisible: boolean; palette: any; dataRange: MinMax; constructor(div: any, palette?: any, options?: any); } export module palettes { var grayscale: ColorPalette } export class SizePalette { isNormalized: boolean; range: MinMax; sizeRange: MinMax; constructor(isNormalized: boolean, sizeRange: MinMax, valueRange?: MinMax); getSize(value: number): any; } export class SizePaletteViewer { axisVisible: boolean; palette: any; dataRange: MinMax; constructor(div: any, palette?: any, options?: any); } export class UncertaintySizePaletteViewer { maxDelta: number; constructor(div: any, options?: any); } //transforms /**Class for coordinate transform, cs is build from plot rect and screen size*/ export class CoordinateTransform { constructor(plotRect?: Rect, screenRect?: any, aspectRatio?: number); plotToScreenX(x: number): number; plotToScreenY(y: number): number; screenToPlotX(left: number): number; screenToPlotY(top: number): number; plotToScreenWidth(x: number): number; plotToScreenHeight(y: number): number; screenToPlotWidth(left: number): number; screenToPlotHeight(top: number): number; /**Builds plot rectangle for the given screen rectangle as {x,y,width,height}, where x,y are left/top of the rectangle.*/ getPlotRect(screenRect: Rect): Rect; /**Returns {x, y}*/ getScale(): any; /**Returns {x, y}*/ getOffset(): any; clone(): CoordinateTransform; } export class DataTransform { constructor(dataToPlot: any, plotToData: any, domain: any, type: any); } export var mercatorTransform: DataTransform; export var logTransform: DataTransform; //Plots export class Plot { isMaster: boolean; /**Indicates whether the last frame included rendering of this plot or not.*/ isRendered: boolean; flatRendering: any; master: any; host: any; centralPart: any; name: any; children: any; screenSize: ScreenSize; xDataTransform: any; yDataTransform: any; coordinateTransform: any; doFitOnDataTransformChanged: any; aspectRatio: any; isAutoFitEnabled: any; isVisible: boolean; order: number; visibleRect: Rect; mapControl: any; tooltipSettings: any; isToolTipEnabled: any; navigation: any; /**Allows to set titles for the plot's properties. E.g. "{ color:'age' }" sets the 'age' title for the color data series. Given titles are displayed in legends and tooltips.*/ titles: any; constructor(div: any, master: any, myCentralPart?: any); selfMapRefresh(): any; /**Returns a user-readable title for a property of a plot. E.g. can return "age" for property "color". If there is no user-defined title, returns the given property name as it is.*/ getTitle(property: string): string; setTitles(titles: any, suppressFireAppearanceChanged?: any): any; /**Uninitialize the plot (clears its input)*/ destroy(): any; /**Removes this plot from its master and physically destroys its host element.*/ remove(): any; removeMap(): any; addChild(childPlot: any): any; /**The function is called when this plot is added(removed) to the new master.*/ onAddedTo(master: any): any; /**Removes a child from this plot. Argument plot is either the plot object or its name*/ removeChild(plot: any): boolean; /**Gets linear list of plots from hierarchy*/ getPlotsSequence(): any; /**Gets the bounds of inner content of this plot (excluding its children plots)*/ getLocalBounds(step: any, computedBounds: any): Rect; /**Computes bounds of inner content of this plot (excluding its children plots)*/ computeLocalBounds(step: any, computedBounds: any): Rect; /**Invalidates local bounding box stored in the cache. To be called by derived plots. Returns previous local bounding box.*/ invalidateLocalBounds(): any; /**Aggregates all bounds of this plot and its children plots*/ aggregateBounds(): Rect; /**Computes padding of inner content of this plot. Returns 4 margins in the screen coordinate system.*/ getLocalPadding(): any; /**Aggregates padding of both content of this plot and its children plots. Returns 4 margins in the plot plane coordinate system.*/ aggregatePadding(): any; requestNextFrame(plot?: any): any; requestUpdateLayout(settings?: any): any; /**Updates output of this plot using the current coordinate transform and screen size. Returns true, if the plot actually has rendered something; otherwise, returns false.*/ render(plotRect: Rect, screenSize: ScreenSize): boolean; /**Updates output of this plot using the current coordinate transform and screen size.*/ renderCore(plotRect: Rect, screenSize: ScreenSize): any; /**Renders the plot to the svg and returns the svg object.*/ exportToSvg(): any; exportContentToSvg(plotRect: Rect, screenSize: ScreenSize, svg: any): any; /**Renders this plot to svg using the current coordinate transform and screen size.*/ renderCoreSvg(plotRect: Rect, screenSize: ScreenSize, svg: any): any; fit(screenSize: ScreenSize, finalPath: boolean, plotScreenSizeChanged: boolean): Rect; /**Makes layout of all children elements of the plot and invalidates the plots' images.*/ updateLayout(): any; measure(availibleSize: any, plotScreenSizeChanged: any): any; arrange(finalRect: any): any; fitToView(): any; fitToViewX(): any; fitToViewY(): any; /**If auto fit is on and bound box changed, updates the layout; otherwise, requests next frame for this plot.*/ requestNextFrameOrUpdate(): any; getTooltip(xd: number, yd: number, xp?: number, yp?: number): any; /**Gets the plot object with the given name. If plot is not found, returns undefined.*/ get(p: any): any; polyline(name: string, data?: any): Polyline; markers(name: string, data?: any, titles?: any): Markers; area(name: string, data?: any): Area; heatmap(name: string, data?: any, titles?: any): Heatmap; getLegend(): any; updateOrder(elem?: any, isPrev?: boolean): any; } /**Class for plots and axes arrangement.Takes into account "placement" property of an element use it for element arrangement*/ export class Figure extends Plot { constructor(div: any, master?: any); getAxes(placement?: any): any; get(p: any): any; addDiv(htmlCode: any, placement: any): any; removeDiv(divToRemove: any): any; addAxis(placement: any, axisType: any, params: any, insertBeforeDiv: any): any; measure(screenSize: ScreenSize): any; arrange(finalRect: any): any; exportContentToSvg(plotRect: Rect, screenSize: ScreenSize, svg: any): any; } export class Chart extends Figure { legend: Legend; constructor(div: any, master?: any); onDataTranformChangedCore(arg: any): any; //onChildrenChanged(arg); } /**Base class for plots rendering on a private canvas.*/ export class CanvasPlot extends Plot { constructor(div: any, master: any); getContext(doClear: boolean): any; destroy(): any; arrange(finalRect: any): any; /**Gets the transform functions from data to screen coordinates. Returns { dataToScreenX, dataToScreenY }*/ getTransform(): any; /**Gets the transform functions from screen to data coordinates. Returns { screenToDataX, screenToDataY }*/ getScreenToDataTransform(): any; } /**Renders a function y=f(x) as a polyline.*/ export class Polyline extends CanvasPlot { thickness: number; stroke: any; lineCap: any; lineJoin: any; fill68: any; fill95: any; constructor(div: any, master: any); draw(data: any): any; computeLocalBounds(step: any, computedBounds: any): Rect; /**Returns 4 margins in the screen coordinate system*/ getLocalPadding(): any; getTooltip(xd: any, yd: any, px: any, py: any): any; renderCore(plotRect: Rect, screenSize: ScreenSize): any; renderCoreSvg(plotRect: Rect, screenSize: ScreenSize, svg: any): any; onDataTransformChanged(arg: any): any; getLegend(): any; } type MarkersDefaults = { color: string colorPalette: ColorPalette border: string size: number } export class Markers extends CanvasPlot { constructor(div: any, master: any); /**return copy of data*/ getDataCopy(): any; /**Draws the data as markers.*/ draw(data: any, titles?: any): any; /**Returns a rectangle in the plot plane.*/ computeLocalBounds(step: any, computedBounds: any): any; /**Returns 4 margins in the screen coordinate system*/ getLocalPadding(): any; renderCore(plotRect: any, screenSize: any): any; findToolTipMarkers(xd: number, yd: number, xp?: number, yp?: number): any; /**Builds a tooltip <div> for a point*/ getTooltip(xd: any, yd: any, xp: any, yp: any): any; getLegend(): any; onDataTransformChanged(arg: any): any; static defaults: MarkersDefaults; static shapes: any; } /**Area plot takes data with coordinates named 'x', 'y1', 'y2' and a fill colour named 'fill'.*/ export class Area extends CanvasPlot { constructor(div: any, master: any); draw(data: any): any; /**Returns a rectangle in the plot plane.*/ computeLocalBounds(): any; /**Returns 4 margins in the screen coordinate system*/ getLocalPadding(): any; renderCore(plotRect: Rect, screenSize: ScreenSize): any; onDataTransformChanged(arg: any): any; getLegend(): any; } /**Renders a fuction f(x, y) on a regular grid (x, y) as a heat map using color palette*/ export class Heatmap extends CanvasPlot { palette: ColorPalette; opacity: number; mode: any; constructor(div: any, master: any); onRenderTaskCompleted(completedTask: any): any; draw(data: any, titles?: any): any; /**Returns a rectangle in the plot plane.*/ computeLocalBounds(): any; /**Updates output of this plot using the current coordinate transform and screen size. plotRect - rectangle in the plot plane which is visible, (x,y) is left/bottom of the rectangle screenSize - size of the output region to render inside Returns true, if the plot actually has rendered something; otherwise, returns false.*/ renderCore(plotRect: Rect, screenSize: ScreenSize): any; onIsRenderedChanged(): any; onDataTransformChanged(arg: any): any; /**Gets the value (probably, interpolated) for the heatmap in the point (xd,yd) in data coordinates. Depends on the heatmap mode. Returns null, if the point is outside of the plot.*/ getValue(xd: any, yd: any, array: any): any; getTooltip(xd: number, yd: number, xp?: number, yp?: number, changeInterval?: MinMax): any; getLegend(): any; } /**Renders set of DOM elements in the data space of this plot*/ export class DOMPlot extends Plot { domElements: any; constructor(host: any, master: any); computeLocalBounds(): Rect; /**Returns 4 margins in the screen coordinate system*/ getLocalPadding(): any; arrange(finalRect: any): any; renderCore(plotRect: Rect, screenSize: ScreenSize): any; onIsRenderedChanged(): any; clear(): any; /**Adds new DIV element to the plot. element is an HTML describing the new DIV element; scaleMode is either 'element', 'content', or 'none'; returns added DOM element*/ add(element: any, scaleMode: any, x: number, y: number, width?: number, height?: number, originX?: number, originY?: number): any; /**Removes DIV element from the plot. element is DOM object.*/ remove(element?: any): any; /**Set the position and optionally width and height of the element element is DOM object which must be added to the plot prior to call this method left, top are new coordinates of the left top corner of the element in the plot's data space ox, oy are optional new originX and originY which range from 0 to 1 and determines binding point of element to plots coordinates*/ set(element: any, x: number, y: number, width?: number, height?: number, ox?: number, oy?: number): any; } export class GridlinesPlot extends CanvasPlot { xAxis: any; yAxis: any; thickness: number; stroke: any; constructor(host: any, master: any); renderCore(plotRect: Rect, screenSize: ScreenSize): any; renderCoreSvg(plotRect: Rect, screenSize: ScreenSize, svg: any): any; } export class BingMapsPlot extends Plot { map: any; constructor(div: any, master: any); arrange(finalRect: any): any; /**Sets the map provided as an argument which is either a tile source (Microsoft.Maps.TileSource, e.g. see InteractiveDataDisplay.BingMaps.OpenStreetMap.GetTileSource), or a map type of Bing Maps (Microsoft.Maps.MapTypeId).*/ setMap(map: any): any; constraint(plotRect: Rect, screenSize: ScreenSize): any; } //Navigation export class NavigationPanel { constructor(plot: any, div: any, url?: any); remove(): any; } export class Navigation { animation: any; gestureSource: any; constructor(_plot: any, _setVisibleRegion: any); /**Changes the visible rectangle of the plot. visible is { x, y, width, height } in the plot plane, (x,y) is the left-bottom corner if animate is true, uses elliptical zoom animation*/ setVisibleRect(visible: any, animate: any, settings: any): any; stop(): any; } export module NavigationUtils { /**Suppress default multitouch for web pages to enable special handling of multitouch in InteractiveDataDisplay. Suitable for iPad, Mac. For Windows 8, idd.css contains special css property for this effect.*/ function SuppressDefaultMultitouch(): any; function calcPannedRect(plotRect: Rect, screenSize: ScreenSize, panGesture: any): Rect; function calcZoomedRect(plotRect: Rect, coordinateTransform: any, zoomGesture: any): any; } //Workers export class SharedRenderWorker { constructor(scriptUri: any, onTaskCompleted: any); enqueue(task: any, source: any): any; /**Cancels the pending task for the given source.*/ cancelPending(source: any): any; } //Uncertain Shapes interface UncertainShape { prepare(data: any): void; preRender(data: any, plotRect: any, screenSize: any, dt: any, context: any): any; draw(marker: any, plotRect: any, screenSize: any, transform: any, context: any): void; hitTest(marker: any, transform: any, ps: any, pd: any): boolean; getLegend(data: any, getTitle: any, legendDiv: any): any; getTooltipData(originalData: any, index: number): any; } export var Petal: UncertainShape; export var BullEye: UncertainShape; export var BoxWhisker: UncertainShape; //Legend export class Legend { isVisible: boolean; constructor(_plot: any, _jqdiv: any, isCompact?: any, hasTooltip?: any); remove(): any; } //Utils type Rect = { x: number; y: number; width: number; height: number; } type MinMax = { min: number; max: number; } type ScreenSize = { width: number; height: number; } export module Utils { function applyMask(mask: number[], array: any, newLength: number): any; function maskNaN(mask: number[], numArray: number[]): any; /**Returns true if value is Array or TypedArray*/ function isArray(arr: any): boolean; function isOrderedArray(arr: any): boolean; function cutArray(arr: any, len: number): any; /**Returns intersection of two rectangles {x,y,width,height}, left-bottom corner If no intersection, returns undefined.*/ function intersect(rect1: Rect, rect2: Rect): Rect; /**Returns boolean value indicating whether rectOuter includes entire rectInner, or not. Rect is {x,y,width,height}*/ function includes(rectOuter: Rect, rectInner: Rect): boolean; /**Returns boolean value indicating whether rect1 equals rect2, or not. Rect is {x,y,width,height}*/ function equalRect(rect1: Rect, rect2: Rect): boolean; function calcCSWithPadding(plotRect: any, screenSize: any, padding: any, aspectRatio: any): any;//?? /**Browser-specific function. Should be replaced with the optimal implementation on the page loading.*/ function requestAnimationFrame(handler: any, args?: any): any; /**Creates and initializes an array with values from start to end with step 1.*/ function range(start: any, end: any): any; /**finalRect should contain units in its values. f.e. "px" or "%"*/ function arrangeDiv(div: any, finalRect: any): any; /**Computes minimum rect, containing rect1 and rect 2*/ function unionRects(rect1: Rect, rect2: Rect): Rect; /**Parses the attribute data-idd-style of jqElement and adds the properties to the target e.g. data-idd-style="thickness: 5px; lineCap: round; lineJoin: round; stroke: #ff6a00"*/ function readStyle(jqElement: any, target: any): any;//?? function getDataSourceFunction(jqElem: any, defaultSource: any): any; function makeNonEqual(range: MinMax): MinMax; function getMinMax(array: number[]): MinMax; function getMin(array: number[]): number; function getMax(array: number[]): number; /**Returns structure {minx, maxx, miny, maxy}*/ function getMinMaxForPair(arrayx: any, arrayy: any): any; function enumPlots(plot: any): any;//??? function reorder(p: any, p_before: any, isPrev: any): any;//?? function getMaxOrder(p: any): number; function getBoundingBoxForArrays(_x: any, _y: any, dataToPlotX: any, dataToPlotY: any): any//?? function getAndClearTextContent(jqElement: any): any; function getPlotRectForMap(map: any, screenSize: any): any; } export module Binding { /**Binds visible rectangles of two plots. filter is either "v" (binds vertical ranges), "h" (binds horizontal ranges), or "vh" (default, binds both ranges).*/ function bindPlots(plot1: any, plot2: any, filter?: string): any; function getBoundPlots(plot: any): any; } //Formatter export class AdaptiveFormatter { constructor(series: any, segment?: any); getPrintFormat(min: any, max: any, std: any): any; } //Axis export function InitializeAxis(div: any, params?: any): any; //Base /**Registers new plot type key: string, plot-factory: jqDiv x master plot -> plot*/ export function register(key: string, factory: any): any; /**Instantiates a plot for the given DIV element. jqDiv is either ID of a DIV element within the HTML page or jQuery to the element to be initialized as a plot. Returns new InteractiveDataDisplay.Plot instance.*/ export function asPlot(div: any): any; /**Tries to get IDD plot object from jQuery selector Returns null if selector is null or DOM object is not an IDD master plot*/ function tryGetMasterPlot(jqElem: any): any; /**Traverses descendants of jQuery selector and invokes updateLayout for all IDD master plots*/ function updateLayouts(jqElem: any): any; } export module Plot { module MarkerShape { var Box: string; var Circle: string; var Diamond: string; var Cross: string; var Triangle: string; } /**If treatAs is "Function" (default value), the series x[i] and y[i] are sorted by increasing values x. Otherwise, "Trajectory": the arrays are rendered as is.*/ module HeatmapRenderType { var Gradient: string; var Discrete: string; } module LineTreatAs { var Function: string; var Trajectory: string; } /**allows to represent an array of uncertain values by providing the quantiles for each uncertain value*/ type Quantiles = { median: number[]; lower68: number[]; upper68: number[]; lower95: number[]; upper95: number[]; }; /**Color is a string that supports same color definition as in CSS: "blue", "#606060", "rgba(10,150,200,100)"*/ type Color = string; /**ColorPalette is a string that has specific syntax to define palettes, e.g. "reg,green,blue" or "0=red=white=blue=100"*/ type ColorPalette = string; type LineTitles = { x?: string; y?: string; }; type MarkersTitles = { x?: string; y?: string; color?: string; size?: string; }; type HeatmapTitles = { x?: string; y?: string; values?: string; }; type AreaTitles = { x?: string; y1?: string; y2?: string; }; type BoxPlotTitles = { x?: string; y?: string; }; type LineDefinition = { x?: number[]; y: number[] | Quantiles; stroke?: Color; thickness?: number; /**use Plot.LineTreatAs*/ treatAs?: string; lineCap?: string; lineJoin?: string; fill68?: Color; fill95?: Color; displayName?: string; titles?: LineTitles; }; type AreaDefinition = { x?: number[]; y1: number[]; y2: number[]; fill?: Color; opacity?: number; displayName?: string; titles?: AreaTitles; }; type BoxPlotDefinition = { y: Quantiles; x?: number[]; borderColor?: Color; color?: Color; displayName?: string; titles?: BoxPlotTitles; }; type MarkersDefinition = { x?: number[]; y: number[]; /**use Plot.MarkerShape*/ shape?: string; color?: Color | number[] | Quantiles; colorPalette?: ColorPalette; size?: number | number[] | Quantiles; sizePalette?: InteractiveDataDisplay.SizePalette; border?: Color; displayName?: string; titles?: MarkersTitles; }; type HeatmapDefinition = { x: number[]; y: number[]; values: number[] | Quantiles; colorPalette?: ColorPalette; /**use Plot.HeatmapRenderType*/ treatAs?: string; displayName?: string; titles?: HeatmapTitles; }; /**line draws a grid function y[i] = y(x[i]) where y[i] is either a scalar value or a random variable distribution. In former case, a single polyline is drawn; in the latter case, a median polyline along with filled bands for percentiles of the distribution is rendered.*/ function line(element: LineDefinition): InteractiveDataDisplay.PlotInfo; /**The plot draws a colored area between two scalar grid functions. The space between lines y1[i](x[i]) and y2[i](x[i]) is filled with a solid color; the boundaries are not stroked.*/ function area(element: AreaDefinition): InteractiveDataDisplay.PlotInfo; /**The plot draws a colored boxplot.*/ function boxplot(element: BoxPlotDefinition): InteractiveDataDisplay.PlotInfo; /**Displays data as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis. Also variables can be bound to marker size and color. Dependent variable, size-bound variable or color-bound variable can be real or uncertain; the latter is represented as a set of quantiles.*/ function markers(element: MarkersDefinition): InteractiveDataDisplay.PlotInfo; /**Heatmap plot renders values defined on a rectangular grid using color palette*/ function heatmap(element: HeatmapDefinition): InteractiveDataDisplay.PlotInfo; }
the_stack
import { Command, flags } from "@oclif/command"; import { OutputFlags } from "@oclif/parser"; import { error as oclifError } from "@oclif/errors"; import { readFile, outputFile, existsSync } from "fs-extra"; import { join, relative, parse } from "path"; import slash from "slash"; import ts from "typescript"; import { generate, GenerateProps } from "./core/generate"; import { TsToZodConfig, Config } from "./config"; import { tsToZodConfigSchema, getSchemaNameSchema, nameFilterSchema, } from "./config.zod"; import { getImportPath } from "./utils/getImportPath"; import ora from "ora"; import prettier from "prettier"; import * as worker from "./worker"; import inquirer from "inquirer"; import { eachSeries } from "async"; import { createConfig } from "./createConfig"; import chokidar from "chokidar"; // Try to load `ts-to-zod.config.js` // We are doing this here to be able to infer the `flags` & `usage` in the cli help const tsToZodConfigJs = "ts-to-zod.config.js"; const configPath = join(process.cwd(), tsToZodConfigJs); let config: TsToZodConfig | undefined; let haveMultiConfig = false; const configKeys: string[] = []; try { if (existsSync(configPath)) { const rawConfig = require(slash(relative(__dirname, configPath))); config = tsToZodConfigSchema.parse(rawConfig); if (Array.isArray(config)) { haveMultiConfig = true; configKeys.push(...config.map((c) => c.name)); } } } catch (e) { if (e instanceof Error) { oclifError( `"${tsToZodConfigJs}" invalid: ${e.message} Please fix the invalid configuration You can generate a new config with --init`, { exit: false } ); } process.exit(2); } class TsToZod extends Command { static description = "Generate Zod schemas from a Typescript file"; static usage = haveMultiConfig ? [ "--all", ...configKeys.map( (key) => `--config ${key.includes(" ") ? `"${key}"` : key}` ), ] : undefined; static flags = { version: flags.version({ char: "v" }), help: flags.help({ char: "h" }), maxRun: flags.integer({ hidden: true, default: 10, description: "max iteration number to resolve the declaration order", }), keepComments: flags.boolean({ char: "k", description: "Keep parameters comments", }), init: flags.boolean({ char: "i", description: "Create a ts-to-zod.config.js file", }), skipParseJSDoc: flags.boolean({ default: false, description: "Skip the creation of zod validators from JSDoc annotations", }), skipValidation: flags.boolean({ default: false, description: "Skip the validation step (not recommended)", }), watch: flags.boolean({ char: "w", default: false, description: "Watch input file(s) for changes and re-run related task", }), // -- Multi config flags -- config: flags.enum({ char: "c", options: configKeys, description: "Execute one config", hidden: !haveMultiConfig, }), all: flags.boolean({ char: "a", default: false, description: "Execute all configs", hidden: !haveMultiConfig, }), }; static args = [ { name: "input", description: "input file (typescript)" }, { name: "output", description: "output file (zod schemas)", }, ]; async run() { const { args, flags } = this.parse(TsToZod); if (flags.init) { (await createConfig(configPath)) ? this.log(`🧐 ts-to-zod.config.js created!`) : this.log(`Nothing changed!`); return; } const fileConfig = await this.loadFileConfig(config, flags); if (Array.isArray(fileConfig)) { if (args.input || args.output) { this.error(`INPUT and OUTPUT arguments are not compatible with --all`); } await eachSeries(fileConfig, async (config) => { this.log(`Generating "${config.name}"`); const result = await this.generate(args, config, flags); if (result.success) { this.log(` 🎉 Zod schemas generated!`); } else { this.error(result.error, { exit: false }); } this.log(); // empty line between configs }).catch((e) => this.error(e, { exit: false })); } else { const result = await this.generate(args, fileConfig, flags); if (result.success) { this.log(`🎉 Zod schemas generated!`); } else { this.error(result.error); } } if (flags.watch) { const inputs = Array.isArray(fileConfig) ? fileConfig.map((i) => i.input) : fileConfig?.input || args.input; this.log("\nWatching for changes…"); chokidar.watch(inputs).on("change", async (path) => { console.clear(); this.log(`Changes detected in "${slash(path)}"`); const config = Array.isArray(fileConfig) ? fileConfig.find((i) => i.input === slash(path)) : fileConfig; const result = await this.generate(args, config, flags); if (result.success) { this.log(`🎉 Zod schemas generated!`); } else { this.error(result.error); } this.log("\nWatching for changes…"); }); } } /** * Generate on zod schema file. * @param args * @param fileConfig * @param flags */ async generate( args: { input?: string; output?: string }, fileConfig: Config | undefined, flags: OutputFlags<typeof TsToZod.flags> ): Promise<{ success: true } | { success: false; error: string }> { const input = args.input || fileConfig?.input; const output = args.output || fileConfig?.output; if (!input) { return { success: false, error: `Missing 1 required arg: ${TsToZod.args[0].description} See more help with --help`, }; } const inputPath = join(process.cwd(), input); const outputPath = join(process.cwd(), output || input); // Check args/flags file extensions const extErrors: { path: string; expectedExtensions: string[] }[] = []; if (!hasExtensions(input, typescriptExtensions)) { extErrors.push({ path: input, expectedExtensions: typescriptExtensions, }); } if ( output && !hasExtensions(output, [...typescriptExtensions, ...javascriptExtensions]) ) { extErrors.push({ path: output, expectedExtensions: [...typescriptExtensions, ...javascriptExtensions], }); } if (extErrors.length) { return { success: false, error: `Unexpected file extension:\n${extErrors .map( ({ path, expectedExtensions }) => `"${path}" must be ${expectedExtensions .map((i) => `"${i}"`) .join(", ")}` ) .join("\n")}`, }; } const sourceText = await readFile(inputPath, "utf-8"); const generateOptions: GenerateProps = { sourceText, ...fileConfig, }; if (typeof flags.maxRun === "number") { generateOptions.maxRun = flags.maxRun; } if (typeof flags.keepComments === "boolean") { generateOptions.keepComments = flags.keepComments; } if (typeof flags.skipParseJSDoc === "boolean") { generateOptions.skipParseJSDoc = flags.skipParseJSDoc; } const { errors, transformedSourceText, getZodSchemasFile, getIntegrationTestFile, hasCircularDependencies, } = generate(generateOptions); if (hasCircularDependencies && !output) { return { success: false, error: "--output= must also be provided when input file have some circular dependencies", }; } errors.map(this.warn); if (!flags.skipValidation) { const validatorSpinner = ora("Validating generated types").start(); if (flags.all) validatorSpinner.indent = 1; const generationErrors = await worker.validateGeneratedTypesInWorker({ sourceTypes: { sourceText: transformedSourceText, relativePath: "./source.ts", }, integrationTests: { sourceText: getIntegrationTestFile("./source", "./source.zod"), relativePath: "./source.integration.ts", }, zodSchemas: { sourceText: getZodSchemasFile("./source"), relativePath: "./source.zod.ts", }, skipParseJSDoc: Boolean(generateOptions.skipParseJSDoc), }); generationErrors.length ? validatorSpinner.fail() : validatorSpinner.succeed(); if (generationErrors.length > 0) { return { success: false, error: generationErrors.join("\n"), }; } } const zodSchemasFile = getZodSchemasFile( getImportPath(outputPath, inputPath) ); const prettierConfig = await prettier.resolveConfig(process.cwd()); if (output && hasExtensions(output, javascriptExtensions)) { await outputFile( outputPath, prettier.format( ts.transpileModule(zodSchemasFile, { compilerOptions: { target: ts.ScriptTarget.Latest, module: ts.ModuleKind.ESNext, newLine: ts.NewLineKind.LineFeed, }, }).outputText, { parser: "babel-ts", ...prettierConfig } ) ); } else { await outputFile( outputPath, prettier.format(zodSchemasFile, { parser: "babel-ts", ...prettierConfig, }) ); } return { success: true }; } /** * Load user config from `ts-to-zod.config.js` */ async loadFileConfig( config: TsToZodConfig | undefined, flags: OutputFlags<typeof TsToZod.flags> ): Promise<TsToZodConfig | undefined> { if (!config) { return undefined; } if (Array.isArray(config)) { if (!flags.all && !flags.config) { const { mode } = await inquirer.prompt<{ mode: "none" | "multi" | `single-${string}`; }>([ { name: "mode", message: `You have multiple configs available in "${tsToZodConfigJs}"\n What do you want?`, type: "list", choices: [ { value: "multi", name: `${TsToZod.flags.all.description} (--all)`, }, ...configKeys.map((key) => ({ value: `single-${key}`, name: `Execute "${key}" config (--config=${key})`, })), { value: "none", name: "Don't use the config" }, ], }, ]); if (mode.startsWith("single-")) { flags.config = mode.slice("single-".length); } else if (mode === "multi") { flags.all = true; } } if (flags.all) { return config; } if (flags.config) { const selectedConfig = config.find((c) => c.name === flags.config); if (!selectedConfig) { this.error(`${flags.config} configuration not found!`); } return selectedConfig; } return undefined; } return { ...config, getSchemaName: config.getSchemaName ? getSchemaNameSchema.implement(config.getSchemaName) : undefined, nameFilter: config.nameFilter ? nameFilterSchema.implement(config.nameFilter) : undefined, }; } } const typescriptExtensions = [".ts", ".tsx"]; const javascriptExtensions = [".js", ".jsx"]; /** * Validate if the file extension is ts or tsx. * * @param path relative path * @param extensions list of allowed extensions * @returns true if the extension is valid */ function hasExtensions(path: string, extensions: string[]) { const { ext } = parse(path); return extensions.includes(ext); } export = TsToZod;
the_stack
import type { Context } from './src/server/context/index'; import type { core } from 'nexus'; declare global { interface NexusGenCustomInputMethods<TypeName extends string> { /** * Json custom scalar type */ json<FieldName extends string>(fieldName: FieldName, opts?: core.CommonInputFieldConfig<TypeName, FieldName>): void; // "Json"; /** * Decimal custom scalar type */ decimal<FieldName extends string>( fieldName: FieldName, opts?: core.CommonInputFieldConfig<TypeName, FieldName>, ): void; // "Decimal"; /** * BigInt custom scalar type */ bigint<FieldName extends string>( fieldName: FieldName, opts?: core.CommonInputFieldConfig<TypeName, FieldName>, ): void; // "BigInt"; /** * Date custom scalar type */ date<FieldName extends string>(fieldName: FieldName, opts?: core.CommonInputFieldConfig<TypeName, FieldName>): void; // "DateTime"; } } declare global { interface NexusGenCustomOutputMethods<TypeName extends string> { /** * Json custom scalar type */ json<FieldName extends string>(fieldName: FieldName, ...opts: core.ScalarOutSpread<TypeName, FieldName>): void; // "Json"; /** * Decimal custom scalar type */ decimal<FieldName extends string>(fieldName: FieldName, ...opts: core.ScalarOutSpread<TypeName, FieldName>): void; // "Decimal"; /** * BigInt custom scalar type */ bigint<FieldName extends string>(fieldName: FieldName, ...opts: core.ScalarOutSpread<TypeName, FieldName>): void; // "BigInt"; /** * Date custom scalar type */ date<FieldName extends string>(fieldName: FieldName, ...opts: core.ScalarOutSpread<TypeName, FieldName>): void; // "DateTime"; } } declare global { interface NexusGen extends NexusGenTypes {} } export interface NexusGenInputs { BoolFieldUpdateOperationsInput: { // input type set?: boolean | null; // Boolean }; BoolFilter: { // input type equals?: boolean | null; // Boolean not?: NexusGenInputs['NestedBoolFilter'] | null; // NestedBoolFilter }; BoolWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedBoolFilter'] | null; // NestedBoolFilter _min?: NexusGenInputs['NestedBoolFilter'] | null; // NestedBoolFilter equals?: boolean | null; // Boolean not?: NexusGenInputs['NestedBoolWithAggregatesFilter'] | null; // NestedBoolWithAggregatesFilter }; CommentAvgOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder postId?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentCountOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder contain?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder postId?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentCreateInput: { // input type author?: NexusGenInputs['UserCreateNestedOneWithoutCommentsInput'] | null; // UserCreateNestedOneWithoutCommentsInput contain: string; // String! createdAt?: NexusGenScalars['DateTime'] | null; // DateTime post: NexusGenInputs['PostCreateNestedOneWithoutCommentsInput']; // PostCreateNestedOneWithoutCommentsInput! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentCreateNestedManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutAuthorInput'] | null> | null; // [CommentCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['CommentCreateWithoutAuthorInput'] | null> | null; // [CommentCreateWithoutAuthorInput] }; CommentCreateNestedManyWithoutPostInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutPostInput'] | null> | null; // [CommentCreateOrConnectWithoutPostInput] create?: Array<NexusGenInputs['CommentCreateWithoutPostInput'] | null> | null; // [CommentCreateWithoutPostInput] }; CommentCreateOrConnectWithoutAuthorInput: { // input type create: NexusGenInputs['CommentUncheckedCreateWithoutAuthorInput']; // CommentUncheckedCreateWithoutAuthorInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; CommentCreateOrConnectWithoutPostInput: { // input type create: NexusGenInputs['CommentUncheckedCreateWithoutPostInput']; // CommentUncheckedCreateWithoutPostInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; CommentCreateWithoutAuthorInput: { // input type contain: string; // String! createdAt?: NexusGenScalars['DateTime'] | null; // DateTime post: NexusGenInputs['PostCreateNestedOneWithoutCommentsInput']; // PostCreateNestedOneWithoutCommentsInput! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentCreateWithoutPostInput: { // input type author?: NexusGenInputs['UserCreateNestedOneWithoutCommentsInput'] | null; // UserCreateNestedOneWithoutCommentsInput contain: string; // String! createdAt?: NexusGenScalars['DateTime'] | null; // DateTime updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentListRelationFilter: { // input type every?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput none?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput some?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; CommentMaxOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder contain?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder postId?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentMinOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder contain?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder postId?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentOrderByRelationAggregateInput: { // input type _count?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentOrderByWithAggregationInput: { // input type _avg?: NexusGenInputs['CommentAvgOrderByAggregateInput'] | null; // CommentAvgOrderByAggregateInput _count?: NexusGenInputs['CommentCountOrderByAggregateInput'] | null; // CommentCountOrderByAggregateInput _max?: NexusGenInputs['CommentMaxOrderByAggregateInput'] | null; // CommentMaxOrderByAggregateInput _min?: NexusGenInputs['CommentMinOrderByAggregateInput'] | null; // CommentMinOrderByAggregateInput _sum?: NexusGenInputs['CommentSumOrderByAggregateInput'] | null; // CommentSumOrderByAggregateInput authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder contain?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder postId?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentOrderByWithRelationInput: { // input type author?: NexusGenInputs['UserOrderByWithRelationInput'] | null; // UserOrderByWithRelationInput authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder contain?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder post?: NexusGenInputs['PostOrderByWithRelationInput'] | null; // PostOrderByWithRelationInput postId?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentScalarWhereInput: { // input type AND?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] NOT?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] OR?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] authorId?: NexusGenInputs['IntNullableFilter'] | null; // IntNullableFilter contain?: NexusGenInputs['StringFilter'] | null; // StringFilter createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter postId?: NexusGenInputs['IntFilter'] | null; // IntFilter updatedAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter }; CommentScalarWhereWithAggregatesInput: { // input type AND?: Array<NexusGenInputs['CommentScalarWhereWithAggregatesInput'] | null> | null; // [CommentScalarWhereWithAggregatesInput] NOT?: Array<NexusGenInputs['CommentScalarWhereWithAggregatesInput'] | null> | null; // [CommentScalarWhereWithAggregatesInput] OR?: Array<NexusGenInputs['CommentScalarWhereWithAggregatesInput'] | null> | null; // [CommentScalarWhereWithAggregatesInput] authorId?: NexusGenInputs['IntNullableWithAggregatesFilter'] | null; // IntNullableWithAggregatesFilter contain?: NexusGenInputs['StringWithAggregatesFilter'] | null; // StringWithAggregatesFilter createdAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter id?: NexusGenInputs['IntWithAggregatesFilter'] | null; // IntWithAggregatesFilter postId?: NexusGenInputs['IntWithAggregatesFilter'] | null; // IntWithAggregatesFilter updatedAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter }; CommentSumOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder postId?: NexusGenEnums['SortOrder'] | null; // SortOrder }; CommentUncheckedCreateInput: { // input type authorId?: number | null; // Int contain: string; // String! createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int postId: number; // Int! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentUncheckedCreateNestedManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutAuthorInput'] | null> | null; // [CommentCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['CommentCreateWithoutAuthorInput'] | null> | null; // [CommentCreateWithoutAuthorInput] }; CommentUncheckedCreateNestedManyWithoutPostInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutPostInput'] | null> | null; // [CommentCreateOrConnectWithoutPostInput] create?: Array<NexusGenInputs['CommentCreateWithoutPostInput'] | null> | null; // [CommentCreateWithoutPostInput] }; CommentUncheckedCreateWithoutAuthorInput: { // input type contain: string; // String! createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int postId: number; // Int! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentUncheckedCreateWithoutPostInput: { // input type authorId?: number | null; // Int contain: string; // String! createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentUncheckedUpdateInput: { // input type authorId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput postId?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUncheckedUpdateManyInput: { // input type authorId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput postId?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUncheckedUpdateManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutAuthorInput'] | null> | null; // [CommentCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['CommentCreateWithoutAuthorInput'] | null> | null; // [CommentCreateWithoutAuthorInput] delete?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] deleteMany?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] disconnect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] set?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] update?: Array<NexusGenInputs['CommentUpdateWithWhereUniqueWithoutAuthorInput'] | null> | null; // [CommentUpdateWithWhereUniqueWithoutAuthorInput] updateMany?: Array<NexusGenInputs['CommentUpdateManyWithWhereWithoutAuthorInput'] | null> | null; // [CommentUpdateManyWithWhereWithoutAuthorInput] upsert?: Array<NexusGenInputs['CommentUpsertWithWhereUniqueWithoutAuthorInput'] | null> | null; // [CommentUpsertWithWhereUniqueWithoutAuthorInput] }; CommentUncheckedUpdateManyWithoutCommentsInput: { // input type contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput postId?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUncheckedUpdateManyWithoutPostInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutPostInput'] | null> | null; // [CommentCreateOrConnectWithoutPostInput] create?: Array<NexusGenInputs['CommentCreateWithoutPostInput'] | null> | null; // [CommentCreateWithoutPostInput] delete?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] deleteMany?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] disconnect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] set?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] update?: Array<NexusGenInputs['CommentUpdateWithWhereUniqueWithoutPostInput'] | null> | null; // [CommentUpdateWithWhereUniqueWithoutPostInput] updateMany?: Array<NexusGenInputs['CommentUpdateManyWithWhereWithoutPostInput'] | null> | null; // [CommentUpdateManyWithWhereWithoutPostInput] upsert?: Array<NexusGenInputs['CommentUpsertWithWhereUniqueWithoutPostInput'] | null> | null; // [CommentUpsertWithWhereUniqueWithoutPostInput] }; CommentUncheckedUpdateWithoutAuthorInput: { // input type contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput postId?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUncheckedUpdateWithoutPostInput: { // input type authorId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUpdateInput: { // input type author?: NexusGenInputs['UserUpdateOneWithoutCommentsInput'] | null; // UserUpdateOneWithoutCommentsInput contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput post?: NexusGenInputs['PostUpdateOneRequiredWithoutCommentsInput'] | null; // PostUpdateOneRequiredWithoutCommentsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUpdateManyMutationInput: { // input type contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUpdateManyWithWhereWithoutAuthorInput: { // input type data: NexusGenInputs['CommentUncheckedUpdateManyWithoutCommentsInput']; // CommentUncheckedUpdateManyWithoutCommentsInput! where: NexusGenInputs['CommentScalarWhereInput']; // CommentScalarWhereInput! }; CommentUpdateManyWithWhereWithoutPostInput: { // input type data: NexusGenInputs['CommentUncheckedUpdateManyWithoutCommentsInput']; // CommentUncheckedUpdateManyWithoutCommentsInput! where: NexusGenInputs['CommentScalarWhereInput']; // CommentScalarWhereInput! }; CommentUpdateManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutAuthorInput'] | null> | null; // [CommentCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['CommentCreateWithoutAuthorInput'] | null> | null; // [CommentCreateWithoutAuthorInput] delete?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] deleteMany?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] disconnect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] set?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] update?: Array<NexusGenInputs['CommentUpdateWithWhereUniqueWithoutAuthorInput'] | null> | null; // [CommentUpdateWithWhereUniqueWithoutAuthorInput] updateMany?: Array<NexusGenInputs['CommentUpdateManyWithWhereWithoutAuthorInput'] | null> | null; // [CommentUpdateManyWithWhereWithoutAuthorInput] upsert?: Array<NexusGenInputs['CommentUpsertWithWhereUniqueWithoutAuthorInput'] | null> | null; // [CommentUpsertWithWhereUniqueWithoutAuthorInput] }; CommentUpdateManyWithoutPostInput: { // input type connect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['CommentCreateOrConnectWithoutPostInput'] | null> | null; // [CommentCreateOrConnectWithoutPostInput] create?: Array<NexusGenInputs['CommentCreateWithoutPostInput'] | null> | null; // [CommentCreateWithoutPostInput] delete?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] deleteMany?: Array<NexusGenInputs['CommentScalarWhereInput'] | null> | null; // [CommentScalarWhereInput] disconnect?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] set?: Array<NexusGenInputs['CommentWhereUniqueInput'] | null> | null; // [CommentWhereUniqueInput] update?: Array<NexusGenInputs['CommentUpdateWithWhereUniqueWithoutPostInput'] | null> | null; // [CommentUpdateWithWhereUniqueWithoutPostInput] updateMany?: Array<NexusGenInputs['CommentUpdateManyWithWhereWithoutPostInput'] | null> | null; // [CommentUpdateManyWithWhereWithoutPostInput] upsert?: Array<NexusGenInputs['CommentUpsertWithWhereUniqueWithoutPostInput'] | null> | null; // [CommentUpsertWithWhereUniqueWithoutPostInput] }; CommentUpdateWithWhereUniqueWithoutAuthorInput: { // input type data: NexusGenInputs['CommentUncheckedUpdateWithoutAuthorInput']; // CommentUncheckedUpdateWithoutAuthorInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; CommentUpdateWithWhereUniqueWithoutPostInput: { // input type data: NexusGenInputs['CommentUncheckedUpdateWithoutPostInput']; // CommentUncheckedUpdateWithoutPostInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; CommentUpdateWithoutAuthorInput: { // input type contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput post?: NexusGenInputs['PostUpdateOneRequiredWithoutCommentsInput'] | null; // PostUpdateOneRequiredWithoutCommentsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUpdateWithoutPostInput: { // input type author?: NexusGenInputs['UserUpdateOneWithoutCommentsInput'] | null; // UserUpdateOneWithoutCommentsInput contain?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; CommentUpsertWithWhereUniqueWithoutAuthorInput: { // input type create: NexusGenInputs['CommentUncheckedCreateWithoutAuthorInput']; // CommentUncheckedCreateWithoutAuthorInput! update: NexusGenInputs['CommentUncheckedUpdateWithoutAuthorInput']; // CommentUncheckedUpdateWithoutAuthorInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; CommentUpsertWithWhereUniqueWithoutPostInput: { // input type create: NexusGenInputs['CommentUncheckedCreateWithoutPostInput']; // CommentUncheckedCreateWithoutPostInput! update: NexusGenInputs['CommentUncheckedUpdateWithoutPostInput']; // CommentUncheckedUpdateWithoutPostInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; CommentWhereInput: { // input type AND?: Array<NexusGenInputs['CommentWhereInput'] | null> | null; // [CommentWhereInput] NOT?: Array<NexusGenInputs['CommentWhereInput'] | null> | null; // [CommentWhereInput] OR?: Array<NexusGenInputs['CommentWhereInput'] | null> | null; // [CommentWhereInput] author?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput authorId?: NexusGenInputs['IntNullableFilter'] | null; // IntNullableFilter contain?: NexusGenInputs['StringFilter'] | null; // StringFilter createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter post?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput postId?: NexusGenInputs['IntFilter'] | null; // IntFilter updatedAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter }; CommentWhereUniqueInput: { // input type id?: number | null; // Int }; DateTimeFieldUpdateOperationsInput: { // input type set?: NexusGenScalars['DateTime'] | null; // DateTime }; DateTimeFilter: { // input type equals?: NexusGenScalars['DateTime'] | null; // DateTime gt?: NexusGenScalars['DateTime'] | null; // DateTime gte?: NexusGenScalars['DateTime'] | null; // DateTime in?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] lt?: NexusGenScalars['DateTime'] | null; // DateTime lte?: NexusGenScalars['DateTime'] | null; // DateTime not?: NexusGenInputs['NestedDateTimeFilter'] | null; // NestedDateTimeFilter notIn?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] }; DateTimeWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedDateTimeFilter'] | null; // NestedDateTimeFilter _min?: NexusGenInputs['NestedDateTimeFilter'] | null; // NestedDateTimeFilter equals?: NexusGenScalars['DateTime'] | null; // DateTime gt?: NexusGenScalars['DateTime'] | null; // DateTime gte?: NexusGenScalars['DateTime'] | null; // DateTime in?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] lt?: NexusGenScalars['DateTime'] | null; // DateTime lte?: NexusGenScalars['DateTime'] | null; // DateTime not?: NexusGenInputs['NestedDateTimeWithAggregatesFilter'] | null; // NestedDateTimeWithAggregatesFilter notIn?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] }; GroupAvgOrderByAggregateInput: { // input type id?: NexusGenEnums['SortOrder'] | null; // SortOrder }; GroupCountOrderByAggregateInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; GroupCreateInput: { // input type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime name: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime users?: NexusGenInputs['UserCreateNestedManyWithoutGroupInput'] | null; // UserCreateNestedManyWithoutGroupInput }; GroupCreateNestedOneWithoutUsersInput: { // input type connect?: NexusGenInputs['GroupWhereUniqueInput'] | null; // GroupWhereUniqueInput connectOrCreate?: NexusGenInputs['GroupCreateOrConnectWithoutUsersInput'] | null; // GroupCreateOrConnectWithoutUsersInput create?: NexusGenInputs['GroupUncheckedCreateWithoutUsersInput'] | null; // GroupUncheckedCreateWithoutUsersInput }; GroupCreateOrConnectWithoutUsersInput: { // input type create: NexusGenInputs['GroupUncheckedCreateWithoutUsersInput']; // GroupUncheckedCreateWithoutUsersInput! where: NexusGenInputs['GroupWhereUniqueInput']; // GroupWhereUniqueInput! }; GroupCreateWithoutUsersInput: { // input type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime name: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; GroupMaxOrderByAggregateInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; GroupMinOrderByAggregateInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; GroupOrderByWithAggregationInput: { // input type _avg?: NexusGenInputs['GroupAvgOrderByAggregateInput'] | null; // GroupAvgOrderByAggregateInput _count?: NexusGenInputs['GroupCountOrderByAggregateInput'] | null; // GroupCountOrderByAggregateInput _max?: NexusGenInputs['GroupMaxOrderByAggregateInput'] | null; // GroupMaxOrderByAggregateInput _min?: NexusGenInputs['GroupMinOrderByAggregateInput'] | null; // GroupMinOrderByAggregateInput _sum?: NexusGenInputs['GroupSumOrderByAggregateInput'] | null; // GroupSumOrderByAggregateInput createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; GroupOrderByWithRelationInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder users?: NexusGenInputs['UserOrderByRelationAggregateInput'] | null; // UserOrderByRelationAggregateInput }; GroupRelationFilter: { // input type is?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput isNot?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; GroupScalarWhereWithAggregatesInput: { // input type AND?: Array<NexusGenInputs['GroupScalarWhereWithAggregatesInput'] | null> | null; // [GroupScalarWhereWithAggregatesInput] NOT?: Array<NexusGenInputs['GroupScalarWhereWithAggregatesInput'] | null> | null; // [GroupScalarWhereWithAggregatesInput] OR?: Array<NexusGenInputs['GroupScalarWhereWithAggregatesInput'] | null> | null; // [GroupScalarWhereWithAggregatesInput] createdAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter id?: NexusGenInputs['IntWithAggregatesFilter'] | null; // IntWithAggregatesFilter name?: NexusGenInputs['StringWithAggregatesFilter'] | null; // StringWithAggregatesFilter updatedAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter }; GroupSumOrderByAggregateInput: { // input type id?: NexusGenEnums['SortOrder'] | null; // SortOrder }; GroupUncheckedCreateInput: { // input type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int name: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime users?: NexusGenInputs['UserUncheckedCreateNestedManyWithoutGroupInput'] | null; // UserUncheckedCreateNestedManyWithoutGroupInput }; GroupUncheckedCreateWithoutUsersInput: { // input type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int name: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; GroupUncheckedUpdateInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput users?: NexusGenInputs['UserUncheckedUpdateManyWithoutGroupInput'] | null; // UserUncheckedUpdateManyWithoutGroupInput }; GroupUncheckedUpdateManyInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; GroupUncheckedUpdateWithoutUsersInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; GroupUpdateInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput name?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput users?: NexusGenInputs['UserUpdateManyWithoutGroupInput'] | null; // UserUpdateManyWithoutGroupInput }; GroupUpdateManyMutationInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput name?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; GroupUpdateOneWithoutUsersInput: { // input type connect?: NexusGenInputs['GroupWhereUniqueInput'] | null; // GroupWhereUniqueInput connectOrCreate?: NexusGenInputs['GroupCreateOrConnectWithoutUsersInput'] | null; // GroupCreateOrConnectWithoutUsersInput create?: NexusGenInputs['GroupUncheckedCreateWithoutUsersInput'] | null; // GroupUncheckedCreateWithoutUsersInput delete?: boolean | null; // Boolean disconnect?: boolean | null; // Boolean update?: NexusGenInputs['GroupUncheckedUpdateWithoutUsersInput'] | null; // GroupUncheckedUpdateWithoutUsersInput upsert?: NexusGenInputs['GroupUpsertWithoutUsersInput'] | null; // GroupUpsertWithoutUsersInput }; GroupUpdateWithoutUsersInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput name?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; GroupUpsertWithoutUsersInput: { // input type create: NexusGenInputs['GroupUncheckedCreateWithoutUsersInput']; // GroupUncheckedCreateWithoutUsersInput! update: NexusGenInputs['GroupUncheckedUpdateWithoutUsersInput']; // GroupUncheckedUpdateWithoutUsersInput! }; GroupWhereInput: { // input type AND?: Array<NexusGenInputs['GroupWhereInput'] | null> | null; // [GroupWhereInput] NOT?: Array<NexusGenInputs['GroupWhereInput'] | null> | null; // [GroupWhereInput] OR?: Array<NexusGenInputs['GroupWhereInput'] | null> | null; // [GroupWhereInput] createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter name?: NexusGenInputs['StringFilter'] | null; // StringFilter updatedAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter users?: NexusGenInputs['UserListRelationFilter'] | null; // UserListRelationFilter }; GroupWhereUniqueInput: { // input type id?: number | null; // Int }; IntFieldUpdateOperationsInput: { // input type decrement?: number | null; // Int divide?: number | null; // Int increment?: number | null; // Int multiply?: number | null; // Int set?: number | null; // Int }; IntFilter: { // input type equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter notIn?: Array<number | null> | null; // [Int] }; IntNullableFilter: { // input type equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter notIn?: Array<number | null> | null; // [Int] }; IntNullableWithAggregatesFilter: { // input type _avg?: NexusGenInputs['NestedFloatNullableFilter'] | null; // NestedFloatNullableFilter _count?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _max?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _min?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _sum?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntNullableWithAggregatesFilter'] | null; // NestedIntNullableWithAggregatesFilter notIn?: Array<number | null> | null; // [Int] }; IntWithAggregatesFilter: { // input type _avg?: NexusGenInputs['NestedFloatFilter'] | null; // NestedFloatFilter _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _min?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _sum?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntWithAggregatesFilter'] | null; // NestedIntWithAggregatesFilter notIn?: Array<number | null> | null; // [Int] }; NestedBoolFilter: { // input type equals?: boolean | null; // Boolean not?: NexusGenInputs['NestedBoolFilter'] | null; // NestedBoolFilter }; NestedBoolWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedBoolFilter'] | null; // NestedBoolFilter _min?: NexusGenInputs['NestedBoolFilter'] | null; // NestedBoolFilter equals?: boolean | null; // Boolean not?: NexusGenInputs['NestedBoolWithAggregatesFilter'] | null; // NestedBoolWithAggregatesFilter }; NestedDateTimeFilter: { // input type equals?: NexusGenScalars['DateTime'] | null; // DateTime gt?: NexusGenScalars['DateTime'] | null; // DateTime gte?: NexusGenScalars['DateTime'] | null; // DateTime in?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] lt?: NexusGenScalars['DateTime'] | null; // DateTime lte?: NexusGenScalars['DateTime'] | null; // DateTime not?: NexusGenInputs['NestedDateTimeFilter'] | null; // NestedDateTimeFilter notIn?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] }; NestedDateTimeWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedDateTimeFilter'] | null; // NestedDateTimeFilter _min?: NexusGenInputs['NestedDateTimeFilter'] | null; // NestedDateTimeFilter equals?: NexusGenScalars['DateTime'] | null; // DateTime gt?: NexusGenScalars['DateTime'] | null; // DateTime gte?: NexusGenScalars['DateTime'] | null; // DateTime in?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] lt?: NexusGenScalars['DateTime'] | null; // DateTime lte?: NexusGenScalars['DateTime'] | null; // DateTime not?: NexusGenInputs['NestedDateTimeWithAggregatesFilter'] | null; // NestedDateTimeWithAggregatesFilter notIn?: Array<NexusGenScalars['DateTime'] | null> | null; // [DateTime] }; NestedFloatFilter: { // input type equals?: number | null; // Float gt?: number | null; // Float gte?: number | null; // Float in?: Array<number | null> | null; // [Float] lt?: number | null; // Float lte?: number | null; // Float not?: NexusGenInputs['NestedFloatFilter'] | null; // NestedFloatFilter notIn?: Array<number | null> | null; // [Float] }; NestedFloatNullableFilter: { // input type equals?: number | null; // Float gt?: number | null; // Float gte?: number | null; // Float in?: Array<number | null> | null; // [Float] lt?: number | null; // Float lte?: number | null; // Float not?: NexusGenInputs['NestedFloatNullableFilter'] | null; // NestedFloatNullableFilter notIn?: Array<number | null> | null; // [Float] }; NestedIntFilter: { // input type equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter notIn?: Array<number | null> | null; // [Int] }; NestedIntNullableFilter: { // input type equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter notIn?: Array<number | null> | null; // [Int] }; NestedIntNullableWithAggregatesFilter: { // input type _avg?: NexusGenInputs['NestedFloatNullableFilter'] | null; // NestedFloatNullableFilter _count?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _max?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _min?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _sum?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntNullableWithAggregatesFilter'] | null; // NestedIntNullableWithAggregatesFilter notIn?: Array<number | null> | null; // [Int] }; NestedIntWithAggregatesFilter: { // input type _avg?: NexusGenInputs['NestedFloatFilter'] | null; // NestedFloatFilter _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _min?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _sum?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter equals?: number | null; // Int gt?: number | null; // Int gte?: number | null; // Int in?: Array<number | null> | null; // [Int] lt?: number | null; // Int lte?: number | null; // Int not?: NexusGenInputs['NestedIntWithAggregatesFilter'] | null; // NestedIntWithAggregatesFilter notIn?: Array<number | null> | null; // [Int] }; NestedStringFilter: { // input type contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringFilter'] | null; // NestedStringFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; NestedStringNullableFilter: { // input type contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringNullableFilter'] | null; // NestedStringNullableFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; NestedStringNullableWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _max?: NexusGenInputs['NestedStringNullableFilter'] | null; // NestedStringNullableFilter _min?: NexusGenInputs['NestedStringNullableFilter'] | null; // NestedStringNullableFilter contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringNullableWithAggregatesFilter'] | null; // NestedStringNullableWithAggregatesFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; NestedStringWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedStringFilter'] | null; // NestedStringFilter _min?: NexusGenInputs['NestedStringFilter'] | null; // NestedStringFilter contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringWithAggregatesFilter'] | null; // NestedStringWithAggregatesFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; NullableIntFieldUpdateOperationsInput: { // input type decrement?: number | null; // Int divide?: number | null; // Int increment?: number | null; // Int multiply?: number | null; // Int set?: number | null; // Int }; NullableStringFieldUpdateOperationsInput: { // input type set?: string | null; // String }; PostAvgOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostCountOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder published?: NexusGenEnums['SortOrder'] | null; // SortOrder title?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostCreateInput: { // input type author?: NexusGenInputs['UserCreateNestedOneWithoutPostsInput'] | null; // UserCreateNestedOneWithoutPostsInput comments?: NexusGenInputs['CommentCreateNestedManyWithoutPostInput'] | null; // CommentCreateNestedManyWithoutPostInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime published?: boolean | null; // Boolean title: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostCreateNestedManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['PostCreateOrConnectWithoutAuthorInput'] | null> | null; // [PostCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['PostCreateWithoutAuthorInput'] | null> | null; // [PostCreateWithoutAuthorInput] }; PostCreateNestedOneWithoutCommentsInput: { // input type connect?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput connectOrCreate?: NexusGenInputs['PostCreateOrConnectWithoutCommentsInput'] | null; // PostCreateOrConnectWithoutCommentsInput create?: NexusGenInputs['PostUncheckedCreateWithoutCommentsInput'] | null; // PostUncheckedCreateWithoutCommentsInput }; PostCreateOrConnectWithoutAuthorInput: { // input type create: NexusGenInputs['PostUncheckedCreateWithoutAuthorInput']; // PostUncheckedCreateWithoutAuthorInput! where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; PostCreateOrConnectWithoutCommentsInput: { // input type create: NexusGenInputs['PostUncheckedCreateWithoutCommentsInput']; // PostUncheckedCreateWithoutCommentsInput! where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; PostCreateWithoutAuthorInput: { // input type comments?: NexusGenInputs['CommentCreateNestedManyWithoutPostInput'] | null; // CommentCreateNestedManyWithoutPostInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime published?: boolean | null; // Boolean title: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostCreateWithoutCommentsInput: { // input type author?: NexusGenInputs['UserCreateNestedOneWithoutPostsInput'] | null; // UserCreateNestedOneWithoutPostsInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime published?: boolean | null; // Boolean title: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostListRelationFilter: { // input type every?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput none?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput some?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; PostMaxOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder published?: NexusGenEnums['SortOrder'] | null; // SortOrder title?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostMinOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder published?: NexusGenEnums['SortOrder'] | null; // SortOrder title?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostOrderByRelationAggregateInput: { // input type _count?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostOrderByWithAggregationInput: { // input type _avg?: NexusGenInputs['PostAvgOrderByAggregateInput'] | null; // PostAvgOrderByAggregateInput _count?: NexusGenInputs['PostCountOrderByAggregateInput'] | null; // PostCountOrderByAggregateInput _max?: NexusGenInputs['PostMaxOrderByAggregateInput'] | null; // PostMaxOrderByAggregateInput _min?: NexusGenInputs['PostMinOrderByAggregateInput'] | null; // PostMinOrderByAggregateInput _sum?: NexusGenInputs['PostSumOrderByAggregateInput'] | null; // PostSumOrderByAggregateInput authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder published?: NexusGenEnums['SortOrder'] | null; // SortOrder title?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostOrderByWithRelationInput: { // input type author?: NexusGenInputs['UserOrderByWithRelationInput'] | null; // UserOrderByWithRelationInput authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder comments?: NexusGenInputs['CommentOrderByRelationAggregateInput'] | null; // CommentOrderByRelationAggregateInput createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder published?: NexusGenEnums['SortOrder'] | null; // SortOrder title?: NexusGenEnums['SortOrder'] | null; // SortOrder updatedAt?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostRelationFilter: { // input type is?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput isNot?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; PostScalarWhereInput: { // input type AND?: Array<NexusGenInputs['PostScalarWhereInput'] | null> | null; // [PostScalarWhereInput] NOT?: Array<NexusGenInputs['PostScalarWhereInput'] | null> | null; // [PostScalarWhereInput] OR?: Array<NexusGenInputs['PostScalarWhereInput'] | null> | null; // [PostScalarWhereInput] authorId?: NexusGenInputs['IntNullableFilter'] | null; // IntNullableFilter createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter published?: NexusGenInputs['BoolFilter'] | null; // BoolFilter title?: NexusGenInputs['StringFilter'] | null; // StringFilter updatedAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter }; PostScalarWhereWithAggregatesInput: { // input type AND?: Array<NexusGenInputs['PostScalarWhereWithAggregatesInput'] | null> | null; // [PostScalarWhereWithAggregatesInput] NOT?: Array<NexusGenInputs['PostScalarWhereWithAggregatesInput'] | null> | null; // [PostScalarWhereWithAggregatesInput] OR?: Array<NexusGenInputs['PostScalarWhereWithAggregatesInput'] | null> | null; // [PostScalarWhereWithAggregatesInput] authorId?: NexusGenInputs['IntNullableWithAggregatesFilter'] | null; // IntNullableWithAggregatesFilter createdAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter id?: NexusGenInputs['IntWithAggregatesFilter'] | null; // IntWithAggregatesFilter published?: NexusGenInputs['BoolWithAggregatesFilter'] | null; // BoolWithAggregatesFilter title?: NexusGenInputs['StringWithAggregatesFilter'] | null; // StringWithAggregatesFilter updatedAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter }; PostSumOrderByAggregateInput: { // input type authorId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder }; PostUncheckedCreateInput: { // input type authorId?: number | null; // Int comments?: NexusGenInputs['CommentUncheckedCreateNestedManyWithoutPostInput'] | null; // CommentUncheckedCreateNestedManyWithoutPostInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int published?: boolean | null; // Boolean title: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostUncheckedCreateNestedManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['PostCreateOrConnectWithoutAuthorInput'] | null> | null; // [PostCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['PostCreateWithoutAuthorInput'] | null> | null; // [PostCreateWithoutAuthorInput] }; PostUncheckedCreateWithoutAuthorInput: { // input type comments?: NexusGenInputs['CommentUncheckedCreateNestedManyWithoutPostInput'] | null; // CommentUncheckedCreateNestedManyWithoutPostInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int published?: boolean | null; // Boolean title: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostUncheckedCreateWithoutCommentsInput: { // input type authorId?: number | null; // Int createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int published?: boolean | null; // Boolean title: string; // String! updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostUncheckedUpdateInput: { // input type authorId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput comments?: NexusGenInputs['CommentUncheckedUpdateManyWithoutPostInput'] | null; // CommentUncheckedUpdateManyWithoutPostInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUncheckedUpdateManyInput: { // input type authorId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUncheckedUpdateManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['PostCreateOrConnectWithoutAuthorInput'] | null> | null; // [PostCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['PostCreateWithoutAuthorInput'] | null> | null; // [PostCreateWithoutAuthorInput] delete?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] deleteMany?: Array<NexusGenInputs['PostScalarWhereInput'] | null> | null; // [PostScalarWhereInput] disconnect?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] set?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] update?: Array<NexusGenInputs['PostUpdateWithWhereUniqueWithoutAuthorInput'] | null> | null; // [PostUpdateWithWhereUniqueWithoutAuthorInput] updateMany?: Array<NexusGenInputs['PostUpdateManyWithWhereWithoutAuthorInput'] | null> | null; // [PostUpdateManyWithWhereWithoutAuthorInput] upsert?: Array<NexusGenInputs['PostUpsertWithWhereUniqueWithoutAuthorInput'] | null> | null; // [PostUpsertWithWhereUniqueWithoutAuthorInput] }; PostUncheckedUpdateManyWithoutPostsInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUncheckedUpdateWithoutAuthorInput: { // input type comments?: NexusGenInputs['CommentUncheckedUpdateManyWithoutPostInput'] | null; // CommentUncheckedUpdateManyWithoutPostInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUncheckedUpdateWithoutCommentsInput: { // input type authorId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUpdateInput: { // input type author?: NexusGenInputs['UserUpdateOneWithoutPostsInput'] | null; // UserUpdateOneWithoutPostsInput comments?: NexusGenInputs['CommentUpdateManyWithoutPostInput'] | null; // CommentUpdateManyWithoutPostInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUpdateManyMutationInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUpdateManyWithWhereWithoutAuthorInput: { // input type data: NexusGenInputs['PostUncheckedUpdateManyWithoutPostsInput']; // PostUncheckedUpdateManyWithoutPostsInput! where: NexusGenInputs['PostScalarWhereInput']; // PostScalarWhereInput! }; PostUpdateManyWithoutAuthorInput: { // input type connect?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['PostCreateOrConnectWithoutAuthorInput'] | null> | null; // [PostCreateOrConnectWithoutAuthorInput] create?: Array<NexusGenInputs['PostCreateWithoutAuthorInput'] | null> | null; // [PostCreateWithoutAuthorInput] delete?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] deleteMany?: Array<NexusGenInputs['PostScalarWhereInput'] | null> | null; // [PostScalarWhereInput] disconnect?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] set?: Array<NexusGenInputs['PostWhereUniqueInput'] | null> | null; // [PostWhereUniqueInput] update?: Array<NexusGenInputs['PostUpdateWithWhereUniqueWithoutAuthorInput'] | null> | null; // [PostUpdateWithWhereUniqueWithoutAuthorInput] updateMany?: Array<NexusGenInputs['PostUpdateManyWithWhereWithoutAuthorInput'] | null> | null; // [PostUpdateManyWithWhereWithoutAuthorInput] upsert?: Array<NexusGenInputs['PostUpsertWithWhereUniqueWithoutAuthorInput'] | null> | null; // [PostUpsertWithWhereUniqueWithoutAuthorInput] }; PostUpdateOneRequiredWithoutCommentsInput: { // input type connect?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput connectOrCreate?: NexusGenInputs['PostCreateOrConnectWithoutCommentsInput'] | null; // PostCreateOrConnectWithoutCommentsInput create?: NexusGenInputs['PostUncheckedCreateWithoutCommentsInput'] | null; // PostUncheckedCreateWithoutCommentsInput update?: NexusGenInputs['PostUncheckedUpdateWithoutCommentsInput'] | null; // PostUncheckedUpdateWithoutCommentsInput upsert?: NexusGenInputs['PostUpsertWithoutCommentsInput'] | null; // PostUpsertWithoutCommentsInput }; PostUpdateWithWhereUniqueWithoutAuthorInput: { // input type data: NexusGenInputs['PostUncheckedUpdateWithoutAuthorInput']; // PostUncheckedUpdateWithoutAuthorInput! where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; PostUpdateWithoutAuthorInput: { // input type comments?: NexusGenInputs['CommentUpdateManyWithoutPostInput'] | null; // CommentUpdateManyWithoutPostInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUpdateWithoutCommentsInput: { // input type author?: NexusGenInputs['UserUpdateOneWithoutPostsInput'] | null; // UserUpdateOneWithoutPostsInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput published?: NexusGenInputs['BoolFieldUpdateOperationsInput'] | null; // BoolFieldUpdateOperationsInput title?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput updatedAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput }; PostUpsertWithWhereUniqueWithoutAuthorInput: { // input type create: NexusGenInputs['PostUncheckedCreateWithoutAuthorInput']; // PostUncheckedCreateWithoutAuthorInput! update: NexusGenInputs['PostUncheckedUpdateWithoutAuthorInput']; // PostUncheckedUpdateWithoutAuthorInput! where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; PostUpsertWithoutCommentsInput: { // input type create: NexusGenInputs['PostUncheckedCreateWithoutCommentsInput']; // PostUncheckedCreateWithoutCommentsInput! update: NexusGenInputs['PostUncheckedUpdateWithoutCommentsInput']; // PostUncheckedUpdateWithoutCommentsInput! }; PostWhereInput: { // input type AND?: Array<NexusGenInputs['PostWhereInput'] | null> | null; // [PostWhereInput] NOT?: Array<NexusGenInputs['PostWhereInput'] | null> | null; // [PostWhereInput] OR?: Array<NexusGenInputs['PostWhereInput'] | null> | null; // [PostWhereInput] author?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput authorId?: NexusGenInputs['IntNullableFilter'] | null; // IntNullableFilter comments?: NexusGenInputs['CommentListRelationFilter'] | null; // CommentListRelationFilter createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter published?: NexusGenInputs['BoolFilter'] | null; // BoolFilter title?: NexusGenInputs['StringFilter'] | null; // StringFilter updatedAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter }; PostWhereUniqueInput: { // input type id?: number | null; // Int }; StringFieldUpdateOperationsInput: { // input type set?: string | null; // String }; StringFilter: { // input type contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringFilter'] | null; // NestedStringFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; StringNullableFilter: { // input type contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringNullableFilter'] | null; // NestedStringNullableFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; StringNullableWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntNullableFilter'] | null; // NestedIntNullableFilter _max?: NexusGenInputs['NestedStringNullableFilter'] | null; // NestedStringNullableFilter _min?: NexusGenInputs['NestedStringNullableFilter'] | null; // NestedStringNullableFilter contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringNullableWithAggregatesFilter'] | null; // NestedStringNullableWithAggregatesFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; StringWithAggregatesFilter: { // input type _count?: NexusGenInputs['NestedIntFilter'] | null; // NestedIntFilter _max?: NexusGenInputs['NestedStringFilter'] | null; // NestedStringFilter _min?: NexusGenInputs['NestedStringFilter'] | null; // NestedStringFilter contains?: string | null; // String endsWith?: string | null; // String equals?: string | null; // String gt?: string | null; // String gte?: string | null; // String in?: Array<string | null> | null; // [String] lt?: string | null; // String lte?: string | null; // String not?: NexusGenInputs['NestedStringWithAggregatesFilter'] | null; // NestedStringWithAggregatesFilter notIn?: Array<string | null> | null; // [String] startsWith?: string | null; // String }; UpdateFieldInput: { // input type create?: boolean | null; // Boolean editor?: boolean | null; // Boolean filter?: boolean | null; // Boolean id?: string | null; // String isId?: boolean | null; // Boolean kind?: NexusGenEnums['KindEnum'] | null; // KindEnum list?: boolean | null; // Boolean name?: string | null; // String order?: number | null; // Int read?: boolean | null; // Boolean relationField?: boolean | null; // Boolean required?: boolean | null; // Boolean sort?: boolean | null; // Boolean title?: string | null; // String type?: string | null; // String unique?: boolean | null; // Boolean update?: boolean | null; // Boolean upload?: boolean | null; // Boolean }; UpdateModelInput: { // input type create?: boolean | null; // Boolean delete?: boolean | null; // Boolean displayFields?: Array<string | null> | null; // [String] fields?: Array<NexusGenInputs['UpdateFieldInput'] | null> | null; // [UpdateFieldInput] idField?: string | null; // String name?: string | null; // String update?: boolean | null; // Boolean }; UserAvgOrderByAggregateInput: { // input type groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserCountOrderByAggregateInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder email?: NexusGenEnums['SortOrder'] | null; // SortOrder groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder password?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserCreateInput: { // input type comments?: NexusGenInputs['CommentCreateNestedManyWithoutAuthorInput'] | null; // CommentCreateNestedManyWithoutAuthorInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! group?: NexusGenInputs['GroupCreateNestedOneWithoutUsersInput'] | null; // GroupCreateNestedOneWithoutUsersInput name?: string | null; // String password: string; // String! posts?: NexusGenInputs['PostCreateNestedManyWithoutAuthorInput'] | null; // PostCreateNestedManyWithoutAuthorInput }; UserCreateNestedManyWithoutGroupInput: { // input type connect?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['UserCreateOrConnectWithoutGroupInput'] | null> | null; // [UserCreateOrConnectWithoutGroupInput] create?: Array<NexusGenInputs['UserCreateWithoutGroupInput'] | null> | null; // [UserCreateWithoutGroupInput] }; UserCreateNestedOneWithoutCommentsInput: { // input type connect?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput connectOrCreate?: NexusGenInputs['UserCreateOrConnectWithoutCommentsInput'] | null; // UserCreateOrConnectWithoutCommentsInput create?: NexusGenInputs['UserUncheckedCreateWithoutCommentsInput'] | null; // UserUncheckedCreateWithoutCommentsInput }; UserCreateNestedOneWithoutPostsInput: { // input type connect?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput connectOrCreate?: NexusGenInputs['UserCreateOrConnectWithoutPostsInput'] | null; // UserCreateOrConnectWithoutPostsInput create?: NexusGenInputs['UserUncheckedCreateWithoutPostsInput'] | null; // UserUncheckedCreateWithoutPostsInput }; UserCreateOrConnectWithoutCommentsInput: { // input type create: NexusGenInputs['UserUncheckedCreateWithoutCommentsInput']; // UserUncheckedCreateWithoutCommentsInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; UserCreateOrConnectWithoutGroupInput: { // input type create: NexusGenInputs['UserUncheckedCreateWithoutGroupInput']; // UserUncheckedCreateWithoutGroupInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; UserCreateOrConnectWithoutPostsInput: { // input type create: NexusGenInputs['UserUncheckedCreateWithoutPostsInput']; // UserUncheckedCreateWithoutPostsInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; UserCreateWithoutCommentsInput: { // input type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! group?: NexusGenInputs['GroupCreateNestedOneWithoutUsersInput'] | null; // GroupCreateNestedOneWithoutUsersInput name?: string | null; // String password: string; // String! posts?: NexusGenInputs['PostCreateNestedManyWithoutAuthorInput'] | null; // PostCreateNestedManyWithoutAuthorInput }; UserCreateWithoutGroupInput: { // input type comments?: NexusGenInputs['CommentCreateNestedManyWithoutAuthorInput'] | null; // CommentCreateNestedManyWithoutAuthorInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! name?: string | null; // String password: string; // String! posts?: NexusGenInputs['PostCreateNestedManyWithoutAuthorInput'] | null; // PostCreateNestedManyWithoutAuthorInput }; UserCreateWithoutPostsInput: { // input type comments?: NexusGenInputs['CommentCreateNestedManyWithoutAuthorInput'] | null; // CommentCreateNestedManyWithoutAuthorInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! group?: NexusGenInputs['GroupCreateNestedOneWithoutUsersInput'] | null; // GroupCreateNestedOneWithoutUsersInput name?: string | null; // String password: string; // String! }; UserListRelationFilter: { // input type every?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput none?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput some?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; UserMaxOrderByAggregateInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder email?: NexusGenEnums['SortOrder'] | null; // SortOrder groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder password?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserMinOrderByAggregateInput: { // input type createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder email?: NexusGenEnums['SortOrder'] | null; // SortOrder groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder password?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserOrderByRelationAggregateInput: { // input type _count?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserOrderByWithAggregationInput: { // input type _avg?: NexusGenInputs['UserAvgOrderByAggregateInput'] | null; // UserAvgOrderByAggregateInput _count?: NexusGenInputs['UserCountOrderByAggregateInput'] | null; // UserCountOrderByAggregateInput _max?: NexusGenInputs['UserMaxOrderByAggregateInput'] | null; // UserMaxOrderByAggregateInput _min?: NexusGenInputs['UserMinOrderByAggregateInput'] | null; // UserMinOrderByAggregateInput _sum?: NexusGenInputs['UserSumOrderByAggregateInput'] | null; // UserSumOrderByAggregateInput createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder email?: NexusGenEnums['SortOrder'] | null; // SortOrder groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder password?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserOrderByWithRelationInput: { // input type comments?: NexusGenInputs['CommentOrderByRelationAggregateInput'] | null; // CommentOrderByRelationAggregateInput createdAt?: NexusGenEnums['SortOrder'] | null; // SortOrder email?: NexusGenEnums['SortOrder'] | null; // SortOrder group?: NexusGenInputs['GroupOrderByWithRelationInput'] | null; // GroupOrderByWithRelationInput groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder name?: NexusGenEnums['SortOrder'] | null; // SortOrder password?: NexusGenEnums['SortOrder'] | null; // SortOrder posts?: NexusGenInputs['PostOrderByRelationAggregateInput'] | null; // PostOrderByRelationAggregateInput }; UserRelationFilter: { // input type is?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput isNot?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; UserScalarWhereInput: { // input type AND?: Array<NexusGenInputs['UserScalarWhereInput'] | null> | null; // [UserScalarWhereInput] NOT?: Array<NexusGenInputs['UserScalarWhereInput'] | null> | null; // [UserScalarWhereInput] OR?: Array<NexusGenInputs['UserScalarWhereInput'] | null> | null; // [UserScalarWhereInput] createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter email?: NexusGenInputs['StringFilter'] | null; // StringFilter groupId?: NexusGenInputs['IntNullableFilter'] | null; // IntNullableFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter name?: NexusGenInputs['StringNullableFilter'] | null; // StringNullableFilter password?: NexusGenInputs['StringFilter'] | null; // StringFilter }; UserScalarWhereWithAggregatesInput: { // input type AND?: Array<NexusGenInputs['UserScalarWhereWithAggregatesInput'] | null> | null; // [UserScalarWhereWithAggregatesInput] NOT?: Array<NexusGenInputs['UserScalarWhereWithAggregatesInput'] | null> | null; // [UserScalarWhereWithAggregatesInput] OR?: Array<NexusGenInputs['UserScalarWhereWithAggregatesInput'] | null> | null; // [UserScalarWhereWithAggregatesInput] createdAt?: NexusGenInputs['DateTimeWithAggregatesFilter'] | null; // DateTimeWithAggregatesFilter email?: NexusGenInputs['StringWithAggregatesFilter'] | null; // StringWithAggregatesFilter groupId?: NexusGenInputs['IntNullableWithAggregatesFilter'] | null; // IntNullableWithAggregatesFilter id?: NexusGenInputs['IntWithAggregatesFilter'] | null; // IntWithAggregatesFilter name?: NexusGenInputs['StringNullableWithAggregatesFilter'] | null; // StringNullableWithAggregatesFilter password?: NexusGenInputs['StringWithAggregatesFilter'] | null; // StringWithAggregatesFilter }; UserSumOrderByAggregateInput: { // input type groupId?: NexusGenEnums['SortOrder'] | null; // SortOrder id?: NexusGenEnums['SortOrder'] | null; // SortOrder }; UserUncheckedCreateInput: { // input type comments?: NexusGenInputs['CommentUncheckedCreateNestedManyWithoutAuthorInput'] | null; // CommentUncheckedCreateNestedManyWithoutAuthorInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! groupId?: number | null; // Int id?: number | null; // Int name?: string | null; // String password: string; // String! posts?: NexusGenInputs['PostUncheckedCreateNestedManyWithoutAuthorInput'] | null; // PostUncheckedCreateNestedManyWithoutAuthorInput }; UserUncheckedCreateNestedManyWithoutGroupInput: { // input type connect?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['UserCreateOrConnectWithoutGroupInput'] | null> | null; // [UserCreateOrConnectWithoutGroupInput] create?: Array<NexusGenInputs['UserCreateWithoutGroupInput'] | null> | null; // [UserCreateWithoutGroupInput] }; UserUncheckedCreateWithoutCommentsInput: { // input type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! groupId?: number | null; // Int id?: number | null; // Int name?: string | null; // String password: string; // String! posts?: NexusGenInputs['PostUncheckedCreateNestedManyWithoutAuthorInput'] | null; // PostUncheckedCreateNestedManyWithoutAuthorInput }; UserUncheckedCreateWithoutGroupInput: { // input type comments?: NexusGenInputs['CommentUncheckedCreateNestedManyWithoutAuthorInput'] | null; // CommentUncheckedCreateNestedManyWithoutAuthorInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! id?: number | null; // Int name?: string | null; // String password: string; // String! posts?: NexusGenInputs['PostUncheckedCreateNestedManyWithoutAuthorInput'] | null; // PostUncheckedCreateNestedManyWithoutAuthorInput }; UserUncheckedCreateWithoutPostsInput: { // input type comments?: NexusGenInputs['CommentUncheckedCreateNestedManyWithoutAuthorInput'] | null; // CommentUncheckedCreateNestedManyWithoutAuthorInput createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email: string; // String! groupId?: number | null; // Int id?: number | null; // Int name?: string | null; // String password: string; // String! }; UserUncheckedUpdateInput: { // input type comments?: NexusGenInputs['CommentUncheckedUpdateManyWithoutAuthorInput'] | null; // CommentUncheckedUpdateManyWithoutAuthorInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput groupId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput posts?: NexusGenInputs['PostUncheckedUpdateManyWithoutAuthorInput'] | null; // PostUncheckedUpdateManyWithoutAuthorInput }; UserUncheckedUpdateManyInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput groupId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput }; UserUncheckedUpdateManyWithoutGroupInput: { // input type connect?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['UserCreateOrConnectWithoutGroupInput'] | null> | null; // [UserCreateOrConnectWithoutGroupInput] create?: Array<NexusGenInputs['UserCreateWithoutGroupInput'] | null> | null; // [UserCreateWithoutGroupInput] delete?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] deleteMany?: Array<NexusGenInputs['UserScalarWhereInput'] | null> | null; // [UserScalarWhereInput] disconnect?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] set?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] update?: Array<NexusGenInputs['UserUpdateWithWhereUniqueWithoutGroupInput'] | null> | null; // [UserUpdateWithWhereUniqueWithoutGroupInput] updateMany?: Array<NexusGenInputs['UserUpdateManyWithWhereWithoutGroupInput'] | null> | null; // [UserUpdateManyWithWhereWithoutGroupInput] upsert?: Array<NexusGenInputs['UserUpsertWithWhereUniqueWithoutGroupInput'] | null> | null; // [UserUpsertWithWhereUniqueWithoutGroupInput] }; UserUncheckedUpdateManyWithoutUsersInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput }; UserUncheckedUpdateWithoutCommentsInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput groupId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput posts?: NexusGenInputs['PostUncheckedUpdateManyWithoutAuthorInput'] | null; // PostUncheckedUpdateManyWithoutAuthorInput }; UserUncheckedUpdateWithoutGroupInput: { // input type comments?: NexusGenInputs['CommentUncheckedUpdateManyWithoutAuthorInput'] | null; // CommentUncheckedUpdateManyWithoutAuthorInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput posts?: NexusGenInputs['PostUncheckedUpdateManyWithoutAuthorInput'] | null; // PostUncheckedUpdateManyWithoutAuthorInput }; UserUncheckedUpdateWithoutPostsInput: { // input type comments?: NexusGenInputs['CommentUncheckedUpdateManyWithoutAuthorInput'] | null; // CommentUncheckedUpdateManyWithoutAuthorInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput groupId?: NexusGenInputs['NullableIntFieldUpdateOperationsInput'] | null; // NullableIntFieldUpdateOperationsInput id?: NexusGenInputs['IntFieldUpdateOperationsInput'] | null; // IntFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput }; UserUpdateInput: { // input type comments?: NexusGenInputs['CommentUpdateManyWithoutAuthorInput'] | null; // CommentUpdateManyWithoutAuthorInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput group?: NexusGenInputs['GroupUpdateOneWithoutUsersInput'] | null; // GroupUpdateOneWithoutUsersInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput posts?: NexusGenInputs['PostUpdateManyWithoutAuthorInput'] | null; // PostUpdateManyWithoutAuthorInput }; UserUpdateManyMutationInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput }; UserUpdateManyWithWhereWithoutGroupInput: { // input type data: NexusGenInputs['UserUncheckedUpdateManyWithoutUsersInput']; // UserUncheckedUpdateManyWithoutUsersInput! where: NexusGenInputs['UserScalarWhereInput']; // UserScalarWhereInput! }; UserUpdateManyWithoutGroupInput: { // input type connect?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] connectOrCreate?: Array<NexusGenInputs['UserCreateOrConnectWithoutGroupInput'] | null> | null; // [UserCreateOrConnectWithoutGroupInput] create?: Array<NexusGenInputs['UserCreateWithoutGroupInput'] | null> | null; // [UserCreateWithoutGroupInput] delete?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] deleteMany?: Array<NexusGenInputs['UserScalarWhereInput'] | null> | null; // [UserScalarWhereInput] disconnect?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] set?: Array<NexusGenInputs['UserWhereUniqueInput'] | null> | null; // [UserWhereUniqueInput] update?: Array<NexusGenInputs['UserUpdateWithWhereUniqueWithoutGroupInput'] | null> | null; // [UserUpdateWithWhereUniqueWithoutGroupInput] updateMany?: Array<NexusGenInputs['UserUpdateManyWithWhereWithoutGroupInput'] | null> | null; // [UserUpdateManyWithWhereWithoutGroupInput] upsert?: Array<NexusGenInputs['UserUpsertWithWhereUniqueWithoutGroupInput'] | null> | null; // [UserUpsertWithWhereUniqueWithoutGroupInput] }; UserUpdateOneWithoutCommentsInput: { // input type connect?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput connectOrCreate?: NexusGenInputs['UserCreateOrConnectWithoutCommentsInput'] | null; // UserCreateOrConnectWithoutCommentsInput create?: NexusGenInputs['UserUncheckedCreateWithoutCommentsInput'] | null; // UserUncheckedCreateWithoutCommentsInput delete?: boolean | null; // Boolean disconnect?: boolean | null; // Boolean update?: NexusGenInputs['UserUncheckedUpdateWithoutCommentsInput'] | null; // UserUncheckedUpdateWithoutCommentsInput upsert?: NexusGenInputs['UserUpsertWithoutCommentsInput'] | null; // UserUpsertWithoutCommentsInput }; UserUpdateOneWithoutPostsInput: { // input type connect?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput connectOrCreate?: NexusGenInputs['UserCreateOrConnectWithoutPostsInput'] | null; // UserCreateOrConnectWithoutPostsInput create?: NexusGenInputs['UserUncheckedCreateWithoutPostsInput'] | null; // UserUncheckedCreateWithoutPostsInput delete?: boolean | null; // Boolean disconnect?: boolean | null; // Boolean update?: NexusGenInputs['UserUncheckedUpdateWithoutPostsInput'] | null; // UserUncheckedUpdateWithoutPostsInput upsert?: NexusGenInputs['UserUpsertWithoutPostsInput'] | null; // UserUpsertWithoutPostsInput }; UserUpdateWithWhereUniqueWithoutGroupInput: { // input type data: NexusGenInputs['UserUncheckedUpdateWithoutGroupInput']; // UserUncheckedUpdateWithoutGroupInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; UserUpdateWithoutCommentsInput: { // input type createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput group?: NexusGenInputs['GroupUpdateOneWithoutUsersInput'] | null; // GroupUpdateOneWithoutUsersInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput posts?: NexusGenInputs['PostUpdateManyWithoutAuthorInput'] | null; // PostUpdateManyWithoutAuthorInput }; UserUpdateWithoutGroupInput: { // input type comments?: NexusGenInputs['CommentUpdateManyWithoutAuthorInput'] | null; // CommentUpdateManyWithoutAuthorInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput posts?: NexusGenInputs['PostUpdateManyWithoutAuthorInput'] | null; // PostUpdateManyWithoutAuthorInput }; UserUpdateWithoutPostsInput: { // input type comments?: NexusGenInputs['CommentUpdateManyWithoutAuthorInput'] | null; // CommentUpdateManyWithoutAuthorInput createdAt?: NexusGenInputs['DateTimeFieldUpdateOperationsInput'] | null; // DateTimeFieldUpdateOperationsInput email?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput group?: NexusGenInputs['GroupUpdateOneWithoutUsersInput'] | null; // GroupUpdateOneWithoutUsersInput name?: NexusGenInputs['NullableStringFieldUpdateOperationsInput'] | null; // NullableStringFieldUpdateOperationsInput password?: NexusGenInputs['StringFieldUpdateOperationsInput'] | null; // StringFieldUpdateOperationsInput }; UserUpsertWithWhereUniqueWithoutGroupInput: { // input type create: NexusGenInputs['UserUncheckedCreateWithoutGroupInput']; // UserUncheckedCreateWithoutGroupInput! update: NexusGenInputs['UserUncheckedUpdateWithoutGroupInput']; // UserUncheckedUpdateWithoutGroupInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; UserUpsertWithoutCommentsInput: { // input type create: NexusGenInputs['UserUncheckedCreateWithoutCommentsInput']; // UserUncheckedCreateWithoutCommentsInput! update: NexusGenInputs['UserUncheckedUpdateWithoutCommentsInput']; // UserUncheckedUpdateWithoutCommentsInput! }; UserUpsertWithoutPostsInput: { // input type create: NexusGenInputs['UserUncheckedCreateWithoutPostsInput']; // UserUncheckedCreateWithoutPostsInput! update: NexusGenInputs['UserUncheckedUpdateWithoutPostsInput']; // UserUncheckedUpdateWithoutPostsInput! }; UserWhereInput: { // input type AND?: Array<NexusGenInputs['UserWhereInput'] | null> | null; // [UserWhereInput] NOT?: Array<NexusGenInputs['UserWhereInput'] | null> | null; // [UserWhereInput] OR?: Array<NexusGenInputs['UserWhereInput'] | null> | null; // [UserWhereInput] comments?: NexusGenInputs['CommentListRelationFilter'] | null; // CommentListRelationFilter createdAt?: NexusGenInputs['DateTimeFilter'] | null; // DateTimeFilter email?: NexusGenInputs['StringFilter'] | null; // StringFilter group?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput groupId?: NexusGenInputs['IntNullableFilter'] | null; // IntNullableFilter id?: NexusGenInputs['IntFilter'] | null; // IntFilter name?: NexusGenInputs['StringNullableFilter'] | null; // StringNullableFilter password?: NexusGenInputs['StringFilter'] | null; // StringFilter posts?: NexusGenInputs['PostListRelationFilter'] | null; // PostListRelationFilter }; UserWhereUniqueInput: { // input type email?: string | null; // String id?: number | null; // Int }; } export interface NexusGenEnums { CommentScalarFieldEnum: 'authorId' | 'contain' | 'createdAt' | 'id' | 'postId' | 'updatedAt'; GroupScalarFieldEnum: 'createdAt' | 'id' | 'name' | 'updatedAt'; KindEnum: 'enum' | 'object' | 'scalar'; PostScalarFieldEnum: 'authorId' | 'createdAt' | 'id' | 'published' | 'title' | 'updatedAt'; SortOrder: 'asc' | 'desc'; UserScalarFieldEnum: 'createdAt' | 'email' | 'groupId' | 'id' | 'name' | 'password'; } export interface NexusGenScalars { String: string; Int: number; Float: number; Boolean: boolean; ID: string; BigInt: any; DateTime: any; Decimal: any; Json: any; } export interface NexusGenObjects { AggregateComment: { // root type _avg?: NexusGenRootTypes['CommentAvgAggregateOutputType'] | null; // CommentAvgAggregateOutputType _count?: NexusGenRootTypes['CommentCountAggregateOutputType'] | null; // CommentCountAggregateOutputType _max?: NexusGenRootTypes['CommentMaxAggregateOutputType'] | null; // CommentMaxAggregateOutputType _min?: NexusGenRootTypes['CommentMinAggregateOutputType'] | null; // CommentMinAggregateOutputType _sum?: NexusGenRootTypes['CommentSumAggregateOutputType'] | null; // CommentSumAggregateOutputType }; AggregateGroup: { // root type _avg?: NexusGenRootTypes['GroupAvgAggregateOutputType'] | null; // GroupAvgAggregateOutputType _count?: NexusGenRootTypes['GroupCountAggregateOutputType'] | null; // GroupCountAggregateOutputType _max?: NexusGenRootTypes['GroupMaxAggregateOutputType'] | null; // GroupMaxAggregateOutputType _min?: NexusGenRootTypes['GroupMinAggregateOutputType'] | null; // GroupMinAggregateOutputType _sum?: NexusGenRootTypes['GroupSumAggregateOutputType'] | null; // GroupSumAggregateOutputType }; AggregatePost: { // root type _avg?: NexusGenRootTypes['PostAvgAggregateOutputType'] | null; // PostAvgAggregateOutputType _count?: NexusGenRootTypes['PostCountAggregateOutputType'] | null; // PostCountAggregateOutputType _max?: NexusGenRootTypes['PostMaxAggregateOutputType'] | null; // PostMaxAggregateOutputType _min?: NexusGenRootTypes['PostMinAggregateOutputType'] | null; // PostMinAggregateOutputType _sum?: NexusGenRootTypes['PostSumAggregateOutputType'] | null; // PostSumAggregateOutputType }; AggregateUser: { // root type _avg?: NexusGenRootTypes['UserAvgAggregateOutputType'] | null; // UserAvgAggregateOutputType _count?: NexusGenRootTypes['UserCountAggregateOutputType'] | null; // UserCountAggregateOutputType _max?: NexusGenRootTypes['UserMaxAggregateOutputType'] | null; // UserMaxAggregateOutputType _min?: NexusGenRootTypes['UserMinAggregateOutputType'] | null; // UserMinAggregateOutputType _sum?: NexusGenRootTypes['UserSumAggregateOutputType'] | null; // UserSumAggregateOutputType }; BatchPayload: { // root type count: number; // Int! }; Comment: { // root type authorId?: number | null; // Int contain: string; // String! createdAt: NexusGenScalars['DateTime']; // DateTime! id: number; // Int! postId: number; // Int! updatedAt: NexusGenScalars['DateTime']; // DateTime! }; CommentAvgAggregateOutputType: { // root type authorId?: number | null; // Float id?: number | null; // Float postId?: number | null; // Float }; CommentCountAggregateOutputType: { // root type _all: number; // Int! authorId: number; // Int! contain: number; // Int! createdAt: number; // Int! id: number; // Int! postId: number; // Int! updatedAt: number; // Int! }; CommentMaxAggregateOutputType: { // root type authorId?: number | null; // Int contain?: string | null; // String createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int postId?: number | null; // Int updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentMinAggregateOutputType: { // root type authorId?: number | null; // Int contain?: string | null; // String createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int postId?: number | null; // Int updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; CommentSumAggregateOutputType: { // root type authorId?: number | null; // Int id?: number | null; // Int postId?: number | null; // Int }; Enum: { // root type fields: string[]; // [String!]! name: string; // String! }; Field: { // root type create: boolean; // Boolean! editor: boolean; // Boolean! filter: boolean; // Boolean! id: string; // String! isId: boolean; // Boolean! kind: NexusGenEnums['KindEnum']; // KindEnum! list: boolean; // Boolean! name: string; // String! order: number; // Int! read: boolean; // Boolean! relationField?: boolean | null; // Boolean required: boolean; // Boolean! sort: boolean; // Boolean! title: string; // String! type: string; // String! unique: boolean; // Boolean! update: boolean; // Boolean! upload: boolean; // Boolean! }; Group: { // root type createdAt: NexusGenScalars['DateTime']; // DateTime! id: number; // Int! name: string; // String! updatedAt: NexusGenScalars['DateTime']; // DateTime! }; GroupAvgAggregateOutputType: { // root type id?: number | null; // Float }; GroupCountAggregateOutputType: { // root type _all: number; // Int! createdAt: number; // Int! id: number; // Int! name: number; // Int! updatedAt: number; // Int! }; GroupCountOutputType: { // root type users: number; // Int! }; GroupMaxAggregateOutputType: { // root type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int name?: string | null; // String updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; GroupMinAggregateOutputType: { // root type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int name?: string | null; // String updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; GroupSumAggregateOutputType: { // root type id?: number | null; // Int }; Model: { // root type create: boolean; // Boolean! delete: boolean; // Boolean! displayFields: string[]; // [String!]! fields: NexusGenRootTypes['Field'][]; // [Field!]! id: string; // String! idField: string; // String! name: string; // String! update: boolean; // Boolean! }; Mutation: {}; Post: { // root type authorId?: number | null; // Int createdAt: NexusGenScalars['DateTime']; // DateTime! id: number; // Int! published: boolean; // Boolean! title: string; // String! updatedAt: NexusGenScalars['DateTime']; // DateTime! }; PostAvgAggregateOutputType: { // root type authorId?: number | null; // Float id?: number | null; // Float }; PostCountAggregateOutputType: { // root type _all: number; // Int! authorId: number; // Int! createdAt: number; // Int! id: number; // Int! published: number; // Int! title: number; // Int! updatedAt: number; // Int! }; PostCountOutputType: { // root type comments: number; // Int! }; PostMaxAggregateOutputType: { // root type authorId?: number | null; // Int createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int published?: boolean | null; // Boolean title?: string | null; // String updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostMinAggregateOutputType: { // root type authorId?: number | null; // Int createdAt?: NexusGenScalars['DateTime'] | null; // DateTime id?: number | null; // Int published?: boolean | null; // Boolean title?: string | null; // String updatedAt?: NexusGenScalars['DateTime'] | null; // DateTime }; PostSumAggregateOutputType: { // root type authorId?: number | null; // Int id?: number | null; // Int }; Query: {}; Schema: { // root type enums: NexusGenRootTypes['Enum'][]; // [Enum!]! models: NexusGenRootTypes['Model'][]; // [Model!]! }; User: { // root type createdAt: NexusGenScalars['DateTime']; // DateTime! email: string; // String! groupId?: number | null; // Int id: number; // Int! name?: string | null; // String password: string; // String! }; UserAvgAggregateOutputType: { // root type groupId?: number | null; // Float id?: number | null; // Float }; UserCountAggregateOutputType: { // root type _all: number; // Int! createdAt: number; // Int! email: number; // Int! groupId: number; // Int! id: number; // Int! name: number; // Int! password: number; // Int! }; UserCountOutputType: { // root type comments: number; // Int! posts: number; // Int! }; UserMaxAggregateOutputType: { // root type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email?: string | null; // String groupId?: number | null; // Int id?: number | null; // Int name?: string | null; // String password?: string | null; // String }; UserMinAggregateOutputType: { // root type createdAt?: NexusGenScalars['DateTime'] | null; // DateTime email?: string | null; // String groupId?: number | null; // Int id?: number | null; // Int name?: string | null; // String password?: string | null; // String }; UserSumAggregateOutputType: { // root type groupId?: number | null; // Int id?: number | null; // Int }; } export interface NexusGenInterfaces {} export interface NexusGenUnions {} export type NexusGenRootTypes = NexusGenObjects; export type NexusGenAllTypes = NexusGenRootTypes & NexusGenScalars & NexusGenEnums; export interface NexusGenFieldTypes { AggregateComment: { // field return type _avg: NexusGenRootTypes['CommentAvgAggregateOutputType'] | null; // CommentAvgAggregateOutputType _count: NexusGenRootTypes['CommentCountAggregateOutputType'] | null; // CommentCountAggregateOutputType _max: NexusGenRootTypes['CommentMaxAggregateOutputType'] | null; // CommentMaxAggregateOutputType _min: NexusGenRootTypes['CommentMinAggregateOutputType'] | null; // CommentMinAggregateOutputType _sum: NexusGenRootTypes['CommentSumAggregateOutputType'] | null; // CommentSumAggregateOutputType }; AggregateGroup: { // field return type _avg: NexusGenRootTypes['GroupAvgAggregateOutputType'] | null; // GroupAvgAggregateOutputType _count: NexusGenRootTypes['GroupCountAggregateOutputType'] | null; // GroupCountAggregateOutputType _max: NexusGenRootTypes['GroupMaxAggregateOutputType'] | null; // GroupMaxAggregateOutputType _min: NexusGenRootTypes['GroupMinAggregateOutputType'] | null; // GroupMinAggregateOutputType _sum: NexusGenRootTypes['GroupSumAggregateOutputType'] | null; // GroupSumAggregateOutputType }; AggregatePost: { // field return type _avg: NexusGenRootTypes['PostAvgAggregateOutputType'] | null; // PostAvgAggregateOutputType _count: NexusGenRootTypes['PostCountAggregateOutputType'] | null; // PostCountAggregateOutputType _max: NexusGenRootTypes['PostMaxAggregateOutputType'] | null; // PostMaxAggregateOutputType _min: NexusGenRootTypes['PostMinAggregateOutputType'] | null; // PostMinAggregateOutputType _sum: NexusGenRootTypes['PostSumAggregateOutputType'] | null; // PostSumAggregateOutputType }; AggregateUser: { // field return type _avg: NexusGenRootTypes['UserAvgAggregateOutputType'] | null; // UserAvgAggregateOutputType _count: NexusGenRootTypes['UserCountAggregateOutputType'] | null; // UserCountAggregateOutputType _max: NexusGenRootTypes['UserMaxAggregateOutputType'] | null; // UserMaxAggregateOutputType _min: NexusGenRootTypes['UserMinAggregateOutputType'] | null; // UserMinAggregateOutputType _sum: NexusGenRootTypes['UserSumAggregateOutputType'] | null; // UserSumAggregateOutputType }; BatchPayload: { // field return type count: number; // Int! }; Comment: { // field return type author: NexusGenRootTypes['User'] | null; // User authorId: number | null; // Int contain: string; // String! createdAt: NexusGenScalars['DateTime']; // DateTime! id: number; // Int! post: NexusGenRootTypes['Post']; // Post! postId: number; // Int! updatedAt: NexusGenScalars['DateTime']; // DateTime! }; CommentAvgAggregateOutputType: { // field return type authorId: number | null; // Float id: number | null; // Float postId: number | null; // Float }; CommentCountAggregateOutputType: { // field return type _all: number; // Int! authorId: number; // Int! contain: number; // Int! createdAt: number; // Int! id: number; // Int! postId: number; // Int! updatedAt: number; // Int! }; CommentMaxAggregateOutputType: { // field return type authorId: number | null; // Int contain: string | null; // String createdAt: NexusGenScalars['DateTime'] | null; // DateTime id: number | null; // Int postId: number | null; // Int updatedAt: NexusGenScalars['DateTime'] | null; // DateTime }; CommentMinAggregateOutputType: { // field return type authorId: number | null; // Int contain: string | null; // String createdAt: NexusGenScalars['DateTime'] | null; // DateTime id: number | null; // Int postId: number | null; // Int updatedAt: NexusGenScalars['DateTime'] | null; // DateTime }; CommentSumAggregateOutputType: { // field return type authorId: number | null; // Int id: number | null; // Int postId: number | null; // Int }; Enum: { // field return type fields: string[]; // [String!]! name: string; // String! }; Field: { // field return type create: boolean; // Boolean! editor: boolean; // Boolean! filter: boolean; // Boolean! id: string; // String! isId: boolean; // Boolean! kind: NexusGenEnums['KindEnum']; // KindEnum! list: boolean; // Boolean! name: string; // String! order: number; // Int! read: boolean; // Boolean! relationField: boolean | null; // Boolean required: boolean; // Boolean! sort: boolean; // Boolean! title: string; // String! type: string; // String! unique: boolean; // Boolean! update: boolean; // Boolean! upload: boolean; // Boolean! }; Group: { // field return type _count: NexusGenRootTypes['GroupCountOutputType']; // GroupCountOutputType! createdAt: NexusGenScalars['DateTime']; // DateTime! id: number; // Int! name: string; // String! updatedAt: NexusGenScalars['DateTime']; // DateTime! users: NexusGenRootTypes['User'][]; // [User!]! }; GroupAvgAggregateOutputType: { // field return type id: number | null; // Float }; GroupCountAggregateOutputType: { // field return type _all: number; // Int! createdAt: number; // Int! id: number; // Int! name: number; // Int! updatedAt: number; // Int! }; GroupCountOutputType: { // field return type users: number; // Int! }; GroupMaxAggregateOutputType: { // field return type createdAt: NexusGenScalars['DateTime'] | null; // DateTime id: number | null; // Int name: string | null; // String updatedAt: NexusGenScalars['DateTime'] | null; // DateTime }; GroupMinAggregateOutputType: { // field return type createdAt: NexusGenScalars['DateTime'] | null; // DateTime id: number | null; // Int name: string | null; // String updatedAt: NexusGenScalars['DateTime'] | null; // DateTime }; GroupSumAggregateOutputType: { // field return type id: number | null; // Int }; Model: { // field return type create: boolean; // Boolean! delete: boolean; // Boolean! displayFields: string[]; // [String!]! fields: NexusGenRootTypes['Field'][]; // [Field!]! id: string; // String! idField: string; // String! name: string; // String! update: boolean; // Boolean! }; Mutation: { // field return type createOneComment: NexusGenRootTypes['Comment']; // Comment! createOneGroup: NexusGenRootTypes['Group']; // Group! createOnePost: NexusGenRootTypes['Post']; // Post! createOneUser: NexusGenRootTypes['User']; // User! deleteManyComment: NexusGenRootTypes['BatchPayload']; // BatchPayload! deleteManyGroup: NexusGenRootTypes['BatchPayload']; // BatchPayload! deleteManyPost: NexusGenRootTypes['BatchPayload']; // BatchPayload! deleteManyUser: NexusGenRootTypes['BatchPayload']; // BatchPayload! deleteOneComment: NexusGenRootTypes['Comment'] | null; // Comment deleteOneGroup: NexusGenRootTypes['Group'] | null; // Group deleteOnePost: NexusGenRootTypes['Post'] | null; // Post deleteOneUser: NexusGenRootTypes['User'] | null; // User login: NexusGenRootTypes['User'] | null; // User logout: boolean | null; // Boolean signup: NexusGenRootTypes['User'] | null; // User updateField: NexusGenRootTypes['Field']; // Field! updateManyComment: NexusGenRootTypes['BatchPayload']; // BatchPayload! updateManyGroup: NexusGenRootTypes['BatchPayload']; // BatchPayload! updateManyPost: NexusGenRootTypes['BatchPayload']; // BatchPayload! updateManyUser: NexusGenRootTypes['BatchPayload']; // BatchPayload! updateModel: NexusGenRootTypes['Model']; // Model! updateOneComment: NexusGenRootTypes['Comment']; // Comment! updateOneGroup: NexusGenRootTypes['Group']; // Group! updateOnePost: NexusGenRootTypes['Post']; // Post! updateOneUser: NexusGenRootTypes['User']; // User! updatePassword: boolean | null; // Boolean upsertOneComment: NexusGenRootTypes['Comment']; // Comment! upsertOneGroup: NexusGenRootTypes['Group']; // Group! upsertOnePost: NexusGenRootTypes['Post']; // Post! upsertOneUser: NexusGenRootTypes['User']; // User! }; Post: { // field return type _count: NexusGenRootTypes['PostCountOutputType']; // PostCountOutputType! author: NexusGenRootTypes['User'] | null; // User authorId: number | null; // Int comments: NexusGenRootTypes['Comment'][]; // [Comment!]! createdAt: NexusGenScalars['DateTime']; // DateTime! id: number; // Int! published: boolean; // Boolean! title: string; // String! updatedAt: NexusGenScalars['DateTime']; // DateTime! }; PostAvgAggregateOutputType: { // field return type authorId: number | null; // Float id: number | null; // Float }; PostCountAggregateOutputType: { // field return type _all: number; // Int! authorId: number; // Int! createdAt: number; // Int! id: number; // Int! published: number; // Int! title: number; // Int! updatedAt: number; // Int! }; PostCountOutputType: { // field return type comments: number; // Int! }; PostMaxAggregateOutputType: { // field return type authorId: number | null; // Int createdAt: NexusGenScalars['DateTime'] | null; // DateTime id: number | null; // Int published: boolean | null; // Boolean title: string | null; // String updatedAt: NexusGenScalars['DateTime'] | null; // DateTime }; PostMinAggregateOutputType: { // field return type authorId: number | null; // Int createdAt: NexusGenScalars['DateTime'] | null; // DateTime id: number | null; // Int published: boolean | null; // Boolean title: string | null; // String updatedAt: NexusGenScalars['DateTime'] | null; // DateTime }; PostSumAggregateOutputType: { // field return type authorId: number | null; // Int id: number | null; // Int }; Query: { // field return type aggregateComment: NexusGenRootTypes['AggregateComment'] | null; // AggregateComment aggregateGroup: NexusGenRootTypes['AggregateGroup'] | null; // AggregateGroup aggregatePost: NexusGenRootTypes['AggregatePost'] | null; // AggregatePost aggregateUser: NexusGenRootTypes['AggregateUser'] | null; // AggregateUser findFirstComment: NexusGenRootTypes['Comment'] | null; // Comment findFirstGroup: NexusGenRootTypes['Group'] | null; // Group findFirstPost: NexusGenRootTypes['Post'] | null; // Post findFirstUser: NexusGenRootTypes['User'] | null; // User findManyComment: NexusGenRootTypes['Comment'][]; // [Comment!]! findManyCommentCount: number; // Int! findManyGroup: NexusGenRootTypes['Group'][]; // [Group!]! findManyGroupCount: number; // Int! findManyPost: NexusGenRootTypes['Post'][]; // [Post!]! findManyPostCount: number; // Int! findManyUser: NexusGenRootTypes['User'][]; // [User!]! findManyUserCount: number; // Int! findUniqueComment: NexusGenRootTypes['Comment'] | null; // Comment findUniqueGroup: NexusGenRootTypes['Group'] | null; // Group findUniquePost: NexusGenRootTypes['Post'] | null; // Post findUniqueUser: NexusGenRootTypes['User'] | null; // User getSchema: NexusGenRootTypes['Schema']; // Schema! me: NexusGenRootTypes['User'] | null; // User }; Schema: { // field return type enums: NexusGenRootTypes['Enum'][]; // [Enum!]! models: NexusGenRootTypes['Model'][]; // [Model!]! }; User: { // field return type _count: NexusGenRootTypes['UserCountOutputType']; // UserCountOutputType! comments: NexusGenRootTypes['Comment'][]; // [Comment!]! createdAt: NexusGenScalars['DateTime']; // DateTime! email: string; // String! group: NexusGenRootTypes['Group'] | null; // Group groupId: number | null; // Int id: number; // Int! name: string | null; // String password: string; // String! posts: NexusGenRootTypes['Post'][]; // [Post!]! }; UserAvgAggregateOutputType: { // field return type groupId: number | null; // Float id: number | null; // Float }; UserCountAggregateOutputType: { // field return type _all: number; // Int! createdAt: number; // Int! email: number; // Int! groupId: number; // Int! id: number; // Int! name: number; // Int! password: number; // Int! }; UserCountOutputType: { // field return type comments: number; // Int! posts: number; // Int! }; UserMaxAggregateOutputType: { // field return type createdAt: NexusGenScalars['DateTime'] | null; // DateTime email: string | null; // String groupId: number | null; // Int id: number | null; // Int name: string | null; // String password: string | null; // String }; UserMinAggregateOutputType: { // field return type createdAt: NexusGenScalars['DateTime'] | null; // DateTime email: string | null; // String groupId: number | null; // Int id: number | null; // Int name: string | null; // String password: string | null; // String }; UserSumAggregateOutputType: { // field return type groupId: number | null; // Int id: number | null; // Int }; } export interface NexusGenFieldTypeNames { AggregateComment: { // field return type name _avg: 'CommentAvgAggregateOutputType'; _count: 'CommentCountAggregateOutputType'; _max: 'CommentMaxAggregateOutputType'; _min: 'CommentMinAggregateOutputType'; _sum: 'CommentSumAggregateOutputType'; }; AggregateGroup: { // field return type name _avg: 'GroupAvgAggregateOutputType'; _count: 'GroupCountAggregateOutputType'; _max: 'GroupMaxAggregateOutputType'; _min: 'GroupMinAggregateOutputType'; _sum: 'GroupSumAggregateOutputType'; }; AggregatePost: { // field return type name _avg: 'PostAvgAggregateOutputType'; _count: 'PostCountAggregateOutputType'; _max: 'PostMaxAggregateOutputType'; _min: 'PostMinAggregateOutputType'; _sum: 'PostSumAggregateOutputType'; }; AggregateUser: { // field return type name _avg: 'UserAvgAggregateOutputType'; _count: 'UserCountAggregateOutputType'; _max: 'UserMaxAggregateOutputType'; _min: 'UserMinAggregateOutputType'; _sum: 'UserSumAggregateOutputType'; }; BatchPayload: { // field return type name count: 'Int'; }; Comment: { // field return type name author: 'User'; authorId: 'Int'; contain: 'String'; createdAt: 'DateTime'; id: 'Int'; post: 'Post'; postId: 'Int'; updatedAt: 'DateTime'; }; CommentAvgAggregateOutputType: { // field return type name authorId: 'Float'; id: 'Float'; postId: 'Float'; }; CommentCountAggregateOutputType: { // field return type name _all: 'Int'; authorId: 'Int'; contain: 'Int'; createdAt: 'Int'; id: 'Int'; postId: 'Int'; updatedAt: 'Int'; }; CommentMaxAggregateOutputType: { // field return type name authorId: 'Int'; contain: 'String'; createdAt: 'DateTime'; id: 'Int'; postId: 'Int'; updatedAt: 'DateTime'; }; CommentMinAggregateOutputType: { // field return type name authorId: 'Int'; contain: 'String'; createdAt: 'DateTime'; id: 'Int'; postId: 'Int'; updatedAt: 'DateTime'; }; CommentSumAggregateOutputType: { // field return type name authorId: 'Int'; id: 'Int'; postId: 'Int'; }; Enum: { // field return type name fields: 'String'; name: 'String'; }; Field: { // field return type name create: 'Boolean'; editor: 'Boolean'; filter: 'Boolean'; id: 'String'; isId: 'Boolean'; kind: 'KindEnum'; list: 'Boolean'; name: 'String'; order: 'Int'; read: 'Boolean'; relationField: 'Boolean'; required: 'Boolean'; sort: 'Boolean'; title: 'String'; type: 'String'; unique: 'Boolean'; update: 'Boolean'; upload: 'Boolean'; }; Group: { // field return type name _count: 'GroupCountOutputType'; createdAt: 'DateTime'; id: 'Int'; name: 'String'; updatedAt: 'DateTime'; users: 'User'; }; GroupAvgAggregateOutputType: { // field return type name id: 'Float'; }; GroupCountAggregateOutputType: { // field return type name _all: 'Int'; createdAt: 'Int'; id: 'Int'; name: 'Int'; updatedAt: 'Int'; }; GroupCountOutputType: { // field return type name users: 'Int'; }; GroupMaxAggregateOutputType: { // field return type name createdAt: 'DateTime'; id: 'Int'; name: 'String'; updatedAt: 'DateTime'; }; GroupMinAggregateOutputType: { // field return type name createdAt: 'DateTime'; id: 'Int'; name: 'String'; updatedAt: 'DateTime'; }; GroupSumAggregateOutputType: { // field return type name id: 'Int'; }; Model: { // field return type name create: 'Boolean'; delete: 'Boolean'; displayFields: 'String'; fields: 'Field'; id: 'String'; idField: 'String'; name: 'String'; update: 'Boolean'; }; Mutation: { // field return type name createOneComment: 'Comment'; createOneGroup: 'Group'; createOnePost: 'Post'; createOneUser: 'User'; deleteManyComment: 'BatchPayload'; deleteManyGroup: 'BatchPayload'; deleteManyPost: 'BatchPayload'; deleteManyUser: 'BatchPayload'; deleteOneComment: 'Comment'; deleteOneGroup: 'Group'; deleteOnePost: 'Post'; deleteOneUser: 'User'; login: 'User'; logout: 'Boolean'; signup: 'User'; updateField: 'Field'; updateManyComment: 'BatchPayload'; updateManyGroup: 'BatchPayload'; updateManyPost: 'BatchPayload'; updateManyUser: 'BatchPayload'; updateModel: 'Model'; updateOneComment: 'Comment'; updateOneGroup: 'Group'; updateOnePost: 'Post'; updateOneUser: 'User'; updatePassword: 'Boolean'; upsertOneComment: 'Comment'; upsertOneGroup: 'Group'; upsertOnePost: 'Post'; upsertOneUser: 'User'; }; Post: { // field return type name _count: 'PostCountOutputType'; author: 'User'; authorId: 'Int'; comments: 'Comment'; createdAt: 'DateTime'; id: 'Int'; published: 'Boolean'; title: 'String'; updatedAt: 'DateTime'; }; PostAvgAggregateOutputType: { // field return type name authorId: 'Float'; id: 'Float'; }; PostCountAggregateOutputType: { // field return type name _all: 'Int'; authorId: 'Int'; createdAt: 'Int'; id: 'Int'; published: 'Int'; title: 'Int'; updatedAt: 'Int'; }; PostCountOutputType: { // field return type name comments: 'Int'; }; PostMaxAggregateOutputType: { // field return type name authorId: 'Int'; createdAt: 'DateTime'; id: 'Int'; published: 'Boolean'; title: 'String'; updatedAt: 'DateTime'; }; PostMinAggregateOutputType: { // field return type name authorId: 'Int'; createdAt: 'DateTime'; id: 'Int'; published: 'Boolean'; title: 'String'; updatedAt: 'DateTime'; }; PostSumAggregateOutputType: { // field return type name authorId: 'Int'; id: 'Int'; }; Query: { // field return type name aggregateComment: 'AggregateComment'; aggregateGroup: 'AggregateGroup'; aggregatePost: 'AggregatePost'; aggregateUser: 'AggregateUser'; findFirstComment: 'Comment'; findFirstGroup: 'Group'; findFirstPost: 'Post'; findFirstUser: 'User'; findManyComment: 'Comment'; findManyCommentCount: 'Int'; findManyGroup: 'Group'; findManyGroupCount: 'Int'; findManyPost: 'Post'; findManyPostCount: 'Int'; findManyUser: 'User'; findManyUserCount: 'Int'; findUniqueComment: 'Comment'; findUniqueGroup: 'Group'; findUniquePost: 'Post'; findUniqueUser: 'User'; getSchema: 'Schema'; me: 'User'; }; Schema: { // field return type name enums: 'Enum'; models: 'Model'; }; User: { // field return type name _count: 'UserCountOutputType'; comments: 'Comment'; createdAt: 'DateTime'; email: 'String'; group: 'Group'; groupId: 'Int'; id: 'Int'; name: 'String'; password: 'String'; posts: 'Post'; }; UserAvgAggregateOutputType: { // field return type name groupId: 'Float'; id: 'Float'; }; UserCountAggregateOutputType: { // field return type name _all: 'Int'; createdAt: 'Int'; email: 'Int'; groupId: 'Int'; id: 'Int'; name: 'Int'; password: 'Int'; }; UserCountOutputType: { // field return type name comments: 'Int'; posts: 'Int'; }; UserMaxAggregateOutputType: { // field return type name createdAt: 'DateTime'; email: 'String'; groupId: 'Int'; id: 'Int'; name: 'String'; password: 'String'; }; UserMinAggregateOutputType: { // field return type name createdAt: 'DateTime'; email: 'String'; groupId: 'Int'; id: 'Int'; name: 'String'; password: 'String'; }; UserSumAggregateOutputType: { // field return type name groupId: 'Int'; id: 'Int'; }; } export interface NexusGenArgTypes { Group: { users: { // args cursor?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput distinct?: NexusGenEnums['UserScalarFieldEnum'] | null; // UserScalarFieldEnum orderBy?: NexusGenInputs['UserOrderByWithRelationInput'] | null; // UserOrderByWithRelationInput skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; }; Mutation: { createOneComment: { // args data: NexusGenInputs['CommentCreateInput']; // CommentCreateInput! }; createOneGroup: { // args data: NexusGenInputs['GroupCreateInput']; // GroupCreateInput! }; createOnePost: { // args data: NexusGenInputs['PostCreateInput']; // PostCreateInput! }; createOneUser: { // args data: NexusGenInputs['UserCreateInput']; // UserCreateInput! }; deleteManyComment: { // args where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; deleteManyGroup: { // args where?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; deleteManyPost: { // args where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; deleteManyUser: { // args where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; deleteOneComment: { // args where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; deleteOneGroup: { // args where: NexusGenInputs['GroupWhereUniqueInput']; // GroupWhereUniqueInput! }; deleteOnePost: { // args where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; deleteOneUser: { // args where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; login: { // args email: string; // String! password: string; // String! }; signup: { // args email: string; // String! name?: string | null; // String password: string; // String! }; updateField: { // args data: NexusGenInputs['UpdateFieldInput']; // UpdateFieldInput! id: string; // String! modelId: string; // String! }; updateManyComment: { // args data: NexusGenInputs['CommentUpdateManyMutationInput']; // CommentUpdateManyMutationInput! where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; updateManyGroup: { // args data: NexusGenInputs['GroupUpdateManyMutationInput']; // GroupUpdateManyMutationInput! where?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; updateManyPost: { // args data: NexusGenInputs['PostUpdateManyMutationInput']; // PostUpdateManyMutationInput! where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; updateManyUser: { // args data: NexusGenInputs['UserUpdateManyMutationInput']; // UserUpdateManyMutationInput! where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; updateModel: { // args data: NexusGenInputs['UpdateModelInput']; // UpdateModelInput! id: string; // String! }; updateOneComment: { // args data: NexusGenInputs['CommentUpdateInput']; // CommentUpdateInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; updateOneGroup: { // args data: NexusGenInputs['GroupUpdateInput']; // GroupUpdateInput! where: NexusGenInputs['GroupWhereUniqueInput']; // GroupWhereUniqueInput! }; updateOnePost: { // args data: NexusGenInputs['PostUpdateInput']; // PostUpdateInput! where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; updateOneUser: { // args data: NexusGenInputs['UserUpdateInput']; // UserUpdateInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; updatePassword: { // args currentPassword: string; // String! password: string; // String! }; upsertOneComment: { // args create: NexusGenInputs['CommentCreateInput']; // CommentCreateInput! update: NexusGenInputs['CommentUpdateInput']; // CommentUpdateInput! where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; upsertOneGroup: { // args create: NexusGenInputs['GroupCreateInput']; // GroupCreateInput! update: NexusGenInputs['GroupUpdateInput']; // GroupUpdateInput! where: NexusGenInputs['GroupWhereUniqueInput']; // GroupWhereUniqueInput! }; upsertOnePost: { // args create: NexusGenInputs['PostCreateInput']; // PostCreateInput! update: NexusGenInputs['PostUpdateInput']; // PostUpdateInput! where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; upsertOneUser: { // args create: NexusGenInputs['UserCreateInput']; // UserCreateInput! update: NexusGenInputs['UserUpdateInput']; // UserUpdateInput! where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; }; Post: { comments: { // args cursor?: NexusGenInputs['CommentWhereUniqueInput'] | null; // CommentWhereUniqueInput distinct?: NexusGenEnums['CommentScalarFieldEnum'] | null; // CommentScalarFieldEnum orderBy?: NexusGenInputs['CommentOrderByWithRelationInput'] | null; // CommentOrderByWithRelationInput skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; }; Query: { aggregateComment: { // args cursor?: NexusGenInputs['CommentWhereUniqueInput'] | null; // CommentWhereUniqueInput orderBy?: Array<NexusGenInputs['CommentOrderByWithRelationInput'] | null> | null; // [CommentOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; aggregateGroup: { // args cursor?: NexusGenInputs['GroupWhereUniqueInput'] | null; // GroupWhereUniqueInput orderBy?: Array<NexusGenInputs['GroupOrderByWithRelationInput'] | null> | null; // [GroupOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; aggregatePost: { // args cursor?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput orderBy?: Array<NexusGenInputs['PostOrderByWithRelationInput'] | null> | null; // [PostOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; aggregateUser: { // args cursor?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput orderBy?: Array<NexusGenInputs['UserOrderByWithRelationInput'] | null> | null; // [UserOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; findFirstComment: { // args cursor?: NexusGenInputs['CommentWhereUniqueInput'] | null; // CommentWhereUniqueInput distinct?: Array<NexusGenEnums['CommentScalarFieldEnum'] | null> | null; // [CommentScalarFieldEnum] orderBy?: Array<NexusGenInputs['CommentOrderByWithRelationInput'] | null> | null; // [CommentOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; findFirstGroup: { // args cursor?: NexusGenInputs['GroupWhereUniqueInput'] | null; // GroupWhereUniqueInput distinct?: Array<NexusGenEnums['GroupScalarFieldEnum'] | null> | null; // [GroupScalarFieldEnum] orderBy?: Array<NexusGenInputs['GroupOrderByWithRelationInput'] | null> | null; // [GroupOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; findFirstPost: { // args cursor?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput distinct?: Array<NexusGenEnums['PostScalarFieldEnum'] | null> | null; // [PostScalarFieldEnum] orderBy?: Array<NexusGenInputs['PostOrderByWithRelationInput'] | null> | null; // [PostOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; findFirstUser: { // args cursor?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput distinct?: Array<NexusGenEnums['UserScalarFieldEnum'] | null> | null; // [UserScalarFieldEnum] orderBy?: Array<NexusGenInputs['UserOrderByWithRelationInput'] | null> | null; // [UserOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; findManyComment: { // args cursor?: NexusGenInputs['CommentWhereUniqueInput'] | null; // CommentWhereUniqueInput distinct?: Array<NexusGenEnums['CommentScalarFieldEnum'] | null> | null; // [CommentScalarFieldEnum] orderBy?: Array<NexusGenInputs['CommentOrderByWithRelationInput'] | null> | null; // [CommentOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; findManyCommentCount: { // args cursor?: NexusGenInputs['CommentWhereUniqueInput'] | null; // CommentWhereUniqueInput distinct?: Array<NexusGenEnums['CommentScalarFieldEnum'] | null> | null; // [CommentScalarFieldEnum] orderBy?: Array<NexusGenInputs['CommentOrderByWithRelationInput'] | null> | null; // [CommentOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; findManyGroup: { // args cursor?: NexusGenInputs['GroupWhereUniqueInput'] | null; // GroupWhereUniqueInput distinct?: Array<NexusGenEnums['GroupScalarFieldEnum'] | null> | null; // [GroupScalarFieldEnum] orderBy?: Array<NexusGenInputs['GroupOrderByWithRelationInput'] | null> | null; // [GroupOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; findManyGroupCount: { // args cursor?: NexusGenInputs['GroupWhereUniqueInput'] | null; // GroupWhereUniqueInput distinct?: Array<NexusGenEnums['GroupScalarFieldEnum'] | null> | null; // [GroupScalarFieldEnum] orderBy?: Array<NexusGenInputs['GroupOrderByWithRelationInput'] | null> | null; // [GroupOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['GroupWhereInput'] | null; // GroupWhereInput }; findManyPost: { // args cursor?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput distinct?: Array<NexusGenEnums['PostScalarFieldEnum'] | null> | null; // [PostScalarFieldEnum] orderBy?: Array<NexusGenInputs['PostOrderByWithRelationInput'] | null> | null; // [PostOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; findManyPostCount: { // args cursor?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput distinct?: Array<NexusGenEnums['PostScalarFieldEnum'] | null> | null; // [PostScalarFieldEnum] orderBy?: Array<NexusGenInputs['PostOrderByWithRelationInput'] | null> | null; // [PostOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; findManyUser: { // args cursor?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput distinct?: Array<NexusGenEnums['UserScalarFieldEnum'] | null> | null; // [UserScalarFieldEnum] orderBy?: Array<NexusGenInputs['UserOrderByWithRelationInput'] | null> | null; // [UserOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; findManyUserCount: { // args cursor?: NexusGenInputs['UserWhereUniqueInput'] | null; // UserWhereUniqueInput distinct?: Array<NexusGenEnums['UserScalarFieldEnum'] | null> | null; // [UserScalarFieldEnum] orderBy?: Array<NexusGenInputs['UserOrderByWithRelationInput'] | null> | null; // [UserOrderByWithRelationInput] skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['UserWhereInput'] | null; // UserWhereInput }; findUniqueComment: { // args where: NexusGenInputs['CommentWhereUniqueInput']; // CommentWhereUniqueInput! }; findUniqueGroup: { // args where: NexusGenInputs['GroupWhereUniqueInput']; // GroupWhereUniqueInput! }; findUniquePost: { // args where: NexusGenInputs['PostWhereUniqueInput']; // PostWhereUniqueInput! }; findUniqueUser: { // args where: NexusGenInputs['UserWhereUniqueInput']; // UserWhereUniqueInput! }; }; User: { comments: { // args cursor?: NexusGenInputs['CommentWhereUniqueInput'] | null; // CommentWhereUniqueInput distinct?: NexusGenEnums['CommentScalarFieldEnum'] | null; // CommentScalarFieldEnum orderBy?: NexusGenInputs['CommentOrderByWithRelationInput'] | null; // CommentOrderByWithRelationInput skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['CommentWhereInput'] | null; // CommentWhereInput }; posts: { // args cursor?: NexusGenInputs['PostWhereUniqueInput'] | null; // PostWhereUniqueInput distinct?: NexusGenEnums['PostScalarFieldEnum'] | null; // PostScalarFieldEnum orderBy?: NexusGenInputs['PostOrderByWithRelationInput'] | null; // PostOrderByWithRelationInput skip?: number | null; // Int take?: number | null; // Int where?: NexusGenInputs['PostWhereInput'] | null; // PostWhereInput }; }; } export interface NexusGenAbstractTypeMembers {} export interface NexusGenTypeInterfaces {} export type NexusGenObjectNames = keyof NexusGenObjects; export type NexusGenInputNames = keyof NexusGenInputs; export type NexusGenEnumNames = keyof NexusGenEnums; export type NexusGenInterfaceNames = never; export type NexusGenScalarNames = keyof NexusGenScalars; export type NexusGenUnionNames = never; export type NexusGenObjectsUsingAbstractStrategyIsTypeOf = never; export type NexusGenAbstractsUsingStrategyResolveType = never; export type NexusGenFeaturesConfig = { abstractTypeStrategies: { isTypeOf: false; resolveType: true; __typename: false; }; }; export interface NexusGenTypes { context: Context; inputTypes: NexusGenInputs; rootTypes: NexusGenRootTypes; inputTypeShapes: NexusGenInputs & NexusGenEnums & NexusGenScalars; argTypes: NexusGenArgTypes; fieldTypes: NexusGenFieldTypes; fieldTypeNames: NexusGenFieldTypeNames; allTypes: NexusGenAllTypes; typeInterfaces: NexusGenTypeInterfaces; objectNames: NexusGenObjectNames; inputNames: NexusGenInputNames; enumNames: NexusGenEnumNames; interfaceNames: NexusGenInterfaceNames; scalarNames: NexusGenScalarNames; unionNames: NexusGenUnionNames; allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames']; allOutputTypes: | NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames']; allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes']; abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames']; abstractTypeMembers: NexusGenAbstractTypeMembers; objectsUsingAbstractStrategyIsTypeOf: NexusGenObjectsUsingAbstractStrategyIsTypeOf; abstractsUsingStrategyResolveType: NexusGenAbstractsUsingStrategyResolveType; features: NexusGenFeaturesConfig; } declare global { interface NexusGenPluginTypeConfig<TypeName extends string> {} interface NexusGenPluginInputTypeConfig<TypeName extends string> {} interface NexusGenPluginFieldConfig<TypeName extends string, FieldName extends string> {} interface NexusGenPluginInputFieldConfig<TypeName extends string, FieldName extends string> {} interface NexusGenPluginSchemaConfig {} interface NexusGenPluginArgConfig {} }
the_stack
import { $, append, clearNode, createStyleSheet, getContentHeight, getContentWidth } from 'vs/base/browser/dom'; import { IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; import { IListOptions, IListOptionsUpdate, IListStyles, List } from 'vs/base/browser/ui/list/listWidget'; import { ISplitViewDescriptor, IView, Orientation, SplitView } from 'vs/base/browser/ui/splitview/splitview'; import { ITableColumn, ITableContextMenuEvent, ITableEvent, ITableGestureEvent, ITableMouseEvent, ITableRenderer, ITableTouchEvent, ITableVirtualDelegate } from 'vs/base/browser/ui/table/table'; import { Emitter, Event } from 'vs/base/common/event'; import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle'; import { ScrollbarVisibility, ScrollEvent } from 'vs/base/common/scrollable'; import { ISpliceable } from 'vs/base/common/sequence'; import { IThemable } from 'vs/base/common/styler'; import 'vs/css!./table'; // TODO@joao type TCell = any; interface RowTemplateData { readonly container: HTMLElement; readonly cellContainers: HTMLElement[]; readonly cellTemplateData: unknown[]; } class TableListRenderer<TRow> implements IListRenderer<TRow, RowTemplateData> { static TemplateId = 'row'; readonly templateId = TableListRenderer.TemplateId; private renderers: ITableRenderer<TCell, unknown>[]; private renderedTemplates = new Set<RowTemplateData>(); constructor( private columns: ITableColumn<TRow, TCell>[], renderers: ITableRenderer<TCell, unknown>[], private getColumnSize: (index: number) => number ) { const rendererMap = new Map(renderers.map(r => [r.templateId, r])); this.renderers = []; for (const column of columns) { const renderer = rendererMap.get(column.templateId); if (!renderer) { throw new Error(`Table cell renderer for template id ${column.templateId} not found.`); } this.renderers.push(renderer); } } renderTemplate(container: HTMLElement) { const rowContainer = append(container, $('.monaco-table-tr')); const cellContainers: HTMLElement[] = []; const cellTemplateData: unknown[] = []; for (let i = 0; i < this.columns.length; i++) { const renderer = this.renderers[i]; const cellContainer = append(rowContainer, $('.monaco-table-td', { 'data-col-index': i })); cellContainer.style.width = `${this.getColumnSize(i)}px`; cellContainers.push(cellContainer); cellTemplateData.push(renderer.renderTemplate(cellContainer)); } const result = { container, cellContainers, cellTemplateData }; this.renderedTemplates.add(result); return result; } renderElement(element: TRow, index: number, templateData: RowTemplateData, height: number | undefined): void { for (let i = 0; i < this.columns.length; i++) { const column = this.columns[i]; const cell = column.project(element); const renderer = this.renderers[i]; renderer.renderElement(cell, index, templateData.cellTemplateData[i], height); } } disposeElement(element: TRow, index: number, templateData: RowTemplateData, height: number | undefined): void { for (let i = 0; i < this.columns.length; i++) { const renderer = this.renderers[i]; if (renderer.disposeElement) { const column = this.columns[i]; const cell = column.project(element); renderer.disposeElement(cell, index, templateData.cellTemplateData[i], height); } } } disposeTemplate(templateData: RowTemplateData): void { for (let i = 0; i < this.columns.length; i++) { const renderer = this.renderers[i]; renderer.disposeTemplate(templateData.cellTemplateData[i]); } clearNode(templateData.container); this.renderedTemplates.delete(templateData); } layoutColumn(index: number, size: number): void { for (const { cellContainers } of this.renderedTemplates) { cellContainers[index].style.width = `${size}px`; } } } function asListVirtualDelegate<TRow>(delegate: ITableVirtualDelegate<TRow>): IListVirtualDelegate<TRow> { return { getHeight(row) { return delegate.getHeight(row); }, getTemplateId() { return TableListRenderer.TemplateId; }, }; } class ColumnHeader<TRow, TCell> implements IView { readonly element: HTMLElement; get minimumSize() { return this.column.minimumWidth ?? 120; } get maximumSize() { return this.column.maximumWidth ?? Number.POSITIVE_INFINITY; } get onDidChange() { return this.column.onDidChangeWidthConstraints ?? Event.None; } private _onDidLayout = new Emitter<[number, number]>(); readonly onDidLayout = this._onDidLayout.event; constructor(readonly column: ITableColumn<TRow, TCell>, private index: number) { this.element = $('.monaco-table-th', { 'data-col-index': index, title: column.tooltip }, column.label); } layout(size: number): void { this._onDidLayout.fire([this.index, size]); } } export interface ITableOptions<TRow> extends IListOptions<TRow> { } export interface ITableOptionsUpdate extends IListOptionsUpdate { } export interface ITableStyles extends IListStyles { } export class Table<TRow> implements ISpliceable<TRow>, IThemable, IDisposable { private static InstanceCount = 0; readonly domId = `table_id_${++Table.InstanceCount}`; readonly domNode: HTMLElement; private splitview: SplitView; private list: List<TRow>; private styleElement: HTMLStyleElement; protected readonly disposables = new DisposableStore(); private cachedWidth: number = 0; private cachedHeight: number = 0; get onDidChangeFocus(): Event<ITableEvent<TRow>> { return this.list.onDidChangeFocus; } get onDidChangeSelection(): Event<ITableEvent<TRow>> { return this.list.onDidChangeSelection; } get onDidScroll(): Event<ScrollEvent> { return this.list.onDidScroll; } get onMouseClick(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseClick; } get onMouseDblClick(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseDblClick; } get onMouseMiddleClick(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseMiddleClick; } get onPointer(): Event<ITableMouseEvent<TRow>> { return this.list.onPointer; } get onMouseUp(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseUp; } get onMouseDown(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseDown; } get onMouseOver(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseOver; } get onMouseMove(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseMove; } get onMouseOut(): Event<ITableMouseEvent<TRow>> { return this.list.onMouseOut; } get onTouchStart(): Event<ITableTouchEvent<TRow>> { return this.list.onTouchStart; } get onTap(): Event<ITableGestureEvent<TRow>> { return this.list.onTap; } get onContextMenu(): Event<ITableContextMenuEvent<TRow>> { return this.list.onContextMenu; } get onDidFocus(): Event<void> { return this.list.onDidFocus; } get onDidBlur(): Event<void> { return this.list.onDidBlur; } get scrollTop(): number { return this.list.scrollTop; } set scrollTop(scrollTop: number) { this.list.scrollTop = scrollTop; } get scrollLeft(): number { return this.list.scrollLeft; } set scrollLeft(scrollLeft: number) { this.list.scrollLeft = scrollLeft; } get scrollHeight(): number { return this.list.scrollHeight; } get renderHeight(): number { return this.list.renderHeight; } get onDidDispose(): Event<void> { return this.list.onDidDispose; } constructor( user: string, container: HTMLElement, private virtualDelegate: ITableVirtualDelegate<TRow>, columns: ITableColumn<TRow, TCell>[], renderers: ITableRenderer<TCell, unknown>[], _options?: ITableOptions<TRow> ) { this.domNode = append(container, $(`.monaco-table.${this.domId}`)); const headers = columns.map((c, i) => new ColumnHeader(c, i)); const descriptor: ISplitViewDescriptor = { size: headers.reduce((a, b) => a + b.column.weight, 0), views: headers.map(view => ({ size: view.column.weight, view })) }; this.splitview = this.disposables.add(new SplitView(this.domNode, { orientation: Orientation.HORIZONTAL, scrollbarVisibility: ScrollbarVisibility.Hidden, getSashOrthogonalSize: () => this.cachedHeight, descriptor })); this.splitview.el.style.height = `${virtualDelegate.headerRowHeight}px`; this.splitview.el.style.lineHeight = `${virtualDelegate.headerRowHeight}px`; const renderer = new TableListRenderer(columns, renderers, i => this.splitview.getViewSize(i)); this.list = this.disposables.add(new List(user, this.domNode, asListVirtualDelegate(virtualDelegate), [renderer], _options)); Event.any(...headers.map(h => h.onDidLayout)) (([index, size]) => renderer.layoutColumn(index, size), null, this.disposables); this.splitview.onDidSashReset(index => { const totalWeight = columns.reduce((r, c) => r + c.weight, 0); const size = columns[index].weight / totalWeight * this.cachedWidth; this.splitview.resizeView(index, size); }, null, this.disposables); this.styleElement = createStyleSheet(this.domNode); this.style({}); } updateOptions(options: ITableOptionsUpdate): void { this.list.updateOptions(options); } splice(start: number, deleteCount: number, elements: TRow[] = []): void { this.list.splice(start, deleteCount, elements); } rerender(): void { this.list.rerender(); } row(index: number): TRow { return this.list.element(index); } indexOf(element: TRow): number { return this.list.indexOf(element); } get length(): number { return this.list.length; } getHTMLElement(): HTMLElement { return this.domNode; } layout(height?: number, width?: number): void { height = height ?? getContentHeight(this.domNode); width = width ?? getContentWidth(this.domNode); this.cachedWidth = width; this.cachedHeight = height; this.splitview.layout(width); const listHeight = height - this.virtualDelegate.headerRowHeight; this.list.getHTMLElement().style.height = `${listHeight}px`; this.list.layout(listHeight, width); } toggleKeyboardNavigation(): void { this.list.toggleKeyboardNavigation(); } style(styles: ITableStyles): void { const content: string[] = []; content.push(`.monaco-table.${this.domId} > .monaco-split-view2 .monaco-sash.vertical::before { top: ${this.virtualDelegate.headerRowHeight + 1}px; height: calc(100% - ${this.virtualDelegate.headerRowHeight}px); }`); this.styleElement.textContent = content.join('\n'); this.list.style(styles); } domFocus(): void { this.list.domFocus(); } setAnchor(index: number | undefined): void { this.list.setAnchor(index); } getAnchor(): number | undefined { return this.list.getAnchor(); } getSelectedElements(): TRow[] { return this.list.getSelectedElements(); } setSelection(indexes: number[], browserEvent?: UIEvent): void { this.list.setSelection(indexes, browserEvent); } getSelection(): number[] { return this.list.getSelection(); } setFocus(indexes: number[], browserEvent?: UIEvent): void { this.list.setFocus(indexes, browserEvent); } focusNext(n = 1, loop = false, browserEvent?: UIEvent): void { this.list.focusNext(n, loop, browserEvent); } focusPrevious(n = 1, loop = false, browserEvent?: UIEvent): void { this.list.focusPrevious(n, loop, browserEvent); } focusNextPage(browserEvent?: UIEvent): Promise<void> { return this.list.focusNextPage(browserEvent); } focusPreviousPage(browserEvent?: UIEvent): Promise<void> { return this.list.focusPreviousPage(browserEvent); } focusFirst(browserEvent?: UIEvent): void { this.list.focusFirst(browserEvent); } focusLast(browserEvent?: UIEvent): void { this.list.focusLast(browserEvent); } getFocus(): number[] { return this.list.getFocus(); } getFocusedElements(): TRow[] { return this.list.getFocusedElements(); } reveal(index: number, relativeTop?: number): void { this.list.reveal(index, relativeTop); } dispose(): void { this.disposables.dispose(); } }
the_stack
import { coins, makeSignDoc, Secp256k1HdWallet } from "@cosmjs/amino"; import { sleep } from "@cosmjs/utils"; import { assertIsBroadcastTxSuccess } from "../cosmosclient"; import { SigningCosmosClient } from "../signingcosmosclient"; import { dateTimeStampMatcher, faucet, launchpad, launchpadEnabled, nonNegativeIntegerMatcher, pendingWithoutLaunchpad, } from "../testutils.spec"; import { GovExtension, GovParametersType, setupGovExtension } from "./gov"; import { LcdClient } from "./lcdclient"; function makeGovClient(apiUrl: string): LcdClient & GovExtension { return LcdClient.withExtensions({ apiUrl }, setupGovExtension); } describe("GovExtension", () => { const defaultFee = { amount: coins(25000, "ucosm"), gas: "1500000", // 1.5 million }; let proposalId: string; beforeAll(async () => { if (launchpadEnabled()) { const wallet = await Secp256k1HdWallet.fromMnemonic(faucet.mnemonic); const client = new SigningCosmosClient(launchpad.endpoint, faucet.address0, wallet); const chainId = await client.getChainId(); const proposalMsg = { type: "cosmos-sdk/MsgSubmitProposal", value: { content: { type: "cosmos-sdk/TextProposal", value: { description: "This proposal proposes to test whether this proposal passes", title: "Test Proposal", }, }, proposer: faucet.address0, initial_deposit: coins(25000000, "ustake"), }, }; const proposalMemo = "Test proposal for wasmd"; const { accountNumber: proposalAccountNumber, sequence: proposalSequence } = await client.getSequence(); const proposalSignDoc = makeSignDoc( [proposalMsg], defaultFee, chainId, proposalMemo, proposalAccountNumber, proposalSequence, ); const { signature: proposalSignature } = await wallet.signAmino(faucet.address0, proposalSignDoc); const proposalTx = { msg: [proposalMsg], fee: defaultFee, memo: proposalMemo, signatures: [proposalSignature], }; const proposalResult = await client.broadcastTx(proposalTx); assertIsBroadcastTxSuccess(proposalResult); proposalId = proposalResult.logs[0].events .find(({ type }) => type === "submit_proposal")! .attributes.find(({ key }) => key === "proposal_id")!.value; const voteMsg = { type: "cosmos-sdk/MsgVote", value: { proposal_id: proposalId, voter: faucet.address0, option: "Yes", }, }; const voteMemo = "Test vote for wasmd"; const { accountNumber: voteAccountNumber, sequence: voteSequence } = await client.getSequence(); const voteSignDoc = makeSignDoc( [voteMsg], defaultFee, chainId, voteMemo, voteAccountNumber, voteSequence, ); const { signature: voteSignature } = await wallet.signAmino(faucet.address0, voteSignDoc); const voteTx = { msg: [voteMsg], fee: defaultFee, memo: voteMemo, signatures: [voteSignature], }; await client.broadcastTx(voteTx); await sleep(75); // wait until transactions are indexed } }); describe("parameters", () => { it("works for deposit", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const paramsType = GovParametersType.Deposit; const response = await client.gov.parameters(paramsType); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { min_deposit: [{ denom: "ustake", amount: "10000000" }], max_deposit_period: "172800000000000", }, }); }); it("works for tallying", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const paramsType = GovParametersType.Tallying; const response = await client.gov.parameters(paramsType); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { quorum: "0.334000000000000000", threshold: "0.500000000000000000", veto: "0.334000000000000000", }, }); }); it("works for voting", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const paramsType = GovParametersType.Voting; const response = await client.gov.parameters(paramsType); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { voting_period: "172800000000000", }, }); }); }); describe("proposals", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.proposals(); expect(response.height).toMatch(nonNegativeIntegerMatcher); expect(response.result.length).toBeGreaterThanOrEqual(1); expect(response.result[response.result.length - 1]).toEqual({ content: { type: "cosmos-sdk/TextProposal", value: { title: "Test Proposal", description: "This proposal proposes to test whether this proposal passes", }, }, id: proposalId, proposal_status: "VotingPeriod", final_tally_result: { yes: "0", abstain: "0", no: "0", no_with_veto: "0" }, submit_time: jasmine.stringMatching(dateTimeStampMatcher), deposit_end_time: jasmine.stringMatching(dateTimeStampMatcher), total_deposit: [{ denom: "ustake", amount: "25000000" }], voting_start_time: jasmine.stringMatching(dateTimeStampMatcher), voting_end_time: jasmine.stringMatching(dateTimeStampMatcher), }); }); }); describe("proposal", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.proposal(proposalId); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { content: { type: "cosmos-sdk/TextProposal", value: { title: "Test Proposal", description: "This proposal proposes to test whether this proposal passes", }, }, id: proposalId, proposal_status: "VotingPeriod", final_tally_result: { yes: "0", abstain: "0", no: "0", no_with_veto: "0" }, submit_time: jasmine.stringMatching(dateTimeStampMatcher), deposit_end_time: jasmine.stringMatching(dateTimeStampMatcher), total_deposit: [{ denom: "ustake", amount: "25000000" }], voting_start_time: jasmine.stringMatching(dateTimeStampMatcher), voting_end_time: jasmine.stringMatching(dateTimeStampMatcher), }, }); }); }); describe("proposer", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.proposer(proposalId); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { proposal_id: proposalId, proposer: faucet.address0, }, }); }); }); describe("deposits", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.deposits(proposalId); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: [ { proposal_id: proposalId, depositor: faucet.address0, amount: [{ denom: "ustake", amount: "25000000" }], }, ], }); }); }); describe("deposit", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.deposit(proposalId, faucet.address0); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { proposal_id: proposalId, depositor: faucet.address0, amount: [{ denom: "ustake", amount: "25000000" }], }, }); }); }); describe("tally", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.tally(proposalId); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { yes: jasmine.stringMatching(nonNegativeIntegerMatcher), abstain: jasmine.stringMatching(nonNegativeIntegerMatcher), no: jasmine.stringMatching(nonNegativeIntegerMatcher), no_with_veto: jasmine.stringMatching(nonNegativeIntegerMatcher), }, }); }); }); describe("votes", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.votes(proposalId); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: [ { proposal_id: proposalId, voter: faucet.address0, option: "Yes", }, ], }); }); }); describe("vote", () => { it("works", async () => { pendingWithoutLaunchpad(); const client = makeGovClient(launchpad.endpoint); const response = await client.gov.vote(proposalId, faucet.address0); expect(response).toEqual({ height: jasmine.stringMatching(nonNegativeIntegerMatcher), result: { voter: faucet.address0, proposal_id: proposalId, option: "Yes", }, }); }); }); });
the_stack
import { Request, RequestHandler } from 'express'; declare global { namespace Express { namespace Multer { /** Object containing file metadata and access information. */ interface File { /** Name of the form field associated with this file. */ fieldname: string; /** Name of the file on the uploader's computer. */ originalname: string; /** * Value of the `Content-Transfer-Encoding` header for this file. * @deprecated since July 2015 * @see RFC 7578, Section 4.7 */ encoding: string; /** Value of the `Content-Type` header for this file. */ mimetype: string; /** Size of the file in bytes. */ size: number; /** `DiskStorage` Directory to which this file has been uploaded. */ destination: string; /** `DiskStorage` Name of this file within `destination`. */ filename: string; /** `DiskStorage` Full path to the uploaded file. */ path: string; /** `MemoryStorage` A Buffer containing the entire file. */ buffer: Buffer; } } interface Request { /** `Multer.File` object populated by `single()` middleware. */ file: Multer.File; /** * Array or dictionary of `Multer.File` object populated by `array()`, * `fields()`, and `any()` middleware. */ files: { [fieldname: string]: Multer.File[]; } | Multer.File[]; } } } declare class Multer { /** * Returns middleware that processes a single file associated with the * given form field. * * The `Request` object will be populated with a `file` object containing * information about the processed file. * * @param fieldName Name of the multipart form field to process. */ single(fieldName: string): RequestHandler; /** * Returns middleware that processes multiple files sharing the same field * name. * * The `Request` object will be populated with a `files` array containing * an information object for each processed file. * * @param fieldName Shared name of the multipart form fields to process. * @param maxCount Optional. Maximum number of files to process. (default: Infinity) * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` */ array(fieldName: string, maxCount?: number): RequestHandler; /** * Returns middleware that processes multiple files associated with the * given form fields. * * The `Request` object will be populated with a `files` object which * maps each field name to an array of the associated file information * objects. * * @param fields Array of `Field` objects describing multipart form fields to process. * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` for any field. */ fields(fields: ReadonlyArray<multer.Field>): RequestHandler; /** * Returns middleware that processes all files contained in the multipart * request. * * The `Request` object will be populated with a `files` array containing * an information object for each processed file. */ any(): RequestHandler; /** * Returns middleware that accepts only non-file multipart form fields. * * @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if any file is encountered. */ none(): RequestHandler; } /** * Returns a Multer instance that provides several methods for generating * middleware that process files uploaded in `multipart/form-data` format. * * The `StorageEngine` specified in `storage` will be used to store files. If * `storage` is not set and `dest` is, files will be stored in `dest` on the * local file system with random names. If neither are set, files will be stored * in memory. * * In addition to files, all generated middleware process all text fields in * the request. For each non-file field, the `Request.body` object will be * populated with an entry mapping the field name to its string value, or array * of string values if multiple fields share the same name. */ declare function multer(options?: multer.Options): Multer; declare namespace multer { /** * Returns a `StorageEngine` implementation configured to store files on * the local file system. * * A string or function may be specified to determine the destination * directory, and a function to determine filenames. If no options are set, * files will be stored in the system's temporary directory with random 32 * character filenames. */ function diskStorage(options: DiskStorageOptions): StorageEngine; /** * Returns a `StorageEngine` implementation configured to store files in * memory as `Buffer` objects. */ function memoryStorage(): StorageEngine; type ErrorCode = | 'LIMIT_PART_COUNT' | 'LIMIT_FILE_SIZE' | 'LIMIT_FILE_COUNT' | 'LIMIT_FIELD_KEY' | 'LIMIT_FIELD_VALUE' | 'LIMIT_FIELD_COUNT' | 'LIMIT_UNEXPECTED_FILE'; class MulterError extends Error { constructor(code: ErrorCode, field?: string); /** Name of the MulterError constructor. */ name: string; /** Identifying error code. */ code: ErrorCode; /** Descriptive error message. */ message: string; /** Name of the multipart form field associated with this error. */ field?: string; } /** * a function to control which files should be uploaded and which should be skipped * pass a boolean to indicate if the file should be accepted * pass an error if something goes wrong */ interface FileFilterCallback { (error: Error): void; (error: null, acceptFile: boolean): void; } /** Options for initializing a Multer instance. */ interface Options { /** * A `StorageEngine` responsible for processing files uploaded via Multer. * Takes precedence over `dest`. */ storage?: StorageEngine; /** * The destination directory for uploaded files. If `storage` is not set * and `dest` is, Multer will create a `DiskStorage` instance configured * to store files at `dest` with random filenames. * * Ignored if `storage` is set. */ dest?: string; /** * An object specifying various limits on incoming data. This object is * passed to Busboy directly, and the details of properties can be found * at https://github.com/mscdex/busboy#busboy-methods. */ limits?: { /** Maximum size of each form field name in bytes. (Default: 100) */ fieldNameSize?: number; /** Maximum size of each form field value in bytes. (Default: 1048576) */ fieldSize?: number; /** Maximum number of non-file form fields. (Default: Infinity) */ fields?: number; /** Maximum size of each file in bytes. (Default: Infinity) */ fileSize?: number; /** Maximum number of file fields. (Default: Infinity) */ files?: number; /** Maximum number of parts (non-file fields + files). (Default: Infinity) */ parts?: number; /** Maximum number of headers. (Default: 2000) */ headerPairs?: number; }; /** Preserve the full path of the original filename rather than the basename. (Default: false) */ preservePath?: boolean; /** * Optional function to control which files are uploaded. This is called * for every file that is processed. * * @param req The Express `Request` object. * @param file Object containing information about the processed file. * @param callback a function to control which files should be uploaded and which should be skipped. */ fileFilter?( req: Request, file: Express.Multer.File, callback: FileFilterCallback, ): void; } /** * Implementations of this interface are responsible for storing files * encountered by Multer and returning information on how to access them * once stored. Implementations must also provide a method for removing * files in the event that an error occurs. */ interface StorageEngine { /** * Store the file described by `file`, then invoke the callback with * information about the stored file. * * File contents are available as a stream via `file.stream`. Information * passed to the callback will be merged with `file` for subsequent * middleware. * * @param req The Express `Request` object. * @param file Object with `stream`, `fieldname`, `originalname`, `encoding`, and `mimetype` defined. * @param callback Callback to specify file information. */ _handleFile( req: Request, file: Express.Multer.File, callback: (error?: any, info?: Partial<Express.Multer.File>) => void ): void; /** * Remove the file described by `file`, then invoke the callback with. * * `file` contains all the properties available to `_handleFile`, as * well as those returned by `_handleFile`. * * @param req The Express `Request` object. * @param file Object containing information about the processed file. * @param callback Callback to indicate completion. */ _removeFile( req: Request, file: Express.Multer.File, callback: (error: Error) => void ): void; } interface DiskStorageOptions { /** * A string or function that determines the destination path for uploaded * files. If a string is passed and the directory does not exist, Multer * attempts to create it recursively. If neither a string or a function * is passed, the destination defaults to `os.tmpdir()`. * * @param req The Express `Request` object. * @param file Object containing information about the processed file. * @param callback Callback to determine the destination path. */ destination?: string | (( req: Request, file: Express.Multer.File, callback: (error: Error | null, destination: string) => void ) => void); /** * A function that determines the name of the uploaded file. If nothing * is passed, Multer will generate a 32 character pseudorandom hex string * with no extension. * * @param req The Express `Request` object. * @param file Object containing information about the processed file. * @param callback Callback to determine the name of the uploaded file. */ filename?( req: Request, file: Express.Multer.File, callback: (error: Error | null, filename: string) => void ): void; } /** * An object describing a field name and the maximum number of files with * that field name to accept. */ interface Field { /** The field name. */ name: string; /** Optional maximum number of files per field to accept. (Default: Infinity) */ maxCount?: number; } } export = multer;
the_stack
import { Color, CanvasTexture, Vector3, Matrix4 } from 'three' import '../shader/SDFFont.vert' import '../shader/SDFFont.frag' import { BufferRegistry } from '../globals' import { createParams } from '../utils' import MappedQuadBuffer from './mappedquad-buffer' import { IgnorePicker } from '../utils/picker' import { edt } from '../utils/edt' import { BufferDefaultParameters, BufferParameterTypes, BufferData, BufferTypes } from './buffer' const TextAtlasCache: { [k: string]: TextAtlas } = {} function getTextAtlas (params: Partial<TextAtlasParams>) { const hash = JSON.stringify(params) if (TextAtlasCache[ hash ] === undefined) { TextAtlasCache[ hash ] = new TextAtlas(params) } return TextAtlasCache[ hash ] } type TextFonts = 'sans-serif'|'monospace'|'serif' type TextStyles = 'normal'|'italic' type TextVariants = 'normal' type TextWeights = 'normal'|'bold' export const TextAtlasDefaultParams = { font: 'sans-serif' as TextFonts, size: 36, style: 'normal' as TextStyles, variant: 'normal' as TextVariants, weight: 'normal' as TextWeights, outline: 3, width: 1024, height: 1024 } export type TextAtlasParams = typeof TextAtlasDefaultParams export type TextAtlasMap = { x: number, y: number, w: number, h: number } export class TextAtlas { parameters: TextAtlasParams gamma = 1 mapped: { [k: string]: TextAtlasMap } = {} scratchW = 0 scratchH = 0 currentX = 0 currentY = 0 cutoff = 0.25 padding: number radius: number gridOuter: Float64Array gridInner: Float64Array f: Float64Array d: Float64Array z: Float64Array v: Int16Array paddedSize: number middle: number texture: CanvasTexture canvas: HTMLCanvasElement context: CanvasRenderingContext2D lineHeight: number maxWidth: number colors: string[] scratch: Uint8Array canvas2: HTMLCanvasElement context2: CanvasRenderingContext2D data: Uint8Array placeholder: TextAtlasMap constructor (params: Partial<TextAtlasParams> = {}) { this.parameters = createParams(params, TextAtlasDefaultParams) const p = this.parameters this.radius = p.size / 8 this.padding = p.size / 3 // Prepare line-height with room for outline and descenders/ascenders const lineHeight = this.lineHeight = p.size + 2 * p.outline + Math.round(p.size / 4) const maxWidth = this.maxWidth = p.width / 4 // Prepare scratch canvas const canvas = this.canvas = document.createElement('canvas') canvas.width = maxWidth canvas.height = lineHeight const ctx = this.context = this.canvas.getContext('2d')! ctx.font = `${p.style} ${p.variant} ${p.weight} ${p.size}px ${p.font}` ctx.fillStyle = 'black' ctx.textAlign = 'left' ctx.textBaseline = 'bottom' ctx.lineJoin = 'round' // temporary arrays for the distance transform this.gridOuter = new Float64Array(lineHeight * maxWidth) this.gridInner = new Float64Array(lineHeight * maxWidth) this.f = new Float64Array(Math.max(lineHeight, maxWidth)) this.d = new Float64Array(Math.max(lineHeight, maxWidth)) this.z = new Float64Array(Math.max(lineHeight, maxWidth) + 1) this.v = new Int16Array(Math.max(lineHeight, maxWidth)) // this.data = new Uint8Array(p.width * p.height * 4) this.canvas2 = document.createElement('canvas') this.canvas2.width = p.width this.canvas2.height = p.height this.context2 = this.canvas2.getContext('2d')! // Replacement Character this.placeholder = this.map(String.fromCharCode(0xFFFD)) // Basic Latin (subset) for (let i = 0x0020; i <= 0x007E; ++i) { this.map(String.fromCharCode(i)) } // TODO: to slow to always prepare them // // Latin-1 Supplement (subset) // for (let i = 0x00A1; i <= 0x00FF; ++i) { // this.map(String.fromCharCode(i)) // } // Degree sign this.map(String.fromCharCode(0x00B0)) // // Greek and Coptic (subset) // for (let i = 0x0391; i <= 0x03C9; ++i) { // this.map(String.fromCharCode(i)) // } // // Cyrillic (subset) // for (let i = 0x0400; i <= 0x044F; ++i) { // this.map(String.fromCharCode(i)) // } // Angstrom Sign this.map(String.fromCharCode(0x212B)) this.texture = new CanvasTexture(this.canvas2) this.texture.flipY = false this.texture.needsUpdate = true } map (text: string) { const p = this.parameters if (this.mapped[ text ] === undefined) { this.draw(text) if (this.currentX + this.scratchW > p.width) { this.currentX = 0 this.currentY += this.scratchH } if (this.currentY + this.scratchH > p.height) { console.warn('canvas to small') } this.mapped[ text ] = { x: this.currentX, y: this.currentY, w: this.scratchW, h: this.scratchH } this.context2.drawImage( this.canvas, 0, 0, this.scratchW, this.scratchH, this.currentX, this.currentY, this.scratchW, this.scratchH ) this.currentX += this.scratchW } return this.mapped[ text ] } get (text: string) { return this.mapped[ text ] || this.placeholder } draw (text: string) { const p = this.parameters const h = this.lineHeight const o = p.outline const ctx = this.context // const dst = this.scratch const max = this.maxWidth // const colors = this.colors // Bottom aligned, take outline into account const x = o const y = h - p.outline // Measure text const m = ctx.measureText(text) const w = Math.min(max, Math.ceil(m.width + 2 * x + 1)) const n = w * h // Clear scratch area ctx.clearRect(0, 0, w, h) // Draw text ctx.fillText(text, x, y) const imageData = ctx.getImageData(0, 0, w, h) const data = imageData.data for (let i = 0; i < n; i++) { const a = imageData.data[i * 4 + 3] / 255; // alpha value this.gridOuter[i] = a === 1 ? 0 : a === 0 ? Number.MAX_SAFE_INTEGER : Math.pow(Math.max(0, 0.5 - a), 2); this.gridInner[i] = a === 1 ? Number.MAX_SAFE_INTEGER : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2); } edt(this.gridOuter, w, h, this.f, this.d, this.v, this.z); edt(this.gridInner, w, h, this.f, this.d, this.v, this.z); for (let i = 0; i < n; i++) { const d = this.gridOuter[i] - this.gridInner[i]; data[i * 4 + 3] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff)))); } ctx.putImageData(imageData, 0, 0) this.scratchW = w this.scratchH = h } } /** * Text buffer parameter object. * @typedef {Object} TextBufferParameters - text buffer parameters * * @property {Float} opacity - translucency: 1 is fully opaque, 0 is fully transparent * @property {Integer} clipNear - position of camera near/front clipping plane * in percent of scene bounding box * @property {String} labelType - type of the label, one of: * "atomname", "atomindex", "occupancy", "bfactor", * "serial", "element", "atom", "resname", "resno", * "res", "text", "qualified". When set to "text", the * `labelText` list is used. * @property {String[]} labelText - list of label strings, must set `labelType` to "text" * to take effect * @property {String} fontFamily - font family, one of: "sans-serif", "monospace", "serif" * @property {String} fontStyle - font style, "normal" or "italic" * @property {String} fontWeight - font weight, "normal" or "bold" * @property {Float} xOffset - offset in x-direction * @property {Float} yOffset - offset in y-direction * @property {Float} zOffset - offset in z-direction (i.e. in camera direction) * @property {String} attachment - attachment of the label, one of: * "bottom-left", "bottom-center", "bottom-right", * "middle-left", "middle-center", "middle-right", * "top-left", "top-center", "top-right" * @property {Boolean} showBorder - show border/outline * @property {Color} borderColor - color of the border/outline * @property {Float} borderWidth - width of the border/outline * @property {Boolean} showBackground - show background rectangle * @property {Color} backgroundColor - color of the background * @property {Float} backgroundMargin - width of the background * @property {Float} backgroundOpacity - opacity of the background * @property {Boolean} fixedSize - show text with a fixed pixel size */ export interface TextBufferData extends BufferData { size: Float32Array text: string[] } type TextAttachments = 'bottom-left'|'bottom-center'|'bottom-right'|'middle-left'|'middle-center'|'middle-right'|'top-left'|'top-center'|'top-right' export const TextBufferDefaultParameters = Object.assign({ fontFamily: 'sans-serif' as TextFonts, fontStyle: 'normal' as TextStyles, fontWeight: 'bold' as TextWeights, fontSize: 36, xOffset: 0.0, yOffset: 0.0, zOffset: 0.5, attachment: 'bottom-left' as TextAttachments, showBorder: false, borderColor: 'lightgrey' as number|string, borderWidth: 0.15, showBackground: false, backgroundColor: 'lightgrey' as number|string, backgroundMargin: 0.5, backgroundOpacity: 1.0, forceTransparent: true, fixedSize: false }, BufferDefaultParameters) export type TextBufferParameters = typeof TextBufferDefaultParameters const TextBufferParameterTypes = Object.assign({ fontFamily: { uniform: true }, fontStyle: { uniform: true }, fontWeight: { uniform: true }, fontSize: { uniform: true }, xOffset: { uniform: true }, yOffset: { uniform: true }, zOffset: { uniform: true }, showBorder: { uniform: true }, borderColor: { uniform: true }, borderWidth: { uniform: true }, backgroundColor: { uniform: true }, backgroundOpacity: { uniform: true }, fixedSize: { updateShader: true } }, BufferParameterTypes) function getCharCount (data: TextBufferData, params: Partial<TextBufferParameters>) { const n = data.position!.length / 3 let charCount = 0 for (let i = 0; i < n; ++i) { charCount += data.text[ i ].length } if (params.showBackground) charCount += n return charCount } /** * Text buffer. Renders screen-aligned text strings. * * @example * var textBuffer = new TextBuffer({ * position: new Float32Array([ 0, 0, 0 ]), * color: new Float32Array([ 1, 0, 0 ]), * size: new Float32Array([ 2 ]), * text: [ "Hello" ] * }); */ class TextBuffer extends MappedQuadBuffer { parameterTypes = TextBufferParameterTypes get defaultParameters() { return TextBufferDefaultParameters } parameters: TextBufferParameters alwaysTransparent = true hasWireframe = false isText = true vertexShader = 'SDFFont.vert' fragmentShader = 'SDFFont.frag' text: string[] positionCount: number texture: CanvasTexture textAtlas: TextAtlas /** * @param {Object} data - attribute object * @param {Float32Array} data.position - positions * @param {Float32Array} data.color - colors * @param {Float32Array} data.size - sizes * @param {String[]} data.text - text strings * @param {TextBufferParameters} params - parameters object */ constructor (data: TextBufferData, params: Partial<TextBufferParameters> = {}) { super({ position: new Float32Array(getCharCount(data, params) * 3), color: new Float32Array(getCharCount(data, params) * 3), picking: new IgnorePicker() }, params) this.text = data.text this.positionCount = data.position!.length / 3 this.addUniforms({ 'fontTexture': { value: null }, 'xOffset': { value: this.parameters.xOffset }, 'yOffset': { value: this.parameters.yOffset }, 'zOffset': { value: this.parameters.zOffset }, 'ortho': { value: false }, 'showBorder': { value: this.parameters.showBorder }, 'borderColor': { value: new Color(this.parameters.borderColor as number) }, 'borderWidth': { value: this.parameters.borderWidth }, 'backgroundColor': { value: new Color(this.parameters.backgroundColor as number) }, 'backgroundOpacity': { value: this.parameters.backgroundOpacity }, 'canvasHeight': { value: 1.0 }, 'pixelRatio': { value: 1.0 } }) this.addAttributes({ 'inputTexCoord': { type: 'v2', value: null }, 'inputSize': { type: 'f', value: null } }) this.setAttributes(data) this.makeTexture() this.makeMapping() } makeMaterial () { super.makeMaterial() const tex = this.texture const m = this.material m.transparent = true m.extensions.derivatives = true m.lights = false m.uniforms.fontTexture.value = tex m.needsUpdate = true const wm = this.wireframeMaterial wm.transparent = true wm.extensions.derivatives = true wm.lights = false wm.uniforms.fontTexture.value = tex wm.needsUpdate = true const pm = this.pickingMaterial pm.extensions.derivatives = true pm.lights = false pm.uniforms.fontTexture.value = tex pm.needsUpdate = true } setAttributes (data: Partial<TextBufferData> = {}) { let position, size, color let aPosition, inputSize, aColor const text = this.text const attributes = this.geometry.attributes as any // TODO if (data.position) { position = data.position aPosition = attributes.position.array attributes.position.needsUpdate = true } if (data.size) { size = data.size inputSize = attributes.inputSize.array attributes.inputSize.needsUpdate = true } if (data.color) { color = data.color aColor = attributes.color.array attributes.color.needsUpdate = true } const n = this.positionCount let j, o let iCharAll = 0 let txt, iChar, nChar for (let v = 0; v < n; ++v) { o = 3 * v txt = text[ v ] nChar = txt.length if (this.parameters.showBackground) nChar += 1 for (iChar = 0; iChar < nChar; ++iChar, ++iCharAll) { for (let m = 0; m < 4; m++) { j = iCharAll * 4 * 3 + (3 * m) if (position) { aPosition[ j ] = position[ o ] aPosition[ j + 1 ] = position[ o + 1 ] aPosition[ j + 2 ] = position[ o + 2 ] } if (size) { inputSize[ (iCharAll * 4) + m ] = size[ v ] } if (color) { aColor[ j ] = color[ o ] aColor[ j + 1 ] = color[ o + 1 ] aColor[ j + 2 ] = color[ o + 2 ] } } } } } makeTexture () { this.textAtlas = getTextAtlas({ font: this.parameters.fontFamily, style: this.parameters.fontStyle, weight: this.parameters.fontWeight, size: this.parameters.fontSize }) this.texture = this.textAtlas.texture } makeMapping () { const ta = this.textAtlas const text = this.text const attachment = this.parameters.attachment const margin = (ta.lineHeight * this.parameters.backgroundMargin * 0.1) - 10 const attribs = this.geometry.attributes as any // TODO const inputTexCoord = attribs.inputTexCoord.array const inputMapping = attribs.mapping.array const n = this.positionCount let iCharAll = 0 let c, i, txt, xadvance, iChar, nChar, xShift, yShift for (let v = 0; v < n; ++v) { txt = text[ v ] xadvance = 0 nChar = txt.length // calculate width for (iChar = 0; iChar < nChar; ++iChar) { c = ta.get(txt[ iChar ]) xadvance += c.w - 2 * ta.parameters.outline } // attachment if (attachment.startsWith('top')) { yShift = ta.lineHeight / 1.25 } else if (attachment.startsWith('middle')) { yShift = ta.lineHeight / 2.5 } else { yShift = 0 // "bottom" } if (attachment.endsWith('right')) { xShift = xadvance } else if (attachment.endsWith('center')) { xShift = xadvance / 2 } else { xShift = 0 // "left" } xShift += ta.parameters.outline yShift += ta.parameters.outline // background if (this.parameters.showBackground) { i = iCharAll * 2 * 4 inputMapping[ i + 0 ] = -ta.lineHeight / 6 - xShift - margin // top left inputMapping[ i + 1 ] = ta.lineHeight - yShift + margin inputMapping[ i + 2 ] = -ta.lineHeight / 6 - xShift - margin // bottom left inputMapping[ i + 3 ] = 0 - yShift - margin inputMapping[ i + 4 ] = xadvance + ta.lineHeight / 6 - xShift + 2 * ta.parameters.outline + margin // top right inputMapping[ i + 5 ] = ta.lineHeight - yShift + margin inputMapping[ i + 6 ] = xadvance + ta.lineHeight / 6 - xShift + 2 * ta.parameters.outline + margin // bottom right inputMapping[ i + 7 ] = 0 - yShift - margin inputTexCoord[ i + 0 ] = 10 inputTexCoord[ i + 2 ] = 10 inputTexCoord[ i + 4 ] = 10 inputTexCoord[ i + 6 ] = 10 iCharAll += 1 } xadvance = 0 for (iChar = 0; iChar < nChar; ++iChar, ++iCharAll) { c = ta.get(txt[ iChar ]) i = iCharAll * 2 * 4 inputMapping[ i + 0 ] = xadvance - xShift // top left inputMapping[ i + 1 ] = c.h - yShift inputMapping[ i + 2 ] = xadvance - xShift // bottom left inputMapping[ i + 3 ] = 0 - yShift inputMapping[ i + 4 ] = xadvance + c.w - xShift // top right inputMapping[ i + 5 ] = c.h - yShift inputMapping[ i + 6 ] = xadvance + c.w - xShift // bottom right inputMapping[ i + 7 ] = 0 - yShift const texWidth = ta.parameters.width const texHeight = ta.parameters.height const texCoords = [ c.x / texWidth, c.y / texHeight, // top left c.x / texWidth, (c.y + c.h) / texHeight, // bottom left (c.x + c.w) / texWidth, c.y / texHeight, // top right (c.x + c.w) / texWidth, (c.y + c.h) / texHeight // bottom right ] inputTexCoord.set(texCoords, i) xadvance += c.w - 2 * ta.parameters.outline } } attribs.inputTexCoord.needsUpdate = true attribs.mapping.needsUpdate = true } getDefines (type: BufferTypes) { const defines = super.getDefines(type) if (this.parameters.fixedSize) { defines.FIXED_SIZE = 1 } return defines } setUniforms (data: any) { // TODO if (data && ( data.fontFamily !== undefined || data.fontStyle !== undefined || data.fontWeight !== undefined || data.fontSize !== undefined )) { this.makeTexture() this.makeMapping() this.texture.needsUpdate = true data.fontTexture = this.texture } super.setUniforms(data) } } BufferRegistry.add('text', TextBuffer) export default TextBuffer
the_stack
import axios from 'axios'; import { List } from 'immutable'; import { pick } from 'lodash'; import qs from 'qs'; import { IParams, } from './types'; import { ArticleModel, CommentFlagModel, CommentModel, CommentScoreModel, IArticleModel, IAuthorCountsModel, ICommentDate, ICommentFlagModel, ICommentModel, ICommentScore, ICommentScoreModel, IPreselectModel, IRuleModel, ITaggingSensitivityModel, ITagModel, IUserModel, ModelId, UserModel, } from '../../models'; import { ServerStates } from '../../types'; import { API_URL } from '../config'; export type IValidModelNames = 'moderation_rule' | 'preselect' | 'tagging_sensitivity' | 'tag'; /** * Convert Partial<IParams> type to a query string. */ function serializeParams(originalParams?: Partial<IParams> | null): string { if (!originalParams) { return ''; } // Clone to avoid mutability issues. const params = { ...originalParams } as any; if (originalParams.sort) { params.sort = originalParams.sort.join(','); } return '?' + qs.stringify(params, { encode: false }); } const BASE_RANGE_ATTRIBUTES = ['categoryId', 'tagId', 'lowerThreshold', 'upperThreshold']; /** * Base AUTH API Path */ const AUTH_URL = `/auth`; /** * Base Services API Path */ const SERVICES_URL = `/services`; /** * The URL of a service. */ export function serviceURL(service: string, path?: string | null, params?: Partial<IParams>): string { return `${API_URL}${SERVICES_URL}/${service}${path ? path : ''}${serializeParams(params)}`; } export async function listTextSizesByIds( ids: Array<string>, width: number, ): Promise<Map<string, number>> { const response: any = await axios.post( serviceURL('textSizes', null, { width } as Partial<IParams>), { data: ids }, ); const data = response.data.data; return new Map<ModelId, number>(Object.entries(data)); } function packCommentScoreData(data: Array<{ commentId: ModelId, score: number }>): Array<ICommentScore> { return data.map(({commentId, score}) => ({commentId, score})); } function packCommentDateData(data: Array<{ commentId: ModelId, date: string }>): Array<ICommentDate> { return data.map(({date, commentId}) => ({ commentId, date: new Date(date), })); } export async function listHistogramScoresByArticle( articleId: string, tagId: string | 'DATE', sort: Array<string>, ): Promise<Array<ICommentScore>> { const response: any = await axios.get( serviceURL('histogramScores', `/articles/${articleId}/tags/${tagId}`, { sort }), ); return packCommentScoreData(response.data.data); } export async function listMaxSummaryScoreByArticle( articleId: string, sort: Array<string>, ): Promise<Array<ICommentScore>> { const response: any = await axios.get( serviceURL('histogramScores', `/articles/${articleId}/summaryScore`, { sort }), ); return packCommentScoreData(response.data.data); } export async function listHistogramScoresByArticleByDate( articleId: ModelId, sort: Array<string>, ): Promise<Array<ICommentDate>> { const response: any = await axios.get( serviceURL('histogramScores', `/articles/${articleId}/byDate`, { sort }), ); return packCommentDateData(response.data.data); } export async function listHistogramScoresByCategory( categoryId: string | 'all', tagId: string, sort: Array<string>, ): Promise<Array<ICommentScore>> { const response: any = await axios.get( serviceURL('histogramScores', `/categories/${categoryId}/tags/${tagId}`, { sort }), ); return packCommentScoreData(response.data.data); } export async function listMaxHistogramScoresByCategory( categoryId: string | 'all', sort: Array<string>, ): Promise<Array<ICommentScore>> { const response: any = await axios.get( serviceURL('histogramScores', `/categories/${categoryId}/summaryScore`, { sort }), ); return packCommentScoreData(response.data.data); } export async function listHistogramScoresByCategoryByDate( categoryId: ModelId | 'all', sort: Array<string>, ): Promise<Array<ICommentDate>> { const response: any = await axios.get( serviceURL('histogramScores', `/categories/${categoryId}/byDate`, { sort }), ); return packCommentDateData(response.data.data); } export async function getComments( commentIds: Array<ModelId>, ): Promise<Array<ICommentModel>> { const url = serviceURL('simple', `/comments`); const response = await axios.post(url, commentIds); return response.data.map((a: any) => (CommentModel(a))); } /** * Search comment models. */ export async function search( query: string, params?: Partial<IParams>, ): Promise<Array<string>> { const requestParams = { ...params, term: query, }; const { data }: any = await axios.get(serviceURL('search', null, requestParams)); return data.data; } /** * Send updated comment text and rescore comment. */ export async function editAndRescoreCommentRequest( commentId: string, text: string, authorName: string, authorLocation: string, ): Promise<void> { await axios.patch( serviceURL('editComment', null), { data: { commentId, text, authorName, authorLocation, }, }); } export async function updateCategoryModerators(categoryId: ModelId, moderatorIds: Array<ModelId>): Promise<void> { const url = serviceURL('assignments', `/categories/${categoryId}`); await axios.post(url, { data: moderatorIds }); } export async function updateArticleModerators(articleId: ModelId, moderatorIds: Array<ModelId>): Promise<void> { const url = serviceURL('assignments', `/article/${articleId}`); await axios.post(url, { data: moderatorIds }); } export type IModeratedComments = Readonly<{ approved: Array<ModelId>; highlighted: Array<ModelId>; rejected: Array<ModelId>; deferred: Array<ModelId>; flagged: Array<ModelId>; batched: Array<ModelId>; automated: Array<ModelId>; [key: string]: Array<ModelId>; }>; export async function getModeratedCommentIdsForArticle( articleId: ModelId, sort: Array<string>, ): Promise<IModeratedComments> { const { data }: any = await axios.get( serviceURL('moderatedCounts', `/articles/${articleId}`, { sort }), ); return data.data; } export async function getModeratedCommentIdsForCategory( categoryId: ModelId | 'all', sort: Array<string>, ): Promise<IModeratedComments> { const { data }: any = await axios.get( serviceURL('moderatedCounts', `/categories/${categoryId}`, { sort }), ); return data.data; } export async function getArticles(ids: Array<ModelId>): Promise<Array<IArticleModel>> { const url = serviceURL('simple', `/articles`); const response = await axios.post(url, ids); return response.data.map((a: any) => (ArticleModel(a))); } export async function getArticleText(id: ModelId) { const url = serviceURL('simple', `/article/${id}/text`); const response = await axios.get(url); return response.data.text; } export async function updateArticle(id: string, isCommentingEnabled: boolean, isAutoModerated: boolean) { const url = serviceURL('simple', `/article/${id}`); await axios.post(url, {isCommentingEnabled, isAutoModerated}); } async function createThing(url: string, attributes: {[key: string]: string | number | boolean}) { try { await axios.post(url, attributes); } catch (e) { if (e.response) { throw new Error(e.response.data); } throw e; } } async function updateThing(url: string, attributes: {[key: string]: string | number | boolean}) { try { await axios.patch(url, attributes); } catch (e) { if (e.response) { throw new Error(e.response.data); } throw e; } } export async function createUser(user: IUserModel) { const url = serviceURL('simple', `/user`); const attributes = pick(user, ['name', 'email', 'group', 'isActive']); return createThing(url, attributes); } export async function createTag(tag: ITagModel) { const url = serviceURL('simple', `/tag`); const attributes = pick(tag, ['color', 'description', 'key', 'label', 'isInBatchView', 'inSummaryScore', 'isTaggable']); return createThing(url, attributes); } export async function createRule(rule: IRuleModel) { const url = serviceURL('simple', `/moderation_rule`); const attributes = pick(rule, [...BASE_RANGE_ATTRIBUTES, 'action']); return createThing(url, attributes); } export async function createPreselect(preselect: IPreselectModel) { const url = serviceURL('simple', `/preselect`); const attributes = pick(preselect, BASE_RANGE_ATTRIBUTES); return createThing(url, attributes); } export async function createSensitivity(sensitivity: ITaggingSensitivityModel) { const url = serviceURL('simple', `/tagging_sensitivity`); const attributes = pick(sensitivity, BASE_RANGE_ATTRIBUTES); return createThing(url, attributes); } export async function updateUser(user: IUserModel) { const url = serviceURL('simple', `/user/${user.id}`); const attributes = pick(user, ['name', 'email', 'group', 'isActive']); await axios.post(url, attributes); } export async function updateTag(tag: ITagModel) { const url = serviceURL('simple', `/tag/${tag.id}`); const attributes = pick(tag, ['color', 'description', 'key', 'label', 'isInBatchView', 'inSummaryScore', 'isTaggable']); return updateThing(url, attributes); } export async function updateRule(rule: IRuleModel) { const url = serviceURL('simple', `/moderation_rule/${rule.id}`); const attributes = pick(rule, [...BASE_RANGE_ATTRIBUTES, 'action']); return updateThing(url, attributes); } export async function updatePreselect(preselect: IPreselectModel) { const url = serviceURL('simple', `/preselect/${preselect.id}`); const attributes = pick(preselect, BASE_RANGE_ATTRIBUTES); return updateThing(url, attributes); } export async function updateSensitivity(sensitivity: ITaggingSensitivityModel) { const url = serviceURL('simple', `/tagging_sensitivity/${sensitivity.id}`); const attributes = pick(sensitivity, BASE_RANGE_ATTRIBUTES); return updateThing(url, attributes); } /** * Destroy a model. */ export async function destroyModel( type: IValidModelNames, id: string, ): Promise<void> { await axios.delete(serviceURL('simple', `/${type}/${id}`)); } export async function getCommentScores(commentId: string): Promise<Array<ICommentScoreModel>> { const url = serviceURL('simple', `/comment/${commentId}/scores`); const response = await axios.get(url); return response.data.map((s: any) => (CommentScoreModel(s))); } export async function getCommentFlags(commentId: string): Promise<Array<ICommentFlagModel>> { const url = serviceURL('simple', `/comment/${commentId}/flags`); const response = await axios.get(url); return response.data.map((s: any) => (CommentFlagModel(s))); } export async function checkServerStatus(): Promise<ServerStates> { const response = await axios.get( `${API_URL}${AUTH_URL}/healthcheck`, ); if (response.status === 218) { switch (response.data) { case 'init_oauth': return 's_init_oauth'; case 'init_first_user': return 's_init_first_user'; case 'init_check_oauth': return 's_init_check_oauth'; } } return 's_gtg'; } /** * Ping the backend to see if the auth succeeds. */ export async function checkAuthorization(): Promise<void> { await axios.get( `${API_URL}${AUTH_URL}/test`, ); } async function makeCommentAction(path: string, ids: Array<string>): Promise<void> { if (ids.length <= 0) { return; } const idUserArray = ids.map((commentId) => { return { commentId, }; }); const url = serviceURL('commentActions', path); await axios.post(url, { data: idUserArray, runImmediately: true }); } async function makeCommentActionForId(path: string, commentId: string): Promise<void> { const url = serviceURL('commentActions', path); await axios.post(url, { data: { commentId } }); } export async function deleteCommentScoreRequest(commentId: string, commentScoreId: string): Promise<void> { const url = serviceURL('commentActions', `/${commentId}/scores/${commentScoreId}`); await axios.delete(url); } export function highlightCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/highlight', ids); } export function resetCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/reset', ids); } export function approveCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/approve', ids); } export function approveFlagsAndCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/approve-flags', ids); } export function resolveFlagsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/resolve-flags', ids); } export function deferCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/defer', ids); } export function rejectCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/reject', ids); } export function rejectFlagsAndCommentsRequest(ids: Array<string>): Promise<void> { return makeCommentAction('/reject-flags', ids); } export function tagCommentsRequest(ids: Array<string>, tagId: string): Promise<void> { return makeCommentAction(`/tag/${tagId}`, ids); } export function tagCommentSummaryScoresRequest(ids: Array<string>, tagId: string): Promise<void> { return makeCommentAction(`/tagCommentSummaryScores/${tagId}`, ids); } export async function confirmCommentSummaryScoreRequest(commentId: string, tagId: string): Promise<void> { return makeCommentActionForId( `/${commentId}/tagCommentSummaryScores/${tagId}/confirm`, commentId); } export async function rejectCommentSummaryScoreRequest(commentId: string, tagId: string): Promise<void> { return makeCommentActionForId(`/${commentId}/tagCommentSummaryScores/${tagId}/reject`, commentId); } export async function tagCommentsAnnotationRequest(commentId: string, tagId: string, start: number, end: number): Promise<void> { const url = serviceURL('commentActions', `/${commentId}/scores`); await axios.post(url, { data: { tagId, annotationStart: start, annotationEnd: end, }, }); } export async function confirmCommentScoreRequest(commentId: string, commentScoreId: string): Promise<void> { const url = serviceURL('commentActions', `/${commentId}/scores/${commentScoreId}/confirm`); await axios.post(url); } export async function rejectCommentScoreRequest(commentId: string, commentScoreId: string): Promise<void> { const url = serviceURL('commentActions', `/${commentId}/scores/${commentScoreId}/reject`); await axios.post(url); } export async function resetCommentScoreRequest(commentId: string, commentScoreId: string): Promise<void> { const url = serviceURL('commentActions', `/${commentId}/scores/${commentScoreId}/reset`); await axios.post(url); } export async function listAuthorCounts( authorSourceIds: Array<string>, ): Promise<Map<string, IAuthorCountsModel>> { const response: any = await axios.post( serviceURL('authorCounts'), { data: authorSourceIds }, ); return new Map<string, IAuthorCountsModel>(Object.entries(response.data.data)); } export async function listSystemUsers(type: string): Promise<List<IUserModel>> { const response: any = await axios.get(serviceURL('simple', `/systemUsers/${type}`)); return List<IUserModel>(response.data.users.map((u: any) => { u.id = u.id.toString(); return UserModel(u); })); } export async function kickProcessor(type: string): Promise<void> { await axios.get(serviceURL('processing', `/trigger/${type}`)); } export async function activateCommentSource(categoryId: ModelId, activate: boolean): Promise<void> { await axios.post(serviceURL('comment_sources', `/activate/${categoryId}`), { data: {activate} }); } export async function syncCommentSource(categoryId: ModelId): Promise<void> { await axios.get(serviceURL('comment_sources', `/sync/${categoryId}`)); } export interface IApiConfiguration { id: string; secret: string; } export async function getOAuthConfig(): Promise<IApiConfiguration> { const response: any = await axios.get(`${API_URL}${AUTH_URL}/config`); return response.data.google_oauth_config as IApiConfiguration; } export async function updateOAuthConfig(config: IApiConfiguration): Promise<void> { await axios.post(`${API_URL}${AUTH_URL}/config`, {data: config}); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Represents a Target gRPC Proxy resource. A target gRPC proxy is a component * of load balancers intended for load balancing gRPC traffic. Global forwarding * rules reference a target gRPC proxy. The Target gRPC Proxy references * a URL map which specifies how traffic routes to gRPC backend services. * * To get more information about TargetGrpcProxy, see: * * * [API documentation](https://cloud.google.com/compute/docs/reference/rest/v1/targetGrpcProxies) * * How-to Guides * * [Using Target gRPC Proxies](https://cloud.google.com/traffic-director/docs/proxyless-overview) * * ## Example Usage * ### Target Grpc Proxy Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const defaultHealthCheck = new gcp.compute.HealthCheck("defaultHealthCheck", { * timeoutSec: 1, * checkIntervalSec: 1, * grpcHealthCheck: { * portName: "health-check-port", * portSpecification: "USE_NAMED_PORT", * grpcServiceName: "testservice", * }, * }); * const home = new gcp.compute.BackendService("home", { * portName: "grpc", * protocol: "GRPC", * timeoutSec: 10, * healthChecks: [defaultHealthCheck.id], * loadBalancingScheme: "INTERNAL_SELF_MANAGED", * }); * const urlmap = new gcp.compute.URLMap("urlmap", { * description: "a description", * defaultService: home.id, * hostRules: [{ * hosts: ["mysite.com"], * pathMatcher: "allpaths", * }], * pathMatchers: [{ * name: "allpaths", * defaultService: home.id, * routeRules: [{ * priority: 1, * headerAction: { * requestHeadersToRemoves: ["RemoveMe2"], * requestHeadersToAdds: [{ * headerName: "AddSomethingElse", * headerValue: "MyOtherValue", * replace: true, * }], * responseHeadersToRemoves: ["RemoveMe3"], * responseHeadersToAdds: [{ * headerName: "AddMe", * headerValue: "MyValue", * replace: false, * }], * }, * matchRules: [{ * fullPathMatch: "a full path", * headerMatches: [{ * headerName: "someheader", * exactMatch: "match this exactly", * invertMatch: true, * }], * ignoreCase: true, * metadataFilters: [{ * filterMatchCriteria: "MATCH_ANY", * filterLabels: [{ * name: "PLANET", * value: "MARS", * }], * }], * queryParameterMatches: [{ * name: "a query parameter", * presentMatch: true, * }], * }], * urlRedirect: { * hostRedirect: "A host", * httpsRedirect: false, * pathRedirect: "some/path", * redirectResponseCode: "TEMPORARY_REDIRECT", * stripQuery: true, * }, * }], * }], * tests: [{ * service: home.id, * host: "hi.com", * path: "/home", * }], * }); * const defaultTargetGrpcProxy = new gcp.compute.TargetGrpcProxy("defaultTargetGrpcProxy", { * urlMap: urlmap.id, * validateForProxyless: true, * }); * ``` * * ## Import * * TargetGrpcProxy can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:compute/targetGrpcProxy:TargetGrpcProxy default projects/{{project}}/global/targetGrpcProxies/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/targetGrpcProxy:TargetGrpcProxy default {{project}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:compute/targetGrpcProxy:TargetGrpcProxy default {{name}} * ``` */ export class TargetGrpcProxy extends pulumi.CustomResource { /** * Get an existing TargetGrpcProxy resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: TargetGrpcProxyState, opts?: pulumi.CustomResourceOptions): TargetGrpcProxy { return new TargetGrpcProxy(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:compute/targetGrpcProxy:TargetGrpcProxy'; /** * Returns true if the given object is an instance of TargetGrpcProxy. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is TargetGrpcProxy { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === TargetGrpcProxy.__pulumiType; } /** * Creation timestamp in RFC3339 text format. */ public /*out*/ readonly creationTimestamp!: pulumi.Output<string>; /** * An optional description of this resource. */ public readonly description!: pulumi.Output<string | undefined>; /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. * This field will be ignored when inserting a TargetGrpcProxy. An up-to-date fingerprint must be provided in order to * patch/update the TargetGrpcProxy; otherwise, the request will fail with error 412 conditionNotMet. To see the latest * fingerprint, make a get() request to retrieve the TargetGrpcProxy. A base64-encoded string. */ public /*out*/ readonly fingerprint!: pulumi.Output<string>; /** * Name of the resource. Provided by the client when the resource * is created. The name must be 1-63 characters long, and comply * with RFC1035. Specifically, the name must be 1-63 characters long * and match the regular expression `a-z?` which * means the first character must be a lowercase letter, and all * following characters must be a dash, lowercase letter, or digit, * except the last character, which cannot be a dash. */ public readonly name!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The URI of the created resource. */ public /*out*/ readonly selfLink!: pulumi.Output<string>; /** * Server-defined URL with id for the resource. */ public /*out*/ readonly selfLinkWithId!: pulumi.Output<string>; /** * URL to the UrlMap resource that defines the mapping from URL to * the BackendService. The protocol field in the BackendService * must be set to GRPC. */ public readonly urlMap!: pulumi.Output<string | undefined>; /** * If true, indicates that the BackendServices referenced by * the urlMap may be accessed by gRPC applications without using * a sidecar proxy. This will enable configuration checks on urlMap * and its referenced BackendServices to not allow unsupported features. * A gRPC application must use "xds:///" scheme in the target URI * of the service it is connecting to. If false, indicates that the * BackendServices referenced by the urlMap will be accessed by gRPC * applications via a sidecar proxy. In this case, a gRPC application * must not use "xds:///" scheme in the target URI of the service * it is connecting to */ public readonly validateForProxyless!: pulumi.Output<boolean | undefined>; /** * Create a TargetGrpcProxy resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args?: TargetGrpcProxyArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: TargetGrpcProxyArgs | TargetGrpcProxyState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as TargetGrpcProxyState | undefined; inputs["creationTimestamp"] = state ? state.creationTimestamp : undefined; inputs["description"] = state ? state.description : undefined; inputs["fingerprint"] = state ? state.fingerprint : undefined; inputs["name"] = state ? state.name : undefined; inputs["project"] = state ? state.project : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["selfLinkWithId"] = state ? state.selfLinkWithId : undefined; inputs["urlMap"] = state ? state.urlMap : undefined; inputs["validateForProxyless"] = state ? state.validateForProxyless : undefined; } else { const args = argsOrState as TargetGrpcProxyArgs | undefined; inputs["description"] = args ? args.description : undefined; inputs["name"] = args ? args.name : undefined; inputs["project"] = args ? args.project : undefined; inputs["urlMap"] = args ? args.urlMap : undefined; inputs["validateForProxyless"] = args ? args.validateForProxyless : undefined; inputs["creationTimestamp"] = undefined /*out*/; inputs["fingerprint"] = undefined /*out*/; inputs["selfLink"] = undefined /*out*/; inputs["selfLinkWithId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(TargetGrpcProxy.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering TargetGrpcProxy resources. */ export interface TargetGrpcProxyState { /** * Creation timestamp in RFC3339 text format. */ creationTimestamp?: pulumi.Input<string>; /** * An optional description of this resource. */ description?: pulumi.Input<string>; /** * Fingerprint of this resource. A hash of the contents stored in this object. This field is used in optimistic locking. * This field will be ignored when inserting a TargetGrpcProxy. An up-to-date fingerprint must be provided in order to * patch/update the TargetGrpcProxy; otherwise, the request will fail with error 412 conditionNotMet. To see the latest * fingerprint, make a get() request to retrieve the TargetGrpcProxy. A base64-encoded string. */ fingerprint?: pulumi.Input<string>; /** * Name of the resource. Provided by the client when the resource * is created. The name must be 1-63 characters long, and comply * with RFC1035. Specifically, the name must be 1-63 characters long * and match the regular expression `a-z?` which * means the first character must be a lowercase letter, and all * following characters must be a dash, lowercase letter, or digit, * except the last character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The URI of the created resource. */ selfLink?: pulumi.Input<string>; /** * Server-defined URL with id for the resource. */ selfLinkWithId?: pulumi.Input<string>; /** * URL to the UrlMap resource that defines the mapping from URL to * the BackendService. The protocol field in the BackendService * must be set to GRPC. */ urlMap?: pulumi.Input<string>; /** * If true, indicates that the BackendServices referenced by * the urlMap may be accessed by gRPC applications without using * a sidecar proxy. This will enable configuration checks on urlMap * and its referenced BackendServices to not allow unsupported features. * A gRPC application must use "xds:///" scheme in the target URI * of the service it is connecting to. If false, indicates that the * BackendServices referenced by the urlMap will be accessed by gRPC * applications via a sidecar proxy. In this case, a gRPC application * must not use "xds:///" scheme in the target URI of the service * it is connecting to */ validateForProxyless?: pulumi.Input<boolean>; } /** * The set of arguments for constructing a TargetGrpcProxy resource. */ export interface TargetGrpcProxyArgs { /** * An optional description of this resource. */ description?: pulumi.Input<string>; /** * Name of the resource. Provided by the client when the resource * is created. The name must be 1-63 characters long, and comply * with RFC1035. Specifically, the name must be 1-63 characters long * and match the regular expression `a-z?` which * means the first character must be a lowercase letter, and all * following characters must be a dash, lowercase letter, or digit, * except the last character, which cannot be a dash. */ name?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * URL to the UrlMap resource that defines the mapping from URL to * the BackendService. The protocol field in the BackendService * must be set to GRPC. */ urlMap?: pulumi.Input<string>; /** * If true, indicates that the BackendServices referenced by * the urlMap may be accessed by gRPC applications without using * a sidecar proxy. This will enable configuration checks on urlMap * and its referenced BackendServices to not allow unsupported features. * A gRPC application must use "xds:///" scheme in the target URI * of the service it is connecting to. If false, indicates that the * BackendServices referenced by the urlMap will be accessed by gRPC * applications via a sidecar proxy. In this case, a gRPC application * must not use "xds:///" scheme in the target URI of the service * it is connecting to */ validateForProxyless?: pulumi.Input<boolean>; }
the_stack
import { click, render, settled } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import { setupMirage } from 'ember-cli-mirage/test-support'; // @ts-ignore: add ember-flatpickr types import { setFlatpickrDate } from 'ember-flatpickr/test-support/helpers'; import { t } from 'ember-intl/test-support'; import { setupRenderingTest } from 'ember-qunit'; import moment from 'moment'; import { module, test } from 'qunit'; import stripHtmlTags from 'ember-osf-web/utils/strip-html-tags'; module('Integration | Component | finalize-registration-modal', hooks => { setupRenderingTest(hooks); setupMirage(hooks); test('make registration public immediately', async function(assert) { this.store = this.owner.lookup('service:store'); const provider = server.create('registration-provider'); const registration = server.create('registration', { provider }); const node = server.create('node', 'currentUserAdmin'); const draftRegistration = server.create('draft-registration', { branchedFrom: node }); const registrationModel = await this.store.findRecord('registration', registration.id); this.set('draftManager', { provider, draftRegistration, validateAllVisitedPages: () => { /* noop */ } }); this.set('model', registrationModel); this.set('isOpen', false); await render(hbs` <Registries::FinalizeRegistrationModal::Manager @registration={{this.model}} @draftManager={{this.draftManager}} as |manager| > <Registries::FinalizeRegistrationModal @isOpen={{this.isOpen}} @manager={{manager}} /> </Registries::FinalizeRegistrationModal::Manager> `); // Open the dialog this.set('isOpen', true); await settled(); // Check that the submit button is disabled assert.dom('[data-test-submit-registration-button]').isDisabled(); // Click immediate radio button await click('[data-test-immediate-button]'); // Check that the submit button is enabled assert.dom('[data-test-submit-registration-button]').isNotDisabled(); // Check that `embargoEndDate` of the registration model is null assert.equal(registrationModel.embargoEndDate, null); // Click embargo radio button await click('[data-test-embargo-button]'); // Check that the submit button is disabled again assert.dom('[data-test-submit-registration-button]').isDisabled(); // Close the dialog this.set('isOpen', false); }); test('embargo registration', async function(assert) { this.store = this.owner.lookup('service:store'); const provider = server.create('registration-provider'); const registration = server.create('registration', { provider }); const node = server.create('node', 'currentUserAdmin'); const draftRegistration = server.create('draft-registration', { branchedFrom: node }); const registrationModel = await this.store.findRecord('registration', registration.id); this.set('draftManager', { provider, draftRegistration }); this.set('model', registrationModel); this.set('isOpen', false); await render(hbs` <Registries::FinalizeRegistrationModal::Manager @registration={{this.model}} @draftManager={{this.draftManager}} as |manager| > <Registries::FinalizeRegistrationModal @isOpen={{this.isOpen}} @manager={{manager}} /> </Registries::FinalizeRegistrationModal::Manager> `); // Open the dialog this.set('isOpen', true); await settled(); // Check that the submit button is disabled assert.dom('[data-test-submit-registration-button]').isDisabled(); // Click embargo radio button await click('[data-test-embargo-button]'); // Check that the submit button is disabled assert.dom('[data-test-submit-registration-button]').isDisabled(); // Check that `embargoEndDate` of the registration model is null assert.equal(registrationModel.embargoEndDate, null); // Enter an invalid date for embargo await setFlatpickrDate('[data-test-embargo-date-input] > div > input', moment().format('MM/DD/YYYY')); // Check that`embargoEndDate` of the registration model is null // And that the submit button is disabled assert.equal(registrationModel.embargoEndDate, null); assert.dom('[data-test-submit-registration-button]').isDisabled(); // TODO: Uncomment these lines once the potential race condition for validated-input/date is resolved // // Enter a valid date for embargo // const validDate = moment().add('days', 15).startOf('day'); // await fillIn('[data-test-embargo-date-input] > div > input', validDate.format('MM/DD/YYYY')); // await blur('[data-test-embargo-date-input] > div > input'); // assert.deepEqual(registrationModel.embargoEndDate, validDate.toDate()); // // Check that the submit button is enabled // assert.dom('[data-test-submit-registration-button]').isNotDisabled(); // // Click immediate radio button // await click('[data-test-immediate-button]'); // // Check that the submit button is enabled // assert.dom('[data-test-submit-registration-button]').isNotDisabled(); // // Close the dialog this.set('isOpen', false); }); test('almost done modal content: no moderation with project', async function(assert) { this.store = this.owner.lookup('service:store'); const noModerationProvider = server.create('registration-provider', { reviewsWorkflow: null }); const node = server.create('node', 'currentUserAdmin'); const noModRegistration = server.create( 'registration', { provider: noModerationProvider }, ); const draftRegistration = server.create('draft-registration', { branchedFrom: node }); const registrationModel = await this.store.findRecord('registration', noModRegistration.id); this.set('draftManager', { provider: noModerationProvider, draftRegistration, validateAllVisitedPages: () => { /* noop */ }, }); this.set('model', registrationModel); this.set('isOpen', true); await render(hbs` <Registries::FinalizeRegistrationModal::Manager @registration={{this.model}} @draftManager={{this.draftManager}} as |manager| > <Registries::FinalizeRegistrationModal @isOpen={{this.isOpen}} @manager={{manager}} /> </Registries::FinalizeRegistrationModal::Manager> `); // Click immediate radio button await click('[data-test-immediate-button]'); // Click submit button await click('[data-test-submit-registration-button]'); const opts = { learnMoreLink: 'aaa.aa', htmlSafe: true }; assert.dom('[data-test-finalize-main]').hasTextContaining( stripHtmlTags(t('registries.finalizeRegistrationModal.notice.noModerationFromProject', opts).toString()), 'modal shows warning', ); assert.dom('[data-test-finalize-main]').doesNotHaveTextContaining( 'A moderator must review and approve', 'modal does not mention moderation for unmoderated providers', ); }); test('almost done modal content: with moderation with project', async function(assert) { this.store = this.owner.lookup('service:store'); const withModerationProvider = server.create('registration-provider'); const node = server.create('node', 'currentUserAdmin'); const withModRegistration = server.create( 'registration', { provider: withModerationProvider }, ); const draftRegistration = server.create('draft-registration', { branchedFrom: node }); const registrationModel = await this.store.findRecord('registration', withModRegistration.id); this.set( 'draftManager', { provider: withModerationProvider, reviewsWorkflow: 'pre-moderation', draftRegistration, validateAllVisitedPages: () => { /* noop */ }, }, ); this.set('model', registrationModel); this.set('isOpen', true); await render(hbs` <Registries::FinalizeRegistrationModal::Manager @registration={{this.model}} @draftManager={{this.draftManager}} as |manager| > <Registries::FinalizeRegistrationModal @isOpen={{this.isOpen}} @manager={{manager}} /> </Registries::FinalizeRegistrationModal::Manager> `); // Click immediate radio button await click('[data-test-immediate-button]'); // Click submit button await click('[data-test-submit-registration-button]'); const opts = { learnMoreLink: 'aaa.aa', htmlSafe: true }; assert.dom('[data-test-finalize-main]').hasTextContaining( stripHtmlTags(t('registries.finalizeRegistrationModal.notice.withModerationFromProject', opts).toString()), 'modal shows warning with moderation for moderated providers', ); }); test('almost done modal content: no moderation no project', async function(assert) { this.store = this.owner.lookup('service:store'); const noModerationProvider = server.create('registration-provider', { reviewsWorkflow: null }); const noModRegistration = server.create( 'registration', { provider: noModerationProvider }, ); const draftRegistration = server.create('draft-registration', { hasProject: false }); const registrationModel = await this.store.findRecord('registration', noModRegistration.id); this.set('draftManager', { provider: noModerationProvider, draftRegistration, validateAllVisitedPages: () => { /* noop */ }, }); this.set('model', registrationModel); this.set('isOpen', true); await render(hbs` <Registries::FinalizeRegistrationModal::Manager @registration={{this.model}} @draftManager={{this.draftManager}} as |manager| > <Registries::FinalizeRegistrationModal @isOpen={{this.isOpen}} @manager={{manager}} /> </Registries::FinalizeRegistrationModal::Manager> `); // Click immediate radio button await click('[data-test-immediate-button]'); // Click submit button await click('[data-test-submit-registration-button]'); const opts = { learnMoreLink: 'aaa.aa', htmlSafe: true }; assert.dom('[data-test-finalize-main]').hasTextContaining( stripHtmlTags(t('registries.finalizeRegistrationModal.notice.noModerationNoProject', opts).toString()), 'modal shows warning', ); assert.dom('[data-test-finalize-main]').doesNotHaveTextContaining( 'A moderator must review and approve', 'modal does not mention moderation for unmoderated providers', ); }); test('almost done modal content: with moderation no project', async function(assert) { this.store = this.owner.lookup('service:store'); const withModerationProvider = server.create('registration-provider'); const withModRegistration = server.create( 'registration', { provider: withModerationProvider }, ); const draftRegistration = server.create('draft-registration', { hasProject: false }); const registrationModel = await this.store.findRecord('registration', withModRegistration.id); this.set( 'draftManager', { provider: withModerationProvider, reviewsWorkflow: 'pre-moderation', draftRegistration, validateAllVisitedPages: () => { /* noop */ }, }, ); this.set('model', registrationModel); this.set('isOpen', true); await render(hbs` <Registries::FinalizeRegistrationModal::Manager @registration={{this.model}} @draftManager={{this.draftManager}} as |manager| > <Registries::FinalizeRegistrationModal @isOpen={{this.isOpen}} @manager={{manager}} /> </Registries::FinalizeRegistrationModal::Manager> `); // Click immediate radio button await click('[data-test-immediate-button]'); // Click submit button await click('[data-test-submit-registration-button]'); const opts = { learnMoreLink: 'aaa.aa', htmlSafe: true }; assert.dom('[data-test-finalize-main]').hasTextContaining( stripHtmlTags(t('registries.finalizeRegistrationModal.notice.withModerationNoProject', opts).toString()), 'modal shows warning with moderation for moderated providers', ); }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * The JSON-serialized leaf certificate */ export interface CertificateVerificationDescription { /** * base-64 representation of X509 certificate .cer file or just .pem file content. */ certificate?: string; } /** * The description of an X509 CA Certificate. */ export interface CertificateProperties { /** * The certificate's subject name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subject?: string; /** * The certificate's expiration date and time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly expiry?: Date; /** * The certificate's thumbprint. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbprint?: string; /** * Determines whether certificate has been verified. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isVerified?: boolean; /** * The certificate's create date and time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly created?: Date; /** * The certificate's last update date and time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly updated?: Date; /** * The certificate content */ certificate?: string; } /** * The X509 Certificate. */ export interface CertificateDescription extends BaseResource { properties?: CertificateProperties; /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the certificate. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The entity tag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The JSON-serialized array of Certificate objects. */ export interface CertificateListDescription { /** * The array of Certificate objects. */ value?: CertificateDescription[]; } /** * The JSON-serialized X509 Certificate. */ export interface CertificateBodyDescription { /** * base-64 representation of the X509 leaf certificate .cer file or just .pem file content. */ certificate?: string; } /** * The description of an X509 CA Certificate including the challenge nonce issued for the * Proof-Of-Possession flow. */ export interface CertificatePropertiesWithNonce { /** * The certificate's subject name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subject?: string; /** * The certificate's expiration date and time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly expiry?: Date; /** * The certificate's thumbprint. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly thumbprint?: string; /** * Determines whether certificate has been verified. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isVerified?: boolean; /** * The certificate's create date and time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly created?: Date; /** * The certificate's last update date and time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly updated?: Date; /** * The certificate's verification code that will be used for proof of possession. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly verificationCode?: string; /** * The certificate content * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly certificate?: string; } /** * The X509 Certificate. */ export interface CertificateWithNonceDescription extends BaseResource { properties?: CertificatePropertiesWithNonce; /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the certificate. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The entity tag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The properties of an IoT hub shared access policy. */ export interface SharedAccessSignatureAuthorizationRule { /** * The name of the shared access policy. */ keyName: string; /** * The primary key. */ primaryKey?: string; /** * The secondary key. */ secondaryKey?: string; /** * The permissions assigned to the shared access policy. Possible values include: 'RegistryRead', * 'RegistryWrite', 'ServiceConnect', 'DeviceConnect', 'RegistryRead, RegistryWrite', * 'RegistryRead, ServiceConnect', 'RegistryRead, DeviceConnect', 'RegistryWrite, * ServiceConnect', 'RegistryWrite, DeviceConnect', 'ServiceConnect, DeviceConnect', * 'RegistryRead, RegistryWrite, ServiceConnect', 'RegistryRead, RegistryWrite, DeviceConnect', * 'RegistryRead, ServiceConnect, DeviceConnect', 'RegistryWrite, ServiceConnect, DeviceConnect', * 'RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect' */ rights: AccessRights; } /** * The IP filter rules for the IoT hub. */ export interface IpFilterRule { /** * The name of the IP filter rule. */ filterName: string; /** * The desired action for requests captured by this rule. Possible values include: 'Accept', * 'Reject' */ action: IpFilterActionType; /** * A string that contains the IP address range in CIDR notation for the rule. */ ipMask: string; } /** * The properties of the provisioned Event Hub-compatible endpoint used by the IoT hub. */ export interface EventHubProperties { /** * The retention time for device-to-cloud messages in days. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#device-to-cloud-messages */ retentionTimeInDays?: number; /** * The number of partitions for receiving device-to-cloud messages in the Event Hub-compatible * endpoint. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#device-to-cloud-messages. */ partitionCount?: number; /** * The partition ids in the Event Hub-compatible endpoint. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly partitionIds?: string[]; /** * The Event Hub-compatible name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly path?: string; /** * The Event Hub-compatible endpoint. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endpoint?: string; } /** * The properties related to service bus queue endpoint types. */ export interface RoutingServiceBusQueueEndpointProperties { /** * The connection string of the service bus queue endpoint. */ connectionString: string; /** * The name that identifies this endpoint. The name can only include alphanumeric characters, * periods, underscores, hyphens and has a maximum length of 64 characters. The following names * are reserved: events, fileNotifications, $default. Endpoint names must be unique across * endpoint types. The name need not be the same as the actual queue name. */ name: string; /** * The subscription identifier of the service bus queue endpoint. */ subscriptionId?: string; /** * The name of the resource group of the service bus queue endpoint. */ resourceGroup?: string; } /** * The properties related to service bus topic endpoint types. */ export interface RoutingServiceBusTopicEndpointProperties { /** * The connection string of the service bus topic endpoint. */ connectionString: string; /** * The name that identifies this endpoint. The name can only include alphanumeric characters, * periods, underscores, hyphens and has a maximum length of 64 characters. The following names * are reserved: events, fileNotifications, $default. Endpoint names must be unique across * endpoint types. The name need not be the same as the actual topic name. */ name: string; /** * The subscription identifier of the service bus topic endpoint. */ subscriptionId?: string; /** * The name of the resource group of the service bus topic endpoint. */ resourceGroup?: string; } /** * The properties related to an event hub endpoint. */ export interface RoutingEventHubProperties { /** * The connection string of the event hub endpoint. */ connectionString: string; /** * The name that identifies this endpoint. The name can only include alphanumeric characters, * periods, underscores, hyphens and has a maximum length of 64 characters. The following names * are reserved: events, fileNotifications, $default. Endpoint names must be unique across * endpoint types. */ name: string; /** * The subscription identifier of the event hub endpoint. */ subscriptionId?: string; /** * The name of the resource group of the event hub endpoint. */ resourceGroup?: string; } /** * The properties related to a storage container endpoint. */ export interface RoutingStorageContainerProperties { /** * The connection string of the storage account. */ connectionString: string; /** * The name that identifies this endpoint. The name can only include alphanumeric characters, * periods, underscores, hyphens and has a maximum length of 64 characters. The following names * are reserved: events, fileNotifications, $default. Endpoint names must be unique across * endpoint types. */ name: string; /** * The subscription identifier of the storage account. */ subscriptionId?: string; /** * The name of the resource group of the storage account. */ resourceGroup?: string; /** * The name of storage container in the storage account. */ containerName: string; /** * File name format for the blob. Default format is * {iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}. All parameters are mandatory but can be * reordered. */ fileNameFormat?: string; /** * Time interval at which blobs are written to storage. Value should be between 60 and 720 * seconds. Default value is 300 seconds. */ batchFrequencyInSeconds?: number; /** * Maximum number of bytes for each blob written to storage. Value should be between * 10485760(10MB) and 524288000(500MB). Default value is 314572800(300MB). */ maxChunkSizeInBytes?: number; /** * Encoding that is used to serialize messages to blobs. Supported values are 'avro', * 'avrodeflate', and 'JSON'. Default value is 'avro'. Possible values include: 'Avro', * 'AvroDeflate', 'JSON' */ encoding?: Encoding; } /** * The properties related to the custom endpoints to which your IoT hub routes messages based on * the routing rules. A maximum of 10 custom endpoints are allowed across all endpoint types for * paid hubs and only 1 custom endpoint is allowed across all endpoint types for free hubs. */ export interface RoutingEndpoints { /** * The list of Service Bus queue endpoints that IoT hub routes the messages to, based on the * routing rules. */ serviceBusQueues?: RoutingServiceBusQueueEndpointProperties[]; /** * The list of Service Bus topic endpoints that the IoT hub routes the messages to, based on the * routing rules. */ serviceBusTopics?: RoutingServiceBusTopicEndpointProperties[]; /** * The list of Event Hubs endpoints that IoT hub routes messages to, based on the routing rules. * This list does not include the built-in Event Hubs endpoint. */ eventHubs?: RoutingEventHubProperties[]; /** * The list of storage container endpoints that IoT hub routes messages to, based on the routing * rules. */ storageContainers?: RoutingStorageContainerProperties[]; } /** * The properties of a routing rule that your IoT hub uses to route messages to endpoints. */ export interface RouteProperties { /** * The name of the route. The name can only include alphanumeric characters, periods, * underscores, hyphens, has a maximum length of 64 characters, and must be unique. */ name: string; /** * The source that the routing rule is to be applied to, such as DeviceMessages. Possible values * include: 'Invalid', 'DeviceMessages', 'TwinChangeEvents', 'DeviceLifecycleEvents', * 'DeviceJobLifecycleEvents', 'DigitalTwinChangeEvents' */ source: RoutingSource; /** * The condition that is evaluated to apply the routing rule. If no condition is provided, it * evaluates to true by default. For grammar, see: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language */ condition?: string; /** * The list of endpoints to which messages that satisfy the condition are routed. Currently only * one endpoint is allowed. */ endpointNames: string[]; /** * Used to specify whether a route is enabled. */ isEnabled: boolean; } /** * The properties of the fallback route. IoT Hub uses these properties when it routes messages to * the fallback endpoint. */ export interface FallbackRouteProperties { /** * The name of the route. The name can only include alphanumeric characters, periods, * underscores, hyphens, has a maximum length of 64 characters, and must be unique. */ name?: string; /** * The condition which is evaluated in order to apply the fallback route. If the condition is not * provided it will evaluate to true by default. For grammar, See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language */ condition?: string; /** * The list of endpoints to which the messages that satisfy the condition are routed to. * Currently only 1 endpoint is allowed. */ endpointNames: string[]; /** * Used to specify whether the fallback route is enabled. */ isEnabled: boolean; } /** * The properties of an enrichment that your IoT hub applies to messages delivered to endpoints. */ export interface EnrichmentProperties { /** * The key or name for the enrichment property. */ key: string; /** * The value for the enrichment property. */ value: string; /** * The list of endpoints for which the enrichment is applied to the message. */ endpointNames: string[]; } /** * The routing related properties of the IoT hub. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging */ export interface RoutingProperties { endpoints?: RoutingEndpoints; /** * The list of user-provided routing rules that the IoT hub uses to route messages to built-in * and custom endpoints. A maximum of 100 routing rules are allowed for paid hubs and a maximum * of 5 routing rules are allowed for free hubs. */ routes?: RouteProperties[]; /** * The properties of the route that is used as a fall-back route when none of the conditions * specified in the 'routes' section are met. This is an optional parameter. When this property * is not set, the messages which do not meet any of the conditions specified in the 'routes' * section get routed to the built-in eventhub endpoint. */ fallbackRoute?: FallbackRouteProperties; /** * The list of user-provided enrichments that the IoT hub applies to messages to be delivered to * built-in and custom endpoints. See: https://aka.ms/iotmsgenrich */ enrichments?: EnrichmentProperties[]; } /** * The properties of the Azure Storage endpoint for file upload. */ export interface StorageEndpointProperties { /** * The period of time for which the SAS URI generated by IoT Hub for file upload is valid. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload#file-upload-notification-configuration-options. */ sasTtlAsIso8601?: string; /** * The connection string for the Azure Storage account to which files are uploaded. */ connectionString: string; /** * The name of the root container where you upload files. The container need not exist but should * be creatable using the connectionString specified. */ containerName: string; } /** * The properties of the messaging endpoints used by this IoT hub. */ export interface MessagingEndpointProperties { /** * The lock duration. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload. */ lockDurationAsIso8601?: string; /** * The period of time for which a message is available to consume before it is expired by the IoT * hub. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload. */ ttlAsIso8601?: string; /** * The number of times the IoT hub attempts to deliver a message. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-file-upload. */ maxDeliveryCount?: number; } /** * The properties of the feedback queue for cloud-to-device messages. */ export interface FeedbackProperties { /** * The lock duration for the feedback queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. */ lockDurationAsIso8601?: string; /** * The period of time for which a message is available to consume before it is expired by the IoT * hub. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. */ ttlAsIso8601?: string; /** * The number of times the IoT hub attempts to deliver a message on the feedback queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. */ maxDeliveryCount?: number; } /** * The IoT hub cloud-to-device messaging properties. */ export interface CloudToDeviceProperties { /** * The max delivery count for cloud-to-device messages in the device queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. */ maxDeliveryCount?: number; /** * The default time to live for cloud-to-device messages in the device queue. See: * https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages. */ defaultTtlAsIso8601?: string; feedback?: FeedbackProperties; } /** * The device streams properties of iothub. */ export interface IotHubPropertiesDeviceStreams { /** * List of Device Streams Endpoints. */ streamingEndpoints?: string[]; } /** * Public representation of one of the locations where a resource is provisioned. */ export interface IotHubLocationDescription { /** * Azure Geo Regions */ location?: string; /** * Specific Role assigned to this location. Possible values include: 'primary', 'secondary' */ role?: IotHubReplicaRoleType; } /** * The properties of an IoT hub. */ export interface IotHubProperties { /** * The shared access policies you can use to secure a connection to the IoT hub. */ authorizationPolicies?: SharedAccessSignatureAuthorizationRule[]; /** * The IP filter rules. */ ipFilterRules?: IpFilterRule[]; /** * The provisioning state. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: string; /** * The hub state. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly state?: string; /** * The name of the host. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hostName?: string; /** * The Event Hub-compatible endpoint properties. The only possible keys to this dictionary is * events. This key has to be present in the dictionary while making create or update calls for * the IoT hub. */ eventHubEndpoints?: { [propertyName: string]: EventHubProperties }; routing?: RoutingProperties; /** * The list of Azure Storage endpoints where you can upload files. Currently you can configure * only one Azure Storage account and that MUST have its key as $default. Specifying more than * one storage account causes an error to be thrown. Not specifying a value for this property * when the enableFileUploadNotifications property is set to True, causes an error to be thrown. */ storageEndpoints?: { [propertyName: string]: StorageEndpointProperties }; /** * The messaging endpoint properties for the file upload notification queue. */ messagingEndpoints?: { [propertyName: string]: MessagingEndpointProperties }; /** * If True, file upload notifications are enabled. */ enableFileUploadNotifications?: boolean; cloudToDevice?: CloudToDeviceProperties; /** * IoT hub comments. */ comments?: string; /** * The device streams properties of iothub. */ deviceStreams?: IotHubPropertiesDeviceStreams; /** * The capabilities and features enabled for the IoT hub. Possible values include: 'None', * 'DeviceManagement' */ features?: Capabilities; /** * Primary and secondary location for iot hub * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly locations?: IotHubLocationDescription[]; } /** * Information about the SKU of the IoT hub. */ export interface IotHubSkuInfo { /** * The name of the SKU. Possible values include: 'F1', 'S1', 'S2', 'S3', 'B1', 'B2', 'B3' */ name: IotHubSku; /** * The billing tier for the IoT hub. Possible values include: 'Free', 'Standard', 'Basic' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tier?: IotHubSkuTier; /** * The number of provisioned IoT Hub units. See: * https://docs.microsoft.com/azure/azure-subscription-service-limits#iot-hub-limits. */ capacity?: number; } /** * The common properties of an Azure resource. */ export interface Resource extends BaseResource { /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The resource location. */ location: string; /** * The resource tags. */ tags?: { [propertyName: string]: string }; } /** * The description of the IoT hub. */ export interface IotHubDescription extends Resource { /** * The Etag field is *not* required. If it is provided in the response body, it must also be * provided as a header per the normal ETag convention. */ etag?: string; /** * IotHub properties */ properties?: IotHubProperties; /** * IotHub SKU info */ sku: IotHubSkuInfo; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft Devices * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: string; /** * Resource Type: IotHubs * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resource?: string; /** * Name of the operation * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; /** * Description of the operation * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; } /** * IoT Hub REST API operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{read | write | action | delete} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The object that represents the operation. */ display?: OperationDisplay; } /** * Error details. */ export interface ErrorDetails { /** * The error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * The HTTP status code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly httpStatusCode?: string; /** * The error message. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The error details. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: string; } /** * Quota metrics properties. */ export interface IotHubQuotaMetricInfo { /** * The name of the quota metric. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The current value for the quota metric. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly currentValue?: number; /** * The maximum value of the quota metric. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly maxValue?: number; } /** * The health data for an endpoint */ export interface EndpointHealthData { /** * Id of the endpoint */ endpointId?: string; /** * Health statuses have following meanings. The 'healthy' status shows that the endpoint is * accepting messages as expected. The 'unhealthy' status shows that the endpoint is not * accepting messages as expected and IoT Hub is retrying to send data to this endpoint. The * status of an unhealthy endpoint will be updated to healthy when IoT Hub has established an * eventually consistent state of health. The 'dead' status shows that the endpoint is not * accepting messages, after IoT Hub retried sending messages for the retrial period. See IoT Hub * metrics to identify errors and monitor issues with endpoints. The 'unknown' status shows that * the IoT Hub has not established a connection with the endpoint. No messages have been * delivered to or rejected from this endpoint. Possible values include: 'unknown', 'healthy', * 'unhealthy', 'dead' */ healthStatus?: EndpointHealthStatus; } /** * Identity registry statistics. */ export interface RegistryStatistics { /** * The total count of devices in the identity registry. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly totalDeviceCount?: number; /** * The count of enabled devices in the identity registry. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly enabledDeviceCount?: number; /** * The count of disabled devices in the identity registry. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly disabledDeviceCount?: number; } /** * The properties of the Job Response object. */ export interface JobResponse { /** * The job identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly jobId?: string; /** * The start time of the job. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly startTimeUtc?: Date; /** * The time the job stopped processing. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endTimeUtc?: Date; /** * The type of the job. Possible values include: 'unknown', 'export', 'import', 'backup', * 'readDeviceProperties', 'writeDeviceProperties', 'updateDeviceConfiguration', 'rebootDevice', * 'factoryResetDevice', 'firmwareUpdate' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: JobType; /** * The status of the job. Possible values include: 'unknown', 'enqueued', 'running', 'completed', * 'failed', 'cancelled' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: JobStatus; /** * If status == failed, this string containing the reason for the failure. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly failureReason?: string; /** * The status message for the job. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statusMessage?: string; /** * The job identifier of the parent job, if any. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly parentJobId?: string; } /** * IoT Hub capacity information. */ export interface IotHubCapacity { /** * The minimum number of units. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly minimum?: number; /** * The maximum number of units. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly maximum?: number; /** * The default number of units. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly default?: number; /** * The type of the scaling enabled. Possible values include: 'Automatic', 'Manual', 'None' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly scaleType?: IotHubScaleType; } /** * SKU properties. */ export interface IotHubSkuDescription { /** * The type of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resourceType?: string; /** * The type of the resource. */ sku: IotHubSkuInfo; /** * IotHub capacity */ capacity: IotHubCapacity; } /** * A container holding only the Tags for a resource, allowing the user to update the tags on an IoT * Hub instance. */ export interface TagsResource { /** * Resource tags */ tags?: { [propertyName: string]: string }; } /** * The properties of the EventHubConsumerGroupInfo object. */ export interface EventHubConsumerGroupInfo extends BaseResource { /** * The tags. */ properties?: { [propertyName: string]: string }; /** * The Event Hub-compatible consumer group identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The Event Hub-compatible consumer group name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * the resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * Input values. */ export interface OperationInputs { /** * The name of the IoT hub to check. */ name: string; } /** * The properties indicating whether a given IoT hub name is available. */ export interface IotHubNameAvailabilityInfo { /** * The value which indicates whether the provided name is available. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nameAvailable?: boolean; /** * The reason for unavailability. Possible values include: 'Invalid', 'AlreadyExists' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reason?: IotHubNameUnavailabilityReason; /** * The detailed reason message. */ message?: string; } /** * Name of Iot Hub type */ export interface Name { /** * IotHub type */ value?: string; /** * Localized value of name */ localizedValue?: string; } /** * User subscription quota response */ export interface UserSubscriptionQuota { /** * IotHub type id */ id?: string; /** * Response type */ type?: string; /** * Unit of IotHub type */ unit?: string; /** * Current number of IotHub type */ currentValue?: number; /** * Numerical limit on IotHub type */ limit?: number; /** * IotHub type */ name?: Name; } /** * Json-serialized array of User subscription quota response */ export interface UserSubscriptionQuotaListResult { value?: UserSubscriptionQuota[]; /** * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * Routing message */ export interface RoutingMessage { /** * Body of routing message */ body?: string; /** * App properties */ appProperties?: { [propertyName: string]: string }; /** * System properties */ systemProperties?: { [propertyName: string]: string }; } /** * An interface representing RoutingTwinProperties. */ export interface RoutingTwinProperties { /** * Twin desired properties */ desired?: any; /** * Twin desired properties */ reported?: any; } /** * Twin reference input parameter. This is an optional parameter */ export interface RoutingTwin { /** * Twin Tags */ tags?: any; properties?: RoutingTwinProperties; } /** * Input for testing all routes */ export interface TestAllRoutesInput { /** * Routing source. Possible values include: 'Invalid', 'DeviceMessages', 'TwinChangeEvents', * 'DeviceLifecycleEvents', 'DeviceJobLifecycleEvents', 'DigitalTwinChangeEvents' */ routingSource?: RoutingSource; /** * Routing message */ message?: RoutingMessage; /** * Routing Twin Reference */ twin?: RoutingTwin; } /** * Routes that matched */ export interface MatchedRoute { /** * Properties of routes that matched */ properties?: RouteProperties; } /** * Result of testing all routes */ export interface TestAllRoutesResult { /** * JSON-serialized array of matched routes */ routes?: MatchedRoute[]; } /** * Input for testing route */ export interface TestRouteInput { /** * Routing message */ message?: RoutingMessage; /** * Route properties */ route: RouteProperties; /** * Routing Twin Reference */ twin?: RoutingTwin; } /** * Position where the route error happened */ export interface RouteErrorPosition { /** * Line where the route error happened */ line?: number; /** * Column where the route error happened */ column?: number; } /** * Range of route errors */ export interface RouteErrorRange { /** * Start where the route error happened */ start?: RouteErrorPosition; /** * End where the route error happened */ end?: RouteErrorPosition; } /** * Compilation error when evaluating route */ export interface RouteCompilationError { /** * Route error message */ message?: string; /** * Severity of the route error. Possible values include: 'error', 'warning' */ severity?: RouteErrorSeverity; /** * Location where the route error happened */ location?: RouteErrorRange; } /** * Detailed result of testing a route */ export interface TestRouteResultDetails { /** * JSON-serialized list of route compilation errors */ compilationErrors?: RouteCompilationError[]; } /** * Result of testing one route */ export interface TestRouteResult { /** * Result of testing route. Possible values include: 'undefined', 'false', 'true' */ result?: TestResultStatus; /** * Detailed result of testing route */ details?: TestRouteResultDetails; } /** * Use to provide parameters when requesting an export of all devices in the IoT hub. */ export interface ExportDevicesRequest { /** * The export blob container URI. */ exportBlobContainerUri: string; /** * The value indicating whether keys should be excluded during export. */ excludeKeys: boolean; } /** * Use to provide parameters when requesting an import of all devices in the hub. */ export interface ImportDevicesRequest { /** * The input blob container URI. */ inputBlobContainerUri: string; /** * The output blob container URI. */ outputBlobContainerUri: string; } /** * Use to provide failover region when requesting manual Failover for a hub. */ export interface FailoverInput { /** * Region the hub will be failed over to */ failoverRegion: string; } /** * Optional Parameters. */ export interface IotHubResourceCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * ETag of the IoT Hub. Do not specify for creating a brand new IoT Hub. Required to update an * existing IoT Hub. */ ifMatch?: string; } /** * Optional Parameters. */ export interface IotHubResourceBeginCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * ETag of the IoT Hub. Do not specify for creating a brand new IoT Hub. Required to update an * existing IoT Hub. */ ifMatch?: string; } /** * Optional Parameters. */ export interface CertificatesCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * ETag of the Certificate. Do not specify for creating a brand new certificate. Required to * update an existing certificate. */ ifMatch?: string; } /** * An interface representing IotHubClientOptions. */ export interface IotHubClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Result of the request to list IoT Hub operations. It contains a list of operations and a URL * link to get the next set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * URL to get the next set of operation list results if there are any. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The JSON-serialized array of IotHubDescription objects with a next link. * @extends Array<IotHubDescription> */ export interface IotHubDescriptionListResult extends Array<IotHubDescription> { /** * The next link. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The JSON-serialized array of IotHubSkuDescription objects with a next link. * @extends Array<IotHubSkuDescription> */ export interface IotHubSkuDescriptionListResult extends Array<IotHubSkuDescription> { /** * The next link. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The JSON-serialized array of Event Hub-compatible consumer group names with a next link. * @extends Array<EventHubConsumerGroupInfo> */ export interface EventHubConsumerGroupsListResult extends Array<EventHubConsumerGroupInfo> { /** * The next link. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The JSON-serialized array of JobResponse objects with a next link. * @extends Array<JobResponse> */ export interface JobResponseListResult extends Array<JobResponse> { /** * The next link. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The JSON-serialized array of IotHubQuotaMetricInfo objects with a next link. * @extends Array<IotHubQuotaMetricInfo> */ export interface IotHubQuotaMetricInfoListResult extends Array<IotHubQuotaMetricInfo> { /** * The next link. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The JSON-serialized array of EndpointHealthData objects with a next link. * @extends Array<EndpointHealthData> */ export interface EndpointHealthDataListResult extends Array<EndpointHealthData> { /** * Link to more results * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * The list of shared access policies with a next link. * @extends Array<SharedAccessSignatureAuthorizationRule> */ export interface SharedAccessSignatureAuthorizationRuleListResult extends Array<SharedAccessSignatureAuthorizationRule> { /** * The next link. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nextLink?: string; } /** * Defines values for AccessRights. * Possible values include: 'RegistryRead', 'RegistryWrite', 'ServiceConnect', 'DeviceConnect', * 'RegistryRead, RegistryWrite', 'RegistryRead, ServiceConnect', 'RegistryRead, DeviceConnect', * 'RegistryWrite, ServiceConnect', 'RegistryWrite, DeviceConnect', 'ServiceConnect, * DeviceConnect', 'RegistryRead, RegistryWrite, ServiceConnect', 'RegistryRead, RegistryWrite, * DeviceConnect', 'RegistryRead, ServiceConnect, DeviceConnect', 'RegistryWrite, ServiceConnect, * DeviceConnect', 'RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect' * @readonly * @enum {string} */ export type AccessRights = 'RegistryRead' | 'RegistryWrite' | 'ServiceConnect' | 'DeviceConnect' | 'RegistryRead, RegistryWrite' | 'RegistryRead, ServiceConnect' | 'RegistryRead, DeviceConnect' | 'RegistryWrite, ServiceConnect' | 'RegistryWrite, DeviceConnect' | 'ServiceConnect, DeviceConnect' | 'RegistryRead, RegistryWrite, ServiceConnect' | 'RegistryRead, RegistryWrite, DeviceConnect' | 'RegistryRead, ServiceConnect, DeviceConnect' | 'RegistryWrite, ServiceConnect, DeviceConnect' | 'RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect'; /** * Defines values for IpFilterActionType. * Possible values include: 'Accept', 'Reject' * @readonly * @enum {string} */ export type IpFilterActionType = 'Accept' | 'Reject'; /** * Defines values for RoutingSource. * Possible values include: 'Invalid', 'DeviceMessages', 'TwinChangeEvents', * 'DeviceLifecycleEvents', 'DeviceJobLifecycleEvents', 'DigitalTwinChangeEvents' * @readonly * @enum {string} */ export type RoutingSource = 'Invalid' | 'DeviceMessages' | 'TwinChangeEvents' | 'DeviceLifecycleEvents' | 'DeviceJobLifecycleEvents' | 'DigitalTwinChangeEvents'; /** * Defines values for Capabilities. * Possible values include: 'None', 'DeviceManagement' * @readonly * @enum {string} */ export type Capabilities = 'None' | 'DeviceManagement'; /** * Defines values for IotHubReplicaRoleType. * Possible values include: 'primary', 'secondary' * @readonly * @enum {string} */ export type IotHubReplicaRoleType = 'primary' | 'secondary'; /** * Defines values for IotHubSku. * Possible values include: 'F1', 'S1', 'S2', 'S3', 'B1', 'B2', 'B3' * @readonly * @enum {string} */ export type IotHubSku = 'F1' | 'S1' | 'S2' | 'S3' | 'B1' | 'B2' | 'B3'; /** * Defines values for IotHubSkuTier. * Possible values include: 'Free', 'Standard', 'Basic' * @readonly * @enum {string} */ export type IotHubSkuTier = 'Free' | 'Standard' | 'Basic'; /** * Defines values for EndpointHealthStatus. * Possible values include: 'unknown', 'healthy', 'unhealthy', 'dead' * @readonly * @enum {string} */ export type EndpointHealthStatus = 'unknown' | 'healthy' | 'unhealthy' | 'dead'; /** * Defines values for JobType. * Possible values include: 'unknown', 'export', 'import', 'backup', 'readDeviceProperties', * 'writeDeviceProperties', 'updateDeviceConfiguration', 'rebootDevice', 'factoryResetDevice', * 'firmwareUpdate' * @readonly * @enum {string} */ export type JobType = 'unknown' | 'export' | 'import' | 'backup' | 'readDeviceProperties' | 'writeDeviceProperties' | 'updateDeviceConfiguration' | 'rebootDevice' | 'factoryResetDevice' | 'firmwareUpdate'; /** * Defines values for JobStatus. * Possible values include: 'unknown', 'enqueued', 'running', 'completed', 'failed', 'cancelled' * @readonly * @enum {string} */ export type JobStatus = 'unknown' | 'enqueued' | 'running' | 'completed' | 'failed' | 'cancelled'; /** * Defines values for IotHubScaleType. * Possible values include: 'Automatic', 'Manual', 'None' * @readonly * @enum {string} */ export type IotHubScaleType = 'Automatic' | 'Manual' | 'None'; /** * Defines values for IotHubNameUnavailabilityReason. * Possible values include: 'Invalid', 'AlreadyExists' * @readonly * @enum {string} */ export type IotHubNameUnavailabilityReason = 'Invalid' | 'AlreadyExists'; /** * Defines values for TestResultStatus. * Possible values include: 'undefined', 'false', 'true' * @readonly * @enum {string} */ export type TestResultStatus = 'undefined' | 'false' | 'true'; /** * Defines values for RouteErrorSeverity. * Possible values include: 'error', 'warning' * @readonly * @enum {string} */ export type RouteErrorSeverity = 'error' | 'warning'; /** * Defines values for Encoding. * Possible values include: 'Avro', 'AvroDeflate', 'JSON' * @readonly * @enum {string} */ export type Encoding = 'Avro' | 'AvroDeflate' | 'JSON'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the get operation. */ export type IotHubResourceGetResponse = IotHubDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescription; }; }; /** * Contains response data for the createOrUpdate operation. */ export type IotHubResourceCreateOrUpdateResponse = IotHubDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescription; }; }; /** * Contains response data for the update operation. */ export type IotHubResourceUpdateResponse = IotHubDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescription; }; }; /** * Contains response data for the deleteMethod operation. */ export type IotHubResourceDeleteMethodResponse = { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; }; }; /** * Contains response data for the listBySubscription operation. */ export type IotHubResourceListBySubscriptionResponse = IotHubDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type IotHubResourceListByResourceGroupResponse = IotHubDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescriptionListResult; }; }; /** * Contains response data for the getStats operation. */ export type IotHubResourceGetStatsResponse = RegistryStatistics & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RegistryStatistics; }; }; /** * Contains response data for the getValidSkus operation. */ export type IotHubResourceGetValidSkusResponse = IotHubSkuDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubSkuDescriptionListResult; }; }; /** * Contains response data for the listEventHubConsumerGroups operation. */ export type IotHubResourceListEventHubConsumerGroupsResponse = EventHubConsumerGroupsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventHubConsumerGroupsListResult; }; }; /** * Contains response data for the getEventHubConsumerGroup operation. */ export type IotHubResourceGetEventHubConsumerGroupResponse = EventHubConsumerGroupInfo & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventHubConsumerGroupInfo; }; }; /** * Contains response data for the createEventHubConsumerGroup operation. */ export type IotHubResourceCreateEventHubConsumerGroupResponse = EventHubConsumerGroupInfo & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventHubConsumerGroupInfo; }; }; /** * Contains response data for the listJobs operation. */ export type IotHubResourceListJobsResponse = JobResponseListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobResponseListResult; }; }; /** * Contains response data for the getJob operation. */ export type IotHubResourceGetJobResponse = JobResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobResponse; }; }; /** * Contains response data for the getQuotaMetrics operation. */ export type IotHubResourceGetQuotaMetricsResponse = IotHubQuotaMetricInfoListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubQuotaMetricInfoListResult; }; }; /** * Contains response data for the getEndpointHealth operation. */ export type IotHubResourceGetEndpointHealthResponse = EndpointHealthDataListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EndpointHealthDataListResult; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type IotHubResourceCheckNameAvailabilityResponse = IotHubNameAvailabilityInfo & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubNameAvailabilityInfo; }; }; /** * Contains response data for the testAllRoutes operation. */ export type IotHubResourceTestAllRoutesResponse = TestAllRoutesResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: TestAllRoutesResult; }; }; /** * Contains response data for the testRoute operation. */ export type IotHubResourceTestRouteResponse = TestRouteResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: TestRouteResult; }; }; /** * Contains response data for the listKeys operation. */ export type IotHubResourceListKeysResponse = SharedAccessSignatureAuthorizationRuleListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SharedAccessSignatureAuthorizationRuleListResult; }; }; /** * Contains response data for the getKeysForKeyName operation. */ export type IotHubResourceGetKeysForKeyNameResponse = SharedAccessSignatureAuthorizationRule & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SharedAccessSignatureAuthorizationRule; }; }; /** * Contains response data for the exportDevices operation. */ export type IotHubResourceExportDevicesResponse = JobResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobResponse; }; }; /** * Contains response data for the importDevices operation. */ export type IotHubResourceImportDevicesResponse = JobResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobResponse; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type IotHubResourceBeginCreateOrUpdateResponse = IotHubDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescription; }; }; /** * Contains response data for the beginUpdate operation. */ export type IotHubResourceBeginUpdateResponse = IotHubDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescription; }; }; /** * Contains response data for the beginDeleteMethod operation. */ export type IotHubResourceBeginDeleteMethodResponse = { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type IotHubResourceListBySubscriptionNextResponse = IotHubDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type IotHubResourceListByResourceGroupNextResponse = IotHubDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubDescriptionListResult; }; }; /** * Contains response data for the getValidSkusNext operation. */ export type IotHubResourceGetValidSkusNextResponse = IotHubSkuDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubSkuDescriptionListResult; }; }; /** * Contains response data for the listEventHubConsumerGroupsNext operation. */ export type IotHubResourceListEventHubConsumerGroupsNextResponse = EventHubConsumerGroupsListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EventHubConsumerGroupsListResult; }; }; /** * Contains response data for the listJobsNext operation. */ export type IotHubResourceListJobsNextResponse = JobResponseListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobResponseListResult; }; }; /** * Contains response data for the getQuotaMetricsNext operation. */ export type IotHubResourceGetQuotaMetricsNextResponse = IotHubQuotaMetricInfoListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotHubQuotaMetricInfoListResult; }; }; /** * Contains response data for the getEndpointHealthNext operation. */ export type IotHubResourceGetEndpointHealthNextResponse = EndpointHealthDataListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: EndpointHealthDataListResult; }; }; /** * Contains response data for the listKeysNext operation. */ export type IotHubResourceListKeysNextResponse = SharedAccessSignatureAuthorizationRuleListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SharedAccessSignatureAuthorizationRuleListResult; }; }; /** * Contains response data for the getSubscriptionQuota operation. */ export type ResourceProviderCommonGetSubscriptionQuotaResponse = UserSubscriptionQuotaListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: UserSubscriptionQuotaListResult; }; }; /** * Contains response data for the listByIotHub operation. */ export type CertificatesListByIotHubResponse = CertificateListDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateListDescription; }; }; /** * Contains response data for the get operation. */ export type CertificatesGetResponse = CertificateDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateDescription; }; }; /** * Contains response data for the createOrUpdate operation. */ export type CertificatesCreateOrUpdateResponse = CertificateDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateDescription; }; }; /** * Contains response data for the generateVerificationCode operation. */ export type CertificatesGenerateVerificationCodeResponse = CertificateWithNonceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateWithNonceDescription; }; }; /** * Contains response data for the verify operation. */ export type CertificatesVerifyResponse = CertificateDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateDescription; }; };
the_stack
import valueParser from 'postcss-value-parser'; import type { FunctionNode, Dimension, Node, DivNode, WordNode, SpaceNode } from 'postcss-value-parser'; import { oklabToDisplayP3 } from './convert-oklab-to-display-p3'; import { oklchToDisplayP3 } from './convert-oklch-to-display-p3'; import { Declaration, Result } from 'postcss'; import { oklabToSRgb } from './convert-oklab-to-srgb'; import { oklchToSRgb } from './convert-oklch-to-srgb'; export function onCSSFunctionSRgb(node: FunctionNode) { const value = node.value; const rawNodes = node.nodes; const relevantNodes = rawNodes.slice().filter((x) => { return x.type !== 'comment' && x.type !== 'space'; }); let nodes: Lch | Lab | null = null; if (value === 'oklab') { nodes = oklabFunctionContents(relevantNodes); } else if (value === 'oklch') { nodes = oklchFunctionContents(relevantNodes); } if (!nodes) { return; } // rename the Color function to `rgb` node.value = 'rgb'; transformAlpha(node, nodes.slash, nodes.alpha); /** Extracted Color channels. */ const [channelNode1, channelNode2, channelNode3] = channelNodes(nodes); const [channelDimension1, channelDimension2, channelDimension3] = channelDimensions(nodes); /** Corresponding Color transformer. */ const toRGB = value === 'oklab' ? oklabToSRgb : oklchToSRgb; /** RGB channels from the source color. */ const channelNumbers: [number, number, number] = [ channelDimension1.number, channelDimension2.number, channelDimension3.number, ].map( channelNumber => parseFloat(channelNumber), ) as [number, number, number]; const rgbValues = toRGB( channelNumbers, ); node.nodes.splice(node.nodes.indexOf(channelNode1) + 1, 0, commaNode()); node.nodes.splice(node.nodes.indexOf(channelNode2) + 1, 0, commaNode()); replaceWith(node.nodes, channelNode1, { ...channelNode1, value: String(rgbValues[0]), }); replaceWith(node.nodes, channelNode2, { ...channelNode2, value: String(rgbValues[1]), }); replaceWith(node.nodes, channelNode3, { ...channelNode3, value: String(rgbValues[2]), }); } export function onCSSFunctionDisplayP3(node: FunctionNode, decl: Declaration, result: Result, preserve: boolean) { const originalForWarnings = valueParser.stringify(node); const value = node.value; const rawNodes = node.nodes; const relevantNodes = rawNodes.slice().filter((x) => { return x.type !== 'comment' && x.type !== 'space'; }); let nodes: Lch | Lab | null = null; if (value === 'oklab') { nodes = oklabFunctionContents(relevantNodes); } else if (value === 'oklch') { nodes = oklchFunctionContents(relevantNodes); } if (!nodes) { return; } if (relevantNodes.length > 3 && (!nodes.slash || !nodes.alpha)) { return; } // rename the Color function to `color` node.value = 'color'; /** Extracted Color channels. */ const [channelNode1, channelNode2, channelNode3] = channelNodes(nodes); const [channelDimension1, channelDimension2, channelDimension3] = channelDimensions(nodes); /** Corresponding Color transformer. */ const toDisplayP3 = value === 'oklab' ? oklabToDisplayP3 : oklchToDisplayP3; /** RGB channels from the source color. */ const channelNumbers: [number, number, number] = [ channelDimension1.number, channelDimension2.number, channelDimension3.number, ].map( channelNumber => parseFloat(channelNumber), ) as [number, number, number]; const [rgbValues, inGamut] = toDisplayP3( channelNumbers, ); if (!inGamut && preserve) { decl.warn( result, `"${originalForWarnings}" is out of gamut for "display-p3". Given "preserve: true" is set, this will lead to unexpected results in some browsers.`, ); } node.nodes.splice(0, 0, displayP3Node()); node.nodes.splice(1, 0, spaceNode()); replaceWith(node.nodes, channelNode1, { ...channelNode1, value: rgbValues[0].toFixed(5), }); replaceWith(node.nodes, channelNode2, { ...channelNode2, value: rgbValues[1].toFixed(5), }); replaceWith(node.nodes, channelNode3, { ...channelNode3, value: rgbValues[2].toFixed(5), }); } function commaNode(): DivNode { return { sourceIndex: 0, sourceEndIndex: 1, value: ',', type: 'div', before: '', after: '', }; } function spaceNode(): SpaceNode { return { sourceIndex: 0, sourceEndIndex: 1, value: ' ', type: 'space', }; } function displayP3Node(): WordNode { return { sourceIndex: 0, sourceEndIndex: 10, value: 'display-p3', type: 'word', }; } function isNumericNode(node: Node): node is WordNode { if (!node || node.type !== 'word') { return false; } if (!canParseAsUnit(node)) { return false; } const unitAndValue = valueParser.unit(node.value); if (!unitAndValue) { return false; } return !!unitAndValue.number; } function isNumericNodeHueLike(node: Node): node is WordNode { if (!node || node.type !== 'word') { return false; } if (!canParseAsUnit(node)) { return false; } const unitAndValue = valueParser.unit(node.value); if (!unitAndValue) { return false; } return !!unitAndValue.number && ( unitAndValue.unit === 'deg' || unitAndValue.unit === 'grad' || unitAndValue.unit === 'rad' || unitAndValue.unit === 'turn' || unitAndValue.unit === '' ); } function isNumericNodePercentageOrNumber(node: Node): node is WordNode { if (!node || node.type !== 'word') { return false; } if (!canParseAsUnit(node)) { return false; } const unitAndValue = valueParser.unit(node.value); if (!unitAndValue) { return false; } return unitAndValue.unit === '%' || unitAndValue.unit === ''; } function isCalcNode(node: Node): node is FunctionNode { return node && node.type === 'function' && node.value === 'calc'; } function isVarNode(node: Node): node is FunctionNode { return node && node.type === 'function' && node.value === 'var'; } function isSlashNode(node: Node): node is DivNode { return node && node.type === 'div' && node.value === '/'; } type Lch = { l: Dimension, lNode: Node, c: Dimension, cNode: Node, h: Dimension, hNode: Node, slash?: DivNode, alpha?: WordNode|FunctionNode, } function oklchFunctionContents(nodes): Lch|null { if (!isNumericNodePercentageOrNumber(nodes[0])) { return null; } if (!isNumericNodePercentageOrNumber(nodes[1])) { return null; } if (!isNumericNodeHueLike(nodes[2])) { return null; } const out: Lch = { l: valueParser.unit(nodes[0].value) as Dimension, lNode: nodes[0], c: valueParser.unit(nodes[1].value) as Dimension, cNode: nodes[1], h: valueParser.unit(nodes[2].value) as Dimension, hNode: nodes[2], }; normalizeHueNode(out.h); if (out.h.unit !== '') { return null; } if (isSlashNode(nodes[3])) { out.slash = nodes[3]; } if ((isNumericNodePercentageOrNumber(nodes[4]) || isCalcNode(nodes[4]) || isVarNode(nodes[4]))) { out.alpha = nodes[4]; } if (nodes.length > 3 && (!out.slash || !out.alpha)) { return null; } // 0% = 0.0, 100% = 1.0 if (out.l.unit === '%') { out.l.unit = ''; out.l.number = (parseFloat(out.l.number) / 100).toFixed(10); } // -100% = -0.4, 100% = 0.4 if (out.c.unit === '%') { out.c.unit = ''; out.c.number = ((parseFloat(out.c.number) / 100) * 0.4).toFixed(10); } return out; } type Lab = { l: Dimension, lNode: Node, a: Dimension, aNode: Node, b: Dimension, bNode: Node, slash?: DivNode, alpha?: WordNode | FunctionNode, } function oklabFunctionContents(nodes): Lab|null { if (!isNumericNodePercentageOrNumber(nodes[0])) { return null; } if (!isNumericNodePercentageOrNumber(nodes[1])) { return null; } if (!isNumericNodePercentageOrNumber(nodes[2])) { return null; } const out: Lab = { l: valueParser.unit(nodes[0].value) as Dimension, lNode: nodes[0], a: valueParser.unit(nodes[1].value) as Dimension, aNode: nodes[1], b: valueParser.unit(nodes[2].value) as Dimension, bNode: nodes[2], }; if (isSlashNode(nodes[3])) { out.slash = nodes[3]; } if ((isNumericNodePercentageOrNumber(nodes[4]) || isCalcNode(nodes[4]) || isVarNode(nodes[4]))) { out.alpha = nodes[4]; } if (nodes.length > 3 && (!out.slash || !out.alpha)) { return null; } // 0% = 0.0, 100% = 1.0 if (out.l.unit === '%') { out.l.unit = ''; out.l.number = (parseFloat(out.l.number) / 100).toFixed(10); } // -100% = -0.4, 100% = 0.4 if (out.a.unit === '%') { out.a.unit = ''; out.a.number = ((parseFloat(out.a.number) / 100) * 0.4).toFixed(10); } // -100% = -0.4, 100% = 0.4 if (out.b.unit === '%') { out.b.unit = ''; out.b.number = ((parseFloat(out.b.number) / 100) * 0.4).toFixed(10); } return out; } function isLab(x: Lch | Lab): x is Lab { if (typeof (x as Lab).a !== 'undefined') { return true; } return false; } function channelNodes(x: Lch | Lab): [Node, Node, Node] { if (isLab(x)) { return [x.lNode, x.aNode, x.bNode]; } return [x.lNode, x.cNode, x.hNode]; } function channelDimensions(x: Lch | Lab): [Dimension, Dimension, Dimension] { if (isLab(x)) { return [x.l, x.a, x.b]; } return [x.l, x.c, x.h]; } function transformAlpha(node: FunctionNode, slashNode: DivNode | undefined, alphaNode: WordNode | FunctionNode | undefined) { if (!slashNode || !alphaNode) { return; } node.value = 'rgba'; slashNode.value = ','; slashNode.before = ''; if (!isNumericNode(alphaNode)) { return; } const unitAndValue = valueParser.unit(alphaNode.value); if (!unitAndValue) { return; } if (unitAndValue.unit === '%') { // transform the Alpha channel from a Percentage to (0-1) Number unitAndValue.number = String(parseFloat(unitAndValue.number) / 100); alphaNode.value = String(unitAndValue.number); } } function replaceWith(nodes: Array<Node>, oldNode: Node, newNode: Node) { const index = nodes.indexOf(oldNode); nodes[index] = newNode; } function normalizeHueNode(dimension: Dimension) { switch (dimension.unit) { case 'deg': dimension.unit = ''; return; case 'rad': // radians -> degrees dimension.unit = ''; dimension.number = (parseFloat(dimension.number) * 180 / Math.PI).toString(); return; case 'grad': // grades -> degrees dimension.unit = ''; dimension.number = (parseFloat(dimension.number) * 0.9).toString(); return; case 'turn': // turns -> degrees dimension.unit = ''; dimension.number = (parseFloat(dimension.number) * 360).toString(); return; } } function canParseAsUnit(node : Node): boolean { if (!node || !node.value) { return false; } try { return valueParser.unit(node.value) !== false; } catch (e) { return false; } }
the_stack
import {assert} from 'chai'; import * as parse5 from 'parse5'; import * as dom5 from '../index'; /// <reference path="mocha" /> suite('dom5', () => { suite('Parse5 Node Manipulation', () => { const docText = `<!DOCTYPE html>` + `<div id='A' qux>a1<div bar='b1' bar='b2'>b1</div>a2</div>` + `<div bar='b3 b4'>b3 b4</div>` + `<!-- comment -->`; let doc = parse5.parse(docText); setup(() => { doc = parse5.parse(docText); }); suite('Node Identity', () => { test('isElement', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert(dom5.isElement(divA)); }); test('isTextNode', () => { const textA1 = doc.childNodes![1].childNodes![1].childNodes![0].childNodes![0]; assert(dom5.isTextNode(textA1)); }); test('isCommentNode', () => { const commentEnd = doc.childNodes![1].childNodes![1].childNodes!.slice(-1)[0]; assert(dom5.isCommentNode(commentEnd)); }); }); suite('getAttribute', () => { test('returns null for a non-set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert.equal(dom5.getAttribute(divA, 'foo'), null); }); test('returns the value for a set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert.equal(dom5.getAttribute(divA, 'id'), 'A'); }); test('returns the first value for a doubly set attribute', () => { const divB = doc.childNodes![1].childNodes![1].childNodes![0].childNodes![1]; assert.equal(dom5.getAttribute(divB, 'bar'), 'b1'); }); }); suite('hasAttribute', () => { test('returns false for a non-set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert.equal(dom5.hasAttribute(divA, 'foo'), false); }); test('returns true for a set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert.equal(dom5.hasAttribute(divA, 'id'), true); }); test('returns true for a doubly set attribute', () => { const divB = doc.childNodes![1].childNodes![1].childNodes![0].childNodes![1]; assert.equal(dom5.hasAttribute(divB, 'bar'), true); }); test('returns true for attribute with no value', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert.equal(dom5.hasAttribute(divA, 'qux'), true); }); }); suite('setAttribute', () => { test('sets a non-set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; dom5.setAttribute(divA, 'foo', 'bar'); assert.equal(dom5.getAttribute(divA, 'foo'), 'bar'); }); test('sets and already set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; dom5.setAttribute(divA, 'id', 'qux'); assert.equal(dom5.getAttribute(divA, 'id'), 'qux'); }); test('sets the first value for a doubly set attribute', () => { const divB = doc.childNodes![1].childNodes![1].childNodes![0].childNodes![1]; dom5.setAttribute(divB, 'bar', 'baz'); assert.equal(dom5.getAttribute(divB, 'bar'), 'baz'); }); test('throws when called on a text node', () => { const text = doc.childNodes![1].childNodes![1].childNodes![0].childNodes![0]; assert.throws(() => { dom5.setAttribute(text, 'bar', 'baz'); }); }); }); suite('removeAttribute', () => { test('removes a set attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; dom5.removeAttribute(divA, 'foo'); assert.equal(dom5.getAttribute(divA, 'foo'), null); }); test( 'does not throw when called on a node without that attribute', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; assert.doesNotThrow(() => { dom5.removeAttribute(divA, 'ZZZ'); }); }); }); suite('getTextContent', () => { let body = doc.childNodes![1].childNodes![1]; suiteSetup(() => { body = doc.childNodes![1].childNodes![1]; }); test('text node', () => { const node = body.childNodes![0].childNodes![0]; const expected = 'a1'; const actual = dom5.getTextContent(node); assert.equal(actual, expected); }); test('comment node', () => { const node = body.childNodes!.slice(-1)[0]; const expected = ' comment '; const actual = dom5.getTextContent(node); assert.equal(actual, expected); }); test('leaf element', () => { const node = body.childNodes![0].childNodes![1]; const expected = 'b1'; const actual = dom5.getTextContent(node); assert.equal(actual, expected); }); test('recursive element', () => { const expected = 'a1b1a2b3 b4'; const actual = dom5.getTextContent(body); assert.equal(actual, expected); }); }); suite('setTextContent', () => { let body: parse5.ASTNode; const expected = 'test'; suiteSetup(() => { body = doc.childNodes![1].childNodes![1]; }); test('text node', () => { const node = body.childNodes![0].childNodes![0]; dom5.setTextContent(node, expected); const actual = dom5.getTextContent(node); assert.equal(actual, expected); }); test('comment node', () => { const node = body.childNodes!.slice(-1)[0]; dom5.setTextContent(node, expected); const actual = dom5.getTextContent(node); assert.equal(actual, expected); }); test('leaf element', () => { const node = body.childNodes![0].childNodes![1]; dom5.setTextContent(node, expected); const actual = dom5.getTextContent(node); assert.equal(actual, expected); assert.equal(node.childNodes!.length, 1); }); test('recursive element', () => { dom5.setTextContent(body, expected); const actual = dom5.getTextContent(body); assert.equal(actual, expected); assert.equal(body.childNodes!.length, 1); }); }); suite('Replace node', () => { test('New node replaces old node', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; const newNode = dom5.constructors.element('ul'); dom5.replace(divA, newNode); assert.equal(divA.parentNode, null); assert.equal( doc.childNodes![1].childNodes![1].childNodes!.indexOf(divA), -1); assert.equal( doc.childNodes![1].childNodes![1].childNodes!.indexOf(newNode), 0); }); test('accepts document fragments', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; const fragment = dom5.constructors.fragment(); const span = dom5.constructors.element('span'); const text = dom5.constructors.text('foo'); fragment.childNodes!.push(span); fragment.childNodes!.push(text); dom5.replace(divA, fragment); assert.equal(divA.parentNode, null); assert.equal( doc.childNodes![1].childNodes![1].childNodes!.indexOf(divA), -1); assert.equal( doc.childNodes![1].childNodes![1].childNodes!.indexOf(span), 0); assert.equal( doc.childNodes![1].childNodes![1].childNodes!.indexOf(text), 1); }); }); suite('Remove node', () => { test('node is removed from parentNode', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; const parent = divA.parentNode!; dom5.remove(divA); assert.equal(divA.parentNode, null); assert.equal(parent.childNodes!.indexOf(divA), -1); }); test('removed nodes do not throw', () => { const divA = doc.childNodes![1].childNodes![1].childNodes![0]; dom5.remove(divA); dom5.remove(divA); assert.equal(divA.parentNode, null); }); }); suite('Remove node, save children', () => { test('node is removed and children at same position', () => { const html = '<div><em>x</em><span><em>a</em><em>c</em></span>y</div>'; const ast = parse5.parseFragment(html); const span = ast.childNodes![0]!.childNodes![1]!; dom5.removeNodeSaveChildren(span); assert.deepEqual( parse5.serialize(ast), '<div><em>x</em><em>a</em><em>c</em>y</div>'); }); }); suite('Remove fake root elements from tree', () => { test('Fake root elements will be removed', () => { const html = `<div>Just a div</div>`; const ast = parse5.parse(html, {locationInfo: true}); assert.deepEqual( parse5.serialize(ast), '<html><head></head><body><div>Just a div</div></body></html>'); dom5.removeFakeRootElements(ast); assert.deepEqual(parse5.serialize(ast), html); }); test('Real root elements will be preserved', () => { const html = '<html><head></head><body><div>Just a div</div></body></html>'; const ast = parse5.parse(html, {locationInfo: true}); assert.deepEqual(parse5.serialize(ast), html); dom5.removeFakeRootElements(ast); assert.deepEqual(parse5.serialize(ast), html); }); }); suite('Append Node', () => { let dom: parse5.ASTNode, div: parse5.ASTNode, span: parse5.ASTNode; setup(() => { dom = parse5.parseFragment('<div>a</div><span></span>b'); div = dom.childNodes![0]; span = dom.childNodes![1]; }); test('node is only in one parent', () => { const b = dom.childNodes!.slice(-1)[0]; dom5.append(span, b); assert.equal(b.parentNode, span); assert.equal(dom.childNodes!.indexOf(b), -1); }); test('node is appended to the end of childNodes', () => { let bidx = dom.childNodes!.length - 1; const b = dom.childNodes![bidx]; dom5.append(div, b); bidx = div.childNodes!.length - 1; assert.equal(div.childNodes![bidx], b); }); test('a node that is appended to its current parent is reordered', () => { const bidx = dom.childNodes!.length - 1; const b = dom.childNodes![bidx]; const a = div.childNodes![0]; dom5.append(div, b); dom5.append(div, a); assert.equal(div.childNodes![0], b); assert.equal(div.childNodes![1], a); }); test('accepts document fragments', () => { const fragment = dom5.constructors.fragment(); const span = dom5.constructors.element('span'); const text = dom5.constructors.text('foo'); // hold a reference to make sure append() clears childNodes const fragmentChildren = fragment.childNodes!; fragmentChildren.push(span); fragmentChildren.push(text); dom5.append(div, fragment); assert.equal(div.childNodes!.indexOf(span), 1); assert.equal(div.childNodes!.indexOf(text), 2); assert.equal(fragment.childNodes!.length, 0); assert.equal(fragmentChildren.length, 0); }); test('append to node with no children', () => { const emptyBody = parse5.parse('<head></head><body></body>'); const body = emptyBody.childNodes![0].childNodes![1]; const span = dom5.constructors.element('span'); dom5.append(body, span); assert.equal(body.childNodes!.length, 1); }); }); suite('InsertBefore', () => { let dom: parse5.ASTNode, div: parse5.ASTNode, span: parse5.ASTNode, text: parse5.ASTNode; setup(() => { dom = parse5.parseFragment('<div></div><span></span>text'); div = dom.childNodes![0]; span = dom.childNodes![1]; text = dom.childNodes![2]; }); test('ordering is correct', () => { dom5.insertBefore(dom, span, text); assert.equal(dom.childNodes!.indexOf(text), 1); const newHtml = parse5.serialize(dom); assert.equal(newHtml, '<div></div>text<span></span>'); dom5.insertBefore(dom, div, text); assert.equal(dom.childNodes!.indexOf(text), 0); }); test('accepts document fragments', () => { const fragment = dom5.constructors.fragment(); const span2 = dom5.constructors.element('span'); const text2 = dom5.constructors.text('foo'); fragment.childNodes!.push(span2); fragment.childNodes!.push(text2); dom5.insertBefore(dom, span, fragment); assert.equal(dom.childNodes!.indexOf(span2), 1); assert.equal(dom.childNodes!.indexOf(text2), 2); assert.equal(dom.childNodes!.indexOf(span), 3); assert.equal(dom.childNodes!.indexOf(text), 4); assert.equal(fragment.childNodes!.length, 0); }); }); suite('insertAfter', () => { let dom: parse5.ASTNode; let div: parse5.ASTNode; let span: parse5.ASTNode; let text: parse5.ASTNode; setup(() => { dom = parse5.parseFragment('<div></div><span></span>text'); [div, span, text] = dom.childNodes!; }); test('ordering is correct', () => { dom5.insertAfter(dom, div, text); assert.equal(parse5.serialize(dom), '<div></div>text<span></span>'); dom5.insertAfter(dom, span, text); assert.equal(parse5.serialize(dom), '<div></div><span></span>text'); }); test('accepts document fragments', () => { const fragment = parse5.parseFragment('<span></span>foo'); dom5.insertAfter(dom, span, fragment); assert.equal( parse5.serialize(dom), '<div></div><span></span><span></span>footext'); assert.equal(fragment.childNodes!.length, 0); }); }); suite('cloneNode', () => { test('clones a node', () => { const dom = parse5.parseFragment('<div><span foo="bar">a</span></div>'); const div = dom.childNodes![0]; const span = div.childNodes![0]; const clone = dom5.cloneNode(span); assert.equal(clone.parentNode, null); assert.equal(span.parentNode, div); assert.equal(clone.tagName, 'span'); assert.equal(dom5.getAttribute(clone, 'foo'), 'bar'); assert.equal(clone.childNodes![0].nodeName, '#text'); assert.equal(clone.childNodes![0].value, 'a'); assert.equal(span.childNodes![0].nodeName, '#text'); assert.equal(span.childNodes![0].value, 'a'); assert.notStrictEqual(clone.childNodes![0], span.childNodes![0]); }); }); }); suite('Query Predicates', () => { const fragText = '<div id="a" class="b c"><!-- nametag -->Hello World</div>'; let frag: parse5.ASTNode; suiteSetup(() => { frag = parse5.parseFragment(fragText).childNodes![0]; }); test('hasTagName', () => { let fn = dom5.predicates.hasTagName('div'); assert.isFunction(fn); assert.isTrue(fn(frag)); fn = dom5.predicates.hasTagName('a'); assert.isFalse(fn(frag)); }); test('hasAttr', () => { let fn = dom5.predicates.hasAttr('id'); assert.isFunction(fn); assert.isTrue(fn(frag)); fn = dom5.predicates.hasAttr('class'); assert.isTrue(fn(frag)); fn = dom5.predicates.hasAttr('hidden'); assert.isFalse(fn(frag)); }); test('hasAttrValue', () => { let fn = dom5.predicates.hasAttrValue('id', 'a'); assert.isFunction(fn); assert.isTrue(fn(frag)); fn = dom5.predicates.hasAttrValue('class', 'b c'); assert.isTrue(fn(frag)); fn = dom5.predicates.hasAttrValue('id', 'b'); assert.isFalse(fn(frag)); fn = dom5.predicates.hasAttrValue('name', 'b'); assert.isFalse(fn(frag)); }); test('hasSpaceSeparatedAttrValue', () => { let fn = dom5.predicates.hasSpaceSeparatedAttrValue('class', 'c'); assert.isFunction(fn); assert.isTrue(fn(frag)); fn = dom5.predicates.hasAttr('class'); assert.isTrue(fn(frag)); fn = dom5.predicates.hasSpaceSeparatedAttrValue('id', ''); assert.isFalse(fn(frag)); }); test('hasClass', () => { let fn = dom5.predicates.hasClass('b'); assert.isFunction(fn); assert.isTrue(fn(frag)); fn = dom5.predicates.hasClass('c'); assert.isTrue(fn(frag)); fn = dom5.predicates.hasClass('d'); assert.isFalse(fn(frag)); }); test('hasTextValue', () => { let fn = dom5.predicates.hasTextValue('Hello World'); assert.isFunction(fn); assert.isTrue(fn(frag)); const textNode = frag.childNodes![1]; assert.isTrue(fn(textNode)); const commentNode = frag.childNodes![0]; fn = dom5.predicates.hasTextValue(' nametag '); assert.isTrue(fn(commentNode)); }); test('AND', () => { const preds = [ dom5.predicates.hasTagName('div'), dom5.predicates.hasAttrValue('id', 'a'), dom5.predicates.hasClass('b') ]; let fn = dom5.predicates.AND.apply(null, preds); assert.isFunction(fn); assert.isTrue(fn(frag)); preds.push(dom5.predicates.hasClass('d')); fn = dom5.predicates.AND.apply(null, preds); assert.isFalse(fn(frag)); }); test('OR', () => { const preds = [ dom5.predicates.hasTagName('div'), dom5.predicates.hasAttr('hidden') ]; let fn = dom5.predicates.OR.apply(null, preds); assert.isFunction(fn); assert.isTrue(fn(frag)); preds.shift(); fn = dom5.predicates.OR.apply(null, preds); assert.isFalse(fn(frag)); }); test('NOT', () => { const pred = dom5.predicates.hasTagName('a'); const fn = dom5.predicates.NOT(pred); assert.isFunction(fn); assert.isTrue(fn(frag)); assert.isFalse(pred(frag)); }); test('Chaining Predicates', () => { const fn = dom5.predicates.AND( dom5.predicates.hasTagName('div'), dom5.predicates.OR( dom5.predicates.hasClass('b'), dom5.predicates.hasClass('d')), dom5.predicates.NOT(dom5.predicates.hasAttr('hidden'))); assert.isFunction(fn); assert.isTrue(fn(frag)); }); test('parentMatches', () => { const fragText = '<div class="a"><div class="b"><div class="c"></div></div></div>'; const frag = parse5.parseFragment(fragText); const fn = dom5.predicates.parentMatches(dom5.predicates.hasClass('a')); assert.isFalse(fn(frag.childNodes![0])); // a assert.isTrue(fn(frag.childNodes![0].childNodes![0])); // b assert.isTrue( fn(frag.childNodes![0].childNodes![0].childNodes![0])); // c }); }); suite('Constructors', () => { test('text node', () => { const node = dom5.constructors.text('test'); assert.isTrue(dom5.isTextNode(node)); const fn = dom5.predicates.hasTextValue('test'); assert.equal(dom5.nodeWalk(node, fn), node); }); test('comment node', () => { const node = dom5.constructors.comment('test'); assert.isTrue(dom5.isCommentNode(node)); const fn = dom5.predicates.hasTextValue('test'); assert.equal(dom5.nodeWalk(node, fn), node); }); test('element', () => { const node = dom5.constructors.element('div'); assert.isTrue(dom5.isElement(node)); const fn = dom5.predicates.hasTagName('div'); assert.equal(dom5.query(node, fn), node); }); }); suite('Text Normalization', () => { const con = dom5.constructors; test('normalizing text nodes or comment nodes is a noop', () => { const tn = con.text('test'); const cn = con.comment('test2'); dom5.normalize(tn); dom5.normalize(cn); assert.equal(tn, tn); assert.equal(cn, cn); }); test('an element\'s child text nodes are merged', () => { const div = con.element('div'); const tn1 = con.text('foo'); const tn2 = con.text('bar'); dom5.append(div, tn1); dom5.append(div, tn2); const expected = dom5.getTextContent(div); assert.equal(expected, 'foobar'); dom5.normalize(div); const actual = dom5.getTextContent(div); assert.equal(actual, expected); assert.equal(div.childNodes!.length, 1); }); test('only text node ranges are merged', () => { const div = con.element('div'); const tn1 = con.text('foo'); const tn2 = con.text('bar'); const cn = con.comment('combobreaker'); const tn3 = con.text('quux'); dom5.append(div, tn1); dom5.append(div, tn2); dom5.append(div, cn); dom5.append(div, tn3); const expected = dom5.getTextContent(div); assert.equal(expected, 'foobarquux'); dom5.normalize(div); const actual = dom5.getTextContent(div); assert.equal(actual, expected); assert.equal(div.childNodes!.length, 3); assert.equal(dom5.getTextContent(div.childNodes![0]), 'foobar'); assert.equal(dom5.getTextContent(div.childNodes![1]), 'combobreaker'); assert.equal(dom5.getTextContent(div.childNodes![2]), 'quux'); }); test('empty text nodes are removed', () => { const div = con.element('div'); const tn = con.text(''); dom5.append(div, tn); assert.equal(div.childNodes!.length, 1); dom5.normalize(div); assert.equal(div.childNodes!.length, 0); }); test('elements are recursively normalized', () => { const div = con.element('div'); const tn1 = con.text('foo'); const space = con.text(''); dom5.append(div, tn1); dom5.append(div, space); const span = con.element('span'); const tn2 = con.text('bar'); const tn3 = con.text('baz'); dom5.append(span, tn2); dom5.append(span, tn3); dom5.append(div, span); assert.equal(dom5.getTextContent(div), 'foobarbaz'); dom5.normalize(div); assert.equal(div.childNodes!.length, 2); assert.equal(span.childNodes!.length, 1); }); test('document can be normalized', () => { const doc = parse5.parse('<!DOCTYPE html>'); const body = doc.childNodes![1].childNodes![1]; const div = con.element('div'); const tn1 = con.text('foo'); const space = con.text(''); dom5.append(div, tn1); dom5.append(div, space); const span = con.element('span'); const tn2 = con.text('bar'); const tn3 = con.text('baz'); dom5.append(span, tn2); dom5.append(span, tn3); dom5.append(div, span); dom5.append(body, div); assert.equal(dom5.getTextContent(doc), 'foobarbaz'); dom5.normalize(doc); assert.equal(dom5.getTextContent(doc), 'foobarbaz'); assert.equal(div.childNodes!.length, 2); assert.equal(span.childNodes!.length, 1); }); }); });
the_stack
export class NumRange { // TODO: check NaN readonly start: number; readonly end: number; readonly hasStart: boolean; // is start inclusive? readonly hasEnd: boolean; // is end inclusive? constructor(start: number, end: number, hasStart: boolean, hasEnd: boolean) { this.start = start; this.end = end; this.hasStart = hasStart; this.hasEnd = hasEnd; } toString(): string { return `${this.hasStart ? '[' : '('}${this.start}, ${this.end}${this.hasEnd ? ']' : ')'}`; } // return closed range static fromConst(num: number): NumRange { return new NumRange(num, num, true, true); } static genClosed(start: number, end: number): NumRange { return new NumRange(start, end, true, true); } static genTop(): NumRange { return new NumRange(-Infinity, Infinity, false, false); } static genFalse(): NumRange { return new NumRange(1, -1, true, true); } static genLt(num: number): NumRange { return new NumRange(-Infinity, num, false, false); } static genLte(num: number): NumRange { return new NumRange(-Infinity, num, false, true); } static genGt(num: number): NumRange { return new NumRange(num, Infinity, false, false); } static genGte(num: number): NumRange { return new NumRange(num, Infinity, true, false); } valid(): boolean { if (this.start === this.end) return this.hasStart && this.hasEnd; return this.start < this.end; } isConst(): boolean { return this.start === this.end && this.hasStart && this.hasEnd; } // WARNING: this.isTruthy() == false is not means its falsy!! isTruthy(): boolean { return this.gt(0) === true || this.lt(0) === true; } // WARNING: this.isFalsy() == false is not means its truthy!! isFalsy(): boolean { return this.isConst() && this.start === 0; } toIntRange(): NumRange | undefined { if (!this.valid()) return; let start = this.start; let end = this.end; if (start !== -Infinity) { if (Number.isInteger(start)) { start = this.hasStart ? start : start + 1; } else { start = Math.floor(start) + 1; } } if (end !== Infinity) { if (Number.isInteger(end)) { end = this.hasEnd ? end : end - 1; } else { end = Math.floor(end); } } const newValue = new NumRange(start, end, start !== -Infinity, end !== Infinity); if (!newValue.valid()) return; return newValue; } lt(num: number): boolean | undefined { if (!this.valid()) return; if (this.isConst()) return this.start < num; if (this.end < num) return true; if (this.end === num) return this.hasEnd ? undefined : true; if (this.start >= num) return false; return; } lte(num: number): boolean | undefined { if (!this.valid()) return; if (this.isConst()) return this.start <= num; if (this.end <= num) return true; if (this.start > num) return false; if (this.start === num) return this.hasStart ? undefined : false; return; } gt(num: number): boolean | undefined { if (!this.valid()) return; if (this.isConst()) return this.start > num; if (this.end <= num) return false; if (this.start > num) return true; if (this.start === num) return this.hasStart ? undefined : true; return; } gte(num: number): boolean | undefined { if (!this.valid()) return; if (this.isConst()) return this.start >= num; if (this.end < num) return false; if (this.end === num) return this.hasEnd ? undefined : false; if (this.start >= num) return true; return; } eq(num: number): boolean | undefined { if (!this.isConst()) return; return this.start === num; } // TODO: return false if invalid?? ltRange(that: NumRange): boolean | undefined { if (!this.valid() || !that.valid()) return; if (this.end < that.start) return true; if (this.end === that.start && !(this.hasEnd && that.hasStart)) return true; if (that.end <= this.start) return false; return; } lteRange(that: NumRange): boolean | undefined { if (!this.valid() || !that.valid()) return; if (this.end <= that.start) return true; if (that.end < this.start) return false; if (that.end === this.start && !(that.hasEnd && this.hasStart)) return false; return; } gtRange(that: NumRange): boolean | undefined { return that.lteRange(this); } gteRange(that: NumRange): boolean | undefined { return that.ltRange(this); } contains(num: number): boolean { if (!this.valid()) { return false; } if (this.start <= num && num <= this.end) { if (this.start === num) return this.hasStart; if (this.end === num) return this.hasEnd; return true; } return false; } intersect(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } let start: number; let end: number; let hasStart: boolean; let hasEnd: boolean; if (this.start === that.start) { start = this.start; hasStart = this.hasStart && that.hasStart; } else if (this.start < that.start) { start = that.start; hasStart = that.hasStart; } else { start = this.start; hasStart = this.hasStart; } if (this.end === that.end) { end = this.end; hasEnd = this.hasEnd && that.hasEnd; } else if (this.start < that.start) { end = this.end; hasEnd = this.hasEnd; } else { end = that.end; hasEnd = that.hasEnd; } return new NumRange(start, end, hasStart, hasEnd); } union(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } let start: number; let end: number; let hasStart: boolean; let hasEnd: boolean; if (this.start === that.start) { start = this.start; hasStart = this.hasStart || that.hasStart; } else if (this.start < that.start) { start = this.start; hasStart = this.hasStart; } else { start = that.start; hasStart = that.hasStart; } if (this.end === that.end) { end = this.end; hasEnd = this.hasEnd || that.hasEnd; } else if (this.start < that.start) { end = that.end; hasEnd = that.hasEnd; } else { end = this.end; hasEnd = this.hasEnd; } return new NumRange(start, end, hasStart, hasEnd); } neg(): NumRange { if (!this.valid()) return this; return new NumRange(-this.end, -this.start, this.hasEnd, this.hasStart); } abs(): NumRange { if (!this.valid()) return this; if (this.start > 0) return this; if (this.end <= 0) return this.neg(); if (-this.start < this.end) { return new NumRange(0, this.end, true, this.hasEnd); } else if (-this.start === this.end) { return new NumRange(0, this.end, true, this.hasEnd || this.hasStart); } else { return new NumRange(0, -this.start, true, this.hasStart); } } ceil(): NumRange | undefined { if (!this.valid()) return; let start: number; let hasStart = true; let end: number; let hasEnd = true; if (this.start === -Infinity) { start = -Infinity; hasStart = false; } else if (Number.isInteger(this.start)) { start = this.hasStart ? this.start : this.start + 1; } else { start = Math.ceil(this.start); } if (this.end === Infinity) { end = Infinity; hasEnd = false; } else { end = Math.ceil(this.end); } return new NumRange(start, end, hasStart, hasEnd); } floor(): NumRange | undefined { if (!this.valid()) return; let start: number; let hasStart = true; let end: number; let hasEnd = true; if (this.start === -Infinity) { start = -Infinity; hasStart = false; } else { start = Math.floor(this.start); } if (this.end === Infinity) { end = Infinity; hasEnd = false; } else if (Number.isInteger(this.end)) { end = this.hasEnd ? this.end : this.end - 1; } else { end = Math.floor(this.end); } return new NumRange(start, end, hasStart, hasEnd); } add(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } return new NumRange( this.start + that.start, this.end + that.end, this.hasStart && that.hasStart, this.hasEnd && that.hasEnd ); } sub(that: NumRange): NumRange { return this.add(that.neg()); } mul(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } if (this.isConst()) { const start = this.start; if (start === 0) return this; else if (start > 0) return new NumRange(start * that.start, start * that.end, that.hasStart, that.hasEnd); else return new NumRange(start * that.end, start * that.start, that.hasEnd, that.hasStart); } if (that.isConst()) { const start = that.start; if (start === 0) return that; else if (start > 0) return new NumRange(start * this.start, start * this.end, this.hasStart, this.hasEnd); else return new NumRange(start * this.end, start * this.start, this.hasEnd, this.hasStart); } let a = this.start * that.start; let b = this.start * that.end; let c = this.end * that.start; let d = this.end * that.end; // -0, NaN / Infinity resolve if (this.start === 0) { a = 0; b = 0; } if (that.start === 0) { a = 0; c = 0; } if (this.end === 0) { c = 0; d = 0; } if (that.end === 0) { b = 0; d = 0; } const [min, minpos] = min4(a, b, c, d); const [max, maxpos] = max4(a, b, c, d); return new NumRange(min, max, flagByPos(minpos, this, that), flagByPos(maxpos, this, that)); } floordiv(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } if (this.isConst() && that.isConst()) { if (that.start === 0) { return NumRange.genTop(); } return NumRange.fromConst(Math.floor(this.start / that.start)); } if (that.contains(0)) { return NumRange.genTop(); } // TODO: can we do like this?? let a = Math.floor(this.start / that.start); let b = Math.floor(this.start / that.end); let c = Math.floor(this.end / that.start); let d = Math.floor(this.end / that.end); // -0, NaN / Infinity resolve if (that.start === 0) { a = this.start >= 0 ? Infinity : -Infinity; c = this.end >= 0 ? Infinity : -Infinity; } if (that.end === 0) { b = this.start >= 0 ? -Infinity : Infinity; d = this.end >= 0 ? -Infinity : Infinity; } const [min, minpos] = min4(a, b, c, d); const [max, maxpos] = max4(a, b, c, d); return new NumRange( min, max, min === -Infinity ? false : flagByPos(minpos, this, that), max === Infinity ? flagByPos(maxpos, this, that) : false ); } truediv(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } if (this.isConst() && that.isConst()) { if (that.start === 0) { return NumRange.genTop(); } return NumRange.fromConst(this.start / that.start); } if (that.contains(0)) { return NumRange.genTop(); } // TODO: can we do like this?? let a = this.start / that.start; let b = this.start / that.end; let c = this.end / that.start; let d = this.end / that.end; // -0, NaN / Infinity resolve if (that.start === 0) { a = this.start >= 0 ? Infinity : -Infinity; c = this.end >= 0 ? Infinity : -Infinity; } if (that.end === 0) { b = this.start >= 0 ? -Infinity : Infinity; d = this.end >= 0 ? -Infinity : Infinity; } const [min, minpos] = min4(a, b, c, d); const [max, maxpos] = max4(a, b, c, d); return new NumRange( min, max, min === -Infinity ? false : flagByPos(minpos, this, that), max === Infinity ? flagByPos(maxpos, this, that) : false ); } mod(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } if (this.isConst()) { if (that.isConst()) { return NumRange.fromConst(this.start % that.start); } else if (that.gt(Math.abs(this.start))) { return this; } } // TODO: more precisely return new NumRange(0, Math.max(Math.abs(that.start), Math.abs(that.end)), true, false); } pow(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } if (this.isConst()) { const start = this.start; if (start === 0) return this; else if (start > 0) return new NumRange(start * that.start, start * that.end, that.hasStart, that.hasEnd); else return new NumRange(start * that.end, start * that.start, that.hasEnd, that.hasStart); } if (that.isConst()) { const start = that.start; if (start === 0) return that; else if (start > 0) return new NumRange(start * this.start, start * this.end, this.hasStart, this.hasEnd); else return new NumRange(start * this.end, start * this.start, this.hasEnd, this.hasStart); } // TODO: can we do like this?? const a = Math.floor(this.start / that.start); const b = Math.floor(this.start / that.end); const c = Math.floor(this.end / that.start); const d = Math.floor(this.end / that.end); const [min, minpos] = min4(a, b, c, d); const [max, maxpos] = max4(a, b, c, d); return new NumRange( min, max, min === -Infinity ? false : flagByPos(minpos, this, that), max === Infinity ? flagByPos(maxpos, this, that) : false ); } max(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } let start: number; let end: number; let hasStart: boolean; let hasEnd: boolean; if (this.start < that.start) { start = that.start; hasStart = that.hasStart; } else if (this.start === that.start) { start = this.start; hasStart = this.hasStart && that.hasStart; } else { start = this.start; hasStart = this.hasStart; } if (this.end < that.end) { end = that.end; hasEnd = that.hasEnd; } else if (this.end === that.end) { end = this.end; hasEnd = this.hasEnd || that.hasEnd; } else { end = this.end; hasEnd = this.hasEnd; } return new NumRange(start, end, hasStart, hasEnd); } min(that: NumRange): NumRange { if (!this.valid()) { return this; } if (!that.valid()) { return that; } let start: number; let end: number; let hasStart: boolean; let hasEnd: boolean; if (this.start < that.start) { start = this.start; hasStart = this.hasStart; } else if (this.start === that.start) { start = this.start; hasStart = this.hasStart || that.hasStart; } else { start = that.start; hasStart = that.hasStart; } if (this.end < that.end) { end = this.end; hasEnd = this.hasEnd; } else if (this.end === that.end) { end = this.end; hasEnd = this.hasEnd && that.hasEnd; } else { end = that.end; hasEnd = that.hasEnd; } return new NumRange(start, end, hasStart, hasEnd); } } function min4(a: number, b: number, c: number, d: number): [number, number] { if (Number.isNaN(a)) a = Infinity; if (Number.isNaN(b)) b = Infinity; if (Number.isNaN(c)) c = Infinity; if (Number.isNaN(d)) d = Infinity; const ab: [number, number] = a < b ? [a, 0] : [b, 1]; const cd: [number, number] = c < d ? [c, 2] : [d, 3]; return ab[0] < cd[0] ? ab : cd; } function max4(a: number, b: number, c: number, d: number): [number, number] { if (Number.isNaN(a)) a = -Infinity; if (Number.isNaN(b)) b = -Infinity; if (Number.isNaN(c)) c = -Infinity; if (Number.isNaN(d)) d = -Infinity; const ab: [number, number] = a > b ? [a, 0] : [b, 1]; const cd: [number, number] = c > d ? [c, 2] : [d, 3]; return ab[0] > cd[0] ? ab : cd; } // pos: 0 -> (this.start, that.start) // pos: 1 -> (this.start, that.end) // pos: 2 -> (this.end, that.start) // pos: o.w. -> (this.end, that.end) function flagByPos(pos: number, left: NumRange, right: NumRange): boolean { switch (pos) { case 0: return left.hasStart && right.hasStart; case 1: return left.hasStart && right.hasEnd; case 2: return left.hasEnd && right.hasStart; default: return left.hasEnd && right.hasEnd; } }
the_stack
import { ApexTestResultOutcome, HumanReporter, TestLevel, TestResult, TestService } from '@salesforce/apex-node'; import { SfdxProject } from '@salesforce/core'; import * as pathUtils from '@salesforce/salesforcedx-utils-vscode/out/src/helpers'; import { ComponentSet } from '@salesforce/source-deploy-retrieve'; import { expect } from 'chai'; import { join } from 'path'; import { assert, createSandbox, match, SinonStub } from 'sinon'; import { CancellationToken, DiagnosticSeverity, EventEmitter, Progress, Range, Uri } from 'vscode'; import { ApexLibraryTestRunExecutor, resolveTestClassParam, resolveTestMethodParam } from '../../../src/commands/forceApexTestRunCodeAction'; import { workspaceContext } from '../../../src/context'; // return undefined: used to get around strict checks function getUndefined(): any { return undefined; } describe('Force Apex Test Run - Code Action', () => { describe('Cached Test Class', () => { const testClass = 'MyTests'; const testClass2 = 'MyTests2'; it('Should return cached value', async () => { let resolvedTestClass = await resolveTestClassParam(getUndefined()); expect(resolvedTestClass).to.equal(undefined); resolvedTestClass = await resolveTestClassParam(testClass); expect(resolvedTestClass).to.equal(testClass); resolvedTestClass = await resolveTestClassParam(''); expect(resolvedTestClass).to.equal(testClass); resolvedTestClass = await resolveTestClassParam(getUndefined()); expect(resolvedTestClass).to.equal(testClass); resolvedTestClass = await resolveTestClassParam(testClass2); expect(resolvedTestClass).to.equal(testClass2); resolvedTestClass = await resolveTestClassParam(''); expect(resolvedTestClass).to.equal(testClass2); }); }); describe('Cached Test Method', () => { const testMethod = 'MyTests.testMe'; const testMethod2 = 'MyTests.testMe2'; it('Should return cached value', async () => { let resolvedTestMethod = await resolveTestMethodParam(getUndefined()); expect(resolvedTestMethod).to.equal(undefined); resolvedTestMethod = await resolveTestMethodParam(testMethod); expect(resolvedTestMethod).to.equal(testMethod); resolvedTestMethod = await resolveTestMethodParam(''); expect(resolvedTestMethod).to.equal(testMethod); resolvedTestMethod = await resolveTestMethodParam(getUndefined()); expect(resolvedTestMethod).to.equal(testMethod); resolvedTestMethod = await resolveTestMethodParam(testMethod2); expect(resolvedTestMethod).to.equal(testMethod2); resolvedTestMethod = await resolveTestMethodParam(''); expect(resolvedTestMethod).to.equal(testMethod2); }); }); const testResult: TestResult = { summary: { failRate: '0%', failing: 0, testsRan: 2, orgId: 'xxxx908373', outcome: 'Failed', passRate: '100%', passing: 5, skipRate: '0%', skipped: 0, testExecutionTimeInMs: 25, testStartTime: '2:00:00PM', testTotalTimeInMs: 25, commandTimeInMs: 25, hostname: 'NA95', username: 'testusername@testing.com', testRunId: 'xxxx9056', userId: 'xxx555' }, tests: [ { asyncApexJobId: 'xxx9678', id: 'xxxx56', apexClass: { fullName: 'TestClass', name: 'TestClass', namespacePrefix: '', id: 'xx567' }, queueItemId: 'xxxQUEUEID', stackTrace: 'System.AssertException: Assertion Failed Col: 18 Line: 2', message: 'System.AssertException: Assertion Failed', methodName: 'testMethod', outcome: ApexTestResultOutcome.Fail, runTime: 5, apexLogId: 'xxxLogId90', testTimestamp: '2:00:00PM', fullName: 'TestClass.testMethod', diagnostic: { exceptionMessage: 'System.AssertException: Assertion Failed', exceptionStackTrace: 'System.AssertException: Assertion Failed Col: 18 Line: 2', compileProblem: '', lineNumber: 6, columnNumber: 1, className: 'TestClass' } }, { asyncApexJobId: 'xxx9678', id: 'xxxx56', apexClass: { fullName: 'TestClass', name: 'TestClassTwo', namespacePrefix: '', id: 'xx567' }, queueItemId: 'xxxQUEUEID', stackTrace: 'System.AssertException: Assertion Failed Col: 15 Line: 3', message: 'System.AssertException: Assertion Failed', methodName: 'testMethodTwo', outcome: ApexTestResultOutcome.Fail, runTime: 5, apexLogId: 'xxxLogId90', testTimestamp: '2:00:00PM', fullName: 'TestClassTwo.testMethodTwo', diagnostic: { exceptionMessage: 'System.AssertException: Assertion Failed', exceptionStackTrace: 'System.AssertException: Assertion Failed Col: 15 Line: 3', compileProblem: '', lineNumber: 3, columnNumber: 15, className: 'TestClassTwo' } } ] }; const passingResult: TestResult = { summary: { failRate: '0%', failing: 0, testsRan: 2, orgId: 'xxxx908373', outcome: 'Passed', passRate: '100%', passing: 5, skipRate: '0%', skipped: 0, testExecutionTimeInMs: 25, testStartTime: '2:00:00PM', testTotalTimeInMs: 25, commandTimeInMs: 25, hostname: 'NA95', username: 'testusername@testing.com', testRunId: 'xxxx9056', userId: 'xxx555' }, tests: [ { asyncApexJobId: 'xxx9678', id: 'xxxx56', apexClass: { fullName: 'TestClass', name: 'TestClass', namespacePrefix: '', id: 'xx567' }, queueItemId: 'xxxQUEUEID', stackTrace: '', message: '', methodName: 'testMethod', outcome: ApexTestResultOutcome.Pass, runTime: 5, apexLogId: 'xxxLogId90', testTimestamp: '2:00:00PM', fullName: 'TestClass.testMethod' }, { asyncApexJobId: 'xxx9678', id: 'xxxx56', apexClass: { fullName: 'TestClass', name: 'TestClassTwo', namespacePrefix: '', id: 'xx567' }, queueItemId: 'xxxQUEUEID', stackTrace: '', message: '', methodName: 'testMethodTwo', outcome: ApexTestResultOutcome.Pass, runTime: 5, apexLogId: 'xxxLogId90', testTimestamp: '2:00:00PM', fullName: 'TestClassTwo.testMethodTwo' } ] }; const sb = createSandbox(); // tslint:disable:no-unused-expression describe('Apex Library Test Run Executor', async () => { let runTestStub: SinonStub; let buildPayloadStub: SinonStub; let writeResultFilesStub: SinonStub; const defaultPackageDir = 'default/package/dir'; const componentPath = join( defaultPackageDir, 'main', 'default', 'TestClass.cls' ); let reportStub: SinonStub; let progress: Progress<unknown>; let cancellationTokenEventEmitter; let cancellationToken: CancellationToken; beforeEach(async () => { runTestStub = sb .stub(TestService.prototype, 'runTestAsynchronous') .resolves(passingResult); sb.stub(workspaceContext, 'getConnection'); buildPayloadStub = sb.stub(TestService.prototype, 'buildAsyncPayload'); sb.stub(HumanReporter.prototype, 'format'); writeResultFilesStub = sb.stub(TestService.prototype, 'writeResultFiles'); sb.stub(SfdxProject, 'resolve').returns({ getDefaultPackage: () => { return { fullPath: 'default/package/dir' }; } }); sb.stub(ComponentSet, 'fromSource').returns({ getSourceComponents: () => { return { first: () => { return { content: componentPath }; } }; } }); sb.stub(ApexLibraryTestRunExecutor.diagnostics, 'set'); reportStub = sb.stub(); progress = { report: reportStub }; cancellationTokenEventEmitter = new EventEmitter(); cancellationToken = { isCancellationRequested: false, onCancellationRequested: cancellationTokenEventEmitter.event }; }); afterEach(async () => { sb.restore(); }); it('should run test with correct parameters for single test method with code coverage', async () => { buildPayloadStub.resolves({ tests: [{ className: 'testClass', testMethods: ['oneTest'] }], testLevel: TestLevel.RunSpecifiedTests }); const apexLibExecutor = new ApexLibraryTestRunExecutor( ['testClass.oneTest'], 'path/to/dir', true ); await apexLibExecutor.run(undefined, progress, cancellationToken); expect(buildPayloadStub.called).to.be.true; expect(buildPayloadStub.args[0]).to.eql([ 'RunSpecifiedTests', 'testClass.oneTest' ]); assert.calledOnce(runTestStub); assert.calledWith( runTestStub, { tests: [{ className: 'testClass', testMethods: ['oneTest'] }], testLevel: TestLevel.RunSpecifiedTests }, true, false, match.any, cancellationToken ); }); it('should run test with correct parameters for multiple test methods without code coverage', async () => { buildPayloadStub.resolves({ tests: [ { className: 'testClass', testMethods: ['oneTest'] }, { className: 'testClass', testMethods: ['twoTest'] } ], testLevel: TestLevel.RunSpecifiedTests }); const apexLibExecutor = new ApexLibraryTestRunExecutor( ['testClass.oneTest', 'testClass.twoTest'], 'path/to/dir', false ); await apexLibExecutor.run(undefined, progress, cancellationToken); expect(buildPayloadStub.called).to.be.true; expect(buildPayloadStub.args[0]).to.eql([ 'RunSpecifiedTests', 'testClass.oneTest,testClass.twoTest' ]); assert.calledOnce(runTestStub); assert.calledWith( runTestStub, { tests: [ { className: 'testClass', testMethods: ['oneTest'] }, { className: 'testClass', testMethods: ['twoTest'] } ], testLevel: TestLevel.RunSpecifiedTests }, false, false, match.any, cancellationToken ); }); it('should run test with correct parameters for single test class with code coverage', async () => { buildPayloadStub.resolves({ tests: [{ className: 'testClass' }], testLevel: TestLevel.RunSpecifiedTests }); const apexLibExecutor = new ApexLibraryTestRunExecutor( ['testClass'], 'path/to/dir', true ); await apexLibExecutor.run(undefined, progress, cancellationToken); expect(buildPayloadStub.called).to.be.true; expect(buildPayloadStub.args[0]).to.eql([ 'RunSpecifiedTests', 'testClass' ]); assert.calledOnce(runTestStub); assert.calledWith( runTestStub, { tests: [{ className: 'testClass' }], testLevel: TestLevel.RunSpecifiedTests }, true, false, match.any, cancellationToken ); }); it('should run test with correct parameters for multiple test classes without code coverage', async () => { buildPayloadStub.resolves({ tests: [{ className: 'testClass' }, { className: 'secondTestClass' }], testLevel: TestLevel.RunSpecifiedTests }); const apexLibExecutor = new ApexLibraryTestRunExecutor( ['testClass', 'secondTestClass'], 'path/to/dir', false ); await apexLibExecutor.run(undefined, progress, cancellationToken); expect(buildPayloadStub.called).to.be.true; expect(buildPayloadStub.args[0]).to.eql([ 'RunSpecifiedTests', 'testClass,secondTestClass' ]); assert.calledOnce(runTestStub); assert.calledWith( runTestStub, { tests: [{ className: 'testClass' }, { className: 'secondTestClass' }], testLevel: TestLevel.RunSpecifiedTests }, false, false, match.any, cancellationToken ); }); it('should report progress', async () => { buildPayloadStub.resolves({ tests: [ { className: 'testClass' }, { className: 'secondTestClass' } ], testLevel: TestLevel.RunSpecifiedTests }); const apexLibExecutor = new ApexLibraryTestRunExecutor( ['testClass', 'secondTestClass'], 'path/to/dir', false ); runTestStub.callsFake( (payload, codecoverage, exitEarly, progressReporter, token) => { progressReporter.report({ type: 'StreamingClientProgress', value: 'streamingTransportUp', message: 'Listening for streaming state changes...' }); progressReporter.report({ type: 'StreamingClientProgress', value: 'streamingProcessingTestRun', message: 'Processing test run 707500000000000001', testRunId: '707500000000000001' }); progressReporter.report({ type: 'FormatTestResultProgress', value: 'retrievingTestRunSummary', message: 'Retrieving test run summary record' }); progressReporter.report({ type: 'FormatTestResultProgress', value: 'queryingForAggregateCodeCoverage', message: 'Querying for aggregate code coverage results' }); return passingResult; } ); await apexLibExecutor.run(undefined, progress, cancellationToken); assert.calledWith(reportStub, { message: 'Listening for streaming state changes...' }); assert.calledWith(reportStub, { message: 'Processing test run 707500000000000001' }); assert.calledWith(reportStub, { message: 'Retrieving test run summary record' }); assert.calledWith(reportStub, { message: 'Querying for aggregate code coverage results' }); }); it('should return if cancellation is requested', async () => { const apexLibExecutor = new ApexLibraryTestRunExecutor( ['testClass', 'secondTestClass'], 'path/to/dir', false ); runTestStub.callsFake(() => { cancellationToken.isCancellationRequested = true; }); const result = await apexLibExecutor.run( undefined, progress, cancellationToken ); assert.calledOnce(runTestStub); assert.notCalled(writeResultFilesStub); expect(result).to.eql(false); }); }); describe('Report Diagnostics', () => { const executor = new ApexLibraryTestRunExecutor( ['TestClass', 'TestClassTwo'], 'path/to/dir', false ); const defaultPackageDir = 'default/package/dir'; const componentPath = join( defaultPackageDir, 'main', 'default', 'TestClass.cls' ); const diagnostics = testResult.tests.map(test => { const { exceptionMessage, exceptionStackTrace } = testResult.tests[0].diagnostic!; return { message: `${exceptionMessage}\n${exceptionStackTrace}`, severity: DiagnosticSeverity.Error, source: componentPath, range: new Range(5, 0, 5, 0) }; }); let setDiagnosticStub: SinonStub; let runTestStub: SinonStub; let componentPathStub: SinonStub; beforeEach(() => { sb.stub(TestService.prototype, 'writeResultFiles'); sb.stub(workspaceContext, 'getConnection'); sb.stub(SfdxProject, 'resolve').returns({ getDefaultPackage: () => { return { fullPath: 'default/package/dir' }; } }); componentPathStub = sb.stub(ComponentSet, 'fromSource').returns({ getSourceComponents: () => { return { first: () => { return { content: componentPath }; } }; } }); setDiagnosticStub = sb.stub( ApexLibraryTestRunExecutor.diagnostics, 'set' ); runTestStub = sb .stub(TestService.prototype, 'runTestAsynchronous') .resolves(testResult); sb.stub(pathUtils, 'getTestResultsFolder'); }); afterEach(() => { sb.restore(); }); it('should clear diagnostics before setting new ones', async () => { const clearStub = sb.stub( ApexLibraryTestRunExecutor.diagnostics, 'clear' ); await executor.run(); expect(clearStub.calledBefore(setDiagnosticStub)).to.be.true; }); it('should set all diagnostic properties correctly', async () => { await executor.run(); expect( setDiagnosticStub.calledWith(Uri.file(defaultPackageDir), [ diagnostics[0] ]) ); }); it('should set multiple diagnostics correctly', async () => { await executor.run(); expect( setDiagnosticStub.calledWith(Uri.file(defaultPackageDir), [ diagnostics[0] ]) ); expect( setDiagnosticStub.calledWith(Uri.file(defaultPackageDir), [ diagnostics[1] ]) ); }); it('should not set diagnostic if filepath was not found', async () => { componentPathStub.returns({ getSourceComponents: () => { return { first: () => { return { content: undefined }; } }; } }); await executor.run(); expect(setDiagnosticStub.notCalled).to.be.true; }); it('should not set diagnostic if test has no associated diagnostic', async () => { runTestStub.resolves(passingResult); await executor.run(); expect(setDiagnosticStub.notCalled).to.be.true; }); }); });
the_stack
import assert from 'assert'; import * as ThingTalk from 'thingtalk'; import * as db from './db'; import * as entityModel from '../model/entity'; // import * as stringModel from '../model/strings'; import * as userModel from '../model/user'; import { clean, splitParams } from './tokenize'; import ThingpediaClient from './thingpedia-client'; import getExampleName from './example_names'; import { ValidationError } from './errors'; import * as userUtils from './user'; import * as I18n from './i18n'; assert(typeof ThingpediaClient === 'function'); export interface RequestLike { _ : (x : string) => string; user ?: Express.User; } const JAVASCRIPT_MODULE_TYPES = new Set([ 'org.thingpedia.v1', 'org.thingpedia.v2', 'org.thingpedia.builtin', 'org.thingpedia.embedded' ]); const SUBCATEGORIES = new Set(['service','media','social-network','communication','home','health','data-management']); const FORBIDDEN_NAMES = new Set(['__count__', '__noSuchMethod__', '__parent__', '__proto__', 'constructor', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'eval', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toSource', 'toString', 'valueOf']); const ALLOWED_ARG_METADATA = new Set(['canonical', 'prompt', 'question', 'counted_object']); const ALLOWED_FUNCTION_METADATA = new Set(['canonical', 'canonical_short', 'confirmation', 'confirmation_remote', 'result', 'formatted', 'on_error']); const ALLOWED_CLASS_METADATA = new Set(['name', 'description', 'thingpedia_name', 'thingpedia_description', 'canonical', 'help']); function validateAnnotations(annotations : ThingTalk.Ast.AnnotationMap) { for (const name of Object.getOwnPropertyNames(annotations)) { if (FORBIDDEN_NAMES.has(name)) throw new ValidationError(`Invalid implementation annotation ${name}`); } } function validateMetadata(metadata : ThingTalk.Ast.NLAnnotationMap, allowed : Set<string>) { for (const name of Object.getOwnPropertyNames(metadata)) { if (!allowed.has(name)) throw new ValidationError(`Invalid natural language annotation ${name}`); } } async function loadClassDef(dbClient : db.Client, req : RequestLike, kind : string, classCode : string, datasetCode : string) : Promise<[ThingTalk.Ast.ClassDef, ThingTalk.Ast.Dataset]> { const tpClient = new ThingpediaClient(req.user!.developer_key, req.user!.locale, undefined, dbClient); const schemaRetriever = new ThingTalk.SchemaRetriever(tpClient, null, true); let parsed; try { parsed = await ThingTalk.Syntax.parse(`${classCode}\n${datasetCode}`, ThingTalk.Syntax.SyntaxType.Normal, { locale: req.user!.locale, timezone: req.user!.timezone, }).typecheck(schemaRetriever, true); } catch(e) { if (e.name === 'SyntaxError' && e.location) { let lineNumber = e.location.start.line; // add 1 for the \n that we add to separate classCode and datasetCode console.log(classCode); const classLength = 1 + classCode.split('\n').length; const fileName = lineNumber > classLength ? 'dataset.tt' : 'manifest.tt'; // mind the 1-based line numbers... lineNumber = lineNumber > classLength ? lineNumber - classLength + 1 : lineNumber; throw new ValidationError(`Syntax error in ${fileName} line ${lineNumber}: ${e.message}`); } else { throw new ValidationError(e.message); } } if (!(parsed instanceof ThingTalk.Ast.Library) || parsed.classes.length !== 1 || (kind !== null && parsed.classes[0].kind !== kind)) throw new ValidationError("Invalid manifest file: must contain exactly one class, with the same identifier as the device"); const classDef = parsed.classes[0]; if (parsed.datasets.length > 1 || (parsed.datasets.length > 0 && parsed.datasets[0].name !== kind)) throw new ValidationError("Invalid dataset file: must contain exactly one dataset, with the same identifier as the class"); if (parsed.datasets.length > 0 && parsed.datasets[0].language && parsed.datasets[0].language !== 'en') throw new ValidationError("The dataset must be for English: use `en` as the language tag."); const dataset = parsed.datasets.length > 0 ? parsed.datasets[0] : new ThingTalk.Ast.Dataset(null, kind, [], {}); return [classDef, dataset]; } interface DeviceMetadata { name : string; description : string; primary_kind : string; license : string; license_gplcompatible : unknown; subcategory : string; website ?: string; repository ?: string; issue_tracker ?: string; } async function validateDevice(dbClient : db.Client, req : RequestLike, options : DeviceMetadata, classCode : string, datasetCode : string) : Promise<[ThingTalk.Ast.ClassDef, ThingTalk.Ast.Dataset]> { const name = options.name; const description = options.description; const kind = options.primary_kind; const license = options.license; if (!name || !description || !kind || !license) throw new ValidationError("Not all required fields were present"); validateTag(kind, req.user!, userUtils.Role.THINGPEDIA_ADMIN); if (!SUBCATEGORIES.has(options.subcategory)) throw new ValidationError(req._("Invalid device category %s").format(options.subcategory)); const [classDef, dataset] = await loadClassDef(dbClient, req, kind, classCode, datasetCode); validateMetadata(classDef.metadata, ALLOWED_CLASS_METADATA); validateAnnotations(classDef.annotations); if (!classDef.is_abstract) { if (!classDef.loader) throw new ValidationError(req._("Loader mixin missing from class declaration")); if (!classDef.config) classDef.imports.push(new ThingTalk.Ast.MixinImportStmt(null, ['config'], 'org.thingpedia.config.none', [])); } let moduleType : string|null; let fullcode : boolean; if (classDef.is_abstract) { moduleType = null; fullcode = false; } else { moduleType = classDef.loader!.module; fullcode = !JAVASCRIPT_MODULE_TYPES.has(moduleType); } for (const stmt of classDef.entities) { if (typeof stmt.nl_annotations.description !== 'string' || !stmt.nl_annotations.description) throw new ValidationError(req._("A description is required for entity %s").format(stmt.name)); } const [entities, _stringTypes] = await validateAllInvocations(classDef, { checkPollInterval: !classDef.is_abstract, checkUrl: fullcode, deviceName: name }); // add all the parents of declared entities to the list of entities that must exist for (const stmt of classDef.entities) { for (const parent of stmt.extends) entities.push(parent.includes(':') ? parent : classDef.kind + ':' + parent); } // remove from entities those that are declared in this class const filteredEntities = entities.filter((e) => !classDef.entities.find((stmt) => classDef.kind + ':' + stmt.name === e)); const missingEntities = await entityModel.findNonExisting(dbClient, filteredEntities); if (missingEntities.length > 0) throw new ValidationError('Invalid entity types: ' + missingEntities.join(', ')); // const missingStrings = await stringModel.findNonExisting(dbClient, stringTypes); // if (missingStrings.length > 0) // throw new ValidationError('Invalid string types: ' + missingStrings.join(', ')); const tokenizer = I18n.get('en-US').genie.getTokenizer(); if (!classDef.nl_annotations.name) classDef.nl_annotations.name = name; if (!classDef.nl_annotations.description) classDef.nl_annotations.description = description; if (!classDef.nl_annotations.canonical) classDef.nl_annotations.canonical = tokenizer.tokenize(name).tokens.join(' '); classDef.nl_annotations.thingpedia_name = name; classDef.nl_annotations.thingpedia_description = description; classDef.impl_annotations.subcategory = new ThingTalk.Ast.Value.Enum(options.subcategory); classDef.impl_annotations.license = new ThingTalk.Ast.Value.String(options.license); classDef.impl_annotations.license_gplcompatible = new ThingTalk.Ast.Value.Boolean(!!options.license_gplcompatible); if (options.website) classDef.impl_annotations.website = new ThingTalk.Ast.Value.Entity(options.website, 'tt:url', null); if (options.repository) classDef.impl_annotations.repository = new ThingTalk.Ast.Value.Entity(options.repository, 'tt:url', null); if (options.issue_tracker) classDef.impl_annotations.issue_tracker = new ThingTalk.Ast.Value.Entity(options.issue_tracker, 'tt:url', null); await validateDataset(dataset); return [classDef, dataset]; } function autogenExampleName(ex : ThingTalk.Ast.Example, names : Set<string>) { const baseName = getExampleName(ex); if (!names.has(baseName)) { names.add(baseName); return baseName; } let counter = 1; let name = baseName + counter; while (names.has(name)) { counter ++; name = baseName + counter; } names.add(name); return name; } function validateDataset(dataset : ThingTalk.Ast.Dataset) { const names = new Set<string>(); dataset.examples.forEach((ex, i) => { try { // FIXME: we clone the example here to workaround a bug in ThingTalk // we should not need it const ruleprog = ex.clone().toProgram(); // try and convert to NN const allocator = new ThingTalk.Syntax.EntityRetriever('', {}, { timezone: 'UTC' }); ThingTalk.Syntax.serialize(ruleprog, ThingTalk.Syntax.SyntaxType.Tokenized, allocator); // validate placeholders in all utterances validateAnnotations(ex.annotations); if (ex.utterances.length === 0) { if (Object.prototype.hasOwnProperty.call(ex.annotations, 'utterances')) throw new ValidationError(`utterances must be a natural language annotation (with #_[]), not an implementation annotation`); else throw new ValidationError(`missing utterances annotation`); } if (ex.annotations.name) { const value = ex.annotations.name.toJS(); if (typeof value !== 'string') throw new ValidationError(`invalid #[name] annotation (must be a string)`); if (value.length > 128) throw new ValidationError(`the #[name] annotation must be at most 128 characters`); if (names.has(value)) throw new ValidationError(`duplicate name`); names.add(value); } else { ex.annotations.name = new ThingTalk.Ast.Value.String(autogenExampleName(ex, names)); } for (const utterance of ex.utterances) validateUtterance(ex.args, utterance); } catch(e) { throw new ValidationError(`Error in example ${i+1}: ${e.message}`); } }); } function validateUtterance(args : Record<string, ThingTalk.Type>, utterance : string) { if (/_{4}/.test(utterance)) throw new ValidationError('Do not use blanks (4 underscores or more) in utterance, use placeholders'); const placeholders = new Set<string>(); for (const chunk of splitParams(utterance.trim())) { if (chunk === '') continue; if (typeof chunk === 'string') continue; const [match, param1, param2, opt] = chunk; if (match === '$$') continue; const param = param1 || param2; if (!(param in args)) throw new ValidationError(`Invalid placeholder ${param}`); if (opt && opt !== 'const' && opt !== 'no-undefined') throw new ValidationError(`Invalid placeholder option ${opt} for ${param}`); placeholders.add(param); } for (const arg in args) { if (!placeholders.has(arg)) throw new ValidationError(`Missing placeholder for argument ${arg}`); } } function validateAllInvocations(classDef : ThingTalk.Ast.ClassDef, options = {}) : [string[], string[]] { const entities = new Set<string>(); const stringTypes = new Set<string>(); validateInvocation(classDef.kind, classDef.actions, 'action', entities, stringTypes, options); validateInvocation(classDef.kind, classDef.queries, 'query', entities, stringTypes, options); return [Array.from(entities), Array.from(stringTypes)]; } function validateInvocation(kind : string, where : Record<string, ThingTalk.Ast.FunctionDef>, what : string, entities : Set<string>, stringTypes : Set<string>, options : { checkPollInterval ?: boolean, checkUrl ?: boolean } = {}) { for (const name in where) { if (FORBIDDEN_NAMES.has(name)) throw new ValidationError(`${name} is not allowed as a function name`); const fndef = where[name]; validateMetadata(fndef.metadata, ALLOWED_FUNCTION_METADATA); validateAnnotations(fndef.annotations); if (!fndef.metadata.canonical) fndef.metadata.canonical = [clean(name)]; else if (!Array.isArray(fndef.metadata.canonical)) fndef.metadata.canonical = [fndef.metadata.canonical]; if (fndef.annotations.confirm) { if (fndef.annotations.confirm.isEnum) { if (!['confirm', 'auto', 'display_result'].includes(fndef.annotations.confirm.toJS() as string)) throw new ValidationError(`Invalid #[confirm] annotation for ${name}, must be a an enum "confirm", "auto", "display_result"`); } else if (!fndef.annotations.confirm.isBoolean) { throw new ValidationError(`Invalid #[confirm] annotation for ${name}, must be a Boolean`); } } else { if (what === 'query') fndef.annotations.confirm = new ThingTalk.Ast.Value.Boolean(false); else fndef.annotations.confirm = new ThingTalk.Ast.Value.Boolean(true); } if (options.checkPollInterval && what === 'query' && fndef.is_monitorable) { if (!fndef.annotations.poll_interval) throw new ValidationError(`Missing poll interval for monitorable query ${name}`); if (fndef.annotations.poll_interval.toJS() as number < 0) throw new ValidationError(`Invalid negative poll interval for monitorable query ${name}`); } if (options.checkUrl) { if (!fndef.annotations.url) throw new ValidationError(`Missing ${what} url for ${name}`); } for (const argname of fndef.args) { if (FORBIDDEN_NAMES.has(argname)) throw new ValidationError(`${argname} is not allowed as argument name in ${name}`); const arg = fndef.getArgument(argname)!; let type = arg.type; while (type instanceof ThingTalk.Type.Array) type = type.elem as ThingTalk.Type; validateMetadata(arg.metadata, ALLOWED_ARG_METADATA); validateAnnotations(arg.annotations); if (type instanceof ThingTalk.Type.Entity) { entities.add(type.type); if (arg.annotations['string_values']) stringTypes.add(arg.annotations['string_values'].toJS() as string); } else if (type.isString) { if (arg.annotations['string_values']) stringTypes.add(arg.annotations['string_values'].toJS() as string); } else { if (arg.annotations['string_values']) throw new ValidationError('The string_values annotation is valid only for String-typed parameters'); } if (!arg.metadata.canonical) arg.metadata.canonical = clean(argname); } } } function cleanKind(kind : string) { // convert security-camera to 'security camera' and googleDrive to 'google drive' // thingengine.phone -> phone if (kind.startsWith('org.thingpedia.builtin.thingengine.')) kind = kind.substr('org.thingpedia.builtin.thingengine.'.length); // org.thingpedia.builtin.omlet -> omlet if (kind.startsWith('org.thingpedia.builtin.')) kind = kind.substr('org.thingpedia.builtin.'.length); // org.thingpedia.weather -> weather if (kind.startsWith('org.thingpedia.')) kind = kind.substr('org.thingpedia.'.length); // com.xkcd -> xkcd if (kind.startsWith('com.')) kind = kind.substr('com.'.length); if (kind.startsWith('gov.')) kind = kind.substr('gov.'.length); if (kind.startsWith('org.')) kind = kind.substr('org.'.length); if (kind.startsWith('uk.co.')) kind = kind.substr('uk.co.'.length); return kind.replace(/[_\-.]/g, ' ').replace(/([^A-Z])([A-Z])/g, '$1 $2').toLowerCase(); } function tokenizeOneExample(id : number, utterance : string, language : string) { let replaced = ''; const params : Array<[string, string]> = []; for (const chunk of splitParams(utterance.trim())) { if (chunk === '') continue; if (typeof chunk === 'string') { replaced += chunk; continue; } const [match, param1, param2, opt] = chunk; if (match === '$$') { replaced += '$'; continue; } const param = param1 || param2; replaced += '____ '; params.push([param, opt]); } const tokenizer = I18n.get(language).genie.getTokenizer(); const {tokens, entities} = tokenizer.tokenize(replaced); if (Object.keys(entities).length > 0) throw new ValidationError(`Error in Example ${id}: Cannot have entities in the utterance`); let preprocessed = ''; let first = true; for (let token of tokens) { if (token === '____') { const [param, opt] = params.shift()!; if (opt) token = '${' + param + ':' + opt + '}'; else token = '${' + param + '}'; } else if (token === '$') { token = '$$'; } if (!first) preprocessed += ' '; preprocessed += token; first = false; } return preprocessed; } async function tokenizeDataset(dataset : ThingTalk.Ast.Dataset) { return Promise.all(dataset.examples.map(async (ex, i) => { await Promise.all(ex.utterances.map(async (_, j) => { ex.preprocessed[j] = await tokenizeOneExample(i+1, ex.utterances[j], dataset.language || 'en'); })); })); } function validateTag(tag : string, user : userModel.RowWithOrg, adminRole : number|undefined) { // first the security/well-formedness checks // the name must be a valid DNS name: multiple parts separated // by '.'; each part must be alphanumeric, -, or _, // and must be both a valid hostname and a valid ThingTalk class-identifier // (not start or end with -, not start with a number) if (!/^([A-Za-z_][A-Za-z0-9_.-]*)$/.test(tag)) throw new ValidationError(`Invalid ID ${tag}`); if (/\.(js|json|css|htm|html|xml|jpg|jpeg|png|gif|bmp|ico|tif|tiff|woff)$/i.test(tag)) throw new ValidationError(`Invalid ID ${tag}`); const parts = tag.split('.'); for (const part of parts) { if (part.length === 0 || /^[-0-9]/.test(part) || part.endsWith('-')) throw new ValidationError(`Invalid ID ${tag}`); // JS reserved words and unsafe names are forbidden if (FORBIDDEN_NAMES.has(part)) throw new ValidationError(`${tag} is not allowed as ID because it contains the unsafe keyword ${part}`); } if (Buffer.from(tag, 'utf8').length > 128) throw new ValidationError("The chosen identifier is too long"); // now the naming convention checks // if there is an admin role in this context, and the user has it, anything is allowed if (adminRole !== undefined && (user.roles & adminRole) === adminRole) return; // otherwise, single part names (no dots) are always disallowed // names in the org.thingpedia namespace are also disallowed if (parts.length <= 1) throw new ValidationError(`Invalid ID ${tag}: must contain at least one period`); // if the user is in the root org, they're allowed org.thingpedia if (user.developer_org === 1) return; if (parts[0] === 'org' && parts[1] === 'thingpedia') { // ignore the 'org.thingpedia.builtin.test' and 'org.thingpedia.test' namespaces, which are free-for-all if (parts[2] === 'test' || (parts[2] === 'builtin' && parts[3] === 'test')) return; throw new ValidationError(`Invalid ID ${tag}: the @org.thingpedia namespace is reserved`); } } export { ValidationError, JAVASCRIPT_MODULE_TYPES, cleanKind, validateDevice, validateDataset, validateTag, tokenizeDataset, };
the_stack
import { Ipfs } from "ipfs"; import { IdentityProvider } from "orbit-db-identity-provider"; import { InsertOptions, InsertOneOptions, DocumentInterface, FindOptionsInterface, FindOneAndUpdateOptionsInterface, FindOneAndDeleteOptionsInterface, UpdateOptionsInterface, UpdateOneOptionsInterface, UpdateManyOptionsInterface, DeleteOneOptionsInterface, DeleteManyOptionsInterface, ImportOptionsInterface, ImportStreamOptionsInterface, ExportOptionsInterface, IStoreOptions, } from "./interfaces"; import { LogEntry } from "ipfs-log"; const OrbitdbStore = require("orbit-db-store"); const ObjectId = require("bson-objectid"); const CID = require("cids"); const CollectionIndex = require("./CollectionIndex"); const DagCbor = require("ipld-dag-cbor"); class Collection extends OrbitdbStore { constructor( ipfs: Ipfs, id: IdentityProvider, dbname: string, options: IStoreOptions ) { const opts = Object.assign({}, { Index: CollectionIndex }); Object.assign(opts, options); super(ipfs, id, dbname, opts); this._type = "aviondb.collection"; this.events.on( "write", (address: string, entry: LogEntry<any>, heads: LogEntry<any>[]) => { this._index.handleEntry(entry); } ); this.events.on( "replicate.progress", ( address: string, hash: Multihash, entry: LogEntry<any>, progress: number, total: number ) => { this._index.handleEntry(entry); } ); } /** * Inserts multiple records into a Collection * * @param {Array<DocumentInterface>} docs Array of Documents/Records * @param {InsertOptions} options Options for insert() * @param {Function} callback Callback function * @returns {Promise<string>} Returns a Promise that resolves to CID of the inserted DAG that points to the inserted document(s) */ insert( docs: Array<DocumentInterface>, options?: InsertOptions, callback?: Function ): Promise<string> { for (const doc of docs) { if (!doc._id) { doc._id = ObjectId.generate(); } } return this._addOperation({ op: "INSERT", value: docs, }); } /** * Inserts single record into a Collection * * @param {DocumentInterface} doc Single Document/Record * @param {InsertOneOptions} options options for insertOne() * @param {Function} callback Callback function * @returns {Promise<string>} Returns a Promise that resolves to CID of the inserted DAG that points to the inserted document */ async insertOne( doc: DocumentInterface, options?: InsertOneOptions, callback?: Function ): Promise<string> { if (typeof doc !== "object") throw new Error("Object documents are only supported"); return await this.insert([doc]); } /** * Fetches matching record(s) * * @param {object} query Query for find * @param {object|string} projection Projection (not implemented yet) * @param {FindOptionsInterface} options Options for find() * @param {Function} callback Callback function * @returns {Promise<Array<DocumentInterface>>} Returns a Promise that resolves to an Array of Document(s) */ find( query: object, projection?: object | string, options?: FindOptionsInterface, callback?: Function ): Promise<Array<DocumentInterface>> { return this._index.find(query, projection, options, callback); } /** * Fetches the first matching record * * @param {JSON Object} query Query for findOne(), same as for find() * @param {object|string} projection Projection (not implemented yet) * @param {object} options Options for findOne() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves a Document */ findOne( query: object, projection?: object | string, options?: object, callback?: Function ): Promise<DocumentInterface> { return this._index.findOne(query); } /** * Updates the first matching record * * @param {object} query Query for findOneAndUpdate(), same as for find() * @param {object} modification Projection (not implemented yet) * @param {FindOneAndUpdateOptionsInterface} options Options for findOneAndUpdate() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to the updated Document */ async findOneAndUpdate( filter: object = {}, modification: object, options?: FindOneAndUpdateOptionsInterface, callback?: Function ): Promise<DocumentInterface> { const doc = await this.findOne(filter); if (doc) { await this._addOperation({ op: "UPDATE", value: [doc._id], modification: modification, }); } return doc; } /** * Deletes a single document based on the filter and sort criteria, * returning the deleted document. * @param {object} filter The selection criteria for the deletion. The same query selectors as in the find() method are available. * @param {FindOneAndDeleteOptionsInterface} options Options for findOneAndDelete() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to the deleted Document */ async findOneAndDelete( filter: object = {}, options?: FindOneAndDeleteOptionsInterface, callback?: Function ): Promise<DocumentInterface> { const doc = await this.findOne(filter); if (doc) { await this._addOperation({ op: "DELETE", value: [doc._id], }); } return doc; } /** * Finds a record in the collection by Id * * @param {object|string|number} _id "_id" for a Document/Record * @param {object|string} projection Projection (not implemented yet) * @param {object} options Options for findById() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to a Document with matching "_id" */ findById( _id: string | number, projection?: object | string, options?: object, callback?: Function ): Promise<DocumentInterface> { return this._index.findById(_id, projection, options, callback); } /** * Finds & deletes a record in the collection by Id * * @param {object|string|number} _id "_id" for a Document/Record * @param {object} options Options for findByIdAndDelete() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to the deleted Document with matching "_id" */ async findByIdAndDelete( _id: string | number, options?: object, callback?: Function ): Promise<DocumentInterface> { const doc = this._index.findById(_id); if (doc) { await this._addOperation({ op: "DELETE", value: [doc._id], }); } return doc; } /** * * Finds & updates a record in the collection by Id * * @param {object|string|number} _id "_id" for a Document/Record * @param {object} modification Updates that need to made to the matching documents * @param {object} options Options for findByIdAndUpdate() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to the updated Document with matching "_id" */ async findByIdAndUpdate( _id: string | number, modification: object, options: object = {}, callback?: Function ): Promise<DocumentInterface> { const doc = await this._index.findById(_id); if (doc) { await this._addOperation({ op: "UPDATE", value: [doc._id], modification: modification, options: options, }); } return doc; } /** * * Modifies an existing document or documents in a collection. * The method can modify specific fields of an existing document * or documents or replace an existing document entirely, depending * on the update parameter. * * By default, the db.collection.update() method updates a single document. * Include the option multi: true to update all documents that match the query criteria. * * * db.collection.update( <filter>, <modification>, { upsert: <boolean>, multi: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } ) * @param {object} filter Query/Filter criteria for documents, same as for find() * @param {object} modification Updates that need to made to the matching document(s) * @param {UpdateOptionsInterface} options Options for update() * @param {Function} callback Callback function * @returns {Promise<Array<DocumentInterface>>} Returns a Promise that resolves to an Array of updated Document(s) */ async update( filter: object = {}, modification: object, options: UpdateOptionsInterface = {}, callback?: Function ): Promise<Array<DocumentInterface>> { const ids = []; const docs = []; if (options.multi) { docs.push(...(await this.find(filter))); ids.push(...docs.map((item) => item._id)); } if (options.upsert && ids.length === 0) { // TODO: implement upsert condition for $setOnInsert operator } else if ( Object.keys(options).length === 0 && options.constructor === Object ) { const doc = await this.findOne(filter); if (doc) { docs.push(doc); ids.push(...docs.map((item) => item._id)); } } await this._addOperation({ op: "UPDATE", value: ids, modification: modification, options: options, }); return docs; } /** * Updates a single document within the collection based on the filter. * * db.collection.updateOne( <filter>, <modification>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } ) * * @param {object} filter Query/Filter criteria for documents, same as for find() * @param {object} modification Updates that need to made to the matching document * @param {UpdateOneOptionsInterface} options Options for updateOne() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to an updated Document */ async updateOne( filter: object = {}, modification: object, options: UpdateOneOptionsInterface = {}, callback?: Function ): Promise<DocumentInterface> { const doc = await this.findOne(filter); if (doc) { await this._addOperation({ op: "UPDATE", value: [doc._id], modification: modification, options: options, }); } return doc; } /** * * Updates all documents that match the specified filter for a collection. * * db.collection.updateMany( <filter>, <modification>, { upsert: <boolean>, writeConcern: <document>, collation: <document>, arrayFilters: [ <filterdocument1>, ... ], hint: <document|string> } ) * * @param {object} filter Query/Filter criteria for documents, same as for find() * @param {object} modification Updates that need to made to the matching document(s) * @param {UpdateManyOptionsInterface} options Options for updateOneMany() * @param {Function} callback Callback function * @returns {Promise<Array<DocumentInterface>>} Returns a Promise that resolves to an Array of updated Document(s) */ async updateMany( filter: object = {}, modification: object, options: UpdateManyOptionsInterface = {}, callback?: Function ): Promise<Array<DocumentInterface>> { const docs = await this.find(filter); const ids = docs.map((item: DocumentInterface) => item._id); await this._addOperation({ op: "UPDATE", value: ids, modification: modification, options: options, }); return docs; } /** * Deletes a single document based on the filter, returning the deleted document. * * @param {object} filter The selection criteria for the deletion. The same query selectors as in the find() method are available. * @param {DeleteOneOptionsInterface} options Options for deleteOne() * @param {Function} callback Callback function * @returns {Promise<DocumentInterface>} Returns a Promise that resolves to a deleted Document */ async deleteOne( filter: object = {}, options?: DeleteOneOptionsInterface, callback?: Function ): Promise<DocumentInterface> { const doc = await this.findOne(filter); if (doc) { await this._addOperation({ op: "DELETE", value: [doc._id], }); } return doc; } /** * Deletes all the documents based on the filter, returning the deleted documents. * * @param {object} filter The selection criteria for the deletion. The same query selectors as in the find() method are available. * @param {DeleteManyOptionsInterface} options Options for deleteMany() * @param {Function} callback Callback function * @returns {Promise<Array<DocumentInterface>>} Returns a Promise that resolves to an Array of deleted Document */ async deleteMany( filter: object = {}, options?: DeleteManyOptionsInterface, callback?: Function ): Promise<Array<DocumentInterface>> { const docs = await this.find(filter); const ids = docs.map((item: DocumentInterface) => item._id); if (ids.length > 0) { await this._addOperation({ op: "DELETE", value: ids, }); } return docs; } /** * Returns unique (with respect to a key) Documents * @param key name of the field whose values should be unique * @param query Query criteria for documents, same as for find() * @returns {Promise<Array<DocumentInterface>>} Returns a Promise that resolves to an Array of unique Document(s) */ distinct( key: object | string | number, query: object ): Promise<Array<DocumentInterface>> { return this._index.distinct(key, query); } /** * Returns CID string representing oplog heads. * returns null if oplog is empty * @returns {string} Returns CID string representing oplog heads. */ async getHeadHash(): Promise<string | null> { try { return await this._oplog.toMultihash(); } catch { return null; } } /** * Syncs datastore to a supplied CID representing oplog heads. * Pauses all write operations until sync is complete. * @param {string} hash Head hash string * @param {boolean} stopWrites Should we pause write operations while syncing * @returns {Promise<null>} */ async syncFromHeadHash( hash: string, stopWrites?: boolean ): Promise<undefined> { if (new CID(hash).equals(new CID(await this.getHeadHash()))) { //Nothing to do return; } //Retrieve dag of headhash. const { value } = await this._ipfs.dag.get(hash); if (value.id !== this.id) { throw "Head Hash ID does not match store ID."; } //Generate list of head dags from list of hashes const heads = []; for (const hashOfHead of value.heads) { const val = (await this._ipfs.dag.get(hashOfHead)).value; val.hash = hashOfHead.toBaseEncodedString("base58btc"); //Convert to base58btc to prevent orbit-db-store from throwing comparison errors. (File future bug report) heads.push(val); } if (stopWrites) { this._opqueue.pause(); } await this.sync(heads); this._opqueue.start(); } /** * Import data into aviondb through buffer. * * @param {any} data_in Data to be imported in "cbor", "json_mongo", or "raw" format * @param {ImportOptionsInterface} options Options for import() * @param {Function} progressCallback Callback Function for checking progress of import process */ async import( data_in: any, options: ImportOptionsInterface = {}, progressCallback?: Function ) { if (!options.overwrite) { //TODO: drop database and overwrite all entries. options.overwrite = false; } if (!options.type) { options.type = "json_mongo"; //options.type = "cbor"; //options.type = "raw"; } if (!options.batchSize) { options.batchSize = 25; //Insert 25 at a time by default. } let deserialized_object: any = {}; if (options.type === "cbor") { deserialized_object = DagCbor.util.deserialize(data_in); } else if (options.type === "json_mongo") { deserialized_object = JSON.parse(data_in); //Assumes JSON is serialized. } else if (options.type === "raw") { deserialized_object = data_in; } else { throw `Unknown options.type: ${options.type}`; } async function* streamGenerator() { for (const entry of deserialized_object) { yield entry; } } const objTotalLength: number = deserialized_object.length; await this.importStream( streamGenerator(), objTotalLength, { batchSize: options.batchSize }, progressCallback ); } /** * * @param {AsyncIterable} stream Data stream to be imported * @param {number} length Total stream length * @param {ImportStreamOptionsInterface} options Options for importStream() * @param {Function} progressCallback Callback Function for checking progress of import process */ async importStream( stream: AsyncIterable<any>, length: number, options: ImportStreamOptionsInterface, progressCallback?: Function ) { const totalLength = length; //Assumes array at the moment. let currentLength = 0; let queue = []; for await (const entry of stream) { if (queue.length >= options.batchSize) { await this.insert(queue); queue = []; if (progressCallback) { const progressPercent = (currentLength / totalLength) * 100; progressCallback(currentLength, totalLength, progressPercent); } } else { if (typeof entry._id === "object") { //Assume $oid is being used. Mongodb exports the primary key string under object. entry._id = entry._id.$oid; } queue.push(entry); currentLength += queue.length; } } if (queue.length > 0) { await this.insert(queue); currentLength += queue.length; if (progressCallback) { const progressPercent = (currentLength / totalLength) * 100; progressCallback(currentLength, totalLength, progressPercent); } queue = []; } } /** * Exports records in collection * @param {ExportOptionsInterface} options Options for export() * @returns {Promise<string | DocumentInterface[]>} Returns a Promise that resolves to the exported data in "cbor", "json_mongo", "raw" format */ async export( options: ExportOptionsInterface = {} ): Promise<string | DocumentInterface[]> { if (!options.cursor) { options.cursor = {}; // No limit. } if (!options.type) { options.type = "json_mongo"; //options.type = "cbor"; //options.type = "raw"; } if (!options.query) { options.query = {}; } const results = await this.find(options.query, null, options.cursor); switch (options.type) { case "json_mongo": { //TODO: Future streamed json. return JSON.stringify(results); } case "cbor": { return DagCbor.util.serialize(results); } case "raw": { return results; } default: { throw `Unknown options.type: ${options.type}`; } } } async drop() { super.drop(); //TODO: broadcast drop message on binding database } } export default Collection;
the_stack
import * as React from 'react'; import { useConst } from '@fluentui/react-hooks'; import { IFloatingSuggestionItemProps, IFloatingSuggestionItem, IFloatingPeopleSuggestionsProps, } from '@fluentui/react-experiments/lib/FloatingPeopleSuggestionsComposite'; import { UnifiedPeoplePicker } from '@fluentui/react-experiments/lib/UnifiedPeoplePicker'; import { IPersonaProps, IPersona, PersonaSize } from '@fluentui/react/lib/Persona'; import { mru, people } from '@fluentui/example-data'; import { ISelectedPeopleListProps, SelectedPersona, TriggerOnContextMenu, EditableItem, DefaultEditingItem, EditingItemInnerFloatingPickerProps, ItemWithContextMenu, ISelectedItemProps, } from '@fluentui/react-experiments/lib/SelectedItemsList'; import { IInputProps } from '@fluentui/react'; import { FloatingPeopleSuggestions } from '@fluentui/react-experiments/lib/FloatingPeopleSuggestionsComposite'; import { KeyCodes } from '@fluentui/react-experiments/lib/Utilities'; import { mergeStyleSets } from '@fluentui/react/lib/Styling'; const classNames = mergeStyleSets({ to: { display: 'inline-block', position: 'relative', height: 32, lineHeight: 32, margin: '4px', minWidth: '52px', padding: '0 4px', textAlign: 'center', color: '#005A9E', backgroundColor: '#EFF6FC', borderRadius: '2px', }, }); const _suggestions = [ { key: '1', id: '1', displayText: 'Suggestion 1', item: mru[0], isSelected: true, showRemoveButton: true, }, { key: '2', id: '2', displayText: 'Suggestion 2', item: mru[1], isSelected: false, showRemoveButton: true, }, { key: '3', id: '3', displayText: 'Suggestion 3', item: mru[2], isSelected: false, showRemoveButton: true, }, { key: '4', id: '4', displayText: 'Suggestion 4', item: mru[3], isSelected: false, showRemoveButton: true, }, { key: '5', id: '5', displayText: 'Suggestion 5', item: mru[4], isSelected: false, showRemoveButton: true, }, ] as IFloatingSuggestionItem<IPersonaProps>[]; export const UnifiedPeoplePickerWithEditExample = (): JSX.Element => { const [peopleSuggestions, setPeopleSuggestions] = React.useState<IFloatingSuggestionItemProps<IPersonaProps>[]>([ ..._suggestions, ]); const [peopleSelectedItems, setPeopleSelectedItems] = React.useState<IPersonaProps[]>([]); const [inputText, setInputText] = React.useState<string>(''); const [editingIndex, setEditingIndex] = React.useState(-1); const ref = React.useRef<any>(); const suggestionProps = useConst(() => { return { // uncomment below section to see any example of a selectable header item headerItemsProps: [ { renderItem: () => { return <>People Suggestions</>; }, shouldShow: () => { return peopleSuggestions.length > 0; }, /*onExecute: () => { alert('People suggestions selected'); },*/ }, ], footerItemsProps: [ { renderItem: () => { return <>Showing {peopleSuggestions.length} results</>; }, shouldShow: () => { return peopleSuggestions.length > 0; }, // uncomment to see an example of multiple selectable footer items /*onExecute: () => { alert('Showing people suggestions executed'); },*/ }, { renderItem: () => { return <>Select to log out to console</>; }, shouldShow: () => { return peopleSuggestions.length > 0; }, onExecute: () => { console.log(peopleSuggestions); }, }, ], }; }); const _getSuggestions = (value: string): IFloatingSuggestionItemProps<IPersonaProps>[] => { const allPeople = people; const suggestions = allPeople.filter((item: IPersonaProps) => _startsWith(item.text || '', value)); const suggestionList = suggestions.map(item => { return { item: item, isSelected: false, key: item.key } as IFloatingSuggestionItem<IPersonaProps>; }); return suggestionList; }; const _isValid = React.useCallback((item: IPersonaProps): boolean => Boolean(item.secondaryText), []); const SelectedItemInternal = (props: ISelectedItemProps<IPersonaProps>) => { props.item.size = PersonaSize.size48; return <SelectedPersona isValid={_isValid} {...props} />; }; /** * Build a custom selected item capable of being edited when the item is right clicked */ const SelectedItem = EditableItem({ editingItemComponent: DefaultEditingItem({ getEditingItemText: persona => persona.text || '', getSuggestions: _getSuggestions, pickerSuggestionsProps: suggestionProps, onRenderFloatingPicker: (props: EditingItemInnerFloatingPickerProps<IPersonaProps>) => ( <FloatingPeopleSuggestions {...props} isSuggestionsVisible={true} /> ), }), itemComponent: ItemWithContextMenu<IPersona>({ menuItems: (item, onTrigger) => [ { key: 'copy', text: 'copy', onClick: () => { _copyToClipboardWrapper(item); }, }, { key: 'edit', text: 'Edit', onClick: () => onTrigger && onTrigger(), }, ], itemComponent: TriggerOnContextMenu(SelectedItemInternal), }), getIsEditing: (item, index) => index === editingIndex, onEditingStarted: (item, index) => setEditingIndex(index), onEditingCompleted: () => setEditingIndex(-1), }); const _copyToClipboardWrapper = (item: IPersona) => { const selectedItems = ref.current?.getSelectedItems(); if (selectedItems && selectedItems.length > 1) { _copyToClipboard(_getItemsCopyText(selectedItems)); } else { _copyToClipboard(_getItemsCopyText([item])); } }; const _copyToClipboard = (copyString: string): void => { navigator.clipboard.writeText(copyString).then( () => { /* clipboard successfully set */ }, () => { /* clipboard write failed */ throw new Error(); }, ); }; const _onSuggestionSelected = ( ev: React.MouseEvent<HTMLElement, MouseEvent>, item: IFloatingSuggestionItemProps<IPersonaProps>, ) => { _markSuggestionSelected(item); setPeopleSelectedItems(prevPeopleSelectedItems => [...prevPeopleSelectedItems, item.item]); }; const _onSuggestionRemoved = ( ev: React.MouseEvent<HTMLElement, MouseEvent>, suggestionToRemove: IFloatingSuggestionItemProps<IPersonaProps>, ) => { // Intentionally checking on complete item object to ensure it is removed. Id cannot be used as the // property is not populated for all the suggestions, and key does not exist on type checking. setPeopleSuggestions(suggestions => { const modifiedSuggestions = suggestions.filter(suggestion => suggestion.item !== suggestionToRemove.item); return modifiedSuggestions; }); }; const _markSuggestionSelected = (selectedSuggestion: IFloatingSuggestionItemProps<IPersonaProps>) => { setPeopleSuggestions(suggestions => { const modifiedSuggestions = suggestions.map(suggestion => suggestion.id === selectedSuggestion.id ? { ...suggestion, isSelected: true } : { ...suggestion, isSelected: false }, ); return modifiedSuggestions; }); }; const _getItemsCopyText = (itemsToCopy: IPersonaProps[]): string => { let copyText = ''; if (itemsToCopy && itemsToCopy.length > 0) { itemsToCopy.forEach(item => { copyText = copyText.concat((item.text || '') + ','); }); } return copyText; }; const _onPaste = (pastedValue: string, selectedItemsList: IPersonaProps[]): void => { // Find the suggestion corresponding to the specific text name // and update the selectedItemsList to re-render everything. const newList: IPersonaProps[] = []; if (pastedValue !== null) { pastedValue.split(',').forEach(textValue => { if (textValue) { people.forEach(suggestionItem => { if (suggestionItem.text === textValue) { selectedItemsList.push(suggestionItem); newList.push(suggestionItem); } }); } }); } setPeopleSelectedItems(prevPeopleSelectedItems => [...prevPeopleSelectedItems, ...newList]); }; const _onItemsRemoved = (itemsToRemove: IPersonaProps[]): void => { // Updating the local copy as well at the parent level. const currentItems: IPersonaProps[] = [...peopleSelectedItems]; const updatedItems: IPersonaProps[] = currentItems; // Intentionally not using .filter here as we want to only remove a specific // item in case of duplicates of same item. itemsToRemove.forEach(item => { const index: number = updatedItems.indexOf(item); updatedItems.splice(index, 1); }); setPeopleSelectedItems(updatedItems); }; const _replaceItem = (newItem: IPersonaProps | IPersona[], index: number): void => { const newItemsArray = !Array.isArray(newItem) ? [newItem] : newItem; if (index >= 0) { const newItems: IPersonaProps[] = [...peopleSelectedItems]; newItems.splice(index, 1, ...newItemsArray); setPeopleSelectedItems(newItems); } }; const _createGenericItem = (input: string) => { if (input) { return { text: input }; } else { return null; } }; const _addGenericItem = (text: string) => { const newItem = _createGenericItem(text); if (newItem) { setPeopleSelectedItems(prevPeopleSelectedItems => [...prevPeopleSelectedItems, newItem]); ref.current?.clearInput(); setInputText(''); } }; const _onInputChange = (filterText: string): void => { // Add a generic item to the end of the list // and clear the input if the user types a semicolon or comma const lastCharIndex = filterText.length - 1; const lastChar = filterText[lastCharIndex]; if (lastChar === ';' || lastChar === ',') { const itemText = filterText.slice(0, filterText.length - 1); _addGenericItem(itemText); } else { // Save the input text for force resolve setInputText(filterText); } const allPeople = people; const suggestions = allPeople.filter((item: IPersonaProps) => _startsWith(item.text || '', filterText)); const suggestionList = suggestions.map(item => { return { item: item, isSelected: false, key: item.key } as IFloatingSuggestionItem<IPersonaProps>; }); // We want to show top 5 results setPeopleSuggestions(suggestionList.splice(0, 5)); }; function _startsWith(text: string, filterText: string): boolean { return text.toLowerCase().indexOf(filterText.toLowerCase()) === 0; } const _onKeyDown = React.useCallback( (ev: React.KeyboardEvent<HTMLDivElement>) => { // eslint-disable-next-line deprecation/deprecation if (ev.ctrlKey && ev.which === KeyCodes.k) { ev.preventDefault(); // If the input has text, resolve that if (inputText !== undefined && inputText !== '' && inputText !== null) { // try force resolving, then if that doesn't work, add a generic item if (!ref.current?.forceResolve()) { _addGenericItem(inputText); } } else { // put invalid items into edit mode } } }, // eslint-disable-next-line react-hooks/exhaustive-deps [inputText, ref], ); const _onValidateInput = React.useCallback((input: string) => { return true; }, []); const _getAccessibleTextForDelete = React.useCallback((items: IPersonaProps[]): string => { if (items.length !== 1) { return 'Selection deleted'; } return items[0].text || ''; }, []); const floatingPeoplePickerProps = { suggestions: [...peopleSuggestions], isSuggestionsVisible: false, targetElement: null, onSuggestionSelected: _onSuggestionSelected, onRemoveSuggestion: _onSuggestionRemoved, suggestionsHeaderText: 'People suggestions', noResultsFoundText: 'No suggestions', onFloatingSuggestionsDismiss: undefined, showSuggestionRemoveButton: true, pickerWidth: '300px', } as IFloatingPeopleSuggestionsProps; const selectedPeopleListProps = { selectedItems: [...peopleSelectedItems], removeButtonAriaLabel: 'Remove', onItemsRemoved: _onItemsRemoved, getItemCopyText: _getItemsCopyText, onRenderItem: SelectedItem, replaceItem: _replaceItem, createGenericItem: _createGenericItem, } as ISelectedPeopleListProps<IPersonaProps>; const inputProps = { 'aria-label': 'Add people', } as IInputProps; return ( <> <UnifiedPeoplePicker componentRef={ref} selectedItemsListProps={selectedPeopleListProps} floatingSuggestionProps={floatingPeoplePickerProps} inputProps={inputProps} // eslint-disable-next-line react/jsx-no-bind onInputChange={_onInputChange} // eslint-disable-next-line react/jsx-no-bind onPaste={_onPaste} defaultDragDropEnabled={false} onKeyDown={_onKeyDown} onValidateInput={_onValidateInput} itemListAriaLabel="Recipient list" getAccessibleTextForDelete={_getAccessibleTextForDelete} headerComponent={ <div className={classNames.to} data-is-focusable> To </div> } /> </> ); };
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class ChimeSDKMessaging extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: ChimeSDKMessaging.Types.ClientConfiguration) config: Config & ChimeSDKMessaging.Types.ClientConfiguration; /** * Associates a channel flow with a channel. Once associated, all messages to that channel go through channel flow processors. To stop processing, use the DisassociateChannelFlow API. Only administrators or channel moderators can associate a channel flow. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ associateChannelFlow(params: ChimeSDKMessaging.Types.AssociateChannelFlowRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Associates a channel flow with a channel. Once associated, all messages to that channel go through channel flow processors. To stop processing, use the DisassociateChannelFlow API. Only administrators or channel moderators can associate a channel flow. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ associateChannelFlow(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Adds a specified number of users to a channel. */ batchCreateChannelMembership(params: ChimeSDKMessaging.Types.BatchCreateChannelMembershipRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.BatchCreateChannelMembershipResponse) => void): Request<ChimeSDKMessaging.Types.BatchCreateChannelMembershipResponse, AWSError>; /** * Adds a specified number of users to a channel. */ batchCreateChannelMembership(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.BatchCreateChannelMembershipResponse) => void): Request<ChimeSDKMessaging.Types.BatchCreateChannelMembershipResponse, AWSError>; /** * Calls back Chime SDK Messaging with a processing response message. This should be invoked from the processor Lambda. This is a developer API. You can return one of the following processing responses: Update message content or metadata Deny a message Make no changes to the message */ channelFlowCallback(params: ChimeSDKMessaging.Types.ChannelFlowCallbackRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ChannelFlowCallbackResponse) => void): Request<ChimeSDKMessaging.Types.ChannelFlowCallbackResponse, AWSError>; /** * Calls back Chime SDK Messaging with a processing response message. This should be invoked from the processor Lambda. This is a developer API. You can return one of the following processing responses: Update message content or metadata Deny a message Make no changes to the message */ channelFlowCallback(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ChannelFlowCallbackResponse) => void): Request<ChimeSDKMessaging.Types.ChannelFlowCallbackResponse, AWSError>; /** * Creates a channel to which you can add users and send messages. Restriction: You can't change a channel's privacy. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannel(params: ChimeSDKMessaging.Types.CreateChannelRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelResponse, AWSError>; /** * Creates a channel to which you can add users and send messages. Restriction: You can't change a channel's privacy. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannel(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelResponse, AWSError>; /** * Permanently bans a member from a channel. Moderators can't add banned members to a channel. To undo a ban, you first have to DeleteChannelBan, and then CreateChannelMembership. Bans are cleaned up when you delete users or channels. If you ban a user who is already part of a channel, that user is automatically kicked from the channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannelBan(params: ChimeSDKMessaging.Types.CreateChannelBanRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelBanResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelBanResponse, AWSError>; /** * Permanently bans a member from a channel. Moderators can't add banned members to a channel. To undo a ban, you first have to DeleteChannelBan, and then CreateChannelMembership. Bans are cleaned up when you delete users or channels. If you ban a user who is already part of a channel, that user is automatically kicked from the channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannelBan(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelBanResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelBanResponse, AWSError>; /** * Creates a channel flow, a container for processors. Processors are AWS Lambda functions that perform actions on chat messages, such as stripping out profanity. You can associate channel flows with channels, and the processors in the channel flow then take action on all messages sent to that channel. This is a developer API. Channel flows process the following items: New and updated messages Persistent and non-persistent messages The Standard message type Channel flows don't process Control or System messages. For more information about the message types provided by Chime SDK Messaging, refer to Message types in the Amazon Chime developer guide. */ createChannelFlow(params: ChimeSDKMessaging.Types.CreateChannelFlowRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelFlowResponse, AWSError>; /** * Creates a channel flow, a container for processors. Processors are AWS Lambda functions that perform actions on chat messages, such as stripping out profanity. You can associate channel flows with channels, and the processors in the channel flow then take action on all messages sent to that channel. This is a developer API. Channel flows process the following items: New and updated messages Persistent and non-persistent messages The Standard message type Channel flows don't process Control or System messages. For more information about the message types provided by Chime SDK Messaging, refer to Message types in the Amazon Chime developer guide. */ createChannelFlow(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelFlowResponse, AWSError>; /** * Adds a user to a channel. The InvitedBy field in ChannelMembership is derived from the request header. A channel member can: List messages Send messages Receive messages Edit their own messages Leave the channel Privacy settings impact this action as follows: Public Channels: You do not need to be a member to list messages, but you must be a member to send messages. Private Channels: You must be a member to list or send messages. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannelMembership(params: ChimeSDKMessaging.Types.CreateChannelMembershipRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelMembershipResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelMembershipResponse, AWSError>; /** * Adds a user to a channel. The InvitedBy field in ChannelMembership is derived from the request header. A channel member can: List messages Send messages Receive messages Edit their own messages Leave the channel Privacy settings impact this action as follows: Public Channels: You do not need to be a member to list messages, but you must be a member to send messages. Private Channels: You must be a member to list or send messages. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannelMembership(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelMembershipResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelMembershipResponse, AWSError>; /** * Creates a new ChannelModerator. A channel moderator can: Add and remove other members of the channel. Add and remove other moderators of the channel. Add and remove user bans for the channel. Redact messages in the channel. List messages in the channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannelModerator(params: ChimeSDKMessaging.Types.CreateChannelModeratorRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelModeratorResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelModeratorResponse, AWSError>; /** * Creates a new ChannelModerator. A channel moderator can: Add and remove other members of the channel. Add and remove other moderators of the channel. Add and remove user bans for the channel. Redact messages in the channel. List messages in the channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ createChannelModerator(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.CreateChannelModeratorResponse) => void): Request<ChimeSDKMessaging.Types.CreateChannelModeratorResponse, AWSError>; /** * Immediately makes a channel and its memberships inaccessible and marks them for deletion. This is an irreversible process. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannel(params: ChimeSDKMessaging.Types.DeleteChannelRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Immediately makes a channel and its memberships inaccessible and marks them for deletion. This is an irreversible process. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannel(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a user from a channel's ban list. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelBan(params: ChimeSDKMessaging.Types.DeleteChannelBanRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a user from a channel's ban list. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelBan(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a channel flow, an irreversible process. This is a developer API. This API works only when the channel flow is not associated with any channel. To get a list of all channels that a channel flow is associated with, use the ListChannelsAssociatedWithChannelFlow API. Use the DisassociateChannelFlow API to disassociate a channel flow from all channels. */ deleteChannelFlow(params: ChimeSDKMessaging.Types.DeleteChannelFlowRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a channel flow, an irreversible process. This is a developer API. This API works only when the channel flow is not associated with any channel. To get a list of all channels that a channel flow is associated with, use the ListChannelsAssociatedWithChannelFlow API. Use the DisassociateChannelFlow API to disassociate a channel flow from all channels. */ deleteChannelFlow(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a member from a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelMembership(params: ChimeSDKMessaging.Types.DeleteChannelMembershipRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a member from a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelMembership(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a channel message. Only admins can perform this action. Deletion makes messages inaccessible immediately. A background process deletes any revisions created by UpdateChannelMessage. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelMessage(params: ChimeSDKMessaging.Types.DeleteChannelMessageRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a channel message. Only admins can perform this action. Deletion makes messages inaccessible immediately. A background process deletes any revisions created by UpdateChannelMessage. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelMessage(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a channel moderator. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelModerator(params: ChimeSDKMessaging.Types.DeleteChannelModeratorRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes a channel moderator. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ deleteChannelModerator(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Returns the full details of a channel in an Amazon Chime AppInstance. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannel(params: ChimeSDKMessaging.Types.DescribeChannelRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelResponse, AWSError>; /** * Returns the full details of a channel in an Amazon Chime AppInstance. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannel(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelResponse, AWSError>; /** * Returns the full details of a channel ban. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelBan(params: ChimeSDKMessaging.Types.DescribeChannelBanRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelBanResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelBanResponse, AWSError>; /** * Returns the full details of a channel ban. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelBan(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelBanResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelBanResponse, AWSError>; /** * Returns the full details of a channel flow in an Amazon Chime AppInstance. This is a developer API. */ describeChannelFlow(params: ChimeSDKMessaging.Types.DescribeChannelFlowRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelFlowResponse, AWSError>; /** * Returns the full details of a channel flow in an Amazon Chime AppInstance. This is a developer API. */ describeChannelFlow(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelFlowResponse, AWSError>; /** * Returns the full details of a user's channel membership. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelMembership(params: ChimeSDKMessaging.Types.DescribeChannelMembershipRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelMembershipResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelMembershipResponse, AWSError>; /** * Returns the full details of a user's channel membership. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelMembership(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelMembershipResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelMembershipResponse, AWSError>; /** * Returns the details of a channel based on the membership of the specified AppInstanceUser. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelMembershipForAppInstanceUser(params: ChimeSDKMessaging.Types.DescribeChannelMembershipForAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelMembershipForAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelMembershipForAppInstanceUserResponse, AWSError>; /** * Returns the details of a channel based on the membership of the specified AppInstanceUser. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelMembershipForAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelMembershipForAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelMembershipForAppInstanceUserResponse, AWSError>; /** * Returns the full details of a channel moderated by the specified AppInstanceUser. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelModeratedByAppInstanceUser(params: ChimeSDKMessaging.Types.DescribeChannelModeratedByAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelModeratedByAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelModeratedByAppInstanceUserResponse, AWSError>; /** * Returns the full details of a channel moderated by the specified AppInstanceUser. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelModeratedByAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelModeratedByAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelModeratedByAppInstanceUserResponse, AWSError>; /** * Returns the full details of a single ChannelModerator. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelModerator(params: ChimeSDKMessaging.Types.DescribeChannelModeratorRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelModeratorResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelModeratorResponse, AWSError>; /** * Returns the full details of a single ChannelModerator. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ describeChannelModerator(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.DescribeChannelModeratorResponse) => void): Request<ChimeSDKMessaging.Types.DescribeChannelModeratorResponse, AWSError>; /** * Disassociates a channel flow from all its channels. Once disassociated, all messages to that channel stop going through the channel flow processor. Only administrators or channel moderators can disassociate a channel flow. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ disassociateChannelFlow(params: ChimeSDKMessaging.Types.DisassociateChannelFlowRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Disassociates a channel flow from all its channels. Once disassociated, all messages to that channel stop going through the channel flow processor. Only administrators or channel moderators can disassociate a channel flow. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ disassociateChannelFlow(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Gets the membership preferences of an AppInstanceUser for the specified channel. The AppInstanceUser must be a member of the channel. Only the AppInstanceUser who owns the membership can retrieve preferences. Users in the AppInstanceAdmin and channel moderator roles can't retrieve preferences for other users. Banned users can't retrieve membership preferences for the channel from which they are banned. */ getChannelMembershipPreferences(params: ChimeSDKMessaging.Types.GetChannelMembershipPreferencesRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetChannelMembershipPreferencesResponse) => void): Request<ChimeSDKMessaging.Types.GetChannelMembershipPreferencesResponse, AWSError>; /** * Gets the membership preferences of an AppInstanceUser for the specified channel. The AppInstanceUser must be a member of the channel. Only the AppInstanceUser who owns the membership can retrieve preferences. Users in the AppInstanceAdmin and channel moderator roles can't retrieve preferences for other users. Banned users can't retrieve membership preferences for the channel from which they are banned. */ getChannelMembershipPreferences(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetChannelMembershipPreferencesResponse) => void): Request<ChimeSDKMessaging.Types.GetChannelMembershipPreferencesResponse, AWSError>; /** * Gets the full details of a channel message. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ getChannelMessage(params: ChimeSDKMessaging.Types.GetChannelMessageRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.GetChannelMessageResponse, AWSError>; /** * Gets the full details of a channel message. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ getChannelMessage(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.GetChannelMessageResponse, AWSError>; /** * Gets message status for a specified messageId. Use this API to determine the intermediate status of messages going through channel flow processing. The API provides an alternative to retrieving message status if the event was not received because a client wasn't connected to a websocket. Messages can have any one of these statuses. SENT Message processed successfully PENDING Ongoing processing FAILED Processing failed DENIED Messasge denied by the processor This API does not return statuses for denied messages, because we don't store them once the processor denies them. Only the message sender can invoke this API. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header */ getChannelMessageStatus(params: ChimeSDKMessaging.Types.GetChannelMessageStatusRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetChannelMessageStatusResponse) => void): Request<ChimeSDKMessaging.Types.GetChannelMessageStatusResponse, AWSError>; /** * Gets message status for a specified messageId. Use this API to determine the intermediate status of messages going through channel flow processing. The API provides an alternative to retrieving message status if the event was not received because a client wasn't connected to a websocket. Messages can have any one of these statuses. SENT Message processed successfully PENDING Ongoing processing FAILED Processing failed DENIED Messasge denied by the processor This API does not return statuses for denied messages, because we don't store them once the processor denies them. Only the message sender can invoke this API. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header */ getChannelMessageStatus(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetChannelMessageStatusResponse) => void): Request<ChimeSDKMessaging.Types.GetChannelMessageStatusResponse, AWSError>; /** * The details of the endpoint for the messaging session. */ getMessagingSessionEndpoint(params: ChimeSDKMessaging.Types.GetMessagingSessionEndpointRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetMessagingSessionEndpointResponse) => void): Request<ChimeSDKMessaging.Types.GetMessagingSessionEndpointResponse, AWSError>; /** * The details of the endpoint for the messaging session. */ getMessagingSessionEndpoint(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.GetMessagingSessionEndpointResponse) => void): Request<ChimeSDKMessaging.Types.GetMessagingSessionEndpointResponse, AWSError>; /** * Lists all the users banned from a particular channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelBans(params: ChimeSDKMessaging.Types.ListChannelBansRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelBansResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelBansResponse, AWSError>; /** * Lists all the users banned from a particular channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelBans(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelBansResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelBansResponse, AWSError>; /** * Returns a paginated lists of all the channel flows created under a single Chime. This is a developer API. */ listChannelFlows(params: ChimeSDKMessaging.Types.ListChannelFlowsRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelFlowsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelFlowsResponse, AWSError>; /** * Returns a paginated lists of all the channel flows created under a single Chime. This is a developer API. */ listChannelFlows(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelFlowsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelFlowsResponse, AWSError>; /** * Lists all channel memberships in a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. If you want to list the channels to which a specific app instance user belongs, see the ListChannelMembershipsForAppInstanceUser API. */ listChannelMemberships(params: ChimeSDKMessaging.Types.ListChannelMembershipsRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelMembershipsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelMembershipsResponse, AWSError>; /** * Lists all channel memberships in a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. If you want to list the channels to which a specific app instance user belongs, see the ListChannelMembershipsForAppInstanceUser API. */ listChannelMemberships(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelMembershipsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelMembershipsResponse, AWSError>; /** * Lists all channels that a particular AppInstanceUser is a part of. Only an AppInstanceAdmin can call the API with a user ARN that is not their own. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelMembershipsForAppInstanceUser(params: ChimeSDKMessaging.Types.ListChannelMembershipsForAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelMembershipsForAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelMembershipsForAppInstanceUserResponse, AWSError>; /** * Lists all channels that a particular AppInstanceUser is a part of. Only an AppInstanceAdmin can call the API with a user ARN that is not their own. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelMembershipsForAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelMembershipsForAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelMembershipsForAppInstanceUserResponse, AWSError>; /** * List all the messages in a channel. Returns a paginated list of ChannelMessages. By default, sorted by creation timestamp in descending order. Redacted messages appear in the results as empty, since they are only redacted, not deleted. Deleted messages do not appear in the results. This action always returns the latest version of an edited message. Also, the x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelMessages(params: ChimeSDKMessaging.Types.ListChannelMessagesRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelMessagesResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelMessagesResponse, AWSError>; /** * List all the messages in a channel. Returns a paginated list of ChannelMessages. By default, sorted by creation timestamp in descending order. Redacted messages appear in the results as empty, since they are only redacted, not deleted. Deleted messages do not appear in the results. This action always returns the latest version of an edited message. Also, the x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelMessages(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelMessagesResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelMessagesResponse, AWSError>; /** * Lists all the moderators for a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelModerators(params: ChimeSDKMessaging.Types.ListChannelModeratorsRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelModeratorsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelModeratorsResponse, AWSError>; /** * Lists all the moderators for a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelModerators(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelModeratorsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelModeratorsResponse, AWSError>; /** * Lists all Channels created under a single Chime App as a paginated list. You can specify filters to narrow results. Functionality &amp; restrictions Use privacy = PUBLIC to retrieve all public channels in the account. Only an AppInstanceAdmin can set privacy = PRIVATE to list the private channels in an account. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannels(params: ChimeSDKMessaging.Types.ListChannelsRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelsResponse, AWSError>; /** * Lists all Channels created under a single Chime App as a paginated list. You can specify filters to narrow results. Functionality &amp; restrictions Use privacy = PUBLIC to retrieve all public channels in the account. Only an AppInstanceAdmin can set privacy = PRIVATE to list the private channels in an account. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannels(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelsResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelsResponse, AWSError>; /** * Lists all channels associated with a specified channel flow. You can associate a channel flow with multiple channels, but you can only associate a channel with one channel flow. This is a developer API. */ listChannelsAssociatedWithChannelFlow(params: ChimeSDKMessaging.Types.ListChannelsAssociatedWithChannelFlowRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelsAssociatedWithChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelsAssociatedWithChannelFlowResponse, AWSError>; /** * Lists all channels associated with a specified channel flow. You can associate a channel flow with multiple channels, but you can only associate a channel with one channel flow. This is a developer API. */ listChannelsAssociatedWithChannelFlow(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelsAssociatedWithChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelsAssociatedWithChannelFlowResponse, AWSError>; /** * A list of the channels moderated by an AppInstanceUser. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelsModeratedByAppInstanceUser(params: ChimeSDKMessaging.Types.ListChannelsModeratedByAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelsModeratedByAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelsModeratedByAppInstanceUserResponse, AWSError>; /** * A list of the channels moderated by an AppInstanceUser. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ listChannelsModeratedByAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListChannelsModeratedByAppInstanceUserResponse) => void): Request<ChimeSDKMessaging.Types.ListChannelsModeratedByAppInstanceUserResponse, AWSError>; /** * Lists the tags applied to an Amazon Chime SDK messaging resource. */ listTagsForResource(params: ChimeSDKMessaging.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListTagsForResourceResponse) => void): Request<ChimeSDKMessaging.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags applied to an Amazon Chime SDK messaging resource. */ listTagsForResource(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.ListTagsForResourceResponse) => void): Request<ChimeSDKMessaging.Types.ListTagsForResourceResponse, AWSError>; /** * Sets the membership preferences of an AppInstanceUser for the specified channel. The AppInstanceUser must be a member of the channel. Only the AppInstanceUser who owns the membership can set preferences. Users in the AppInstanceAdmin and channel moderator roles can't set preferences for other users. Banned users can't set membership preferences for the channel from which they are banned. */ putChannelMembershipPreferences(params: ChimeSDKMessaging.Types.PutChannelMembershipPreferencesRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.PutChannelMembershipPreferencesResponse) => void): Request<ChimeSDKMessaging.Types.PutChannelMembershipPreferencesResponse, AWSError>; /** * Sets the membership preferences of an AppInstanceUser for the specified channel. The AppInstanceUser must be a member of the channel. Only the AppInstanceUser who owns the membership can set preferences. Users in the AppInstanceAdmin and channel moderator roles can't set preferences for other users. Banned users can't set membership preferences for the channel from which they are banned. */ putChannelMembershipPreferences(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.PutChannelMembershipPreferencesResponse) => void): Request<ChimeSDKMessaging.Types.PutChannelMembershipPreferencesResponse, AWSError>; /** * Redacts message content, but not metadata. The message exists in the back end, but the action returns null content, and the state shows as redacted. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ redactChannelMessage(params: ChimeSDKMessaging.Types.RedactChannelMessageRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.RedactChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.RedactChannelMessageResponse, AWSError>; /** * Redacts message content, but not metadata. The message exists in the back end, but the action returns null content, and the state shows as redacted. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ redactChannelMessage(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.RedactChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.RedactChannelMessageResponse, AWSError>; /** * Sends a message to a particular channel that the member is a part of. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. Also, STANDARD messages can contain 4KB of data and the 1KB of metadata. CONTROL messages can contain 30 bytes of data and no metadata. */ sendChannelMessage(params: ChimeSDKMessaging.Types.SendChannelMessageRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.SendChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.SendChannelMessageResponse, AWSError>; /** * Sends a message to a particular channel that the member is a part of. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. Also, STANDARD messages can contain 4KB of data and the 1KB of metadata. CONTROL messages can contain 30 bytes of data and no metadata. */ sendChannelMessage(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.SendChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.SendChannelMessageResponse, AWSError>; /** * Applies the specified tags to the specified Amazon Chime SDK messaging resource. */ tagResource(params: ChimeSDKMessaging.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Applies the specified tags to the specified Amazon Chime SDK messaging resource. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the specified tags from the specified Amazon Chime SDK messaging resource. */ untagResource(params: ChimeSDKMessaging.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the specified tags from the specified Amazon Chime SDK messaging resource. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Update a channel's attributes. Restriction: You can't change a channel's privacy. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ updateChannel(params: ChimeSDKMessaging.Types.UpdateChannelRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelResponse, AWSError>; /** * Update a channel's attributes. Restriction: You can't change a channel's privacy. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ updateChannel(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelResponse, AWSError>; /** * Updates channel flow attributes. This is a developer API. */ updateChannelFlow(params: ChimeSDKMessaging.Types.UpdateChannelFlowRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelFlowResponse, AWSError>; /** * Updates channel flow attributes. This is a developer API. */ updateChannelFlow(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelFlowResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelFlowResponse, AWSError>; /** * Updates the content of a message. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ updateChannelMessage(params: ChimeSDKMessaging.Types.UpdateChannelMessageRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelMessageResponse, AWSError>; /** * Updates the content of a message. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ updateChannelMessage(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelMessageResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelMessageResponse, AWSError>; /** * The details of the time when a user last read messages in a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ updateChannelReadMarker(params: ChimeSDKMessaging.Types.UpdateChannelReadMarkerRequest, callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelReadMarkerResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelReadMarkerResponse, AWSError>; /** * The details of the time when a user last read messages in a channel. The x-amz-chime-bearer request header is mandatory. Use the AppInstanceUserArn of the user that makes the API call as the value in the header. */ updateChannelReadMarker(callback?: (err: AWSError, data: ChimeSDKMessaging.Types.UpdateChannelReadMarkerResponse) => void): Request<ChimeSDKMessaging.Types.UpdateChannelReadMarkerResponse, AWSError>; } declare namespace ChimeSDKMessaging { export type AllowNotifications = "ALL"|"NONE"|"FILTERED"|string; export interface AppInstanceUserMembershipSummary { /** * The type of ChannelMembership. */ Type?: ChannelMembershipType; /** * The time at which a message was last read. */ ReadMarkerTimestamp?: Timestamp; } export interface AssociateChannelFlowRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The ARN of the channel flow. */ ChannelFlowArn: ChimeArn; /** * The AppInstanceUserArn of the user making the API call. */ ChimeBearer: ChimeArn; } export interface BatchChannelMemberships { /** * The identifier of the member who invited another member. */ InvitedBy?: Identity; /** * The membership types set for the channel users. */ Type?: ChannelMembershipType; /** * The users successfully added to the request. */ Members?: Members; /** * The ARN of the channel to which you're adding users. */ ChannelArn?: ChimeArn; } export interface BatchCreateChannelMembershipError { /** * The AppInstanceUserArn of the member that the service couldn't add. */ MemberArn?: ChimeArn; /** * The error code. */ ErrorCode?: ErrorCode; /** * The error message. */ ErrorMessage?: String; } export type BatchCreateChannelMembershipErrors = BatchCreateChannelMembershipError[]; export interface BatchCreateChannelMembershipRequest { /** * The ARN of the channel to which you're adding users. */ ChannelArn: ChimeArn; /** * The membership type of a user, DEFAULT or HIDDEN. Default members are always returned as part of ListChannelMemberships. Hidden members are only returned if the type filter in ListChannelMemberships equals HIDDEN. Otherwise hidden members are not returned. This is only supported by moderators. */ Type?: ChannelMembershipType; /** * The AppInstanceUserArns of the members you want to add to the channel. */ MemberArns: MemberArns; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface BatchCreateChannelMembershipResponse { /** * The list of channel memberships in the response. */ BatchChannelMemberships?: BatchChannelMemberships; /** * If the action fails for one or more of the memberships in the request, a list of the memberships is returned, along with error codes and error messages. */ Errors?: BatchCreateChannelMembershipErrors; } export type CallbackIdType = string; export interface Channel { /** * The name of a channel. */ Name?: NonEmptyResourceName; /** * The ARN of a channel. */ ChannelArn?: ChimeArn; /** * The mode of the channel. */ Mode?: ChannelMode; /** * The channel's privacy setting. */ Privacy?: ChannelPrivacy; /** * The channel's metadata. */ Metadata?: Metadata; /** * The AppInstanceUser who created the channel. */ CreatedBy?: Identity; /** * The time at which the AppInstanceUser created the channel. */ CreatedTimestamp?: Timestamp; /** * The time at which a member sent the last message in the channel. */ LastMessageTimestamp?: Timestamp; /** * The time at which a channel was last updated. */ LastUpdatedTimestamp?: Timestamp; /** * The ARN of the channel flow. */ ChannelFlowArn?: ChimeArn; } export interface ChannelAssociatedWithFlowSummary { /** * The name of the channel flow. */ Name?: NonEmptyResourceName; /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The mode of the channel. */ Mode?: ChannelMode; /** * The channel's privacy setting. */ Privacy?: ChannelPrivacy; /** * The channel's metadata. */ Metadata?: Metadata; } export type ChannelAssociatedWithFlowSummaryList = ChannelAssociatedWithFlowSummary[]; export interface ChannelBan { /** * The member being banned from the channel. */ Member?: Identity; /** * The ARN of the channel from which a member is being banned. */ ChannelArn?: ChimeArn; /** * The time at which the ban was created. */ CreatedTimestamp?: Timestamp; /** * The AppInstanceUser who created the ban. */ CreatedBy?: Identity; } export interface ChannelBanSummary { /** * The member being banned from a channel. */ Member?: Identity; } export type ChannelBanSummaryList = ChannelBanSummary[]; export interface ChannelFlow { /** * The ARN of the channel flow. */ ChannelFlowArn?: ChimeArn; /** * Information about the processor Lambda functions. */ Processors?: ProcessorList; /** * The name of the channel flow. */ Name?: NonEmptyResourceName; /** * The time at which the channel flow was created. */ CreatedTimestamp?: Timestamp; /** * The time at which a channel flow was updated. */ LastUpdatedTimestamp?: Timestamp; } export interface ChannelFlowCallbackRequest { /** * The identifier passed to the processor by the service when invoked. Use the identifier to call back the service. */ CallbackId: CallbackIdType; /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * When a processor determines that a message needs to be DENIED, pass this parameter with a value of true. */ DeleteResource?: NonNullableBoolean; /** * Stores information about the processed message. */ ChannelMessage: ChannelMessageCallback; } export interface ChannelFlowCallbackResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The call back ID passed in the request. */ CallbackId?: CallbackIdType; } export type ChannelFlowExecutionOrder = number; export interface ChannelFlowSummary { /** * The ARN of the channel flow. */ ChannelFlowArn?: ChimeArn; /** * The name of the channel flow. */ Name?: NonEmptyResourceName; /** * Information about the processor Lambda functions. */ Processors?: ProcessorList; } export type ChannelFlowSummaryList = ChannelFlowSummary[]; export interface ChannelMembership { /** * The identifier of the member who invited another member. */ InvitedBy?: Identity; /** * The membership type set for the channel member. */ Type?: ChannelMembershipType; /** * The data of the channel member. */ Member?: Identity; /** * The ARN of the member's channel. */ ChannelArn?: ChimeArn; /** * The time at which the channel membership was created. */ CreatedTimestamp?: Timestamp; /** * The time at which a channel membership was last updated. */ LastUpdatedTimestamp?: Timestamp; } export interface ChannelMembershipForAppInstanceUserSummary { /** * Returns the channel data for an AppInstance. */ ChannelSummary?: ChannelSummary; /** * Returns the channel membership data for an AppInstance. */ AppInstanceUserMembershipSummary?: AppInstanceUserMembershipSummary; } export type ChannelMembershipForAppInstanceUserSummaryList = ChannelMembershipForAppInstanceUserSummary[]; export interface ChannelMembershipPreferences { /** * The push notification configuration of a message. */ PushNotifications?: PushNotificationPreferences; } export interface ChannelMembershipSummary { /** * A member's summary data. */ Member?: Identity; } export type ChannelMembershipSummaryList = ChannelMembershipSummary[]; export type ChannelMembershipType = "DEFAULT"|"HIDDEN"|string; export interface ChannelMessage { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The ID of a message. */ MessageId?: MessageId; /** * The message content. */ Content?: Content; /** * The message metadata. */ Metadata?: Metadata; /** * The message type. */ Type?: ChannelMessageType; /** * The time at which the message was created. */ CreatedTimestamp?: Timestamp; /** * The time at which a message was edited. */ LastEditedTimestamp?: Timestamp; /** * The time at which a message was updated. */ LastUpdatedTimestamp?: Timestamp; /** * The message sender. */ Sender?: Identity; /** * Hides the content of a message. */ Redacted?: NonNullableBoolean; /** * The persistence setting for a channel message. */ Persistence?: ChannelMessagePersistenceType; /** * The status of the channel message. */ Status?: ChannelMessageStatusStructure; /** * The attributes for the message, used for message filtering along with a FilterRule defined in the PushNotificationPreferences. */ MessageAttributes?: MessageAttributeMap; } export interface ChannelMessageCallback { /** * The message ID. */ MessageId: MessageId; /** * The message content. */ Content?: NonEmptyContent; /** * The message metadata. */ Metadata?: Metadata; /** * The push notification configuration of the message. */ PushNotification?: PushNotificationConfiguration; /** * The attributes for the message, used for message filtering along with a FilterRule defined in the PushNotificationPreferences. */ MessageAttributes?: MessageAttributeMap; } export type ChannelMessagePersistenceType = "PERSISTENT"|"NON_PERSISTENT"|string; export type ChannelMessageStatus = "SENT"|"PENDING"|"FAILED"|"DENIED"|string; export interface ChannelMessageStatusStructure { /** * The message status value. */ Value?: ChannelMessageStatus; /** * Contains more details about the messasge status. */ Detail?: StatusDetail; } export interface ChannelMessageSummary { /** * The ID of the message. */ MessageId?: MessageId; /** * The content of the message. */ Content?: Content; /** * The metadata of the message. */ Metadata?: Metadata; /** * The type of message. */ Type?: ChannelMessageType; /** * The time at which the message summary was created. */ CreatedTimestamp?: Timestamp; /** * The time at which a message was last updated. */ LastUpdatedTimestamp?: Timestamp; /** * The time at which a message was last edited. */ LastEditedTimestamp?: Timestamp; /** * The message sender. */ Sender?: Identity; /** * Indicates whether a message was redacted. */ Redacted?: NonNullableBoolean; /** * The message status. The status value is SENT for messages sent to a channel without a channel flow. For channels associated with channel flow, the value determines the processing stage. */ Status?: ChannelMessageStatusStructure; /** * The message attribues listed in a the summary of a channel message. */ MessageAttributes?: MessageAttributeMap; } export type ChannelMessageSummaryList = ChannelMessageSummary[]; export type ChannelMessageType = "STANDARD"|"CONTROL"|string; export type ChannelMode = "UNRESTRICTED"|"RESTRICTED"|string; export interface ChannelModeratedByAppInstanceUserSummary { /** * Summary of the details of a Channel. */ ChannelSummary?: ChannelSummary; } export type ChannelModeratedByAppInstanceUserSummaryList = ChannelModeratedByAppInstanceUserSummary[]; export interface ChannelModerator { /** * The moderator's data. */ Moderator?: Identity; /** * The ARN of the moderator's channel. */ ChannelArn?: ChimeArn; /** * The time at which the moderator was created. */ CreatedTimestamp?: Timestamp; /** * The AppInstanceUser who created the moderator. */ CreatedBy?: Identity; } export interface ChannelModeratorSummary { /** * The data for a moderator. */ Moderator?: Identity; } export type ChannelModeratorSummaryList = ChannelModeratorSummary[]; export type ChannelPrivacy = "PUBLIC"|"PRIVATE"|string; export interface ChannelSummary { /** * The name of the channel. */ Name?: NonEmptyResourceName; /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The mode of the channel. */ Mode?: ChannelMode; /** * The privacy setting of the channel. */ Privacy?: ChannelPrivacy; /** * The metadata of the channel. */ Metadata?: Metadata; /** * The time at which the last message in a channel was sent. */ LastMessageTimestamp?: Timestamp; } export type ChannelSummaryList = ChannelSummary[]; export type ChimeArn = string; export type ClientRequestToken = string; export type Content = string; export interface CreateChannelBanRequest { /** * The ARN of the ban request. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member being banned. */ MemberArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface CreateChannelBanResponse { /** * The ARN of the response to the ban request. */ ChannelArn?: ChimeArn; /** * The ChannelArn and BannedIdentity of the member in the ban response. */ Member?: Identity; } export interface CreateChannelFlowRequest { /** * The ARN of the channel flow request. */ AppInstanceArn: ChimeArn; /** * Information about the processor Lambda functions. */ Processors: ProcessorList; /** * The name of the channel flow. */ Name: NonEmptyResourceName; /** * The tags for the creation request. */ Tags?: TagList; /** * The client token for the request. An Idempotency token. */ ClientRequestToken: ClientRequestToken; } export interface CreateChannelFlowResponse { /** * The ARN of the channel flow. */ ChannelFlowArn?: ChimeArn; } export interface CreateChannelMembershipRequest { /** * The ARN of the channel to which you're adding users. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member you want to add to the channel. */ MemberArn: ChimeArn; /** * The membership type of a user, DEFAULT or HIDDEN. Default members are always returned as part of ListChannelMemberships. Hidden members are only returned if the type filter in ListChannelMemberships equals HIDDEN. Otherwise hidden members are not returned. This is only supported by moderators. */ Type: ChannelMembershipType; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface CreateChannelMembershipResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The ARN and metadata of the member being added. */ Member?: Identity; } export interface CreateChannelModeratorRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the moderator. */ ChannelModeratorArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface CreateChannelModeratorResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The ARNs of the channel and the moderator. */ ChannelModerator?: Identity; } export interface CreateChannelRequest { /** * The ARN of the channel request. */ AppInstanceArn: ChimeArn; /** * The name of the channel. */ Name: NonEmptyResourceName; /** * The channel mode: UNRESTRICTED or RESTRICTED. Administrators, moderators, and channel members can add themselves and other members to unrestricted channels. Only administrators and moderators can add members to restricted channels. */ Mode?: ChannelMode; /** * The channel's privacy level: PUBLIC or PRIVATE. Private channels aren't discoverable by users outside the channel. Public channels are discoverable by anyone in the AppInstance. */ Privacy?: ChannelPrivacy; /** * The metadata of the creation request. Limited to 1KB and UTF-8. */ Metadata?: Metadata; /** * The client token for the request. An Idempotency token. */ ClientRequestToken: ClientRequestToken; /** * The tags for the creation request. */ Tags?: TagList; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface CreateChannelResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; } export interface DeleteChannelBanRequest { /** * The ARN of the channel from which the AppInstanceUser was banned. */ ChannelArn: ChimeArn; /** * The ARN of the AppInstanceUser that you want to reinstate. */ MemberArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DeleteChannelFlowRequest { /** * The ARN of the channel flow. */ ChannelFlowArn: ChimeArn; } export interface DeleteChannelMembershipRequest { /** * The ARN of the channel from which you want to remove the user. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member that you're removing from the channel. */ MemberArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DeleteChannelMessageRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The ID of the message being deleted. */ MessageId: MessageId; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DeleteChannelModeratorRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the moderator being deleted. */ ChannelModeratorArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DeleteChannelRequest { /** * The ARN of the channel being deleted. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelBanRequest { /** * The ARN of the channel from which the user is banned. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member being banned. */ MemberArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelBanResponse { /** * The details of the ban. */ ChannelBan?: ChannelBan; } export interface DescribeChannelFlowRequest { /** * The ARN of the channel flow. */ ChannelFlowArn: ChimeArn; } export interface DescribeChannelFlowResponse { /** * The channel flow details. */ ChannelFlow?: ChannelFlow; } export interface DescribeChannelMembershipForAppInstanceUserRequest { /** * The ARN of the channel to which the user belongs. */ ChannelArn: ChimeArn; /** * The ARN of the user in a channel. */ AppInstanceUserArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelMembershipForAppInstanceUserResponse { /** * The channel to which a user belongs. */ ChannelMembership?: ChannelMembershipForAppInstanceUserSummary; } export interface DescribeChannelMembershipRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member. */ MemberArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelMembershipResponse { /** * The details of the membership. */ ChannelMembership?: ChannelMembership; } export interface DescribeChannelModeratedByAppInstanceUserRequest { /** * The ARN of the moderated channel. */ ChannelArn: ChimeArn; /** * The ARN of the AppInstanceUser in the moderated channel. */ AppInstanceUserArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelModeratedByAppInstanceUserResponse { /** * The moderated channel. */ Channel?: ChannelModeratedByAppInstanceUserSummary; } export interface DescribeChannelModeratorRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the channel moderator. */ ChannelModeratorArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelModeratorResponse { /** * The details of the channel moderator. */ ChannelModerator?: ChannelModerator; } export interface DescribeChannelRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface DescribeChannelResponse { /** * The channel details. */ Channel?: Channel; } export interface DisassociateChannelFlowRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The ARN of the channel flow. */ ChannelFlowArn: ChimeArn; /** * The AppInstanceUserArn of the user making the API call. */ ChimeBearer: ChimeArn; } export type ErrorCode = "BadRequest"|"Conflict"|"Forbidden"|"NotFound"|"PreconditionFailed"|"ResourceLimitExceeded"|"ServiceFailure"|"AccessDenied"|"ServiceUnavailable"|"Throttled"|"Throttling"|"Unauthorized"|"Unprocessable"|"VoiceConnectorGroupAssociationsExist"|"PhoneNumberAssociationsExist"|string; export type FallbackAction = "CONTINUE"|"ABORT"|string; export type FilterRule = string; export interface GetChannelMembershipPreferencesRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member retrieving the preferences. */ MemberArn: ChimeArn; /** * The AppInstanceUserARN of the user making the API call. */ ChimeBearer: ChimeArn; } export interface GetChannelMembershipPreferencesResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; Member?: Identity; /** * The channel membership preferences for an AppInstanceUser . */ Preferences?: ChannelMembershipPreferences; } export interface GetChannelMessageRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The ID of the message. */ MessageId: MessageId; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface GetChannelMessageResponse { /** * The details of and content in the message. */ ChannelMessage?: ChannelMessage; } export interface GetChannelMessageStatusRequest { /** * The ARN of the channel */ ChannelArn: ChimeArn; /** * The ID of the message. */ MessageId: MessageId; /** * The AppInstanceUserArn of the user making the API call. */ ChimeBearer: ChimeArn; } export interface GetChannelMessageStatusResponse { /** * The message status and details. */ Status?: ChannelMessageStatusStructure; } export interface GetMessagingSessionEndpointRequest { } export interface GetMessagingSessionEndpointResponse { /** * The endpoint returned in the response. */ Endpoint?: MessagingSessionEndpoint; } export interface Identity { /** * The ARN in an Identity. */ Arn?: ChimeArn; /** * The name in an Identity. */ Name?: ResourceName; } export type InvocationType = "ASYNC"|string; export interface LambdaConfiguration { /** * The ARN of the Lambda message processing function. */ ResourceArn: LambdaFunctionArn; /** * Controls how the Lambda function is invoked. */ InvocationType: InvocationType; } export type LambdaFunctionArn = string; export interface ListChannelBansRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The maximum number of bans that you want returned. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested bans are returned. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelBansResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The token passed by previous API calls until all requested bans are returned. */ NextToken?: NextToken; /** * The information for each requested ban. */ ChannelBans?: ChannelBanSummaryList; } export interface ListChannelFlowsRequest { /** * The ARN of the app instance. */ AppInstanceArn: ChimeArn; /** * The maximum number of channel flows that you want to return. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested channel flows are returned. */ NextToken?: NextToken; } export interface ListChannelFlowsResponse { /** * The information about each channel flow. */ ChannelFlows?: ChannelFlowSummaryList; /** * The token passed by previous API calls until all requested channels are returned. */ NextToken?: NextToken; } export interface ListChannelMembershipsForAppInstanceUserRequest { /** * The ARN of the AppInstanceUsers */ AppInstanceUserArn?: ChimeArn; /** * The maximum number of users that you want returned. */ MaxResults?: MaxResults; /** * The token returned from previous API requests until the number of channel memberships is reached. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelMembershipsForAppInstanceUserResponse { /** * The token passed by previous API calls until all requested users are returned. */ ChannelMemberships?: ChannelMembershipForAppInstanceUserSummaryList; /** * The token passed by previous API calls until all requested users are returned. */ NextToken?: NextToken; } export interface ListChannelMembershipsRequest { /** * The maximum number of channel memberships that you want returned. */ ChannelArn: ChimeArn; /** * The membership type of a user, DEFAULT or HIDDEN. Default members are returned as part of ListChannelMemberships if no type is specified. Hidden members are only returned if the type filter in ListChannelMemberships equals HIDDEN. */ Type?: ChannelMembershipType; /** * The maximum number of channel memberships that you want returned. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested channel memberships are returned. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelMembershipsResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The information for the requested channel memberships. */ ChannelMemberships?: ChannelMembershipSummaryList; /** * The token passed by previous API calls until all requested channel memberships are returned. */ NextToken?: NextToken; } export interface ListChannelMessagesRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The order in which you want messages sorted. Default is Descending, based on time created. */ SortOrder?: SortOrder; /** * The initial or starting time stamp for your requested messages. */ NotBefore?: Timestamp; /** * The final or ending time stamp for your requested messages. */ NotAfter?: Timestamp; /** * The maximum number of messages that you want returned. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested messages are returned. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelMessagesResponse { /** * The ARN of the channel containing the requested messages. */ ChannelArn?: ChimeArn; /** * The token passed by previous API calls until all requested messages are returned. */ NextToken?: NextToken; /** * The information about, and content of, each requested message. */ ChannelMessages?: ChannelMessageSummaryList; } export interface ListChannelModeratorsRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The maximum number of moderators that you want returned. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested moderators are returned. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelModeratorsResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The token passed by previous API calls until all requested moderators are returned. */ NextToken?: NextToken; /** * The information about and names of each moderator. */ ChannelModerators?: ChannelModeratorSummaryList; } export interface ListChannelsAssociatedWithChannelFlowRequest { /** * The ARN of the channel flow. */ ChannelFlowArn: ChimeArn; /** * The maximum number of channels that you want to return. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested channels are returned. */ NextToken?: NextToken; } export interface ListChannelsAssociatedWithChannelFlowResponse { /** * The information about each channel. */ Channels?: ChannelAssociatedWithFlowSummaryList; /** * The token passed by previous API calls until all requested channels are returned. */ NextToken?: NextToken; } export interface ListChannelsModeratedByAppInstanceUserRequest { /** * The ARN of the user in the moderated channel. */ AppInstanceUserArn?: ChimeArn; /** * The maximum number of channels in the request. */ MaxResults?: MaxResults; /** * The token returned from previous API requests until the number of channels moderated by the user is reached. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelsModeratedByAppInstanceUserResponse { /** * The moderated channels in the request. */ Channels?: ChannelModeratedByAppInstanceUserSummaryList; /** * The token returned from previous API requests until the number of channels moderated by the user is reached. */ NextToken?: NextToken; } export interface ListChannelsRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; /** * The privacy setting. PUBLIC retrieves all the public channels. PRIVATE retrieves private channels. Only an AppInstanceAdmin can retrieve private channels. */ Privacy?: ChannelPrivacy; /** * The maximum number of channels that you want to return. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested channels are returned. */ NextToken?: NextToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface ListChannelsResponse { /** * The information about each channel. */ Channels?: ChannelSummaryList; /** * The token returned from previous API requests until the number of channels is reached. */ NextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The ARN of the resource. */ ResourceARN: ChimeArn; } export interface ListTagsForResourceResponse { /** * The tag key-value pairs. */ Tags?: TagList; } export type MaxResults = number; export type MemberArns = ChimeArn[]; export type Members = Identity[]; export type MessageAttributeMap = {[key: string]: MessageAttributeValue}; export type MessageAttributeName = string; export type MessageAttributeStringValue = string; export type MessageAttributeStringValues = MessageAttributeStringValue[]; export interface MessageAttributeValue { /** * The strings in a message attribute value. */ StringValues?: MessageAttributeStringValues; } export type MessageId = string; export interface MessagingSessionEndpoint { /** * The endpoint to which you establish a websocket connection. */ Url?: UrlType; } export type Metadata = string; export type NextToken = string; export type NonEmptyContent = string; export type NonEmptyResourceName = string; export type NonNullableBoolean = boolean; export interface Processor { /** * The name of the channel flow. */ Name: NonEmptyResourceName; /** * The information about the type of processor and its identifier. */ Configuration: ProcessorConfiguration; /** * The sequence in which processors run. If you have multiple processors in a channel flow, message processing goes through each processor in the sequence. The value determines the sequence. At this point, we support only 1 processor within a flow. */ ExecutionOrder: ChannelFlowExecutionOrder; /** * Determines whether to continue with message processing or stop it in cases where communication with a processor fails. If a processor has a fallback action of ABORT and communication with it fails, the processor sets the message status to FAILED and does not send the message to any recipients. Note that if the last processor in the channel flow sequence has a fallback action of CONTINUE and communication with the processor fails, then the message is considered processed and sent to recipients of the channel. */ FallbackAction: FallbackAction; } export interface ProcessorConfiguration { /** * Indicates that the processor is of type Lambda. */ Lambda: LambdaConfiguration; } export type ProcessorList = Processor[]; export type PushNotificationBody = string; export interface PushNotificationConfiguration { /** * The title of the push notification. */ Title?: PushNotificationTitle; /** * The body of the push notification. */ Body?: PushNotificationBody; /** * Enum value that indicates the type of the push notification for a message. DEFAULT: Normal mobile push notification. VOIP: VOIP mobile push notification. */ Type?: PushNotificationType; } export interface PushNotificationPreferences { /** * Enum value that indicates which push notifications to send to the requested member of a channel. ALL sends all push notifications, NONE sends no push notifications, FILTERED sends only filtered push notifications. */ AllowNotifications: AllowNotifications; /** * The simple JSON object used to send a subset of a push notification to the requsted member. */ FilterRule?: FilterRule; } export type PushNotificationTitle = string; export type PushNotificationType = "DEFAULT"|"VOIP"|string; export interface PutChannelMembershipPreferencesRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the member setting the preferences. */ MemberArn: ChimeArn; /** * The AppInstanceUserARN of the user making the API call. */ ChimeBearer: ChimeArn; /** * The channel membership preferences of an AppInstanceUser . */ Preferences: ChannelMembershipPreferences; } export interface PutChannelMembershipPreferencesResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; Member?: Identity; /** * The ARN and metadata of the member being added. */ Preferences?: ChannelMembershipPreferences; } export interface RedactChannelMessageRequest { /** * The ARN of the channel containing the messages that you want to redact. */ ChannelArn: ChimeArn; /** * The ID of the message being redacted. */ MessageId: MessageId; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface RedactChannelMessageResponse { /** * The ARN of the channel containing the messages that you want to redact. */ ChannelArn?: ChimeArn; /** * The ID of the message being redacted. */ MessageId?: MessageId; } export type ResourceName = string; export interface SendChannelMessageRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The content of the message. */ Content: NonEmptyContent; /** * The type of message, STANDARD or CONTROL. */ Type: ChannelMessageType; /** * Boolean that controls whether the message is persisted on the back end. Required. */ Persistence: ChannelMessagePersistenceType; /** * The optional metadata for each message. */ Metadata?: Metadata; /** * The Idempotency token for each client request. */ ClientRequestToken: ClientRequestToken; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; /** * The push notification configuration of the message. */ PushNotification?: PushNotificationConfiguration; /** * The attributes for the message, used for message filtering along with a FilterRule defined in the PushNotificationPreferences. */ MessageAttributes?: MessageAttributeMap; } export interface SendChannelMessageResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The ID string assigned to each message. */ MessageId?: MessageId; /** * The status of the channel message. */ Status?: ChannelMessageStatusStructure; } export type SortOrder = "ASCENDING"|"DESCENDING"|string; export type StatusDetail = string; export type String = string; export interface Tag { /** * The key in a tag. */ Key: TagKey; /** * The value in a tag. */ Value: TagValue; } export type TagKey = string; export type TagKeyList = TagKey[]; export type TagList = Tag[]; export interface TagResourceRequest { /** * The resource ARN. */ ResourceARN: ChimeArn; /** * The tag key-value pairs. */ Tags: TagList; } export type TagValue = string; export type Timestamp = Date; export interface UntagResourceRequest { /** * The resource ARN. */ ResourceARN: ChimeArn; /** * The tag keys. */ TagKeys: TagKeyList; } export interface UpdateChannelFlowRequest { /** * The ARN of the channel flow. */ ChannelFlowArn: ChimeArn; /** * Information about the processor Lambda functions */ Processors: ProcessorList; /** * The name of the channel flow. */ Name: NonEmptyResourceName; } export interface UpdateChannelFlowResponse { /** * The ARN of the channel flow. */ ChannelFlowArn?: ChimeArn; } export interface UpdateChannelMessageRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The ID string of the message being updated. */ MessageId: MessageId; /** * The content of the message being updated. */ Content?: Content; /** * The metadata of the message being updated. */ Metadata?: Metadata; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface UpdateChannelMessageResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; /** * The ID string of the message being updated. */ MessageId?: MessageId; /** * The status of the message update. */ Status?: ChannelMessageStatusStructure; } export interface UpdateChannelReadMarkerRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface UpdateChannelReadMarkerResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; } export interface UpdateChannelRequest { /** * The ARN of the channel. */ ChannelArn: ChimeArn; /** * The name of the channel. */ Name: NonEmptyResourceName; /** * The mode of the update request. */ Mode: ChannelMode; /** * The metadata for the update request. */ Metadata?: Metadata; /** * The AppInstanceUserArn of the user that makes the API call. */ ChimeBearer: ChimeArn; } export interface UpdateChannelResponse { /** * The ARN of the channel. */ ChannelArn?: ChimeArn; } export type UrlType = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2021-05-15"|"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 ChimeSDKMessaging client. */ export import Types = ChimeSDKMessaging; } export = ChimeSDKMessaging;
the_stack